Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/ast/e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,12 +344,13 @@ pub struct Arrow {
pub has_react_hooks_suppression: bool,
}
// The fourth bool fits in existing trailing padding.
const _: () = assert!(core::mem::size_of::<Arrow>() == 32);
const _: () = assert!(core::mem::size_of::<Arrow>() == 36);
impl Arrow {
pub const NOOP_RETURN_UNDEFINED: Arrow = Arrow {
args: crate::StoreSlice::EMPTY,
body: G::FnBody {
loc: crate::Loc::EMPTY,
close_brace_loc: crate::Loc::EMPTY,
stmts: crate::StoreSlice::EMPTY,
},
is_async: false,
Expand All @@ -364,6 +365,7 @@ impl Default for Arrow {
args: crate::StoreSlice::EMPTY,
body: G::FnBody {
loc: crate::Loc::EMPTY,
close_brace_loc: crate::Loc::EMPTY,
stmts: crate::StoreSlice::EMPTY,
},
is_async: false,
Expand Down
5 changes: 3 additions & 2 deletions src/ast/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1526,8 +1526,8 @@ const _: () = assert!(core::mem::size_of::<E::RequireString>() <= 8);
const _: () = assert!(core::mem::size_of::<E::NewTarget>() <= 8);
const _: () = assert!(core::mem::size_of::<StoreRef<E::Binary>>() == core::mem::size_of::<usize>());
// Heap-payload shrinks unlocked by the 12-byte StoreSlice<T>:
const _: () = assert!(core::mem::size_of::<crate::G::FnBody>() == 16);
const _: () = assert!(core::mem::size_of::<E::Arrow>() <= 32);
const _: () = assert!(core::mem::size_of::<crate::G::FnBody>() == 20);
const _: () = assert!(core::mem::size_of::<E::Arrow>() <= 36);
const _: () = assert!(core::mem::size_of::<crate::S::Block>() == 16);

// Field-style accessors (`data.e_string()`, `data.e_object()`). The match arms
Expand Down Expand Up @@ -2032,6 +2032,7 @@ impl Data {
args: crate::StoreSlice::new(args.into_bump_slice()),
body: G::FnBody {
loc: el.body.loc,
close_brace_loc: el.body.close_brace_loc,
stmts: el.body.stmts,
},
is_async: el.is_async,
Expand Down
6 changes: 6 additions & 0 deletions src/ast/g.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ pub struct Comment {
pub struct ClassStaticBlock {
pub stmts: Vec<Stmt, bun_alloc::AstAlloc>,
pub loc: crate::Loc,
pub close_brace_loc: crate::Loc,
}

pub struct Property {
Expand Down Expand Up @@ -200,6 +201,7 @@ impl Property {
if let Some(csb_ref) = self.class_static_block_ref() {
let new_block: &mut ClassStaticBlock = bump.alloc(ClassStaticBlock {
loc: csb_ref.loc,
close_brace_loc: csb_ref.close_brace_loc,
stmts: bun_alloc::AstAlloc::vec_from_slice(csb_ref.stmts.slice()),
});
class_static_block = Some(crate::StoreRef::from_bump(new_block));
Expand Down Expand Up @@ -245,6 +247,7 @@ pub enum PropertyKind {

pub struct FnBody {
pub loc: crate::Loc,
pub close_brace_loc: crate::Loc,
pub stmts: StmtNodeList,
}

Expand All @@ -259,6 +262,7 @@ impl FnBody {
Ok(FnBody {
stmts: StoreSlice::new_mut(stmts),
loc: expr.loc,
close_brace_loc: crate::Loc::EMPTY,
})
}
}
Expand All @@ -285,6 +289,7 @@ impl Default for Fn {
args: StoreSlice::EMPTY,
body: FnBody {
loc: crate::Loc::EMPTY,
close_brace_loc: crate::Loc::EMPTY,
stmts: StmtNodeList::EMPTY,
},
arguments_ref: Ref::NONE,
Expand All @@ -310,6 +315,7 @@ impl Fn {
args: StoreSlice::new_mut(args),
body: FnBody {
loc: self.body.loc,
close_brace_loc: self.body.close_brace_loc,
stmts: self.body.stmts,
},
arguments_ref: self.arguments_ref,
Expand Down
2 changes: 2 additions & 0 deletions src/ast/nodes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -713,11 +713,13 @@ pub struct Catch {
pub binding: Option<BindingNodeIndex>,
pub body: StmtNodeList,
pub body_loc: crate::Loc,
pub close_brace_loc: crate::Loc,
}

pub struct Finally {
pub loc: crate::Loc,
pub stmts: StmtNodeList,
pub close_brace_loc: crate::Loc,
}

pub struct Case {
Expand Down
2 changes: 2 additions & 0 deletions src/ast/s.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ pub struct With {

pub struct Try {
pub body_loc: crate::Loc,
pub close_brace_loc: crate::Loc,
pub body: StmtNodeList,

pub catch: Option<Catch>, // = None
Expand All @@ -181,6 +182,7 @@ pub struct Try {
pub struct Switch {
pub test: ExprNodeIndex,
pub body_loc: crate::Loc,
pub close_brace_loc: crate::Loc,
pub cases: StoreSlice<Case>, // arena-owned
}

Expand Down
135 changes: 82 additions & 53 deletions src/bundler/LinkerContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1058,16 +1058,24 @@ impl<'a> LinkerContext<'a> {
.expect("TODO: handle error");
}

/// The relative path from the chunk directory to a file source, as written
/// into the source map's `sources` array. `sources` entries are URLs, so the
/// host separator is normalized to `/` (the invariant `Path::pretty` holds).
/// The `sources` entry for a file: its path relative to the chunk directory, URL-escaped like esbuild.
fn source_map_relative_path(
chunk_abs_dir: &[u8],
source_abs_path: &[u8],
) -> Result<Box<[u8]>, AllocError> {
) -> Result<Vec<u8>, AllocError> {
let mut rel = bun_paths::resolve_path::relative_alloc(chunk_abs_dir, source_abs_path)?;
bun_paths::resolve_path::platform_to_posix_in_place::<u8>(&mut rel);
Ok(rel)
let mut url = Vec::with_capacity(rel.len() + 2);
// "a:b.js" would parse as a URL scheme without the "./" (RFC 3986 4.2).
let first_segment = match strings::index_of_char_usize(&rel, b'/') {
Some(i) => &rel[..i],
None => &rel[..],
};
if strings::contains_char(first_segment, b':') {
url.extend_from_slice(b"./");
}
SourceMap::append_url_escaped_path(&mut url, &rel, false);
Ok(url)
}

pub(crate) fn generate_source_map_for_chunk(
Expand Down Expand Up @@ -1097,56 +1105,39 @@ impl<'a> LinkerContext<'a> {
let mut source_id_map: ArrayHashMap<u32, i32> = ArrayHashMap::new();

let source_indices = results.items_source_index();
let null_entries = results.items_is_null_entry();

j.push_static(b"{\n \"version\": 3,\n \"sources\": [");
if !source_indices.is_empty() {
{
let index = source_indices[0];
let path = &sources[index as usize].path;
source_id_map.put_no_clobber(index, 0)?;

// Note: the relative path lives in a local owned buffer
// (drops at scope exit).
let rel_path_storage;
let pretty: &[u8] = if path.is_file() {
rel_path_storage = Self::source_map_relative_path(chunk_abs_dir, path.text)?;
&rel_path_storage
} else {
path.pretty
};

let mut quote_buf = MutableString::init(pretty.len() + 2)?;
js_printer::quote_for_json(pretty, &mut quote_buf, false)?;
// `to_default_owned` moves the buffer into the joiner
// (joiner owns it until `done`).
j.push_owned(quote_buf.to_default_owned());
let mut next_mapping_source_index: i32 = 0;
for (&index, &is_null_entry) in source_indices.iter().zip(null_entries) {
// A null entry has no original position, so no `sources` entry.
if is_null_entry {
continue;
}
let gop = source_id_map.get_or_put(index)?;
if gop.found_existing {
continue;
}

let mut next_mapping_source_index: i32 = 1;
for &index in &source_indices[1..] {
let gop = source_id_map.get_or_put(index)?;
if gop.found_existing {
continue;
}

*gop.value_ptr = next_mapping_source_index;
next_mapping_source_index += 1;
*gop.value_ptr = next_mapping_source_index;
next_mapping_source_index += 1;

let path = &sources[index as usize].path;
let path = &sources[index as usize].path;

let rel_path_storage;
let pretty: &[u8] = if path.is_file() {
rel_path_storage = Self::source_map_relative_path(chunk_abs_dir, path.text)?;
&rel_path_storage
} else {
path.pretty
};
let rel_path_storage;
let pretty: &[u8] = if path.is_file() {
rel_path_storage = Self::source_map_relative_path(chunk_abs_dir, path.text)?;
&rel_path_storage
} else {
path.pretty
};

let mut quote_buf = MutableString::init(pretty.len() + ", ".len() + 2)?;
let mut quote_buf = MutableString::init(pretty.len() + ", ".len() + 2)?;
if *gop.value_ptr != 0 {
quote_buf.append_assume_capacity(b", ");
js_printer::quote_for_json(pretty, &mut quote_buf, false)?;
j.push_owned(quote_buf.to_default_owned());
}
js_printer::quote_for_json(pretty, &mut quote_buf, false)?;
j.push_owned(quote_buf.to_default_owned());
}

j.push_static(b"],\n \"sourcesContent\": [");
Expand Down Expand Up @@ -1174,40 +1165,67 @@ impl<'a> LinkerContext<'a> {
let mapping_start = j.len;
let mut prev_end_state = SourceMapState::default();
let mut prev_column_offset: i32 = 0;
// Each chunk's name indices start at 0; this is the base for the next chunk.
let mut total_names: i32 = 0;
let source_map_chunks = results.items_source_map_chunk();
let offsets = results.items_generated_offset();
debug_assert_eq!(source_map_chunks.len(), offsets.len());
debug_assert_eq!(source_map_chunks.len(), source_indices.len());
for ((chunk, offset), &current_source_index) in source_map_chunks
for (((chunk, offset), &current_source_index), &is_null_entry) in source_map_chunks
.iter()
.zip(offsets.iter())
.zip(source_indices.iter())
.zip(null_entries.iter())
{
let mapping_source_index = *source_id_map
.get(&current_source_index)
.expect("unreachable"); // the pass above during printing of "sources" must add the index
// Only a null entry can lack a `sources` index; its source does not matter.
let mapping_source_index = match source_id_map.get(&current_source_index) {
Some(&index) => index,
None => {
debug_assert!(is_null_entry);
0
}
};

let mut start_state = SourceMapState {
source_index: mapping_source_index,
generated_line: offset.lines.zero_based(),
generated_column: offset.columns.zero_based(),
original_name: total_names,
..Default::default()
};

if offset.lines.zero_based() == 0 {
start_state.generated_column += prev_column_offset;
}

if is_null_entry {
// Lands where the previous mapped file's code ends; only the generated position advances.
SourceMap::append_null_source_map_segment(&mut j, prev_end_state, start_state)?;
prev_end_state.generated_line = start_state.generated_line;
prev_end_state.generated_column = start_state.generated_column;
prev_column_offset = start_state.generated_column;
continue;
}

SourceMap::append_source_map_chunk(
&mut j,
prev_end_state,
start_state,
&chunk.buffer.list,
chunk.first_name_offset,
)?;

let prev_original_name = prev_end_state.original_name;
prev_end_state = chunk.end_state;
prev_end_state.source_index = mapping_source_index;
if chunk.first_name_offset.is_some() {
prev_end_state.original_name += total_names;
} else {
// No names in this chunk: the delta base is still the last name before it.
prev_end_state.original_name = prev_original_name;
}
prev_column_offset = chunk.final_generated_column;
total_names += i32::try_from(chunk.names_count).expect("int cast");

if prev_end_state.generated_line == 0 {
prev_end_state.generated_column += start_state.generated_column;
Expand All @@ -1223,10 +1241,21 @@ impl<'a> LinkerContext<'a> {
write!(&mut buf, "{}", DebugIDFormatter { id: isolated_hash })
.expect("infallible: in-memory write");
j.push_owned(buf.into_boxed_slice());
j.push_static(b"\",\n \"names\": []\n}");
} else {
j.push_static(b"\",\n \"names\": []\n}");
}
j.push_static(b"\",\n \"names\": [");

let mut is_first_name = true;
for chunk in source_map_chunks {
if chunk.quoted_names.is_empty() {
continue;
}
if !is_first_name {
j.push_static(b", ");
}
is_first_name = false;
j.push_static(&chunk.quoted_names);
}
j.push_static(b"]\n}");

let done = j.done()?;
debug_assert!(done[0] == b'{');
Expand Down
1 change: 1 addition & 0 deletions src/bundler/ServerComponentParseTask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,7 @@ fn generate_client_reference_proxy(
body: G::FnBody {
stmts: bun_ast::StoreSlice::new_mut(arrow_body_stmts),
loc: Loc::EMPTY,
close_brace_loc: Loc::EMPTY,
},
..Default::default()
}),
Expand Down
3 changes: 3 additions & 0 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7726,13 +7726,16 @@ pub mod bv2_impl {
pub source_map_chunk: bun_sourcemap::Chunk,
pub generated_offset: bun_sourcemap::LineColumnOffset,
pub source_index: u32,
/// A file with code but no mappings; it gets a 1-field segment where its code starts.
pub is_null_entry: bool,
}

bun_collections::multi_array_columns! {
pub trait CompileResultForSourceMapColumns for CompileResultForSourceMap {
source_map_chunk: bun_sourcemap::Chunk,
generated_offset: bun_sourcemap::LineColumnOffset,
source_index: u32,
is_null_entry: bool,
}
}

Expand Down
8 changes: 8 additions & 0 deletions src/bundler/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ pub use options_impl::PathTemplate;

pub use HTMLImportManifest::html_import_manifest;
pub use bun_core::cheap_prefix_normalizer;

/// `prefix` (the public path or `./`) is written as is; `rel_path` is URL-escaped.
pub(crate) fn append_source_mapping_url_comment(buf: &mut Vec<u8>, prefix: &[u8], rel_path: &[u8]) {
buf.extend_from_slice(b"//# sourceMappingURL=");
buf.extend_from_slice(prefix);
bun_sourcemap::append_url_escaped_path(buf, rel_path, true);
buf.push(b'\n');
}
pub use bundle_v2::{
CompileResult, CompileResultForSourceMap, ContentHasher, EventLoop, ImportTracker, PartRange,
StableRef, WrapKind, generic_path_with_pretty_initialized, target_from_hashbang,
Expand Down
1 change: 1 addition & 0 deletions src/bundler/linker_context/doStep5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,7 @@ impl LinkerContext<'_> {
let fn_body = G::FnBody {
stmts: stmts_eat1!(Stmt::allocate(arena, S::Return { value: Some(value) }, loc,)),
loc,
close_brace_loc: Loc::EMPTY,
};
properties.push(G::Property {
key: Some(Expr::allocate(
Expand Down
Loading
Loading