Repository navigation
Expand file tree
/
Copy pathinterpreter.rs
More file actions
2504 lines (2298 loc) · 103 KB
/
Copy pathinterpreter.rs
File metadata and controls
2504 lines (2298 loc) · 103 KB
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
//!
//! There are several constraints on the Bun shell language that make this
//! interpreter implementation unique:
//!
//! 1. We try to keep everything in the Bun process as much as possible for
//! performance reasons and also to leverage Bun's existing IO/FS code
//! 2. We try to use non-blocking IO operations as much as possible so the
//! shell does not block the main JS thread
//!
//! The idea is that this is a tree-walking interpreter — except instead of
//! iteratively walking the AST, we build a tree of state-machine nodes so we
//! can suspend/resume without blocking the main thread, driven in
//! continuation-passing style by `Yield::run`.
//!
//! ## NodeId arena
//!
//! A parent/child back-pointer tree would be borrow-checker hostile
//! (overlapping `&mut` of parent and child), so all state nodes live in a
//! flat `Vec<Node>` owned by the `Interpreter`. Nodes refer to each other
//! (and to their parent) by `NodeId` — a `u32` index. Dispatch is a single
//! hoisted `match` on the parent's tag (`Interpreter::child_done`), which
//! keeps the per-tick hot path inlined (see PORTING.md §Dispatch hot-path).
//!
//! State methods take `(&mut Interpreter, this: NodeId)` and look their
//! own data up via `interp.as_<state>(this)` / `interp.as_<state>_mut(this)`.
use bun_collections::VecExt;
use bun_jsc::bindgen::{JsLocal, JsPayload as _, JsScope, JsWrapper};
use bun_jsc::{JsCell, JsCellRefExt as _, JsRef};
use bun_ptr::AliasableBox;
use core::cell::Cell;
use core::fmt;
use std::sync::atomic::Ordering;
use bun_sys::{self, Fd, File};
pub(crate) use crate::generated_bindgen::interpreter::js_ShellInterpreter as js;
pub(crate) use crate::shell::env_map::EnvMap;
use crate::shell::io::IO;
use crate::shell::states::assigns::Assigns;
use crate::shell::states::r#async::Async;
use crate::shell::states::base::{Base, Env};
use crate::shell::states::binary::Binary;
pub(crate) use crate::shell::states::cmd::Cmd;
use crate::shell::states::cond_expr::CondExpr;
use crate::shell::states::expansion::Expansion;
use crate::shell::states::r#if::If;
use crate::shell::states::pipeline::Pipeline;
use crate::shell::states::script::Script;
use crate::shell::states::stmt::Stmt;
use crate::shell::states::subshell::Subshell;
use crate::shell::yield_::Yield;
use crate::shell::{ShellErr, ast};
bun_core::declare_scope!(SHELL, visible);
/// `log!("...")` — scoped debug logger for the shell interpreter. Expands to
/// nothing in release; the `SHELL` static is referenced by absolute path so
/// callers don't need it in scope.
#[macro_export]
macro_rules! shell_log {
($fmt:literal $(, $arg:expr)* $(,)?) => {{
#[allow(unused_imports)]
use $crate::shell::interpreter::SHELL;
bun_core::scoped_log!(SHELL, $fmt $(, $arg)*);
}};
}
pub(crate) use shell_log as log;
// ────────────────────────────────────────────────────────────────────────────
// NodeId arena
// ────────────────────────────────────────────────────────────────────────────
/// Index into `Interpreter::nodes`.
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct NodeId(pub(crate) u32);
impl NodeId {
/// Sentinel: "the parent is the Interpreter itself". The root `Script`
/// node uses this. `Interpreter::child_done` special-cases it.
pub(crate) const INTERPRETER: NodeId = NodeId(u32::MAX);
/// Sentinel for "no node" (e.g. an `Option<NodeId>` packed as a plain id).
pub(crate) const NONE: NodeId = NodeId(u32::MAX - 1);
#[inline]
pub(crate) fn idx(self) -> usize {
self.0 as usize
}
}
impl fmt::Display for NodeId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if *self == NodeId::INTERPRETER {
write!(f, "Node(interp)")
} else {
write!(f, "Node#{}", self.0)
}
}
}
/// One slot in the interpreter's state arena. All state structs
/// live as enum variants in a single `Vec<Node>` so the only outstanding
/// borrow at any time is `&mut Interpreter`.
pub(crate) enum Node {
/// Freed slot, available for reuse by `alloc_node`.
Free,
Script(Script),
Stmt(Stmt),
Binary(Binary),
Pipeline(Pipeline),
Cmd(Cmd),
Assigns(Assigns),
Expansion(Expansion),
If(If),
CondExpr(CondExpr),
Async(Async),
Subshell(Subshell),
}
impl Node {
pub(crate) fn kind(&self) -> StateKind {
match self {
Node::Free => StateKind::Free,
Node::Script(_) => StateKind::Script,
Node::Stmt(_) => StateKind::Stmt,
Node::Binary(_) => StateKind::Binary,
Node::Pipeline(_) => StateKind::Pipeline,
Node::Cmd(_) => StateKind::Cmd,
Node::Assigns(_) => StateKind::Assign,
Node::Expansion(_) => StateKind::Expansion,
Node::If(_) => StateKind::IfClause,
Node::CondExpr(_) => StateKind::Condexpr,
Node::Async(_) => StateKind::Async,
Node::Subshell(_) => StateKind::Subshell,
}
}
/// Every state struct embeds a `Base` header at a known field; this is the
/// hoisted accessor.
pub(crate) fn base(&self) -> Option<&Base> {
match self {
Node::Free => None,
Node::Script(s) => Some(&s.base),
Node::Stmt(s) => Some(&s.base),
Node::Binary(s) => Some(&s.base),
Node::Pipeline(s) => Some(&s.base),
Node::Cmd(s) => Some(&s.base),
Node::Assigns(s) => Some(&s.base),
Node::Expansion(s) => Some(&s.base),
Node::If(s) => Some(&s.base),
Node::CondExpr(s) => Some(&s.base),
Node::Async(s) => Some(&s.base),
Node::Subshell(s) => Some(&s.base),
}
}
fn base_mut(&mut self) -> Option<&mut Base> {
match self {
Node::Free => None,
Node::Script(s) => Some(&mut s.base),
Node::Stmt(s) => Some(&mut s.base),
Node::Binary(s) => Some(&mut s.base),
Node::Pipeline(s) => Some(&mut s.base),
Node::Cmd(s) => Some(&mut s.base),
Node::Assigns(s) => Some(&mut s.base),
Node::Expansion(s) => Some(&mut s.base),
Node::If(s) => Some(&mut s.base),
Node::CondExpr(s) => Some(&mut s.base),
Node::Async(s) => Some(&mut s.base),
Node::Subshell(s) => Some(&mut s.base),
}
}
}
/// Generate `Interpreter::as_<kind>{,_mut}` typed accessors. These panic on
/// tag mismatch.
macro_rules! node_accessors {
($($variant:ident => $ty:ty, $get:ident, $get_mut:ident);* $(;)?) => {
impl Interpreter {
$(
#[inline]
#[track_caller]
pub(crate) fn $get(&self, id: NodeId) -> &$ty {
match &self.nodes.get()[id.idx()] {
Node::$variant(v) => v,
other => panic!(
concat!("expected Node::", stringify!($variant), " at {}, got {:?}"),
id, other.kind()
),
}
}
#[inline]
#[track_caller]
#[allow(clippy::mut_from_ref)]
pub(crate) fn $get_mut(&self, id: NodeId) -> &mut $ty {
// SAFETY: R-2 single-JS-thread invariant — see `nodes_mut`.
match unsafe { &mut self.nodes.get_mut()[id.idx()] } {
Node::$variant(v) => v,
other => panic!(
concat!("expected Node::", stringify!($variant), " at {}, got {:?}"),
id, other.kind()
),
}
}
)*
}
};
}
node_accessors! {
Script => Script, as_script, as_script_mut;
Stmt => Stmt, as_stmt, as_stmt_mut;
Binary => Binary, as_binary, as_binary_mut;
Pipeline => Pipeline, as_pipeline, as_pipeline_mut;
Cmd => Cmd, as_cmd, as_cmd_mut;
Assigns => Assigns, as_assigns, as_assigns_mut;
Expansion => Expansion, as_expansion, as_expansion_mut;
If => If, as_if, as_if_mut;
CondExpr => CondExpr, as_condexpr, as_condexpr_mut;
Async => Async, as_async, as_async_mut;
Subshell => Subshell, as_subshell, as_subshell_mut;
}
// ────────────────────────────────────────────────────────────────────────────
// Small types
// ────────────────────────────────────────────────────────────────────────────
pub(crate) type ExitCode = u16;
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, Debug, strum::IntoStaticStr)]
pub enum StateKind {
Free,
Script,
Stmt,
Assign,
Cmd,
Binary,
Pipeline,
Expansion,
IfClause,
Condexpr,
Async,
Subshell,
}
/// The shell promise's `reject` function and the error to call it with. Kept on the stack, where the GC sees it.
pub(crate) type Rejection = (crate::jsc::JSValue, crate::jsc::JSValue);
// ────────────────────────────────────────────────────────────────────────────
// Interpreter
// ────────────────────────────────────────────────────────────────────────────
/// This interpreter works by basically turning the AST into a state machine so
/// that execution can be suspended and resumed to support async.
// R-2 (host-fn re-entrancy): every JS-exposed method — and the entire
// state-machine dispatch reachable from `run_from_js` — takes `&self`.
// Per-field interior mutability via `Cell` (Copy) / `JsCell` (non-Copy) makes
// the noalias-based `&mut self` caching miscompile structurally impossible:
// `finish()` calls `resolve.call(...)` which can synchronously re-enter
// another `ShellInterpreter` host fn (or, via `Yield::run`, another
// interpreter entirely — see `DbgDepthGuard::MAX_DEPTH`). With every field
// behind `UnsafeCell`, an overlapping `&Interpreter` is sound.
pub(crate) struct Interpreter {
/// Flat arena of state-machine nodes. Indices are `NodeId`s; freed slots
/// are recycled via `free_list`.
pub(crate) nodes: JsCell<Vec<Node>>,
free_list: JsCell<Vec<u32>>,
pub(crate) event_loop: EventLoopHandle,
// Drop order: `nodes`, `root_io` and `root_shell` each borrow from what follows, up to `args`.
pub(crate) root_io: JsCell<IO>,
pub(crate) root_shell: JsCell<ShellExecEnv>,
pub args: JsCell<Box<ShellArgs>>,
pub(crate) keep_alive: bun_io::JsKeepAlive,
/// The `Bun.ModuleGraph` context whose script started this (`run_from_js`), if any. Every
/// child the script spawns belongs to it, and once it stops the script runs no further.
pub(crate) context: Cell<Option<bun_jsc::ContextId>>,
pub(crate) async_commands_executing: Cell<u32>,
// JSC_BORROW: always borrowed, never owned. Stored raw because the struct
// is heap-allocated and outlives any single &JSGlobalObject borrow scope.
pub global_this: Cell<*mut crate::jsc::JSGlobalObject>,
pub(crate) flags: Cell<InterpreterFlags>,
pub(crate) exit_code: Cell<Option<ExitCode>>,
/// The JS wrapper. Strong from `run_from_js` until `finish` has settled the promise.
pub(crate) this_value: JsCell<JsRef>,
pub(crate) estimated_size_for_gc: usize,
/// Lazily-populated UTF-8 cache for the JS-side argv (`$@`/`$N` expansion
/// when running under a Worker). See [`Interpreter::get_vm_args_utf8`].
pub(crate) vm_args_utf8: JsCell<Vec<bun_core::Utf8Bytes<'static>>>,
/// `bun run` CLI context for `$N` expansion on the mini event loop.
/// Null when constructed from JS (no `ContextData` is reachable).
pub(crate) command_ctx: *mut bun_options_types::context::ContextData,
}
#[repr(transparent)]
#[derive(Clone, Copy, Default)]
pub(crate) struct InterpreterFlags(u8);
impl InterpreterFlags {
pub(crate) const fn done(self) -> bool {
self.0 & 0b1 != 0
}
pub(crate) fn set_done(&mut self, v: bool) {
if v { self.0 |= 0b1 } else { self.0 &= !0b1 }
}
pub(crate) const fn quiet(self) -> bool {
self.0 & 0b10 != 0
}
pub(crate) fn set_quiet(&mut self, v: bool) {
if v { self.0 |= 0b10 } else { self.0 &= !0b10 }
}
/// Set by [`Interpreter::take_failure`].
pub(crate) const fn failed(self) -> bool {
self.0 & 0b100 != 0
}
pub(crate) fn set_failed(&mut self, v: bool) {
if v { self.0 |= 0b100 } else { self.0 &= !0b100 }
}
}
// ────────────────────────────────────────────────────────────────────────────
// Construction / standalone-exec entrypoints
// ────────────────────────────────────────────────────────────────────────────
impl ShellArgs {
/// Heap-allocated (returned as `Box`) because the interpreter stores
/// `Box<ShellArgs>` and state nodes hold `*const ast::*` into the arena;
/// the box must not move once `parse()` has filled `script_ast`.
pub(crate) fn init() -> Box<ShellArgs> {
Box::new(ShellArgs {
__arena: bun_alloc::Arena::new(),
// Overwritten by `parse()` before `run()`. An empty stmt list is
// a safe placeholder.
script_ast: ast::Script { stmts: &[] },
})
}
#[inline]
pub(crate) fn arena(&self) -> &bun_alloc::Arena {
&self.__arena
}
/// Store the parsed AST root alongside its owning arena. This is the single
/// self-referential lifetime-erasure point: `script` borrows `self.__arena`
/// for `'a`, but `ShellArgs` is heap-allocated and the arena is never moved
/// or dropped while the interpreter (and thus every state node holding
/// `*const ast::*`) is live. Widening `'a` → `'static` here is therefore
/// sound — every later dereference happens through raw pointers under
/// `unsafe`, which is where the real invariant is checked.
///
/// `Interpreter::parse` returns the lifetime-tied `Script<'a>` so callers
/// that *don't* store (e.g. `TestingAPIs::shell_parse`) get the correct
/// borrow scope; only callers that move the arena into long-lived storage
/// route through this helper.
#[inline]
pub(crate) fn set_script_ast(&mut self, script: bun_shell_parser::ast::Script<'_>) {
// `ast::Script` is `bun_shell_parser::ast::Script<'static>` — identical
// type, only the lifetime parameter differs. `self.__arena` owns every
// node `script.stmts` references and is dropped only when this
// `ShellArgs` is, so the widened references remain valid for the
// interpreter's lifetime. Re-construct field-by-field via a slice
// pointer cast (`Stmt<'a>` and `Stmt<'static>` are layout-identical).
let stmts = script.stmts;
// SAFETY: lifetime-only widen; arena outlives `self` (see above).
let stmts: &'static [ast::Stmt] =
unsafe { core::slice::from_raw_parts(stmts.as_ptr().cast::<ast::Stmt>(), stmts.len()) };
self.script_ast = ast::Script { stmts };
}
/// Reports the arena's `allocated_bytes()` (a superset — tokens + strpool
/// + AST nodes). This is for GC `estimatedSize` reporting only, where
/// over-approximation is preferable to a tree walk on a lifetime-erased
/// AST mirror.
pub(crate) fn memory_cost(&self) -> usize {
core::mem::size_of::<ShellArgs>() + self.__arena.allocated_bytes()
}
}
/// Only used by the construction path (`Interpreter::init`).
pub(crate) type ShellResult<T> = Result<T, ShellErr>;
impl Interpreter {
/// Lex `src` (ASCII or Unicode), build a `Parser`, and return the root
/// `ast::Script`. Tokens and AST nodes are bump-allocated into `arena`.
///
/// On lex error, `out_lex_err` is populated and `ParseError::Lex` returned
/// so the caller can `combineErrors()` for diagnostics; on parse error
/// `out_parse_err` is populated likewise.
pub(crate) fn parse<'a>(
arena: &'a bun_alloc::Arena,
src: &'a [u8],
jsobjs_len: u32,
jsstrings_to_escape: &'a [bun_core::String],
out_parser: &mut Option<bun_shell_parser::Parser<'a>>,
out_lex_result: &mut Option<bun_shell_parser::LexResult<'a>>,
) -> crate::Result<bun_shell_parser::ast::Script<'a>> {
use crate::shell::shell_body::{LexerAscii, LexerUnicode, ParseError, Parser};
let lex_result = if bun_core::is_all_ascii(src) {
let mut lexer = LexerAscii::new(arena, src, jsstrings_to_escape, jsobjs_len);
lexer.lex().map_err(crate::Error::from)?;
lexer.get_result()
} else {
let mut lexer = LexerUnicode::new(arena, src, jsstrings_to_escape, jsobjs_len);
lexer.lex().map_err(crate::Error::from)?;
lexer.get_result()
};
if !lex_result.errors.is_empty() {
*out_lex_result = Some(lex_result);
return Err(ParseError::Lex.into());
}
*out_parser = Some(Parser::new(arena, lex_result));
Ok(out_parser.as_mut().unwrap().parse()?)
}
/// Builds the root `ShellExecEnv` (export env from the event loop's
/// `DotEnv::Loader`, cwd from `getcwd()`, cwd_fd from `open(O_DIRECTORY)`),
/// and dups stdin into an `IOReader`.
/// stdout/stderr stay `.pipe` here — `setup_io_before_run()` (called from
/// `run()`) upgrades them to real `IOWriter`s unless `quiet` was set.
///
/// On success the returned interpreter owns `shargs`; on error `shargs` is
/// dropped.
///
/// Note: `allocator` parameter dropped (always global mimalloc).
/// `ctx` is stored for `bun run` argv access from builtins; held as a raw
/// pointer because the interpreter outlives any single `&mut ContextData`
/// borrow.
// `ShellErr` is the shared shell-wide error type defined in `shell_body.rs`;
// boxing it here would change `pub fn` signatures across every
// `?`-propagating shell caller.
#[allow(clippy::result_large_err)]
pub(crate) fn init(
ctx: *mut bun_options_types::context::ContextData,
event_loop: EventLoopHandle,
shargs: Box<ShellArgs>,
export_env_: Option<EnvMap>,
cwd_: Option<&[u8]>,
) -> ShellResult<Interpreter> {
// ── export_env ─────────────────────────────────────────────────────
// On the `.js` event loop, take `export_env_` (or empty); on `.mini`,
// populate from `event_loop.env()` (the loop's `DotEnv::Loader`).
let export_env = if matches!(event_loop, EventLoopHandle::Js { .. }) {
export_env_.unwrap_or_else(EnvMap::init)
} else {
// SAFETY: `event_loop.env()` returns the `MiniEventLoop`'s
// `DotEnv::Loader`, which is set by `init_global()` and outlives
// the interpreter (thread-lifetime singleton).
let env_loader = unsafe { &mut *event_loop.env() };
let mut export_env = EnvMap::init_with_capacity(env_loader.map.map.count());
let mut iter = env_loader.iterator();
while let Some(entry) = iter.next() {
let key = crate::shell::EnvStr::init_slice(&entry.key_ptr[..]);
let value = crate::shell::EnvStr::init_slice(&entry.value_ptr.value[..]);
export_env.insert(key, value);
}
export_env
};
// ── cwd / cwd_fd ───────────────────────────────────────────────────
// Hoisted PathBuffer so the error's borrowed `.path` stays valid until
// we've converted it to an owned `ShellErr`. Heap-pooled (not stack) —
// on Windows `MAX_PATH_BYTES` is ~96 KiB and `init` runs from
// JS-triggered paths that may already be deep on the stack.
let mut pathbuf = bun_paths::path_buffer_pool::get();
let cwd_z = match bun_sys::getcwd_z(&mut pathbuf) {
Ok(cwd) => cwd,
Err(e) => return Err(ShellErr::new_sys(&e)),
};
let cwd_fd = match bun_sys::open(cwd_z, bun_sys::O::DIRECTORY | bun_sys::O::RDONLY, 0) {
Ok(fd) => OwnedFd(fd),
Err(e) => return Err(ShellErr::new_sys(&e)),
};
// Downstream `cwd()` strips the trailing 0.
let cwd_arr = cwd_z.as_bytes_with_nul().to_vec();
// ── stdin ──────────────────────────────────────────────────────────
log!("Duping stdin");
let stdin_fd_res = if bun_core::output::stdio::is_stdin_null() {
#[cfg(unix)]
{
File::open(bun_core::zstr!("/dev/null"), bun_sys::O::RDONLY, 0)
}
#[cfg(windows)]
{
File::open(bun_core::zstr!("NUL"), bun_sys::O::RDONLY, 0)
}
} else {
shell_dup(Fd::stdin())
};
let stdin_fd = match stdin_fd_res {
Ok(fd) => fd,
Err(e) => return Err(ShellErr::new_sys(&e)),
};
let stdin_reader = IOReader::init(stdin_fd, event_loop);
// ── assemble ───────────────────────────────────────────────────────
let interpreter = Interpreter {
nodes: JsCell::new(Vec::new()),
free_list: JsCell::new(Vec::new()),
event_loop,
args: JsCell::new(shargs),
root_shell: JsCell::new(ShellExecEnv {
_buffered_stdout: Bufio::default(),
_buffered_stderr: Bufio::default(),
shell_env: EnvMap::init(),
cmd_local_env: EnvMap::init(),
export_env,
__prev_cwd: cwd_arr.clone(),
__cwd: cwd_arr,
cwd_fd,
}),
root_io: JsCell::new(IO {
stdin: crate::shell::io::InKind::Fd(stdin_reader),
// By default stdout/stderr should be IOWriters on dup'd
// stdout/stderr, but if the user later calls `.setQuiet(true)`
// that work is wasted. So they start as `.pipe` and `run()`
// upgrades them via `setup_io_before_run()` if `!quiet`.
stdout: crate::shell::io::OutKind::Pipe,
stderr: crate::shell::io::OutKind::Pipe,
}),
keep_alive: bun_io::JsKeepAlive::default(),
context: Cell::new(None),
async_commands_executing: Cell::new(0),
global_this: Cell::new(core::ptr::null_mut()),
flags: Cell::new(InterpreterFlags::default()),
// Starts at `None` so `async_cmd_done` only finishes once
// `on_root_child_done` has recorded the real exit code.
exit_code: Cell::new(None),
this_value: JsCell::new(JsRef::empty()),
estimated_size_for_gc: 0,
vm_args_utf8: JsCell::new(Vec::new()),
command_ctx: ctx,
};
// ── optional cwd override ───────────────────────────────────────────
if let Some(c) = cwd_ {
if let Err(e) = interpreter
.root_shell
.with_mut(|rs| rs.change_cwd_impl(c, true))
{
return Err(ShellErr::new_sys(&e));
}
}
Ok(interpreter)
}
/// Standalone-shell entrypoint for `bun <file>.sh`: parse `src` (already
/// read by the caller), construct an interpreter on a `MiniEventLoop`,
/// drive it to completion, and return the exit code. Differs from
/// `init_and_run_from_source` only in the parse-error diagnostic wording
/// ("Failed to run <basename>" vs "Failed to run script <name>") and in
/// not bumping `standalone_shell` analytics.
pub(crate) fn init_and_run_from_file(
ctx: &mut bun_options_types::context::ContextData,
mini: &'static bun_event_loop::MiniEventLoop::MiniEventLoop,
path: &[u8],
src: &[u8],
) -> crate::Result<ExitCode> {
Self::init_and_run_impl(ctx, mini, bun_paths::basename(path), src, None, false)
}
/// Standalone-shell entrypoint for `bun run <script>` / `bun exec` when
/// `--shell=bun`: parse `src`, construct an interpreter on a
/// `MiniEventLoop`, drive it to completion via `mini.tick()`, and return
/// the script's exit code. `path_for_errors` is only used in diagnostics.
///
/// On any init/parse/run error this prints to stderr and `exit(1)`s
/// directly; the `Result` only carries lexer/parser errors that escaped
/// without a diagnostic.
pub(crate) fn init_and_run_from_source(
ctx: &mut bun_options_types::context::ContextData,
mini: &'static bun_event_loop::MiniEventLoop::MiniEventLoop,
path_for_errors: &[u8],
src: &[u8],
cwd: Option<&[u8]>,
) -> crate::Result<ExitCode> {
Self::init_and_run_impl(ctx, mini, path_for_errors, src, cwd, true)
}
/// Shared body for `init_and_run_from_file` / `init_and_run_from_source`.
/// `from_source` gates the analytics bump and the extra "script " word in
/// the parse-error diagnostic — the only two behavioural deltas between
/// the two entrypoints.
fn init_and_run_impl(
ctx: &mut bun_options_types::context::ContextData,
mini: &'static bun_event_loop::MiniEventLoop::MiniEventLoop,
label: &[u8],
src: &[u8],
cwd: Option<&[u8]>,
from_source: bool,
) -> crate::Result<ExitCode> {
if from_source {
bun_analytics::features::standalone_shell.fetch_add(1, Ordering::Relaxed);
}
// We are the script's shell (`bun run <script>`, `bun exec`, `bun x.sh`).
bun_spawn::ctrl_c::install();
let mut shargs = ShellArgs::init();
// ── parse ──────────────────────────────────────────────────────────
// `out_parser`/`out_lex_result` borrow `shargs.__arena`, so they're
// scoped to a block that ends before `shargs.set_script_ast` below.
let arena_ptr: *const bun_alloc::Arena = shargs.arena();
let script = {
// SAFETY: `shargs` lives on this stack frame for the whole block;
// arena is not moved/dropped while `out_parser`/`out_lex_result`
// borrow it.
let arena = unsafe { &*arena_ptr };
let mut out_parser: Option<bun_shell_parser::Parser<'_>> = None;
let mut out_lex_result: Option<bun_shell_parser::LexResult<'_>> = None;
match Self::parse(arena, src, 0, &[], &mut out_parser, &mut out_lex_result) {
Ok(s) => s,
Err(err) => {
let what = if from_source { "script " } else { "" };
let errstr: &[u8] = if let Some(lex) = out_lex_result.as_ref() {
lex.combine_errors(arena)
} else if let Some(p) = out_parser.as_mut() {
p.combine_errors()
} else {
return Err(err);
};
bun_core::pretty_errorln!(
"<r><red>error<r>: Failed to run {}<b>{}<r> due to error <b>{}<r>",
what,
bstr::BStr::new(label),
bstr::BStr::new(errstr),
);
bun_core::Global::exit(1);
}
}
};
shargs.set_script_ast(script);
// ── init ───────────────────────────────────────────────────────────
let evtloop = EventLoopHandle::init_mini(mini);
// Boxed: `run` hands out its address.
let interp = match Self::init(std::ptr::from_mut(ctx), evtloop, shargs, None, cwd) {
Ok(i) => Box::new(i),
Err(e) => e.throw_mini(),
};
// ── run ────────────────────────────────────────────────────────────
interp.exit_code.set(Some(1));
if let Err(e) = interp.run() {
let name = e.name();
drop(interp);
bun_core::output::err(
name,
"Failed to run script <b>{}<r>",
(bstr::BStr::new(label),),
);
bun_core::Global::exit(1);
}
// ── tick until done ────────────────────────────────────────────────
while !interp.flags.get().done() {
mini.tick_once(core::ptr::null_mut());
}
Ok(interp.exit_code.get().expect("exit_code set by finish()"))
}
}
// ──────────────────────────────────────────────────────────────────────────
// shell_state_dispatch! — single source of truth for the StateKind→handler
// table: each row declares `Variant [=> HandlerType]` once and the macro
// emits `child_done`, `next_node`, and `start_node`. Same precedent as
// `shell_builtins!` (Builtin.rs).
//
// PERF: expands to literal `match` arms — direct calls per arm so LLVM
// inlines the hot states (Stmt/Pipeline/Cmd). No vtable, no extra
// indirection.
//
// Invoked once, inside `impl Interpreter` below. `deinit_node` is kept
// hand-rolled for now (irregular Async/Free arms) — see the NOTE there.
macro_rules! shell_state_dispatch {
// ── internal: tt-munch rows into normalized `(Variant, Handler)` pairs ──
(@norm [$($done:tt)*] $v:ident => $h:ident , $($rest:tt)*) => {
shell_state_dispatch!(@norm [$($done)* ($v, $h)] $($rest)*);
};
(@norm [$($done:tt)*] $v:ident , $($rest:tt)*) => {
shell_state_dispatch!(@norm [$($done)* ($v, $v)] $($rest)*);
};
// ── internal: emit the three dispatch fns from the normalized table ──
(@norm [ $( ($v:ident, $h:ident) )+ ]) => {
/// Signal to `parent` that `child` finished with `exit_code`. This is the
/// single hoisted `match` dispatching on the parent's state tag.
pub(crate) fn child_done(&self, parent: NodeId, child: NodeId, exit_code: ExitCode) -> Yield {
self.propagate_interrupt(parent, child);
if parent == NodeId::INTERPRETER {
return self.on_root_child_done(child, exit_code);
}
match self.nodes.get()[parent.idx()].kind() {
$( StateKind::$v => $h::child_done(self, parent, child, exit_code), )+
StateKind::Free => unreachable!("child_done on freed {}", parent),
}
}
/// Advance node `id` by one step. The trampoline (`Yield::run`) calls
/// this; replaces the per-variant `&mut State` dispatch in Yield.
pub(crate) fn next_node(&self, id: NodeId) -> Yield {
match self.nodes.get()[id.idx()].kind() {
$( StateKind::$v => $h::next(self, id), )+
StateKind::Free => unreachable!("next on freed {}", id),
}
}
/// Start node `id`. Most states return `Yield::<Kind>(id)` immediately;
/// the trampoline then calls `next_node`.
pub(crate) fn start_node(&self, id: NodeId) -> Yield {
match self.nodes.get()[id.idx()].kind() {
$( StateKind::$v => $h::start(self, id), )+
StateKind::Free => unreachable!("start on freed {}", id),
}
}
};
// ── public entry (first token must be an ident, so `@norm` recursion never lands here) ──
( $first:ident $($rest:tt)* ) => {
shell_state_dispatch!(@norm [] $first $($rest)*);
};
}
impl Interpreter {
// ─── R-2 interior-mutability helpers ─────────────────────────────────────
/// `&self` → `*mut Self` for ctx slots.
#[inline]
pub(crate) fn as_ctx_ptr(&self) -> *mut Self {
std::ptr::from_ref::<Self>(self).cast_mut()
}
/// Read-modify-write the packed `Cell<InterpreterFlags>` through `&self`.
#[inline]
fn update_flags(&self, f: impl FnOnce(&mut InterpreterFlags)) {
let mut v = self.flags.get();
f(&mut v);
self.flags.set(v);
}
/// Mutable projection of the node arena from `&self`.
///
/// # Safety
/// R-2 single-JS-thread invariant: the state machine never holds two
/// `&mut` into `nodes` simultaneously (borrowck previously enforced this
/// via `&mut Interpreter`; that discipline is preserved at every call
/// site). Do **not** hold the returned borrow across any call that may
/// reach `finish()`/`throw()` (the only paths that re-enter JS).
#[inline]
#[allow(clippy::mut_from_ref)]
unsafe fn nodes_mut(&self) -> &mut Vec<Node> {
// SAFETY: forwarded to caller — see fn-level contract.
unsafe { self.nodes.get_mut() }
}
// ── arena management ───────────────────────────────────────────────────
/// Allocate a fresh slot in the node arena and return its id. Reuses
/// freed slots when available.
pub(crate) fn alloc_node(&self, node: Node) -> NodeId {
if let Some(slot) = self.free_list.with_mut(|f| f.pop()) {
self.nodes.with_mut(|n| n[slot as usize] = node);
return NodeId(slot);
}
self.nodes.with_mut(|n| {
let id = NodeId(n.len() as u32);
n.push(node);
id
})
}
/// Drop the node and recycle its slot. A `deinit` of the node's own must run first.
pub(crate) fn free_node(&self, id: NodeId) {
// Guard: callers may have stored `NodeId::NONE` in `currently_executing`
// when `spawn_expr` failed (Subshell init error path). Nothing
// touches `currently_executing` on that path, so the later
// `deinit_node`/`free_node` is a no-op there too.
if id == NodeId::NONE || id == NodeId::INTERPRETER {
return;
}
self.nodes.with_mut(|n| {
debug_assert!(!matches!(n[id.idx()], Node::Free), "double-free of {}", id);
n[id.idx()] = Node::Free;
});
self.free_list.with_mut(|f| f.push(id.0));
}
/// A child that a Ctrl+C we left to it killed marks its node `interrupted`
/// (see `bun_spawn::ctrl_c`). bash runs each member of a pipeline in its own
/// process, so inside one the interrupt only cuts that member short — the mark
/// flows up through the sequencing states (which finish early on it, see
/// `interrupted`) to the member, and the pipeline takes it from its rightmost
/// member only. Anywhere else it ends us the way it ended the child, so
/// `a; b` and `a || b` stop at `a`.
fn propagate_interrupt(&self, parent: NodeId, child: NodeId) {
if !self.node(child).base().is_some_and(|b| b.interrupted) {
if bun_spawn::ctrl_c::Child::alive() == 0 {
// A Ctrl+C the job handled is used up with the job (bash resets it per wait).
bun_spawn::ctrl_c::take_received();
}
return;
}
if parent == NodeId::INTERPRETER {
bun_spawn::ctrl_c::exit_like_child();
}
if let Node::Pipeline(p) = self.node(parent) {
let rightmost = p.cmds.as_deref().is_none_or(|c| {
c.len() < 2
|| matches!(c.last(), Some(crate::shell::states::pipeline::CmdOrResult::Cmd(id)) if *id == child)
});
if rightmost {
self.as_pipeline_mut(parent).base.interrupted = true;
}
return;
}
if !self.in_pipeline(parent) {
bun_spawn::ctrl_c::exit_like_child();
}
if let Some(base) = self.node_mut(parent).base_mut() {
base.interrupted = true;
}
}
/// A sequencing state stops early: Ctrl+C cut the member short, or the script failed.
pub(crate) fn interrupted(&self, id: NodeId) -> bool {
self.context_stopped()
|| self.failed()
|| self.node(id).base().is_some_and(|b| b.interrupted)
}
/// Whose script the shell's completion continues: the one that started it (a `Bun.ModuleGraph`'s),
/// if it has one.
fn task_context(&self) -> bun_jsc::ContextId {
match self.context.get() {
Some(context) => context,
None => bun_jsc::ContextId::NONE,
}
}
/// The `Bun.ModuleGraph` whose script started this was disposed (or its realm is going).
pub(crate) fn context_stopped(&self) -> bool {
self.context
.get()
.is_some_and(|id| !bun_jsc::virtual_machine::VirtualMachine::get().is_context_live(id))
}
/// Some ancestor is a member of a multi-command pipeline.
fn in_pipeline(&self, mut id: NodeId) -> bool {
while id != NodeId::INTERPRETER {
let Some(base) = self.node(id).base() else {
return false;
};
if base.parent != NodeId::INTERPRETER {
if let Node::Pipeline(p) = self.node(base.parent) {
if p.cmds.as_deref().is_some_and(|c| c.len() >= 2) {
return true;
}
}
}
id = base.parent;
}
false
}
/// Inside an `&` command: not a foreground job.
pub(crate) fn in_background(&self, mut id: NodeId) -> bool {
while id != NodeId::INTERPRETER {
let node = self.node(id);
if node.kind() == StateKind::Async {
return true;
}
id = match node.base() {
Some(b) => b.parent,
None => return false,
};
}
false
}
#[inline]
pub(crate) fn node(&self, id: NodeId) -> &Node {
&self.nodes.get()[id.idx()]
}
#[inline]
#[allow(clippy::mut_from_ref)]
fn node_mut(&self, id: NodeId) -> &mut Node {
// SAFETY: see `nodes_mut` — single-JS-thread, no overlapping borrow.
unsafe { &mut self.nodes_mut()[id.idx()] }
}
// ── hoisted dispatch (PORTING.md §Dispatch hot-path) ───────────────────
shell_state_dispatch! {
Script,
Stmt,
Binary,
Pipeline,
Cmd,
Assign => Assigns,
Expansion,
IfClause => If,
Condexpr => CondExpr,
Async,
Subshell,
}
/// Init + start a child state node for an `ast::Expr`. For `.subshell`,
/// dupes the parent shell env first; all other variants borrow `shell`.
///
/// Note: `Async` must NOT call this — `Async` restricts its child to
/// pipeline/cmd/if/condexpr and inits without starting (see `Async::next`).
pub(crate) fn spawn_expr(
&self,
shell: *mut ShellExecEnv,
expr: &ast::Expr,
parent: NodeId,
io: IO,
) -> (Option<NodeId>, Yield) {
let child = match expr {
ast::Expr::Cmd(c) => Cmd::init(self, Env::inherited(shell), *c, parent, io),
ast::Expr::Binary(b) => Binary::init(self, shell, *b, parent, io),
ast::Expr::Pipeline(p) => Pipeline::init(self, shell, *p, parent, io),
ast::Expr::Assign(a) => Assigns::init(self, shell, *a, parent, AssignCtx::Shell),
ast::Expr::If(i) => If::init(self, Env::inherited(shell), *i, parent, io),
ast::Expr::CondExpr(c) => CondExpr::init(self, Env::inherited(shell), *c, parent, io),
ast::Expr::Subshell(s) => {
// Stmt/Binary callers dupe
// the env here so `Subshell::start`/`next` can use `shell`
// as-is. (Pipeline dupes itself and calls `Subshell::init`
// directly, so it does NOT go through this path.)
// SAFETY: `shell` is the live parent `ShellExecEnv` borrowed for the
// dupe; `self` is the live interpreter.
match Subshell::init_dupe_shell_state(self, shell, *s, parent, io) {
Ok(id) => id,
Err(e) => {
self.throw(ShellErr::new_sys(&e));
// No child exists, so `parent` is the node that failed.
// Return `None` so callers leave `currently_executing`
// unset (no `NodeId::NONE` sentinel needed in
// `deinit_node`/`free_node` for this path).
return (None, Yield::Failed(parent));
}
}
}
ast::Expr::Async(e) => Async::init(self, shell, *e, parent, io),
};
let y = self.start_node(child);
(Some(child), y)
}
/// Run the per-state cleanup, then recycle the slot.
pub(crate) fn deinit_node(&self, id: NodeId) {
// Guard the `NodeId::NONE` sentinel: `spawn_expr` returns it on
// Subshell init failure, and Stmt/Binary `currently_executing` may
// hold it. Indexing `nodes[u32::MAX-1]` would be OOB.
if id == NodeId::NONE || id == NodeId::INTERPRETER {
return;
}
// NOTE: keep in sync with shell_state_dispatch! table (irregular Async/Free arms keep this hand-rolled for v1).
match self.nodes.get()[id.idx()].kind() {
StateKind::Stmt => Stmt::deinit(self, id),
StateKind::Binary => Binary::deinit(self, id),
StateKind::Pipeline => Pipeline::deinit(self, id),
StateKind::Cmd => Cmd::deinit(self, id),
StateKind::Expansion => Expansion::deinit(self, id),
StateKind::Async => return, // Freed by `async_cmd_done`.
StateKind::Script
| StateKind::Assign
| StateKind::IfClause
| StateKind::Condexpr
| StateKind::Subshell => {}
StateKind::Free => return,
}
self.free_node(id);
}
// ── root (Interpreter-as-parent) ───────────────────────────────────────
fn on_root_child_done(&self, child: NodeId, exit_code: ExitCode) -> Yield {
// Only `Script` can be a direct child of the interpreter.
debug_assert!(matches!(self.nodes.get()[child.idx()], Node::Script(_)));
log!("Interpreter script finish {}", exit_code);
self.free_node(child);
self.exit_code.set(Some(exit_code));
if self.async_commands_executing.get() == 0 {
return self.finish(exit_code);
}