forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1990 lines (1826 loc) · 85.2 KB
/
Copy pathlib.rs
File metadata and controls
1990 lines (1826 loc) · 85.2 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
#![warn(unused_must_use)]
// ──────────────────────────────────────────────────────────────────────────
// The remaining `'static` lifetime erasures and raw-pointer borrow splits in
// this file are documented at each site; removing them is tracked by the
// bun_ini Parser lifetime-restructure work item (external arena, split `env`
// lifetime, `Source` lifetime threading in bun_ast).
// ──────────────────────────────────────────────────────────────────────────
use core::fmt;
use bun_alloc::AllocError;
use bun_ast::{Loc, Log, Source};
type OOM<T> = Result<T, AllocError>;
// ──────────────────────────────────────────────────────────────────────────
// Options
// ──────────────────────────────────────────────────────────────────────────
pub struct Options {
pub bracked_array: bool,
}
impl Default for Options {
fn default() -> Self {
Self {
bracked_array: true,
}
}
}
// ──────────────────────────────────────────────────────────────────────────
// Pure-byte helpers. They touch no parser state; exposed as free fns so
// they are unit-testable without the Expr-carrying struct.
// ──────────────────────────────────────────────────────────────────────────
#[inline]
pub(crate) fn should_skip_line(line: &[u8]) -> bool {
if line.is_empty()
// comments
|| line[0] == b';'
|| line[0] == b'#'
{
return true;
}
// check the rest is whitespace
for &c in line {
match c {
b' ' | b'\t' | b'\n' | b'\r' => {}
b'#' | b';' => return true,
_ => return false,
}
}
true
}
#[inline]
pub(crate) fn is_quoted(val: &[u8]) -> bool {
(bun_core::starts_with_char(val, b'"') && bun_core::ends_with_char(val, b'"'))
|| (bun_core::starts_with_char(val, b'\'') && bun_core::ends_with_char(val, b'\''))
}
#[inline]
pub(crate) fn next_dot(key: &[u8]) -> Option<usize> {
key.iter().position(|&b| b == b'.')
}
// ──────────────────────────────────────────────────────────────────────────
// IniOption — tri-state used by iterators (None != end-of-iteration)
// ──────────────────────────────────────────────────────────────────────────
pub enum IniOption<T> {
Some(T),
None,
}
impl<T> IniOption<T> {
pub(crate) fn get(self) -> Option<T> {
match self {
IniOption::Some(v) => Some(v),
IniOption::None => None,
}
}
}
// ──────────────────────────────────────────────────────────────────────────
// ConfigOpt
// ──────────────────────────────────────────────────────────────────────────
#[derive(Clone, Copy, PartialEq, Eq, strum::IntoStaticStr, strum::EnumString)]
pub enum ConfigOpt {
/// `${username}:${password}` encoded in base64
#[strum(serialize = "_auth")]
_Auth,
/// authentication string
#[strum(serialize = "_authToken")]
_AuthToken,
#[strum(serialize = "username")]
Username,
/// this is encoded as base64 in .npmrc
#[strum(serialize = "_password")]
_Password,
#[strum(serialize = "email")]
Email,
/// path to certificate file
#[strum(serialize = "certfile")]
Certfile,
/// path to key file
#[strum(serialize = "keyfile")]
Keyfile,
}
impl ConfigOpt {
pub fn is_base64_encoded(self) -> bool {
matches!(self, ConfigOpt::_Auth | ConfigOpt::_Password)
}
}
// ──────────────────────────────────────────────────────────────────────────
// ConfigItem
// ──────────────────────────────────────────────────────────────────────────
pub struct ConfigItem {
pub registry_url: Box<[u8]>,
pub optname: ConfigOpt,
pub value: Box<[u8]>,
pub loc: Loc,
}
impl ConfigItem {
/// Duplicate ConfigIterator.Item
pub fn dupe(&self) -> OOM<Option<ConfigItem>> {
Ok(Some(ConfigItem {
registry_url: Box::<[u8]>::from(&*self.registry_url),
optname: self.optname,
value: Box::<[u8]>::from(&*self.value),
loc: self.loc,
}))
}
/// Duplicate the value, decoding it if it is base64 encoded.
pub fn dupe_value_decoded(&self, log: &mut Log, source: &Source) -> OOM<Option<Box<[u8]>>> {
if self.optname.is_base64_encoded() {
if self.value.is_empty() {
return Ok(Some(Box::default()));
}
let len = bun_base64::decode_len(&self.value);
let mut slice = vec![0u8; len].into_boxed_slice();
let result = bun_base64::decode(&mut slice[..], &self.value);
if !result.is_successful() {
log.add_error_fmt_opts(
format_args!("{} is not valid base64", <&'static str>::from(self.optname)),
bun_ast::AddErrorOptions {
source: Some(source),
loc: self.loc,
..Default::default()
},
);
return Ok(None);
}
return Ok(Some(Box::<[u8]>::from(&slice[..result.count])));
}
Ok(Some(Box::<[u8]>::from(&*self.value)))
}
// deinit -> Drop: Box<[u8]> fields drop automatically.
}
impl fmt::Display for ConfigItem {
fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
writer,
"//{}:{}={}",
bstr::BStr::new(&self.registry_url),
<&'static str>::from(self.optname),
bstr::BStr::new(&self.value),
)
}
}
// ──────────────────────────────────────────────────────────────────────────
// NodeLinkerMap
// ──────────────────────────────────────────────────────────────────────────
use bun_install_types::NodeLinker::NodeLinker;
bun_core::comptime_string_map! {
static NODE_LINKER_MAP: NodeLinker = {
// yarn
b"pnpm" => NodeLinker::Isolated,
b"node-modules" => NodeLinker::Hoisted,
// pnpm
b"isolated" => NodeLinker::Isolated,
b"hoisted" => NodeLinker::Hoisted,
};
}
// ──────────────────────────────────────────────────────────────────────────
// ScopeError
// ──────────────────────────────────────────────────────────────────────────
#[derive(thiserror::Error, Debug, strum::IntoStaticStr)]
pub enum ScopeError {
#[error("no_value")]
NoValue,
}
pub use draft::{
ConfigIterator, Parser, ScopeItem, ScopeIterator, ToStringFormatter, load_npmrc,
load_npmrc_config,
};
pub mod config_iterator {
pub use super::{ConfigItem as Item, ConfigIterator as Iter, ConfigOpt as Opt};
}
mod draft {
use core::fmt;
use core::ptr;
use bun_alloc::{AllocError, Arena, ArenaVec, ArenaVecExt as _};
use bun_api::{self, BunInstall, NpmRegistry, npm_registry};
use bun_ast::E::Rope;
use bun_ast::{E, Expr, ExprData};
use bun_ast::{IntoStr, Loc, Log, Source};
use bun_collections::{ArrayHashMap, VecExt};
use bun_core::ZStr;
use bun_core::{Global, Output};
use bun_dotenv::Loader as DotEnvLoader;
use bun_url::URL;
use super::{
ConfigItem, ConfigOpt, IniOption, NODE_LINKER_MAP, NodeLinker, Options, is_quoted,
next_dot, should_skip_line,
};
type OOM<T> = Result<T, AllocError>;
/// Hard cap on dot-separated segments in a section-header rope. The rope is
/// consumed by `E::Object::get_or_put_object`, which recurses once per
/// `rope.next` link, so an unbounded header overflows the stack. Past the
/// cap the remainder of the header (dots included) becomes the final
/// segment. Mirrors `MAX_DOTTED_KEY_SEGMENTS` in the TOML parser.
const MAX_SECTION_ROPE_SEGMENTS: usize = 512;
// ──────────────────────────────────────────────────────────────────────────
// Parser
// ──────────────────────────────────────────────────────────────────────────
pub struct Parser<'a> {
pub opts: Options,
pub source: Source,
pub src: &'a [u8],
pub out: Expr,
pub logger: Log,
pub arena: Arena,
pub env: &'a mut DotEnvLoader<'a>,
}
// The result type depends on the usage (`.section -> *Rope`, `.key ->
// bytes`, `.value -> Expr`). Rust
// const generics cannot select a return type, so we keep a single
// `prepare_str::<USAGE>()` body and wrap the result in
// `PrepareResult`. Callers unwrap with `.into_*()`.
//
// `#[derive(ConstParamTy)]` requires nightly `adt_const_params`.
// Dropped to a runtime arg (the body never uses USAGE in a type position).
#[derive(PartialEq, Eq, Clone, Copy)]
enum Usage {
Section,
Key,
Value,
}
enum PrepareResult<'bump> {
Value(Expr),
Section(&'bump mut Rope),
Key(&'bump [u8]),
}
impl<'bump> PrepareResult<'bump> {
bun_core::enum_unwrap!(PrepareResult, Value => into fn into_value -> Expr);
bun_core::enum_unwrap!(PrepareResult, Section => into fn into_section -> &'bump mut Rope);
bun_core::enum_unwrap!(PrepareResult, Key => into fn into_key -> &'bump [u8]);
}
impl<'a> Parser<'a> {
pub fn init(path: &[u8], src: &'a [u8], env: &'a mut DotEnvLoader<'a>) -> Parser<'a> {
// TODO: bun_ast::Source<'bump> — `Source::init_path_string`
// currently takes `Str = &'static [u8]`; once the lower tier threads a
// lifetime through `Source`, pass `path`/`src` directly. They outlive
// the `Parser` and its `Source`/`Expr` tree (arena-freed in lockstep),
// so no wrong value is produced today.
let path_s: &'static [u8] = path.into_str();
let src_s: &'static [u8] = src.into_str();
Parser {
opts: Options::default(),
logger: Log::init(),
src,
out: Expr::init(E::Object::default(), Loc::EMPTY),
source: Source::init_path_string(path_s, src_s),
arena: Arena::new(),
env,
}
}
// deinit -> Drop: `logger` and `arena` are owned and drop automatically.
pub fn parse(&mut self, bump: &'a Arena) -> OOM<()> {
// borrowck — `arena_allocator` is passed separately (rather than
// read off `self.arena`) to avoid overlapping &mut self borrows.
let src = self.src;
let mut iter = src.split(|&b| b == b'\n');
// TODO: borrowck — `head` aliases into `self.out.data.e_object` while
// `self` is also borrowed mutably for prepare_str(). Kept as raw `*mut`
// (the underlying `E::Object` lives in the Expr Store, not on `self`).
let mut head: *mut E::Object = std::ptr::from_mut::<E::Object>(
self.out
.data
.e_object_mut()
.expect("Parser.out is E.Object"),
);
let ropealloc = bump;
let mut skip_until_next_section = false;
while let Some(line_) = iter.next() {
let line = if !line_.is_empty() && line_[line_.len() - 1] == b'\r' {
&line_[..line_.len() - 1]
} else {
line_
};
if should_skip_line(line) {
continue;
}
// Section
// [foo]
if line[0] == b'[' {
let mut treat_as_key = false;
'treat_as_key: {
skip_until_next_section = false;
let Some(close_bracket_idx) = line.iter().position(|&b| b == b']') else {
// Skip the whole line: treat_as_key stays false and
// we fall through to `continue` below.
break 'treat_as_key;
};
// Make sure the rest is just whitespace
if close_bracket_idx + 1 < line.len() {
for &c in &line[close_bracket_idx + 1..] {
if !matches!(c, b' ' | b'\t') {
treat_as_key = true;
break 'treat_as_key;
}
}
}
let offset = i32::try_from(line.as_ptr() as usize - src.as_ptr() as usize)
.unwrap()
+ 1;
let section: &mut Rope = self
.prepare_str(
Usage::Section,
bump,
ropealloc,
&line[1..close_bracket_idx],
offset,
)?
.into_section();
// SAFETY: `self.out` was constructed as `E.Object` in `init()`.
let root = self
.out
.data
.e_object_mut()
.expect("Parser.out is E.Object");
let mut parent_object = match root.get_or_put_object(section, bump) {
Ok(v) => v,
Err(E::SetError::OutOfMemory) => return Err(AllocError),
Err(E::SetError::Clobber) => {
// We're in here if key exists but it is not an object
//
// This is possible if someone did:
//
// ```ini
// foo = 'bar'
//
// [foo]
// hello = 420
// ```
//
// In the above case, `this.out[section]` would be a string.
// So what should we do in that case?
//
// npm/ini's will chug along happily trying to assign keys to the string.
//
// In JS assigning keys to string does nothing.
//
// Technically, this would have an effect if the value was an array:
//
// ```ini
// foo[] = 0
// foo[] = 1
//
// [foo]
// 0 = 420
// ```
//
// This would result in `foo` being `[420, 1]`.
//
// To be honest this is kind of crazy behavior so we're just going to skip this for now.
skip_until_next_section = true;
break 'treat_as_key;
}
};
head = std::ptr::from_mut::<E::Object>(
parent_object
.data
.e_object_mut()
.expect("get_or_put_object returns E.Object"),
);
break 'treat_as_key;
}
if !treat_as_key {
continue;
}
}
if skip_until_next_section {
continue;
}
// Otherwise it's a key val here
let line_offset = i32::try_from(line.as_ptr() as usize - src.as_ptr() as usize)
.expect("int cast");
let maybe_eq_sign_idx = line.iter().position(|&b| b == b'=');
let key_raw: &[u8] = self
.prepare_str(
Usage::Key,
bump,
ropealloc,
&line[..maybe_eq_sign_idx.unwrap_or(line.len())],
line_offset,
)?
.into_key();
let is_array: bool = {
key_raw.len() > 2 && bun_core::strings::ends_with(key_raw, b"[]")
// Commenting out because options are not supported but we might
// support them.
// if (this.opts.bracked_array) {
// break :brk key_raw.len > 2 and bun.strings.endsWith(key_raw, "[]");
// } else {
// // const gop = try duplicates.getOrPut(allocator, key_raw);
// // if (gop.found_existing) {
// // gop.value_ptr.* = 1;
// // } else gop.value_ptr.* += 1;
// // break :brk gop.value_ptr.* > 1;
// @panic("We don't support this right now");
// }
};
let key = if is_array && bun_core::strings::ends_with(key_raw, b"[]") {
&key_raw[..key_raw.len() - 2]
} else {
key_raw
};
if key == b"__proto__" {
continue;
}
let value_raw: Expr = 'brk: {
if let Some(eq_sign_idx) = maybe_eq_sign_idx {
if eq_sign_idx + 1 < line.len() {
break 'brk self
.prepare_str(
Usage::Value,
bump,
ropealloc,
&line[eq_sign_idx + 1..],
line_offset + i32::try_from(eq_sign_idx).expect("int cast") + 1,
)?
.into_value();
}
break 'brk Expr::init(E::EString::init(b""), Loc::EMPTY);
}
Expr::init(E::Boolean { value: true }, Loc::EMPTY)
};
let value: Expr = match &value_raw.data {
ExprData::EString(s) => {
if s.data == b"true" {
Expr::init(E::Boolean { value: true }, Loc::EMPTY)
} else if s.data == b"false" {
Expr::init(E::Boolean { value: false }, Loc::EMPTY)
} else if s.data == b"null" {
Expr::init(E::Null, Loc::EMPTY)
} else {
value_raw
}
}
_ => value_raw,
};
// SAFETY: head points into self.out's E::Object tree, valid for the
// duration of parse().
let head_ref = unsafe { &mut *head };
if is_array {
if let Some(val) = head_ref.get(key) {
if !matches!(val.data, ExprData::EArray(_)) {
let mut arr = E::Array::default();
arr.push(bump, val)?;
head_ref.put(bump, key, Expr::init(arr, Loc::EMPTY))?;
}
} else {
head_ref.put(bump, key, Expr::init(E::Array::default(), Loc::EMPTY))?;
}
}
// safeguard against resetting a previously defined
// array by accidentally forgetting the brackets
let mut was_already_array = false;
if let Some(mut val) = head_ref.get(key) {
if matches!(val.data, ExprData::EArray(_)) {
was_already_array = true;
val.data
.e_array_mut()
.expect("infallible: variant checked")
.push(bump, value)?;
head_ref.put(bump, key, val)?;
}
}
if !was_already_array {
head_ref.put(bump, key, value)?;
}
}
Ok(())
}
fn prepare_str(
&mut self,
usage: Usage,
bump: &'a Arena,
ropealloc: &'a Arena,
val_: &'a [u8],
offset_: i32,
) -> OOM<PrepareResult<'a>> {
let mut offset = offset_;
let mut val = bun_core::trim(val_, b" \n\r\t");
if is_quoted(val) {
'out: {
// remove single quotes before calling JSON.parse
if !val.is_empty() && val[0] == b'\'' {
val = if val.len() > 1 {
&val[1..val.len() - 1]
} else {
&val[1..]
};
offset += 1;
}
// JSON.parse("") would throw; json::parse_utf8 returns the
// shared EMPTY_OBJECT static, which a later [section] write
// could then mutate. Fall through to the string path instead.
if val.is_empty() {
break 'out;
}
// `bun_parsers::json::parse_utf8_impl` returns the T2
// value-subset `bun_ast::Expr`; lift it into the T4
// `bun_ast::Expr` (via the `From` impl in
// `bun_ast::expr`) so the rest of this body works
// against a single `ExprData`.
// `Str = &'static [u8]` lifetime erasure (see PORTING.md
// §Allocators / `Parser::init` above). `val` is a sub-slice
// of `self.src` and outlives the temporary `Source`.
let val_s: &'static [u8] = val.into_str();
let src = Source::init_path_string(self.source.path.text, val_s);
let mut log = Log::init();
// Try to parse it and if it fails will just treat it as a string
let json_val: Expr =
match bun_parsers::json::parse_utf8_impl::<true>(&src, &mut log, bump) {
Ok(v) => v,
Err(_) => {
// JSON parse failed (e.g., single-quoted string like '${VAR}')
// Still need to expand env vars in the content
if usage == Usage::Value {
let expanded = self.expand_env_vars(bump, val)?;
return Ok(PrepareResult::Value(Expr::init(
E::EString::init(expanded),
Loc { start: offset },
)));
}
break 'out;
}
};
drop(log);
if let ExprData::EString(s) = &json_val.data {
let str_ = s.string(bump)?;
// Expand env vars in the JSON-parsed string
let expanded = if usage == Usage::Value {
self.expand_env_vars(bump, str_)?
} else {
str_
};
if usage == Usage::Value {
return Ok(PrepareResult::Value(Expr::init(
E::EString::init(expanded),
Loc { start: offset },
)));
}
if usage == Usage::Section {
return Ok(PrepareResult::Section(Self::str_to_rope(
ropealloc, expanded,
)?));
}
return Ok(PrepareResult::Key(expanded));
}
if usage == Usage::Value {
// The parsed Expr is returned as-is, preserving
// `E.Array`/`E.Object` tags so downstream `.e_array`/
// `.e_object` checks (e.g. loadNpmrc
// `ca`/`omit`/`include`) fire. `json_val` was lifted to T4
// at the parse site above.
return Ok(PrepareResult::Value(Expr {
loc: Loc { start: offset },
data: json_val.data,
}));
}
// unfortunately, we need to match npm/ini behavior here,
// which requires us to turn these into a string,
// same behavior as doing this:
// ```
// let foo = {}
// const json_val = { hi: 'hello' }
// foo[json_val] = 'nice'
// ```
match &json_val.data {
ExprData::EObject(_) => {
if usage == Usage::Section {
return Ok(PrepareResult::Section(Self::single_str_rope(
ropealloc,
b"[Object object]",
)?));
}
return Ok(PrepareResult::Key(b"[Object object]"));
}
_ => {
// Cold
// npm-quirk path (JSON array/number used as a section
// header or key); format to a temp `String` then copy
// into the arena.
let s = format!("{}", ToStringFormatter { d: &json_val.data });
let str_ = bump.alloc_slice_copy(s.as_bytes());
if usage == Usage::Section {
return Ok(PrepareResult::Section(Self::single_str_rope(
ropealloc, str_,
)?));
}
return Ok(PrepareResult::Key(str_));
}
}
}
} else {
const STACK_BUF_SIZE: usize = 1024;
// walk the val to find the first non-escaped comment character (; or #)
let mut did_any_escape = false;
let mut esc = false;
let mut unesc = ArenaVec::<u8>::with_capacity_in(STACK_BUF_SIZE, bump);
// RopeT is *Rope when usage==Section, else unit. In Rust we just
// keep an Option<&mut Rope> and ignore it for non-section usages.
let mut rope: Option<&'a mut Rope> = None;
let mut rope_parts: usize = 0;
let mut i: usize = 0;
'walk: while i < val.len() {
let c = val[i];
if esc {
match c {
b'\\' => unesc.extend_from_slice(b"\\"),
b';' | b'#' | b'$' => unesc.push(c),
b'.' => {
if usage == Usage::Section {
unesc.push(b'.');
} else {
unesc.extend_from_slice(b"\\.");
}
}
_ => match bun_core::utf8_byte_sequence_length(c) {
0 | 1 => unesc.extend_from_slice(&[b'\\', c]),
2 => {
if val.len() - i >= 2 {
unesc.extend_from_slice(&[b'\\', c, val[i + 1]]);
i += 1;
} else {
unesc.extend_from_slice(&[b'\\', c]);
}
}
3 => {
if val.len() - i >= 3 {
unesc.extend_from_slice(&[
b'\\',
c,
val[i + 1],
val[i + 2],
]);
i += 2;
} else {
unesc.push(b'\\');
unesc.extend_from_slice(&val[i..val.len()]);
i = val.len() - 1;
}
}
4 => {
if val.len() - i >= 4 {
unesc.extend_from_slice(&[
b'\\',
c,
val[i + 1],
val[i + 2],
val[i + 3],
]);
i += 3;
} else {
unesc.push(b'\\');
unesc.extend_from_slice(&val[i..val.len()]);
i = val.len() - 1;
}
}
_ => unreachable!(),
},
}
esc = false;
} else {
match c {
b'$' => {
'not_env_substitution: {
if usage != Usage::Value {
break 'not_env_substitution;
}
if let Some(new_i) =
self.parse_env_substitution(val, i, i, 0, &mut unesc)?
{
// set to true so we heap alloc
did_any_escape = true;
i = new_i;
i += 1;
continue 'walk;
}
}
unesc.push(b'$');
}
b';' | b'#' => break,
b'\\' => {
esc = true;
did_any_escape = true;
}
b'.' => {
if usage == Usage::Section && rope_parts < MAX_SECTION_ROPE_SEGMENTS
{
self.commit_rope_part(bump, ropealloc, &mut unesc, &mut rope)?;
rope_parts += 1;
} else {
unesc.push(b'.');
}
}
_ => match bun_core::utf8_byte_sequence_length(c) {
0 | 1 => unesc.push(c),
2 => {
if val.len() - i >= 2 {
unesc.extend_from_slice(&[c, val[i + 1]]);
i += 1;
} else {
unesc.push(c);
}
}
3 => {
if val.len() - i >= 3 {
unesc.extend_from_slice(&[c, val[i + 1], val[i + 2]]);
i += 2;
} else {
unesc.extend_from_slice(&val[i..val.len()]);
i = val.len() - 1;
}
}
4 => {
if val.len() - i >= 4 {
unesc.extend_from_slice(&[
c,
val[i + 1],
val[i + 2],
val[i + 3],
]);
i += 3;
} else {
unesc.extend_from_slice(&val[i..val.len()]);
i = val.len() - 1;
}
}
_ => unreachable!(),
},
}
}
i += 1;
}
if esc {
unesc.push(b'\\');
}
match usage {
Usage::Section => {
self.commit_rope_part(bump, ropealloc, &mut unesc, &mut rope)?;
return Ok(PrepareResult::Section(rope.unwrap()));
}
Usage::Value => {
if !did_any_escape {
return Ok(PrepareResult::Value(Expr::init(
E::EString::init(val),
Loc { start: offset },
)));
}
if unesc.len() <= STACK_BUF_SIZE {
return Ok(PrepareResult::Value(Expr::init(
E::EString::init(bump.alloc_slice_copy(&unesc)),
Loc { start: offset },
)));
}
return Ok(PrepareResult::Value(Expr::init(
E::EString::init(unesc.into_bump_slice()),
Loc { start: offset },
)));
}
Usage::Key => {
let thestr: &[u8] = 'thestr: {
if !did_any_escape {
break 'thestr bump.alloc_slice_copy(val);
}
if unesc.len() <= STACK_BUF_SIZE {
break 'thestr bump.alloc_slice_copy(&unesc);
}
unesc.into_bump_slice()
};
return Ok(PrepareResult::Key(thestr));
}
}
}
// fallthrough from `break 'out` above
if usage == Usage::Value {
return Ok(PrepareResult::Value(Expr::init(
E::EString::init(val),
Loc { start: offset },
)));
}
if usage == Usage::Key {
// `val` is a subslice of `val_: &'a [u8]`; return the borrow
// directly.
return Ok(PrepareResult::Key(val));
}
Ok(PrepareResult::Section(Self::str_to_rope(ropealloc, val)?))
}
/// Expands ${VAR} and ${VAR?} environment variable substitutions in a string.
/// Used for quoted values after JSON parsing has already handled escape sequences.
///
/// Behavior (same as unquoted):
/// - ${VAR} - if VAR is undefined, leave as "${VAR}" (no expansion)
/// - ${VAR?} - if VAR is undefined, expand to empty string
/// - Backslash escaping is already handled by JSON parsing
fn expand_env_vars(&mut self, bump: &'a Arena, val: &'a [u8]) -> OOM<&'a [u8]> {
// Quick check if there are any env vars to expand
if bun_core::index_of(val, b"${").is_none() {
// Nothing to expand: return the borrow directly.
return Ok(val);
}
let mut result = ArenaVec::<u8>::with_capacity_in(val.len(), bump);
let mut i: usize = 0;
while i < val.len() {
if val[i] == b'$' && i + 2 < val.len() && val[i + 1] == b'{' {
// Find the closing brace
let mut j = i + 2;
let mut depth: usize = 1;
while j < val.len() && depth > 0 {
if val[j] == b'{' {
depth += 1;
} else if val[j] == b'}' {
depth -= 1;
}
if depth > 0 {
j += 1;
}
}
if depth == 0 {
let env_var_raw = &val[i + 2..j];
let optional =
!env_var_raw.is_empty() && env_var_raw[env_var_raw.len() - 1] == b'?';
let env_var = if optional {
&env_var_raw[..env_var_raw.len() - 1]
} else {
env_var_raw
};
if let Some(expanded) = self.env.get(env_var) {
result.extend_from_slice(expanded);
} else if !optional {
// Not found and not optional: leave as-is
result.extend_from_slice(&val[i..j + 1]);
}
// If optional and not found: expand to empty string (append nothing)
i = j + 1;
continue;
}
}
result.push(val[i]);
i += 1;
}
Ok(result.into_bump_slice())
}
/// Returns index to skip or null if not an env substitution
/// Invariants:
/// - `i` must be an index into `val` that points to a '$' char
///
/// npm/ini uses a regex pattern that will select the inner most ${...}
/// Supports ${VAR} and ${VAR?} syntax:
/// - ${VAR} - if undefined, returns null (leaves as-is)
/// - ${VAR?} - if undefined, expands to empty string
fn parse_env_substitution(
&mut self,
val: &[u8],
start: usize,
i: usize,
depth: usize,
unesc: &mut ArenaVec<'a, u8>,
) -> OOM<Option<usize>> {
debug_assert!(val[i] == b'$');
const MAX_ENV_SUBSTITUTION_DEPTH: usize = 32;
if depth >= MAX_ENV_SUBSTITUTION_DEPTH {
return Ok(None);
}
let mut esc = false;
if i + b"{}".len() < val.len() && val[i + 1] == b'{' {
let mut found_closing = false;
let mut j = i + 2;
while j < val.len() {
match val[j] {
b'\\' => esc = !esc,
b'$' => {
if !esc {
return self.parse_env_substitution(
val,
start,
j,
depth + 1,
unesc,
);
}
}
b'{' => {
if !esc {
return Ok(None);
}
}
b'}' => {
if !esc {
found_closing = true;
break;
}
}
_ => {}
}
j += 1;
}
if !found_closing {
return Ok(None);
}
if start != i {
let missed = &val[start..i];
unesc.extend_from_slice(missed);
}
let env_var_raw = &val[i + 2..j];
let optional =
!env_var_raw.is_empty() && env_var_raw[env_var_raw.len() - 1] == b'?';