diff --git a/Cargo.lock b/Cargo.lock index c2b777f63d0f..b59873488a46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -157,37 +157,18 @@ name = "bun_analytics" version = "0.0.0" dependencies = [ "bitflags", - "bstr", "bun_core", - "bun_errno", "bun_semver", - "bun_sys", - "const_format", - "enum-map", - "enumset", "libc", - "scopeguard", - "strum", - "thiserror", ] [[package]] name = "bun_api" version = "0.0.0" dependencies = [ - "bitflags", - "bstr", "bun_alloc", - "bun_collections", - "bun_install_types", "bun_options_types", "bun_url", - "const_format", - "enum-map", - "enumset", - "libc", - "scopeguard", - "strum", ] [[package]] @@ -1452,17 +1433,9 @@ dependencies = [ name = "bun_perf" version = "0.0.0" dependencies = [ - "bitflags", - "bstr", "bun_core", - "bun_paths", "bun_sys", - "const_format", - "enum-map", - "enumset", "libc", - "scopeguard", - "strum", ] [[package]] diff --git a/src/analytics/Cargo.toml b/src/analytics/Cargo.toml index a9b6ede29ce9..fe50a5eb4de1 100644 --- a/src/analytics/Cargo.toml +++ b/src/analytics/Cargo.toml @@ -10,16 +10,7 @@ path = "lib.rs" workspace = true [dependencies] -strum.workspace = true -bstr.workspace = true -scopeguard.workspace = true -const_format.workspace = true -enum-map.workspace = true -enumset.workspace = true libc.workspace = true bitflags.workspace = true bun_core.workspace = true bun_semver.workspace = true -bun_sys.workspace = true -thiserror.workspace = true -bun_errno.workspace = true diff --git a/src/analytics/error.rs b/src/analytics/error.rs deleted file mode 100644 index cdc4496a7120..000000000000 --- a/src/analytics/error.rs +++ /dev/null @@ -1,29 +0,0 @@ -#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] -pub enum Error { - #[error("Unexpected")] - Unexpected, - #[error("EOF")] - EOF, - - #[error(transparent)] - Sys(#[from] bun_errno::SystemErrno), -} - -impl Error { - #[allow(clippy::trivially_copy_pass_by_ref)] - pub fn name(&self) -> &'static str { - match self { - Self::Sys(e) => <&'static str>::from(e), - Self::Unexpected => "Unexpected", - Self::EOF => "EOF", - } - } -} - -impl bun_core::output::ErrName for Error { - fn name(&self) -> &[u8] { - (*self).name().as_bytes() - } -} - -pub type Result = core::result::Result; diff --git a/src/analytics/lib.rs b/src/analytics/lib.rs index 394f83fee086..de8d53485e0f 100644 --- a/src/analytics/lib.rs +++ b/src/analytics/lib.rs @@ -331,17 +331,6 @@ pub(crate) const fn validate_feature_name(name: &[u8]) -> bool { // ────────────────────────────────────────────────────────────────────────── -#[repr(u8)] -#[derive(Copy, Clone, PartialEq, Eq, strum::IntoStaticStr)] -#[allow(non_camel_case_types)] -pub enum EventName { - bundle_success, - bundle_fail, - bundle_start, - http_start, - http_build, -} - const PLATFORM_ARCH: analytics::Architecture = { #[cfg(target_arch = "aarch64")] { @@ -603,7 +592,3 @@ pub mod generate_header { pub use generate_header as GenerateHeader; pub mod schema; -pub use schema::{BufReader, Reader, SchemaInt}; - -pub mod error; -pub use error::{Error, Result}; diff --git a/src/analytics/schema.rs b/src/analytics/schema.rs index 5773e0ee054e..f4d4af57b550 100644 --- a/src/analytics/schema.rs +++ b/src/analytics/schema.rs @@ -1,99 +1,3 @@ -// GENERATED: re-run the analytics schema generator (peechy) with .rs output -// Hand-ported subset — the remaining analytics::* types are unused at runtime -// and come back with the next peechy regen (see the `analytics` mod below). - -use crate::Error; - -// ────────────────────────────────────────────────────────────────────────── -// Reader / Writer -// ────────────────────────────────────────────────────────────────────────── -// -// The peechy codec protocol is the `Reader` trait below; `BufReader` is one -// concrete impl. Only the primitive-int / byte-slice surface is implemented; -// per-type `decode`/`encode` impls call the primitive methods directly -// (which is what the generated schema bodies already do). - -#[inline] -pub(crate) fn eof() -> Error { - crate::Error::EOF -} - -/// Primitive integers encodable in the peechy wire format (native-endian raw -/// bytes). -pub use bun_core::NativeEndianInt as SchemaInt; - -/// Duck-typed reader protocol for peechy `decode` impls. -pub trait Reader { - /// Borrow `count` bytes, advancing the cursor. Errors with `EOF` if - /// fewer than `count` remain. - fn read(&mut self, count: usize) -> Result<&[u8], Error>; - - #[inline] - fn read_byte(&mut self) -> Result { - Ok(self.read(1)?[0]) - } - - #[inline] - fn read_bool(&mut self) -> Result { - Ok(self.read_byte()? > 0) - } - - #[inline] - fn read_int(&mut self) -> Result { - let b = self.read(T::SIZE)?; - Ok(T::from_ne_slice(b)) - } - - /// Primitive-int read; struct/enum cases are expressed as per-type - /// `decode(reader)` fns instead. - #[inline] - fn read_value(&mut self) -> Result { - self.read_int::() - } - - /// `u32` length prefix + raw bytes. - #[inline] - fn read_byte_array(&mut self) -> Result<&[u8], Error> { - let len = self.read_int::()? as usize; - if len == 0 { - return Ok(&[]); - } - self.read(len) - } -} - -// peechy `Writer` lives in `bun_options_types::schema::Writer`. This crate -// keeps only the read side; encode users depend on options_types directly. - -/// Concrete buffer-backed reader. -/// -/// Callers that need owned sub-arrays allocate at the call site. -pub struct BufReader<'a> { - pub buf: &'a [u8], - pub remain: &'a [u8], -} - -impl<'a> BufReader<'a> { - #[inline] - pub fn init(buf: &'a [u8]) -> Self { - Self { buf, remain: buf } - } -} - -impl<'a> Reader for BufReader<'a> { - fn read(&mut self, count: usize) -> Result<&[u8], Error> { - let read_count = core::cmp::min(count, self.remain.len()); - if read_count < count { - return Err(eof()); - } - let (slice, rest) = self.remain.split_at(read_count); - self.remain = rest; - Ok(slice) - } -} - -// ────────────────────────────────────────────────────────────────────────── - // Hand-ported subset of `analytics::*` needed by lib.rs (OperatingSystem, // Architecture, Platform). The full encode/decode machinery and the rest of // the schema (EventKind, EventListHeader, …) are unused at runtime today and diff --git a/src/api/Cargo.toml b/src/api/Cargo.toml index 88e5be3746a5..890d219c438a 100644 --- a/src/api/Cargo.toml +++ b/src/api/Cargo.toml @@ -10,17 +10,6 @@ path = "lib.rs" workspace = true [dependencies] -strum.workspace = true -bstr.workspace = true -scopeguard.workspace = true -const_format.workspace = true -enum-map.workspace = true -enumset.workspace = true -libc.workspace = true -bitflags.workspace = true bun_alloc.workspace = true -bun_collections.workspace = true -bun_install_types.workspace = true bun_options_types.workspace = true bun_url.workspace = true - diff --git a/src/bun_core/env_var.rs b/src/bun_core/env_var.rs index 25cc3222e26f..7e49b470ed0b 100644 --- a/src/bun_core/env_var.rs +++ b/src/bun_core/env_var.rs @@ -113,7 +113,6 @@ platform_specific_new!(pub C_INCLUDE_PATH: string, posix = "C_INCLUDE_PATH", win // Used by bun:ffi's TinyCC integration for systems like NixOS. platform_specific_new!(pub LIBRARY_PATH: string, posix = "LIBRARY_PATH", windows = None, {}); new!(pub BUN_TMPDIR: string, "BUN_TMPDIR", {}); -new!(pub BUN_TRACY_PATH: string, "BUN_TRACY_PATH", {}); new!(pub BUN_WATCHER_TRACE: string, "BUN_WATCHER_TRACE", {}); new!(pub CI: boolean, "CI", {}); new!(pub CI_COMMIT_SHA: string, "CI_COMMIT_SHA", {}); diff --git a/src/bun_core/util.rs b/src/bun_core/util.rs index 59f7ad90d548..8c9d1381f526 100644 --- a/src/bun_core/util.rs +++ b/src/bun_core/util.rs @@ -3557,10 +3557,8 @@ impl_integer!( /// Primitive integers transcodable as native-endian raw bytes. /// -/// Explicit trait -/// bound shared by the peechy wire codec (`bun_analytics::SchemaInt`) and the -/// MySQL protocol reader (`bun_sql::ReadableInt`), which re-export this under -/// their local names. +/// Explicit trait bound used by the MySQL protocol reader +/// (`bun_sql::ReadableInt`), which re-exports this under its local name. pub trait NativeEndianInt: Copy + 'static { const SIZE: usize; /// Reinterpret `b[..SIZE]` as `Self` (native endian). diff --git a/src/bundler/bundle_v2.rs b/src/bundler/bundle_v2.rs index e560c565b689..49d092acb299 100644 --- a/src/bundler/bundle_v2.rs +++ b/src/bundler/bundle_v2.rs @@ -2689,8 +2689,6 @@ pub mod bv2_impl { heap: &'a ThreadLocalArena, ) -> Result>, Error> { // The Box is heap-owned and dropped by the caller. - transpiler.env().load_tracy(); - transpiler.options.mark_builtins_as_external = transpiler.options.target.is_bun() || transpiler.options.target == Target::Node; transpiler.resolver.opts.mark_builtins_as_external = diff --git a/src/clap/args.rs b/src/clap/args.rs index 75150beba62a..0ed6e2a577d3 100644 --- a/src/clap/args.rs +++ b/src/clap/args.rs @@ -1,8 +1,4 @@ -use std::borrow::Cow; - -/// Arg-iterator surface. Implemented by -/// `OsIterator` and `SliceIterator`; `ShellIterator` does not fit (fallible, -/// owned results) and is used standalone. +/// Arg-iterator surface. Implemented by `OsIterator` and `SliceIterator`. pub trait ArgIter<'a> { fn next(&mut self) -> Option<&'a [u8]>; /// Remaining unconsumed args as a slice (for `stop_after_positional_at`). @@ -106,205 +102,6 @@ fn os_argv() -> &'static [&'static [u8]] { unsafe { core::slice::from_raw_parts(z.as_ptr().cast::<&'static [u8]>(), z.len()) } } -#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error, strum::IntoStaticStr)] -pub enum ShellIteratorError { - #[error("DanglingEscape")] - DanglingEscape, - #[error("QuoteNotClosed")] - QuoteNotClosed, - // There is no OutOfMemory variant: Vec aborts - // on OOM under the global mimalloc allocator. -} - -/// An argument iterator that takes a string and parses it into arguments, simulating -/// how shells split arguments. -pub struct ShellIterator<'a> { - // Allocated results are returned as `Cow::Owned` instead of arena-backed slices. - pub str: &'a [u8], -} - -#[derive(Clone, Copy)] -enum State { - SkipWhitespace, - NoQuote, - NoQuoteEscape, - SingleQuote, - DoubleQuote, - DoubleQuoteEscape, - AfterQuote, -} - -impl<'a> ShellIterator<'a> { - pub fn init(str: &'a [u8]) -> ShellIterator<'a> { - ShellIterator { str } - } - - pub fn next(&mut self) -> Result>, ShellIteratorError> { - // Whenever possible, this iterator will return slices into `str` instead of - // allocating. Sometimes this is not possible, for example, escaped characters - // have be be unescape, so we need to allocate in this case. - let mut list: Vec = Vec::new(); - let mut start: usize = 0; - let mut state = State::SkipWhitespace; - - // Copy the slice ref so we can reassign `self.str` before returning. - let s: &'a [u8] = self.str; - - for (i, &c) in s.iter().enumerate() { - match state { - // The state that skips the initial whitespace. - State::SkipWhitespace => match c { - b' ' | b'\t' | b'\n' => {} - b'\'' => { - start = i + 1; - state = State::SingleQuote; - } - b'"' => { - start = i + 1; - state = State::DoubleQuote; - } - b'\\' => { - start = i + 1; - state = State::NoQuoteEscape; - } - _ => { - start = i; - state = State::NoQuote; - } - }, - - // The state that parses the none quoted part of a argument. - State::NoQuote => match c { - // We're done parsing a none quoted argument when we hit a - // whitespace. - b' ' | b'\t' | b'\n' => { - let res = Self::result(s, start, i, list); - self.str = &s[i..]; - return res; - } - - // Slicing is not possible if a quote starts while parsing none - // quoted args. - // Example: - // ab'cd' -> abcd - b'\'' => { - list.extend_from_slice(&s[start..i]); - start = i + 1; - state = State::SingleQuote; - } - b'"' => { - list.extend_from_slice(&s[start..i]); - start = i + 1; - state = State::DoubleQuote; - } - - // Slicing is not possible if we need to escape a character. - // Example: - // ab\"d -> ab"d - b'\\' => { - list.extend_from_slice(&s[start..i]); - start = i + 1; - state = State::NoQuoteEscape; - } - _ => {} - }, - - // We're in this state after having parsed the quoted part of an - // argument. This state works mostly the same as .no_quote, but - // is aware, that the last character seen was a quote, which should - // not be part of the argument. This is why you will see `i - 1` here - // instead of just `i` when `iter.str` is sliced. - State::AfterQuote => match c { - b' ' | b'\t' | b'\n' => { - let res = Self::result(s, start, i - 1, list); - self.str = &s[i..]; - return res; - } - b'\'' => { - list.extend_from_slice(&s[start..i - 1]); - start = i + 1; - state = State::SingleQuote; - } - b'"' => { - list.extend_from_slice(&s[start..i - 1]); - start = i + 1; - state = State::DoubleQuote; - } - b'\\' => { - list.extend_from_slice(&s[start..i - 1]); - start = i + 1; - state = State::NoQuoteEscape; - } - _ => { - list.extend_from_slice(&s[start..i - 1]); - start = i; - state = State::NoQuote; - } - }, - - // The states that parse the quoted part of arguments. The only differnece - // between single and double quoted arguments is that single quoted - // arguments ignore escape sequences, while double quoted arguments - // does escaping. - State::SingleQuote => match c { - b'\'' => state = State::AfterQuote, - _ => {} - }, - State::DoubleQuote => match c { - b'"' => state = State::AfterQuote, - b'\\' => { - list.extend_from_slice(&s[start..i]); - start = i + 1; - state = State::DoubleQuoteEscape; - } - _ => {} - }, - - // The state we end up when after the escape character (`\`). All these - // states do is transition back into the previous state. - // TODO: Are there any escape sequences that does transform the second - // character into something else (e.g. `\n` into the line feed - // ascii character)? - State::NoQuoteEscape => { - state = State::NoQuote; - } - State::DoubleQuoteEscape => { - state = State::DoubleQuote; - } - } - } - - self.str = &s[s.len()..]; - match state { - State::SkipWhitespace => Ok(None), - State::NoQuote => Self::result(s, start, s.len(), list), - State::AfterQuote => Self::result(s, start, s.len() - 1, list), - State::NoQuoteEscape => Err(ShellIteratorError::DanglingEscape), - State::SingleQuote | State::DoubleQuote | State::DoubleQuoteEscape => { - Err(ShellIteratorError::QuoteNotClosed) - } - } - } - - fn result( - s: &'a [u8], - start: usize, - end: usize, - mut list: Vec, - ) -> Result>, ShellIteratorError> { - let res = &s[start..end]; - - // If we already have something in `list` that means that we could not - // parse the argument without allocation. We therefor need to just append - // the rest we have to the list and return that. - if !list.is_empty() { - list.extend_from_slice(res); - return Ok(Some(Cow::Owned(list))); - } - Ok(Some(Cow::Borrowed(res))) - } -} - #[cfg(test)] mod tests { use super::*; @@ -319,101 +116,4 @@ mod tests { debug_assert!(*a == b.unwrap()); } } - - fn test_shell_iterator_ok(str: &[u8], expected_owned_results: usize, expect: &[&[u8]]) { - // There is no allocator injection to count raw allocations with, - // but every allocating result surfaces as a - // `Cow::Owned`, so counting owned results checks the same property: the - // borrowed (zero-copy) fast path is taken whenever possible. - let mut owned_results: usize = 0; - let mut it = ShellIterator::init(str); - - for e in expect { - match it.next() { - Ok(actual) => { - assert!(actual.is_some()); - let actual = actual.unwrap(); - if matches!(actual, Cow::Owned(_)) { - owned_results += 1; - } - assert_eq!(*e, &*actual); - } - Err(err) => panic!("expected {:?}, got error {:?}", e, err), - } - } - - match it.next() { - Ok(actual) => { - assert!(actual.is_none()); - assert_eq!(expected_owned_results, owned_results); - } - Err(err) => panic!("expected end of iterator, got error {:?}", err), - } - } - - fn test_shell_iterator_err(str: &[u8], expect: ShellIteratorError) { - let mut it = ShellIterator::init(str); - - loop { - match it.next() { - Ok(Some(_)) => {} - Ok(None) => break, - Err(err) => { - assert_eq!(expect, err); - return; - } - } - } - - panic!("expected error {:?}, got end of iterator", expect); - } - - #[test] - fn shell_iterator() { - test_shell_iterator_ok(b"a", 0, &[b"a"]); - test_shell_iterator_ok(b"'a'", 0, &[b"a"]); - test_shell_iterator_ok(b"\"a\"", 0, &[b"a"]); - test_shell_iterator_ok(b"a b", 0, &[b"a", b"b"]); - test_shell_iterator_ok(b"'a' b", 0, &[b"a", b"b"]); - test_shell_iterator_ok(b"\"a\" b", 0, &[b"a", b"b"]); - test_shell_iterator_ok(b"a 'b'", 0, &[b"a", b"b"]); - test_shell_iterator_ok(b"a \"b\"", 0, &[b"a", b"b"]); - test_shell_iterator_ok(b"'a b'", 0, &[b"a b"]); - test_shell_iterator_ok(b"\"a b\"", 0, &[b"a b"]); - test_shell_iterator_ok(b"\"a\"\"b\"", 1, &[b"ab"]); - test_shell_iterator_ok(b"'a''b'", 1, &[b"ab"]); - test_shell_iterator_ok(b"'a'b", 1, &[b"ab"]); - test_shell_iterator_ok(b"a'b'", 1, &[b"ab"]); - test_shell_iterator_ok(b"a\\ b", 1, &[b"a b"]); - test_shell_iterator_ok(b"\"a\\ b\"", 1, &[b"a b"]); - test_shell_iterator_ok(b"'a\\ b'", 0, &[b"a\\ b"]); - test_shell_iterator_ok(b" a b ", 0, &[b"a", b"b"]); - test_shell_iterator_ok(b"\\ \\ ", 0, &[b" ", b" "]); - - test_shell_iterator_ok( - br"printf 'run\nuninstall\n'", - 0, - &[b"printf", br"run\nuninstall\n"], - ); - test_shell_iterator_ok( - br#"setsid -f steam "steam://$action/$id""#, - 0, - &[b"setsid", b"-f", b"steam", b"steam://$action/$id"], - ); - test_shell_iterator_ok( - b"xargs -I% rg --no-heading --no-line-number --only-matching\n --case-sensitive --multiline --text --byte-offset '(?-u)%' $@\n", - 0, - &[ - b"xargs", b"-I%", b"rg", b"--no-heading", - b"--no-line-number", b"--only-matching", b"--case-sensitive", b"--multiline", - b"--text", b"--byte-offset", b"(?-u)%", b"$@", - ], - ); - - test_shell_iterator_err(b"'a", ShellIteratorError::QuoteNotClosed); - test_shell_iterator_err(b"'a\\", ShellIteratorError::QuoteNotClosed); - test_shell_iterator_err(b"\"a", ShellIteratorError::QuoteNotClosed); - test_shell_iterator_err(b"\"a\\", ShellIteratorError::QuoteNotClosed); - test_shell_iterator_err(b"a\\", ShellIteratorError::DanglingEscape); - } } diff --git a/src/clap/comptime.rs b/src/clap/comptime.rs index cac65676482e..a04d4c57a24c 100644 --- a/src/clap/comptime.rs +++ b/src/clap/comptime.rs @@ -647,35 +647,4 @@ impl ComptimeClap { pub fn remaining(&self) -> &[&'static [u8]] { &self.passthrough_positionals } - - /// `const fn` so `const { has_flag(PARAMS, b"--foo") }` folds. - pub const fn has_flag(params: &[Param], name: &[u8]) -> bool { - let mut i = 0; - while i < params.len() { - let n = ¶ms[i].names; - if name.len() == 2 && name[0] == b'-' { - if let Some(s) = n.short { - if s == name[1] { - return true; - } - } - } else if name.len() > 2 && name[0] == b'-' && name[1] == b'-' { - let (_, key) = name.split_at(2); - if let Some(l) = n.long { - if bytes_eq(l, key) { - return true; - } - } - let mut a = 0; - while a < n.long_aliases.len() { - if bytes_eq(n.long_aliases[a], key) { - return true; - } - a += 1; - } - } - i += 1; - } - false - } } diff --git a/src/clap/lib.rs b/src/clap/lib.rs index 5898048d11b5..ce4d55b1cd9f 100644 --- a/src/clap/lib.rs +++ b/src/clap/lib.rs @@ -1,7 +1,4 @@ #![warn(unused_must_use)] -use core::fmt; - -use bun_core::fmt::CountingWriter; use bun_core::{self, Output}; pub mod args; @@ -237,20 +234,6 @@ impl Names { } false } - - /// Check whether `name` (with leading `-`/`--`) matches this param's short, - /// long, or any long alias. Shared predicate for `has_flag`/`find_param`. - pub fn matches(&self, name: &[u8]) -> bool { - if let Some(s) = self.short { - if name.len() == 2 && name[0] == b'-' && name[1] == s { - return true; - } - } - if name.len() >= 2 && &name[..2] == b"--" { - return self.matches_long(&name[2..]); - } - false - } } /// Whether a param takes no value (a flag), one value, or can be specified multiple times. @@ -386,9 +369,8 @@ impl Diagnostic { #[derive(Clone, Copy)] pub struct Help { /// The description text exactly as written in the param spec — may still - /// contain `` colour markup. Used by [`help`]/[`help_ex`], which - /// emit it verbatim, and as the source for the ANSI form - /// built lazily by [`pretty_help_desc`] on the `bun --help` colour path. + /// contain `` colour markup. Source for the ANSI form built lazily + /// by [`pretty_help_desc`] on the `bun --help` colour path. pub msg: &'static [u8], /// `msg` with `` colour markup stripped — the non-TTY / piped help form. /// Precomputed at compile time by `parse_param!` (the strip is the only @@ -448,12 +430,6 @@ fn pretty_help_desc(param: &Param) -> std::borrow::Cow<'static, [u8]> { } } -#[cold] -#[inline(never)] -fn get_value_simple(param: &Param) -> &'static [u8] { - param.id.value -} - pub struct Args { pub clap: ComptimeClap, pub exe_arg: Option<&'static [u8]>, @@ -479,10 +455,6 @@ impl Args { pub fn remaining(&self) -> &[&'static [u8]] { self.clap.remaining() } - - pub fn has_flag(params: &[Param], name: &'static [u8]) -> bool { - ComptimeClap::::has_flag(params, name) - } } /// Same as `parse_ex` but uses the `args::OsIterator` by default. @@ -548,173 +520,6 @@ where ComptimeClap::::parse(params, iter, opt) } -/// Will print a help message in the following format: -/// -s, --long helpText -/// -s, helpText -/// -s helpText -/// --long helpText -/// --long helpText -#[cold] -#[inline(never)] -pub fn help_full( - stream: &mut W, - params: &[Param], - context: &C, - help_text: fn(&C, &Param) -> Result<&'static [u8], E>, - value_text: fn(&C, &Param) -> Result<&'static [u8], E>, -) -> crate::Result<()> -where - W: fmt::Write, - Id: Copy, - E: Into, -{ - let max_spacing: usize = 'blk: { - let mut res: usize = 0; - for param in params { - let mut cs = CountingWriter::null(); - print_param(&mut cs, param, context, value_text)?; - if res < cs.count { - res = cs.count; - } - } - break 'blk res; - }; - - for param in params { - if param.names.short.is_none() && param.names.long.is_none() { - continue; - } - - let ht = help_text(context, param).map_err(Into::into)?; - // only print flag if description is defined - if !ht.is_empty() { - let mut cs = CountingWriter::wrap(stream); - write!(cs.inner(), "\t")?; - print_param(&mut cs, param, context, value_text)?; - let written = cs.count; - // stream.splatByteAll(' ', max_spacing - written) - for _ in 0..(max_spacing - written) { - stream.write_char(' ')?; - } - let ht2 = help_text(context, param).map_err(Into::into)?; - writeln!(stream, "\t{}", bstr::BStr::new(ht2))?; - } - } - Ok(()) -} - -#[cold] -#[inline(never)] -fn print_param( - stream: &mut W, - param: &Param, - context: &C, - value_text: fn(&C, &Param) -> Result<&'static [u8], E>, -) -> crate::Result<()> -where - W: fmt::Write, - Id: Copy, - E: Into, -{ - if let Some(s) = param.names.short { - write!(stream, "-{}", s as char)?; - } else { - write!(stream, " ")?; - } - if let Some(l) = param.names.long { - if param.names.short.is_some() { - write!(stream, ", ")?; - } else { - write!(stream, " ")?; - } - write!(stream, "--{}", bstr::BStr::new(l))?; - } - - write_takes_value_suffix(stream, param, context, value_text)?; - Ok(()) -} - -/// Shared by `print_param` and `usage_full`: emit the ` ` / ` ?` / -/// ` ...` suffix for a param's `takes_value`. -#[cold] -#[inline(never)] -fn write_takes_value_suffix( - w: &mut W, - param: &Param, - context: &C, - value_text: fn(&C, &Param) -> Result<&'static [u8], E>, -) -> crate::Result<()> -where - W: fmt::Write, - Id: Copy, - E: Into, -{ - match param.takes_value { - Values::None => {} - Values::One => { - write!( - w, - " <{}>", - bstr::BStr::new(value_text(context, param).map_err(Into::into)?) - )?; - } - Values::OneOptional => { - write!( - w, - " <{}>?", - bstr::BStr::new(value_text(context, param).map_err(Into::into)?) - )?; - } - Values::Many => { - write!( - w, - " <{}>...", - bstr::BStr::new(value_text(context, param).map_err(Into::into)?) - )?; - } - } - Ok(()) -} - -/// A wrapper around help_full for simple help_text and value_text functions that -/// cant return an error or take a context. -#[cold] -#[inline(never)] -pub fn help_ex( - stream: &mut W, - params: &[Param], - help_text: fn(&Param) -> &'static [u8], - value_text: fn(&Param) -> &'static [u8], -) -> crate::Result<()> -where - W: fmt::Write, - Id: Copy, -{ - struct Context { - help_text: fn(&Param) -> &'static [u8], - value_text: fn(&Param) -> &'static [u8], - } - - fn help(c: &Context, p: &Param) -> crate::Result<&'static [u8]> { - Ok((c.help_text)(p)) - } - - fn value(c: &Context, p: &Param) -> crate::Result<&'static [u8]> { - Ok((c.value_text)(p)) - } - - help_full( - stream, - params, - &Context { - help_text, - value_text, - }, - help::, - value::, - ) -} - #[cold] #[inline(never)] pub fn simple_print_param(param: &Param) -> crate::Result<()> { @@ -846,13 +651,6 @@ pub fn simple_help_bun_top_level(params: &[Param]) { } } -/// A wrapper around help_ex that takes a `Param`. -#[cold] -#[inline(never)] -pub fn help(stream: &mut W, params: &[Param]) -> crate::Result<()> { - help_ex(stream, params, get_help_simple, get_value_simple) -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/dotenv/env_loader.rs b/src/dotenv/env_loader.rs index a0da2b4cb3fa..b741cb9f2b47 100644 --- a/src/dotenv/env_loader.rs +++ b/src/dotenv/env_loader.rs @@ -225,8 +225,6 @@ impl Loader { .is_some() } - pub fn load_tracy(&self) {} - pub fn get_s3_credentials(&mut self) -> &S3Credentials { if self.aws_credentials.is_none() { // Copy to `Box<[u8]>` so the cached struct owns its bytes and we diff --git a/src/exe_format/pe.rs b/src/exe_format/pe.rs index 320fe7537442..2acf6d1d6670 100644 --- a/src/exe_format/pe.rs +++ b/src/exe_format/pe.rs @@ -36,16 +36,8 @@ pub enum Error { SecurityDirInsideImage, #[error("UnexpectedOverlayPresent")] UnexpectedOverlayPresent, - #[error("InvalidSectionData")] - InvalidSectionData, - #[error("BunSectionNotFound")] - BunSectionNotFound, - #[error("InvalidBunSection")] - InvalidBunSection, #[error("InsufficientSpace")] InsufficientSpace, - #[error("SizeOfImageMismatch")] - SizeOfImageMismatch, } // Enums for strip modes and options @@ -75,7 +67,6 @@ impl Default for StripOpts { pub struct PEFile { pub data: Vec, // Store offsets instead of pointers to avoid invalidation after resize - pub dos_header_offset: usize, pub pe_header_offset: usize, pub optional_header_offset: usize, pub section_headers_offset: usize, @@ -251,14 +242,6 @@ fn align_up_usize(v: usize, a: usize) -> Result { impl PEFile { // Helper methods to safely access headers using unaligned pointers - fn get_dos_header(&self) -> Result<*const DOSHeader, Error> { - view_at_const::(&self.data, self.dos_header_offset) - } - - fn get_pe_header(&self) -> Result<*const PEHeader, Error> { - view_at_const::(&self.data, self.pe_header_offset) - } - fn get_pe_header_mut(&mut self) -> Result<*mut PEHeader, Error> { view_at_mut::(&mut self.data, self.pe_header_offset) } @@ -397,7 +380,6 @@ impl PEFile { Ok(Box::new(PEFile { data, - dos_header_offset: 0, pe_header_offset: pe_off, optional_header_offset, section_headers_offset, @@ -704,133 +686,11 @@ impl PEFile { Ok(()) } - /// Get the length of the Bun section data - pub fn get_bun_section_length(&self) -> Result { - let section_headers = self.get_section_headers()?; - for section in section_headers { - if section.name[0..8] == BUN_SECTION_NAME { - if (section.size_of_raw_data as usize) < size_of::() { - return Err(Error::InvalidBunSection); - } - - // Bounds check - if section.pointer_to_raw_data as usize >= self.data.len() - || section.pointer_to_raw_data as usize + size_of::() > self.data.len() - { - return Err(Error::InvalidBunSection); - } - - let section_data = &self.data[section.pointer_to_raw_data as usize..]; - return Ok(u64::from_le_bytes( - section_data[0..8] - .try_into() - .expect("infallible: size matches"), - )); - } - } - Err(Error::BunSectionNotFound) - } - /// Write the modified PE file pub fn write(&self, writer: &mut impl std::io::Write) -> crate::Result<()> { writer.write_all(&self.data)?; Ok(()) } - - /// Validate the PE file structure - pub fn validate(&self) -> Result<(), Error> { - // Check DOS & PE signatures - let dos_header = self.get_dos_header()?; - // SAFETY: dos_header points into self.data at validated offset - if unsafe { (*dos_header).e_magic } != DOS_SIGNATURE { - return Err(Error::InvalidDOSSignature); - } - - let pe_header = self.get_pe_header()?; - // SAFETY: pe_header points into self.data at validated offset - if unsafe { (*pe_header).signature } != PE_SIGNATURE { - return Err(Error::InvalidPESignature); - } - - // Check optional header magic is 0x20B (64-bit) - let optional_header = self.get_optional_header()?; - // SAFETY: optional_header points into self.data at validated offset - let optional_header = unsafe { &*optional_header }; - if optional_header.magic != OPTIONAL_HEADER_MAGIC_64 { - return Err(Error::UnsupportedPEFormat); - } - - // Validate file_alignment, section_alignment sanity - if !is_pow2(optional_header.file_alignment) || !is_pow2(optional_header.section_alignment) { - return Err(Error::BadAlignment); - } - // Relational rule - if optional_header.section_alignment < 4096 { - if optional_header.file_alignment != optional_header.section_alignment { - return Err(Error::InvalidPEFile); - } - } - - // Section headers region fits within size_of_headers and file - let section_headers_end = - self.section_headers_offset + size_of::() * self.num_sections as usize; - if section_headers_end > optional_header.size_of_headers as usize - || section_headers_end > self.data.len() - { - return Err(Error::InvalidPEFile); - } - - // Validate each section - let section_headers = self.get_section_headers()?; - let mut max_va_end: u32 = 0; - - for (i, section) in section_headers.iter().enumerate() { - // If size_of_raw_data > 0, validate raw data bounds - if section.size_of_raw_data > 0 { - if section.pointer_to_raw_data < optional_header.size_of_headers - || (section.pointer_to_raw_data + section.size_of_raw_data) as usize - > self.data.len() - { - return Err(Error::InvalidSectionData); - } - - // Check for overlaps with other sections using correct interval test - for other in §ion_headers[i + 1..] { - if other.size_of_raw_data > 0 { - let section_start = section.pointer_to_raw_data; - let section_end = section_start + section.size_of_raw_data; - let other_start = other.pointer_to_raw_data; - let other_end = other_start + other.size_of_raw_data; - // Standard overlap test: max(start) < min(end) - if section_start.max(other_start) < section_end.min(other_end) { - return Err(Error::InvalidPEFile); // Section raw ranges overlap - } - } - } - } - - // Track max virtual address end using effective virtual size - let vs_effective = section.virtual_size.max(section.size_of_raw_data); - let va_end = section.virtual_address - + align_up_u32(vs_effective, optional_header.section_alignment)?; - if va_end > max_va_end { - max_va_end = va_end; - } - } - - // Verify size_of_image equals alignUp(max(VA + alignUp(VS, SA)), SA) - let expected_size_of_image = align_up_u32(max_va_end, optional_header.section_alignment)?; - if optional_header.size_of_image != expected_size_of_image { - return Err(Error::SizeOfImageMismatch); - } - - // Security directory should be 0,0 post-change (if we modified it) - // (This is optional validation, not critical) - - // If checksum recomputed, field should be non-zero - // (Unless we intentionally write zero, which is allowed) - Ok(()) - } } // External C interface declarations - these are implemented in C++ bindings diff --git a/src/libarchive/lib.rs b/src/libarchive/lib.rs index 124e2459cf21..c66a1d9a110e 100644 --- a/src/libarchive/lib.rs +++ b/src/libarchive/lib.rs @@ -879,15 +879,6 @@ pub mod lib { use lib::Archive; -#[repr(i32)] // c_int -#[derive(Copy, Clone, Eq, PartialEq)] -pub enum Seek { - // values are POSIX SEEK_SET/CUR/END constants - Set = 0, - Current = 1, - End = 2, -} - pub struct BufferReadStream { buf: *const [u8], diff --git a/src/perf/Cargo.toml b/src/perf/Cargo.toml index 438cb8cacb48..45479cdfbae8 100644 --- a/src/perf/Cargo.toml +++ b/src/perf/Cargo.toml @@ -10,14 +10,6 @@ path = "lib.rs" workspace = true [dependencies] -strum.workspace = true -bstr.workspace = true -scopeguard.workspace = true -const_format.workspace = true -enum-map.workspace = true -enumset.workspace = true libc.workspace = true -bitflags.workspace = true bun_core.workspace = true -bun_paths.workspace = true bun_sys.workspace = true diff --git a/src/perf/lib.rs b/src/perf/lib.rs index e87b42221ac1..843fb6642649 100644 --- a/src/perf/lib.rs +++ b/src/perf/lib.rs @@ -9,7 +9,6 @@ use std::sync::Once; pub mod generated_perf_trace_events; pub mod system_timer; -pub mod tracy; pub use crate::generated_perf_trace_events::PerfEvent; diff --git a/src/perf/tracy.rs b/src/perf/tracy.rs deleted file mode 100644 index bb08a32c1503..000000000000 --- a/src/perf/tracy.rs +++ /dev/null @@ -1,490 +0,0 @@ -//! https://github.com/wolfpld/tracy -//! To use this module, you must have Tracy installed on your system. -//! On macOS, you can install it with `brew install tracy`. - -use core::ffi::{c_char, c_int, c_void}; -use core::ptr; -use core::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; - -use bun_core::env_var; - -pub const ENABLE_CALLSTACK: bool = false; - -// An AtomicBool keeps reads safe from any thread without `unsafe`. All -// loads/stores are Relaxed. -static ENABLE: AtomicBool = AtomicBool::new(false); - -#[inline(always)] -pub fn enable() -> bool { - ENABLE.load(Ordering::Relaxed) -} -#[inline(always)] -pub fn set_enable(v: bool) { - ENABLE.store(v, Ordering::Relaxed); -} - -#[allow(non_camel_case_types)] -#[repr(C)] -#[derive(Clone, Copy, Default)] -pub struct ___tracy_c_zone_context { - pub id: u32, - pub active: c_int, -} - -impl ___tracy_c_zone_context { - #[inline] - pub fn end(self) { - if !enable() { - return; - } - ___tracy_emit_zone_end(self); - } -} - -pub type Ctx = ___tracy_c_zone_context; - -/// Begin a Tracy zone. The -/// per-callsite static source location is emitted by the `tracy_trace!` -/// macro, which calls this with the already-built static. -#[inline] -pub fn trace(srcloc: &'static ___tracy_source_location_data) -> Ctx { - if !enable() { - return Ctx::default(); - } - - if ENABLE_CALLSTACK { - ___tracy_emit_zone_begin_callstack(srcloc, CALLSTACK_DEPTH, 1) - } else { - ___tracy_emit_zone_begin(srcloc, 1) - } -} - -/// Begin a named Tracy zone. The -/// per-callsite static (with `name` set) is emitted by the -/// `tracy_trace_named!` macro, which calls this with the already-built -/// static. -#[inline] -pub fn trace_named(srcloc: &'static ___tracy_source_location_data) -> Ctx { - if !enable() { - return Ctx::default(); - } - - if ENABLE_CALLSTACK { - ___tracy_emit_zone_begin_callstack(srcloc, CALLSTACK_DEPTH, 1) - } else { - ___tracy_emit_zone_begin(srcloc, 1) - } -} - -/// Begin a Tracy zone with a per-callsite static source location. -/// Expands to a fresh `static SRCLOC` per -/// callsite (no intermediate `SourceLocation` struct) and calls -/// `tracy::trace`. -#[macro_export] -macro_rules! tracy_trace { - () => {{ - static SRCLOC: $crate::tracy::___tracy_source_location_data = - $crate::tracy::___tracy_source_location_data { - name: ::core::ptr::null(), - function: concat!(module_path!(), "\0") - .as_ptr() - .cast::<::core::ffi::c_char>(), - file: concat!(file!(), "\0") - .as_ptr() - .cast::<::core::ffi::c_char>(), - line: line!(), - color: 0, - }; - $crate::tracy::trace(&SRCLOC) - }}; -} - -/// Begin a named Tracy zone with a per-callsite static source location. -/// The name must be a -/// string literal; it is NUL-terminated and stored in the per-callsite -/// static, then passed to `tracy::trace_named`. -#[macro_export] -macro_rules! tracy_trace_named { - ($name:literal) => {{ - static SRCLOC: $crate::tracy::___tracy_source_location_data = - $crate::tracy::___tracy_source_location_data { - name: concat!($name, "\0").as_ptr().cast::<::core::ffi::c_char>(), - function: concat!(module_path!(), "\0") - .as_ptr() - .cast::<::core::ffi::c_char>(), - file: concat!(file!(), "\0") - .as_ptr() - .cast::<::core::ffi::c_char>(), - line: line!(), - color: 0, - }; - $crate::tracy::trace_named(&SRCLOC) - }}; -} - -/// This function only accepts `'static` strings, see `message_copy` for runtime strings -#[inline] -pub fn message(msg: &'static core::ffi::CStr) { - if !enable() { - return; - } - ___tracy_emit_message_l( - msg.as_ptr(), - if ENABLE_CALLSTACK { CALLSTACK_DEPTH } else { 0 }, - ); -} - -#[inline] -pub fn named_frame(name: &'static core::ffi::CStr) -> Frame { - frame_mark_start(name); - Frame { name } -} - -/// Tracy frame span; `name` is stored as a field (one struct serves all -/// names). -pub struct Frame { - name: &'static core::ffi::CStr, -} - -impl Frame { - pub fn end(self) { - frame_mark_end(self.name); - } -} - -#[inline] -fn frame_mark_start(name: &'static core::ffi::CStr) { - if !enable() { - return; - } - ___tracy_emit_frame_mark_start(name.as_ptr()); -} - -#[inline] -fn frame_mark_end(name: &'static core::ffi::CStr) { - if !enable() { - return; - } - ___tracy_emit_frame_mark_end(name.as_ptr()); -} - -/// Function-pointer type aliases for dynamically-loaded Tracy C API. -#[allow(non_camel_case_types)] -mod tracy_fns { - use super::*; - - pub(super) type emit_frame_mark_start = unsafe extern "C" fn(name: *const c_char); - pub(super) type emit_frame_mark_end = unsafe extern "C" fn(name: *const c_char); - pub(super) type emit_zone_begin = unsafe extern "C" fn( - srcloc: *const ___tracy_source_location_data, - active: c_int, - ) -> ___tracy_c_zone_context; - pub(super) type emit_zone_begin_callstack = unsafe extern "C" fn( - srcloc: *const ___tracy_source_location_data, - depth: c_int, - active: c_int, - ) - -> ___tracy_c_zone_context; - pub(super) type emit_zone_end = unsafe extern "C" fn(ctx: ___tracy_c_zone_context); - pub(super) type emit_message = - unsafe extern "C" fn(txt: *const u8, size: usize, callstack: c_int); - pub(super) type emit_message_l = unsafe extern "C" fn(txt: *const c_char, callstack: c_int); - pub(super) type connected = unsafe extern "C" fn() -> c_int; - pub(super) type set_thread_name = unsafe extern "C" fn(name: *const c_char); - pub(super) type startup_profiler = unsafe extern "C" fn(); - pub(super) type shutdown_profiler = unsafe extern "C" fn(); -} - -#[allow(non_snake_case)] -fn ___tracy_startup_profiler() { - // these might not exist - let Some(f) = dlsym::(c"___tracy_startup_profiler") else { - return; - }; - // SAFETY: symbol resolved from libtracy with matching signature - unsafe { f() }; -} - -#[allow(non_snake_case)] -fn ___tracy_shutdown_profiler() { - // these might not exist - let Some(f) = dlsym::(c"___tracy_shutdown_profiler") else { - return; - }; - // SAFETY: symbol resolved from libtracy with matching signature - unsafe { f() }; -} - -static HAS_STARTED: AtomicBool = AtomicBool::new(false); - -pub fn has_started() -> bool { - HAS_STARTED.load(Ordering::Relaxed) -} - -pub fn start() { - if !enable() || HAS_STARTED.load(Ordering::Relaxed) { - return; - } - ___tracy_startup_profiler(); -} - -pub fn stop() { - if !enable() || !HAS_STARTED.load(Ordering::Relaxed) { - return; - } - ___tracy_shutdown_profiler(); -} - -#[allow(non_snake_case)] -fn ___tracy_emit_frame_mark_start(name: *const c_char) { - let f = dlsym::(c"___tracy_emit_frame_mark_start") - .expect("tracy symbol"); - // SAFETY: symbol resolved from libtracy with matching signature - unsafe { f(name) } -} -#[allow(non_snake_case)] -fn ___tracy_emit_frame_mark_end(name: *const c_char) { - let f = dlsym::(c"___tracy_emit_frame_mark_end") - .expect("tracy symbol"); - // SAFETY: symbol resolved from libtracy with matching signature - unsafe { f(name) } -} -#[allow(non_snake_case)] -fn ___tracy_emit_zone_begin( - srcloc: *const ___tracy_source_location_data, - active: c_int, -) -> ___tracy_c_zone_context { - let f = dlsym::(c"___tracy_emit_zone_begin").expect("tracy symbol"); - // SAFETY: symbol resolved from libtracy with matching signature - unsafe { f(srcloc, active) } -} -#[allow(non_snake_case)] -fn ___tracy_emit_zone_begin_callstack( - srcloc: *const ___tracy_source_location_data, - depth: c_int, - active: c_int, -) -> ___tracy_c_zone_context { - let f = dlsym::(c"___tracy_emit_zone_begin_callstack") - .expect("tracy symbol"); - // SAFETY: symbol resolved from libtracy with matching signature - unsafe { f(srcloc, depth, active) } -} -#[allow(non_snake_case)] -fn ___tracy_emit_zone_end(ctx: ___tracy_c_zone_context) { - let f = dlsym::(c"___tracy_emit_zone_end").expect("tracy symbol"); - // SAFETY: symbol resolved from libtracy with matching signature - unsafe { f(ctx) } -} -#[allow(non_snake_case)] -fn ___tracy_emit_message_l(txt: *const c_char, callstack: c_int) { - let f = dlsym::(c"___tracy_emit_messageL").expect("tracy symbol"); - // SAFETY: symbol resolved from libtracy with matching signature - unsafe { f(txt, callstack) } -} - -pub fn init() -> bool { - #[cfg(target_family = "wasm")] - { - return false; - } - - if enable() { - return true; - } - - if dlsym::(c"___tracy_emit_message").is_none() { - return false; - } - set_enable(true); - true -} - -pub fn is_connected() -> bool { - #[cfg(target_family = "wasm")] - { - return false; - } - - if !enable() { - return false; - } - - let f = dlsym::(c"___tracy_connected").expect("tracy symbol"); - // SAFETY: symbol resolved from libtracy with matching signature - unsafe { f() != 0 } -} - -pub fn init_thread(name: &'static core::ffi::CStr) { - #[cfg(target_family = "wasm")] - { - return; - } - - if !enable() { - return; - } - - let f = dlsym::(c"___tracy_set_thread_name").expect("tracy symbol"); - // SAFETY: symbol resolved from libtracy with matching signature - unsafe { f(name.as_ptr()) } -} - -#[allow(non_camel_case_types)] -#[repr(C)] -pub struct ___tracy_source_location_data { - pub name: *const c_char, - pub function: *const c_char, - pub file: *const c_char, - pub line: u32, - pub color: u32, -} - -// SAFETY: Tracy requires srcloc data to have 'static lifetime; all pointer -// fields are populated from string literals (`&'static CStr`) so sending the -// struct across threads is sound. -unsafe impl Sync for ___tracy_source_location_data {} - -impl Default for ___tracy_source_location_data { - fn default() -> Self { - Self { - name: ptr::null(), - function: c"".as_ptr(), - file: c"".as_ptr(), - line: 0, - color: 0, - } - } -} - -// A single shared handle serves all symbols (a per-(Type, symbol) handle -// would wastefully re-dlopen libtracy per symbol; dlopen on the same path is -// refcounted anyway). -static HANDLE: AtomicPtr = AtomicPtr::new(ptr::null_mut()); - -fn handle_getter() -> Option<*mut c_void> { - let h = HANDLE.load(Ordering::Acquire); - if h.is_null() { None } else { Some(h) } -} - -/// `&'static CStr` → `&'static ZStr` (both are NUL-terminated, len excludes NUL). -#[inline(always)] -fn cstr_as_zstr(s: &'static core::ffi::CStr) -> &'static bun_core::ZStr { - bun_core::ZStr::from_cstr(s) -} - -fn dlsym(symbol: &'static core::ffi::CStr) -> Option { - #[cfg(target_family = "wasm")] - { - let _ = symbol; - return None; - } - - #[cfg(not(target_family = "wasm"))] - { - debug_assert_eq!( - core::mem::size_of::(), - core::mem::size_of::<*mut c_void>() - ); - - let sym_z = cstr_as_zstr(symbol); - - #[cfg(any(target_os = "linux", target_os = "android"))] - { - // use LD_PRELOAD on linux (RTLD_DEFAULT lookup) - if let Some(p) = bun_sys::dlsym_impl(None, sym_z) { - // SAFETY: caller asserts `T` is fn-pointer-shaped matching the symbol's ABI. - return Some(unsafe { core::mem::transmute_copy::<*mut c_void, T>(&p) }); - } - } - - 'get: { - if HANDLE.load(Ordering::Acquire).is_null() { - #[cfg(target_os = "macos")] - const PATHS_TO_TRY: &[&core::ffi::CStr] = &[ - c"/usr/local/opt/tracy/lib/libtracy.dylib", - c"/usr/local/lib/libtracy.dylib", - c"/opt/homebrew/lib/libtracy.so", - c"/opt/homebrew/lib/libtracy.dylib", - c"/usr/lib/libtracy.dylib", - c"libtracy.dylib", - c"libtracy.so", - c"libTracyClient.dylib", - c"libTracyClient.so", - ]; - #[cfg(any(target_os = "linux", target_os = "android"))] - const PATHS_TO_TRY: &[&core::ffi::CStr] = &[ - c"/usr/local/lib/libtracy.so", - c"/usr/local/opt/tracy/lib/libtracy.so", - c"/opt/tracy/lib/libtracy.so", - c"/usr/lib/libtracy.so", - c"/usr/local/lib/libTracyClient.so", - c"/usr/local/opt/tracy/lib/libTracyClient.so", - c"/opt/tracy/lib/libTracyClient.so", - c"/usr/lib/libTracyClient.so", - c"libtracy.so", - c"libTracyClient.so", - ]; - #[cfg(windows)] - const PATHS_TO_TRY: &[&core::ffi::CStr] = &[c"tracy.dll"]; - #[cfg(not(any( - target_os = "macos", - target_os = "linux", - target_os = "android", - windows - )))] - const PATHS_TO_TRY: &[&core::ffi::CStr] = &[]; - - // RTLD flags passed straight through to dlopen as raw values: - // -2 on macOS, 0 elsewhere. - #[cfg(target_os = "macos")] - let rtld: i32 = -2; - #[cfg(not(target_os = "macos"))] - let rtld: i32 = 0; - - if let Some(path) = env_var::BUN_TRACY_PATH.get() { - // Copy into a NUL-terminated PathBuffer. - let mut buf = bun_paths::PathBuffer::uninit(); - let zpath = bun_paths::resolve_path::z(path, &mut buf); - if let Some(handle) = bun_sys::dlopen(zpath, rtld) { - HANDLE.store(handle, Ordering::Release); - break 'get; - } - } - for path in PATHS_TO_TRY { - if let Some(handle) = bun_sys::dlopen(cstr_as_zstr(path), rtld) { - HANDLE.store(handle, Ordering::Release); - break; - } - } - - if HANDLE.load(Ordering::Acquire).is_null() { - return None; - } - } - } - - // Uncached lookup through the shared handle. PERF: a per-symbol - // OnceLock cache is possible — profile if it shows up on a hot path. - let p = bun_sys::dlsym_impl(handle_getter(), sym_z)?; - // SAFETY: caller asserts `T` is fn-pointer-shaped matching the symbol's ABI. - Some(unsafe { core::mem::transmute_copy::<*mut c_void, T>(&p) }) - } -} - -// Only consulted when `ENABLE_CALLSTACK` is true. -const CALLSTACK_DEPTH: c_int = 10; - -#[cfg(test)] -mod tests { - // Expand both macros so the per-callsite statics (and their const - // initializers) are compile-checked even though no runtime caller exists - // yet. With `enable()` false (the default), `trace`/`trace_named` return - // `Ctx::default()` and `end()` is a no-op, so this is safe to run. - #[test] - fn trace_macros_expand() { - let ctx = crate::tracy_trace!(); - ctx.end(); - let named = crate::tracy_trace_named!("test"); - named.end(); - } -} diff --git a/src/picohttp/lib.rs b/src/picohttp/lib.rs index 4917de2b390f..42f1e1a09638 100644 --- a/src/picohttp/lib.rs +++ b/src/picohttp/lib.rs @@ -7,28 +7,27 @@ use bstr::BStr; use bun_core::output::enable_ansi_colors_stderr; use bun_core::pretty_fmt; -// `Header::clone` / `Request::clone` / `Response::clone` need the -// unbound-lifetime `append_raw` so they can interleave appends and stash the -// raw ptr/len pairs. The buffer is heap-owned; callers keep the builder (or -// its moved-out buffer) alive while the returned slices are in use. +// `Header::clone` / `Response::clone` need the unbound-lifetime `append_raw` +// so they can interleave appends and stash the raw ptr/len pairs. The buffer +// is heap-owned; callers keep the builder (or its moved-out buffer) alive +// while the returned slices are in use. pub use bun_core::StringBuilder; -// FFI surface over vendor/picohttpparser. Hand-written (three functions, two -// structs) rather than bindgen-generated. +// FFI surface over vendor/picohttpparser. Hand-written rather than +// bindgen-generated. #[allow(non_camel_case_types)] mod c { use core::ffi::{c_char, c_int}; #[repr(C)] - pub struct phr_header { + pub(super) struct phr_header { pub name: *const c_char, pub name_len: usize, pub value: *const c_char, pub value_len: usize, } - pub type struct_phr_header = phr_header; /// Mirrors `struct phr_chunked_decoder` from picohttpparser.h. The HTTP - /// client writes `consume_trailer` directly and inspects `_state` via - /// `phr_decode_chunked_is_in_data`, so the layout must match C exactly. + /// client writes `consume_trailer` and reads `_state` directly, so the + /// layout must match C exactly. #[repr(C)] #[derive(Clone, Copy, Default)] pub struct phr_chunked_decoder { @@ -38,21 +37,8 @@ mod c { pub _hex_count: core::ffi::c_char, pub _state: core::ffi::c_char, } - pub type struct_phr_chunked_decoder = phr_chunked_decoder; unsafe extern "C" { - pub fn phr_parse_request( - buf: *const u8, - len: usize, - method: *mut *const c_char, - method_len: *mut usize, - path: *mut *const c_char, - path_len: *mut usize, - minor_version: *mut c_int, - headers: *mut phr_header, - num_headers: *mut usize, - last_len: usize, - ) -> c_int; - pub fn phr_parse_response( + pub(super) fn phr_parse_response( buf: *const u8, len: usize, minor_version: *mut c_int, @@ -63,19 +49,11 @@ mod c { num_headers: *mut usize, last_len: usize, ) -> c_int; - pub fn phr_parse_headers( - buf: *const u8, - len: usize, - headers: *mut phr_header, - num_headers: *mut usize, - last_len: usize, - ) -> c_int; pub fn phr_decode_chunked( decoder: *mut phr_chunked_decoder, buf: *mut u8, len: *mut usize, ) -> isize; - pub fn phr_decode_chunked_is_in_data(decoder: *mut phr_chunked_decoder) -> c_int; } } @@ -279,13 +257,6 @@ impl<'a> HeaderList<'a> { // Request // ────────────────────────────────────────────────────────────────────────── -#[derive(Debug, strum::IntoStaticStr)] -pub enum ParseRequestError { - BadRequest, - ShortRead, -} -bun_core::impl_tag_error!(ParseRequestError); - pub struct Request<'a> { pub method: &'a [u8], pub path: &'a [u8], @@ -303,22 +274,6 @@ impl<'a> Request<'a> { } } - pub fn clone(&self, headers: &'a mut [Header], builder: &mut StringBuilder) -> Request<'a> { - for (i, header) in self.headers.iter().enumerate() { - headers[i] = header.clone(builder); - } - - Request { - // SAFETY: see `Header::clone` — caller keeps `builder` alive. - method: unsafe { builder.append_raw(self.method) }, - // SAFETY: see `Header::clone` — caller keeps `builder` alive. - path: unsafe { builder.append_raw(self.path) }, - minor_version: self.minor_version, - headers, - bytes_read: self.bytes_read, - } - } - /// Widen the borrowed slices to `'static` for self-referential storage. /// /// Field-by-field move (no bitwise reinterpret). Used when the request's @@ -341,54 +296,6 @@ impl<'a> Request<'a> { bytes_read: self.bytes_read, } } - - pub fn parse(buf: &'a [u8], src: &'a mut [Header]) -> Result, ParseRequestError> { - let mut method_ptr: *const u8 = core::ptr::null(); - let mut method_len: usize = 0; - let mut path_ptr: *const u8 = core::ptr::null(); - let mut path_len: usize = 0; - let mut minor_version: c_int = 0; - let mut num_headers: usize = src.len(); - - // SAFETY: picohttpparser writes back into the out-params; src is - // layout-compatible with phr_header (asserted above). - let rc = unsafe { - c::phr_parse_request( - buf.as_ptr(), - buf.len(), - (&raw mut method_ptr).cast::<*const core::ffi::c_char>(), - &raw mut method_len, - (&raw mut path_ptr).cast::<*const core::ffi::c_char>(), - &raw mut path_len, - &raw mut minor_version, - src.as_mut_ptr().cast::(), - &raw mut num_headers, - 0, - ) - }; - - // Leave a sentinel value, for JavaScriptCore support. - if rc > -1 { - // SAFETY: path_ptr points into buf; the byte after the path is the - // space before "HTTP/1.x" which picohttpparser has already consumed, - // so writing a NUL there is in-bounds. - unsafe { path_ptr.cast_mut().add(path_len).write(0) }; - } - - match rc { - -1 => Err(ParseRequestError::BadRequest), - -2 => Err(ParseRequestError::ShortRead), - _ => Ok(Request { - // SAFETY: on success, ptr/len point into `buf`. - method: unsafe { bun_core::ffi::slice(method_ptr, method_len) }, - // SAFETY: on success, ptr/len point into `buf`. - path: unsafe { bun_core::ffi::slice(path_ptr, path_len) }, - minor_version: usize::try_from(minor_version).expect("int cast"), - headers: &src[0..num_headers], - bytes_read: u32::try_from(rc).expect("int cast"), - }), - } - } } impl fmt::Display for Request<'_> { @@ -690,42 +597,10 @@ impl fmt::Display for Response<'_> { // Headers // ────────────────────────────────────────────────────────────────────────── -#[derive(Debug, strum::IntoStaticStr)] -pub enum ParseHeadersError { - BadHeaders, - ShortRead, -} -bun_core::impl_tag_error!(ParseHeadersError); - pub struct Headers<'a> { pub headers: &'a [Header], } -impl<'a> Headers<'a> { - pub fn parse(buf: &'a [u8], src: &'a mut [Header]) -> Result, ParseHeadersError> { - let mut num_headers: usize = src.len(); - - // SAFETY: src is layout-compatible with phr_header (asserted above). - let rc = unsafe { - c::phr_parse_headers( - buf.as_ptr(), - buf.len(), - src.as_mut_ptr().cast::(), - &raw mut num_headers, - 0, - ) - }; - - match rc { - -1 => Err(ParseHeadersError::BadHeaders), - -2 => Err(ParseHeadersError::ShortRead), - _ => Ok(Headers { - headers: &src[0..num_headers], - }), - } - } -} - impl fmt::Display for Headers<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for header in self.headers { @@ -746,10 +621,3 @@ impl fmt::Display for Headers<'_> { pub use c::phr_chunked_decoder; pub use c::phr_decode_chunked; -pub use c::phr_decode_chunked_is_in_data; -pub use c::phr_header; -pub use c::phr_parse_headers; -pub use c::phr_parse_request; -pub use c::phr_parse_response; -pub use c::struct_phr_chunked_decoder; -pub use c::struct_phr_header; diff --git a/src/runtime/cli/create_command.rs b/src/runtime/cli/create_command.rs index 4422bb0fe7f4..999ba87b65ee 100644 --- a/src/runtime/cli/create_command.rs +++ b/src/runtime/cli/create_command.rs @@ -833,58 +833,8 @@ impl CreateCommand { } } - // const Needs = struct { - // bun_bun_for_nextjs: bool = false, - // bun_macro_relay: bool = false, - // bun_macro_relay_dependency: bool = false, - // bun_framework_next: bool = false, - // react_refresh: bool = false, - // }; - // var needs = Needs{}; - // var has_relay = false; - // var has_bun_framework_next = false; - // var has_react_refresh = false; - // var has_bun_macro_relay = false; - // var has_react = false; - // var has_react_scripts = false; - - // const Prune = struct { - // pub const packages = ComptimeStringMap(void, .{ - // .{ "@parcel/babel-preset", {} }, - // .{ "@parcel/core", {} }, - // .{ "@swc/cli", {} }, - // .{ "@swc/core", {} }, - // .{ "@webpack/cli", {} }, - // .{ "react-scripts", {} }, - // .{ "webpack-cli", {} }, - // .{ "webpack", {} }, - // // one of cosmic config's imports breaks stuff - // .{ "cosmiconfig", {} }, - // }); - // pub var prune_count: u16 = 0; - // - // pub fn prune(list: []js_ast.G.Property) []js_ast.G.Property { - // var i: usize = 0; - // var out_i: usize = 0; - // while (i < list.len) : (i += 1) { - // const key = list[i].key.?.data.e_string.data; - // const do_prune = packages.has(key); - // prune_count += @as(u16, @intCast(@intFromBool(do_prune))); - // if (!do_prune) { - // list[out_i] = list[i]; - // out_i += 1; - // } - // } - // return list[0..out_i]; - // } - // }; - - let mut dev_dependencies: Option = None; - let mut dependencies: Option = None; - if let Some(q) = package_json_expr.as_property(b"devDependencies") { let property = q.expr; - if property.data.is_e_object() && property .data @@ -894,32 +844,12 @@ impl CreateCommand { .len_u32() > 0 { - // unsupported_packages.update(property); - // has_react_scripts = has_react_scripts or property.hasAnyPropertyNamed(&.{"react-scripts"}); - // has_relay = has_relay or property.hasAnyPropertyNamed(&.{ "react-relay", "relay-runtime", "babel-plugin-relay" }); - // property.data.e_object.properties = js_ast.G.Property.List.fromBorrowedSliceDangerous(Prune.prune(property.data.e_object.properties.slice())); - if property - .data - .e_object() - .expect("infallible: variant checked") - .properties - .len_u32() - > 0 - { - has_dependencies = true; - dev_dependencies = Some(q.expr); - - // has_bun_framework_next = has_bun_framework_next or property.hasAnyPropertyNamed(&.{"bun-framework-next"}); - // has_react = has_react or property.hasAnyPropertyNamed(&.{ "react", "react-dom", "react-relay", "@emotion/react" }); - // has_bun_macro_relay = has_bun_macro_relay or property.hasAnyPropertyNamed(&.{"bun-macro-relay"}); - // has_react_refresh = has_react_refresh or property.hasAnyPropertyNamed(&.{"react-refresh"}); - } + has_dependencies = true; } } if let Some(q) = package_json_expr.as_property(b"dependencies") { let property = q.expr; - if property.data.is_e_object() && property .data @@ -929,181 +859,11 @@ impl CreateCommand { .len_u32() > 0 { - // unsupported_packages.update(property); - // has_react_scripts = has_react_scripts or property.hasAnyPropertyNamed(&.{"react-scripts"}); - // has_relay = has_relay or property.hasAnyPropertyNamed(&.{ "react-relay", "relay-runtime", "babel-plugin-relay" }); - // property.data.e_object.properties = js_ast.G.Property.List.fromBorrowedSliceDangerous(Prune.prune(property.data.e_object.properties.slice())); - if property - .data - .e_object() - .expect("infallible: variant checked") - .properties - .len_u32() - > 0 - { - has_dependencies = true; - dependencies = Some(q.expr); - - // if (property.asProperty("next")) |next_q| { - // is_nextjs = true; - // needs.bun_bun_for_nextjs = true; - // next_q.expr.data.e_string.data = @constCast(target_nextjs_version); - // } - // has_bun_framework_next = has_bun_framework_next or property.hasAnyPropertyNamed(&.{"bun-framework-next"}); - // has_react = has_react or is_nextjs or property.hasAnyPropertyNamed(&.{ "react", "react-dom", "react-relay", "@emotion/react" }); - // has_react_refresh = has_react_refresh or property.hasAnyPropertyNamed(&.{"react-refresh"}); - // has_bun_macro_relay = has_bun_macro_relay or property.hasAnyPropertyNamed(&.{"bun-macro-relay"}); - } + has_dependencies = true; } } - let _ = (dev_dependencies, dependencies); - - // needs.bun_macro_relay = !has_bun_macro_relay and has_relay; - // needs.react_refresh = !has_react_refresh and has_react; - // needs.bun_framework_next = is_nextjs and !has_bun_framework_next; - // needs.bun_bun_for_nextjs = is_nextjs; - // needs.bun_macro_relay_dependency = needs.bun_macro_relay; - // var bun_bun_for_react_scripts = false; - // - // var bun_macros_prop: ?js_ast.Expr = null; - // var bun_prop: ?js_ast.Expr = null; - // var bun_relay_prop: ?js_ast.Expr = null; - // - // var needs_bun_prop = needs.bun_macro_relay or has_bun_macro_relay; - // var needs_bun_macros_prop = needs_bun_prop; - // - // if (needs_bun_macros_prop) { - // if (package_json_expr.asProperty("bun")) |bun_| { - // needs_bun_prop = false; - // bun_prop = bun_.expr; - // if (bun_.expr.asProperty("macros")) |macros_q| { - // bun_macros_prop = macros_q.expr; - // needs_bun_macros_prop = false; - // if (macros_q.expr.asProperty("react-relay")) |react_relay_q| { - // bun_relay_prop = react_relay_q.expr; - // needs.bun_macro_relay = react_relay_q.expr.asProperty("graphql") == null; - // } - // if (macros_q.expr.asProperty("babel-plugin-relay/macro")) |react_relay_q| { - // bun_relay_prop = react_relay_q.expr; - // needs.bun_macro_relay = react_relay_q.expr.asProperty("graphql") == null; - // } - // } - // } - // } - // - // if (Prune.prune_count > 0) { - // Output.prettyErrorln("[package.json] Pruned {d} unnecessary packages", .{Prune.prune_count}); - // } - // - // if (create_options.verbose) { - // if (needs.bun_macro_relay) { - // Output.prettyErrorln("[package.json] Detected Relay -> added \"bun-macro-relay\"", .{}); - // } - // if (needs.react_refresh) { - // Output.prettyErrorln("[package.json] Detected React -> added \"react-refresh\"", .{}); - // } - // if (needs.bun_framework_next) { - // Output.prettyErrorln("[package.json] Detected Next -> added \"bun-framework-next\"", .{}); - // } else if (is_nextjs) { - // Output.prettyErrorln("[package.json] Detected Next.js", .{}); - // } - // } - // - // var needs_to_inject_dev_dependency = needs.react_refresh or needs.bun_macro_relay; - // var needs_to_inject_dependency = needs.bun_framework_next; - // - // const dependencies_to_inject_count = @as(usize, @intCast(@intFromBool(needs.bun_framework_next))); - // - // const dev_dependencies_to_inject_count = @as(usize, @intCast(@intFromBool(needs.react_refresh))) + - // @as(usize, @intCast(@intFromBool(needs.bun_macro_relay))); - // - // const new_properties_count = @as(usize, @intCast(@intFromBool(needs_to_inject_dev_dependency and dev_dependencies == null))) + - // @as(usize, @intCast(@intFromBool(needs_to_inject_dependency and dependencies == null))) + - // @as(usize, @intCast(@intFromBool(needs_bun_prop))); - // - // if (new_properties_count != 0) { - // try properties_list.ensureUnusedCapacity(new_properties_count); - // } - - // InjectionPrefill — AST nodes used to inject "bun"/"macros"/dependency - // properties into package.json. Every consumer of it below is - // commented out except `npx_react_scripts_build`, so the module is - // stubbed here with the full structure preserved as a comment for - // reference; if the commented-out injection code is ever revived, the - // statics should be rebuilt on the stack/arena per call rather than as - // mutable statics of non-Sync AST types. mod injection_prefill { - // pub var dependencies_e_string = E.String.init(dependencies_string); - // pub var devDependencies_e_string = E.String.init(dev_dependencies_string); - // pub var bun_e_string = E.String.init(bun_string); - // pub var macros_e_string = E.String.init(macros_string); - // pub var react_relay_string = E.String.init("react-relay"); - // pub var bun_macros_relay_path_string = E.String.init("bun-macro-relay"); - // pub var babel_plugin_relay_macro = E.String.init("babel-plugin-relay/macro"); - // pub var babel_plugin_relay_macro_js = E.String.init("babel-plugin-relay/macro.js"); - // pub var graphql_string = E.String.init("graphql"); - // - // var npx_react_scripts_build_str = E.String.init("npx react-scripts build"); - // pub const npx_react_scripts_build = js_ast.Expr{ .data = .{ .e_string = &npx_react_scripts_build_str }, .loc = logger.Loc.Empty }; - // - // var bun_macro_relay_properties = [_]js_ast.G.Property{ - // js_ast.G.Property{ - // .key = js_ast.Expr{ .data = .{ .e_string = &graphql_string }, .loc = logger.Loc.Empty }, - // .value = js_ast.Expr{ .data = .{ .e_string = &bun_macros_relay_path_string }, .loc = logger.Loc.Empty }, - // }, - // }; - // var bun_macro_relay_object = js_ast.E.Object{ .properties = undefined }; - // - // var bun_macros_relay_object_properties = [_]js_ast.G.Property{ - // .{ .key = Expr{ .e_string = &react_relay_string }, .value = Expr{ .e_object = &bun_macro_relay_object } }, - // .{ .key = Expr{ .e_string = &babel_plugin_relay_macro }, .value = Expr{ .e_object = &bun_macro_relay_object } }, - // .{ .key = Expr{ .e_string = &babel_plugin_relay_macro_js }, .value = Expr{ .e_object = &bun_macro_relay_object } }, - // }; - // pub var bun_macros_relay_object = E.Object{ .properties = undefined }; - // - // var bun_macros_relay_only_object_string = js_ast.E.String.init("macros"); - // pub var bun_macros_relay_only_object_properties = [_]js_ast.G.Property{ - // .{ .key = Expr{ .e_string = &bun_macros_relay_only_object_string }, .value = Expr{ .e_object = &bun_macros_relay_object } }, - // }; - // pub var bun_macros_relay_only_object = E.Object{ .properties = undefined }; - // - // var bun_only_macros_string = js_ast.E.String.init("bun"); - // pub var bun_only_macros_relay_property = js_ast.G.Property{ - // .key = Expr{ .e_string = &bun_only_macros_string }, - // .value = Expr{ .e_object = &bun_macros_relay_only_object }, - // }; - // - // pub var bun_framework_next_string = js_ast.E.String.init("bun-framework-next"); - // pub var bun_framework_next_version = js_ast.E.String.init("latest"); - // pub var bun_framework_next_property = js_ast.G.Property{ - // .key = Expr{ .e_string = &bun_framework_next_string }, - // .value = Expr{ .e_string = &bun_framework_next_version }, - // }; - // - // pub var bun_macro_relay_dependency_string = js_ast.E.String.init("bun-macro-relay"); - // pub var bun_macro_relay_dependency_version = js_ast.E.String.init("latest"); - // pub var bun_macro_relay_dependency = js_ast.G.Property{ - // .key = Expr{ .e_string = &bun_macro_relay_dependency_string }, - // .value = Expr{ .e_string = &bun_macro_relay_dependency_version }, - // }; - // - // pub var refresh_runtime_string = js_ast.E.String.init("react-refresh"); - // pub var refresh_runtime_version = js_ast.E.String.init("0.10.0"); - // pub var react_refresh_dependency = js_ast.G.Property{ - // .key = Expr{ .e_string = &refresh_runtime_string }, - // .value = Expr{ .e_string = &refresh_runtime_version }, - // }; - // - // pub var dev_dependencies_key = js_ast.Expr{ .data = .{ .e_string = &devDependencies_e_string }, .loc = logger.Loc.Empty }; - // pub var dependencies_key = js_ast.Expr{ .data = .{ .e_string = &dependencies_e_string }, .loc = logger.Loc.Empty }; - - // The static objects above were wired together at runtime; that - // wiring only feeds the commented-out injection code below: - // InjectionPrefill.bun_macro_relay_object.properties = ...fromBorrowedSliceDangerous(bun_macro_relay_properties[0..]); - // InjectionPrefill.bun_macros_relay_object.properties = ...fromBorrowedSliceDangerous(&bun_macros_relay_object_properties); - // InjectionPrefill.bun_macros_relay_only_object.properties = ...fromBorrowedSliceDangerous(&bun_macros_relay_only_object_properties); - pub(crate) fn npx_react_scripts_build() -> bun_ast::Expr { bun_ast::Expr::init( bun_ast::E::EString::init(b"npx react-scripts build"), @@ -1112,120 +872,12 @@ impl CreateCommand { } } - // if (needs_to_inject_dev_dependency and dev_dependencies == null) { - // var e_object = try ctx.allocator.create(E.Object); - // e_object.* = E.Object{}; - // const value = js_ast.Expr{ .data = .{ .e_object = e_object }, .loc = logger.Loc.Empty }; - // properties_list.appendAssumeCapacity(js_ast.G.Property{ - // .key = InjectionPrefill.dev_dependencies_key, - // .value = value, - // }); - // dev_dependencies = value; - // } - // - // if (needs_to_inject_dependency and dependencies == null) { - // var e_object = try ctx.allocator.create(E.Object); - // e_object.* = E.Object{}; - // const value = js_ast.Expr{ .data = .{ .e_object = e_object }, .loc = logger.Loc.Empty }; - // properties_list.appendAssumeCapacity(js_ast.G.Property{ - // .key = InjectionPrefill.dependencies_key, - // .value = value, - // }); - // dependencies = value; - // } - - // inject an object like this, handling each permutation of what may or may not exist: - // { - // "bun": { - // "macros": { - // "react-relay": { - // "graphql": "bun-macro-relay" - // } - // } - // } - // } - // bun_section: { - // // "bun.macros.react-relay.graphql" - // if (needs.bun_macro_relay and !needs_bun_prop and !needs_bun_macros_prop) { - // bun_relay_prop.?.data.e_object = InjectionPrefill.bun_macros_relay_object.properties.ptr[0].value.?.data.e_object; - // needs_bun_macros_prop = false; needs_bun_prop = false; needs.bun_macro_relay = false; - // break :bun_section; - // } - // // "bun.macros" - // if (needs_bun_macros_prop and !needs_bun_prop) { - // var obj = bun_prop.?.data.e_object; - // var properties = try std.ArrayList(js_ast.G.Property).initCapacity(ctx.allocator, - // obj.properties.len + InjectionPrefill.bun_macros_relay_object.properties.len); - // defer obj.properties.update(properties); - // try properties.insertSlice(0, obj.properties.slice()); - // try properties.insertSlice(0, InjectionPrefill.bun_macros_relay_object.properties.slice()); - // needs_bun_macros_prop = false; needs_bun_prop = false; needs.bun_macro_relay = false; - // break :bun_section; - // } - // // "bun" - // if (needs_bun_prop) { - // try properties_list.append(InjectionPrefill.bun_only_macros_relay_property); - // needs_bun_macros_prop = false; needs_bun_prop = false; needs.bun_macro_relay = false; - // break :bun_section; - // } - // } - // - // if (needs_to_inject_dependency) { - // defer needs_to_inject_dependency = false; - // var obj = dependencies.?.data.e_object; - // var properties = try std.ArrayList(js_ast.G.Property).initCapacity(ctx.allocator, - // obj.properties.len + dependencies_to_inject_count); - // try properties.insertSlice(0, obj.properties.slice()); - // defer obj.properties.update(properties); - // if (needs.bun_framework_next) { - // properties.appendAssumeCapacity(InjectionPrefill.bun_framework_next_property); - // needs.bun_framework_next = false; - // } - // } - // - // if (needs_to_inject_dev_dependency) { - // defer needs_to_inject_dev_dependency = false; - // var obj = dev_dependencies.?.data.e_object; - // var properties = try std.ArrayList(js_ast.G.Property).initCapacity(ctx.allocator, - // obj.properties.len + dev_dependencies_to_inject_count); - // try properties.insertSlice(0, obj.properties.slice()); - // defer obj.properties.update(properties); - // if (needs.bun_macro_relay_dependency) { - // properties.appendAssumeCapacity(InjectionPrefill.bun_macro_relay_dependency); - // needs.bun_macro_relay_dependency = false; - // } - // if (needs.react_refresh) { - // properties.appendAssumeCapacity(InjectionPrefill.react_refresh_dependency); - // needs.react_refresh = false; - // } - // } - - // this is a little dicey - // The idea is: - // Before the closing tag of Create React App's public/index.html - // Inject "" - // Only do this for create-react-app - // Which we define as: - // 1. has a "public/index.html" - // 2. "react-scripts" in package.json dependencies or devDependencies - // 3. has a src/index.{jsx,tsx,ts,mts,mcjs} - // If at any point those expectations are not matched OR the string /src/index.js already exists in the HTML - // don't do it! - // if (has_react_scripts) { - // bail: { - // // ... (large CRA index.html injection block) - // } - // } - package_json_expr .data .e_object_mut() .expect("infallible: variant checked") .is_single_line = false; - // (See note above; the aliasing round-trip is a no-op while the - // injection appends remain commented out, so `properties` is - // already current.) { use bun_ast::ExprData as LExprData; let mut i: usize = 0; @@ -1340,21 +992,6 @@ impl CreateCommand { let items = tasks.slice(); for task in items { if let Some(task_entry) = task.as_utf8_string_literal() { - // if (needs.bun_bun_for_nextjs or bun_bun_for_react_scripts) { - // var iter = std.mem.splitScalar(u8, task_entry, ' '); - // var last_was_bun = false; - // while (iter.next()) |current| { - // if (strings.eqlComptime(current, "bun")) { - // if (last_was_bun) { - // needs.bun_bun_for_nextjs = false; - // bun_bun_for_react_scripts = false; - // break; - // } - // last_was_bun = true; - // } - // } - // } - postinstall_tasks.push(arena_str(task_entry)); } } diff --git a/src/runtime/cli/repl_command.rs b/src/runtime/cli/repl_command.rs index faf25548c8fd..504026c95dd8 100644 --- a/src/runtime/cli/repl_command.rs +++ b/src/runtime/cli/repl_command.rs @@ -287,8 +287,6 @@ impl<'a, 'r> ReplRunner<'a, 'r> { } } - // SAFETY: transpiler.env is valid. - unsafe { (*vm.transpiler.env).load_tracy() }; Ok(()) } } diff --git a/src/runtime/cli/run_command.rs b/src/runtime/cli/run_command.rs index 1c83beb027c8..d21bbf0379a5 100644 --- a/src/runtime/cli/run_command.rs +++ b/src/runtime/cli/run_command.rs @@ -1067,8 +1067,6 @@ Full documentation is available at https://bun.com/docs/cli/run vm.is_main_thread = true; bun_jsc::virtual_machine::IS_MAIN_THREAD_VM.set(true); - vm.env_loader().load_tracy(); - bun_http::EXPERIMENTAL_HTTP2_CLIENT_FROM_CLI.store( ctx.runtime_options.experimental_http2_fetch, ::core::sync::atomic::Ordering::Relaxed,