Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
37 changes: 37 additions & 0 deletions src/js_parser/react_compiler_host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,15 @@ impl<'a, const TS: bool, const SCAN_ONLY: bool> bun_react_compiler::Host
ref_
}

fn new_local(&mut self, name: &[u8]) -> js_ast::Ref {
let p = &mut *self.p;
let name = p.arena.alloc_slice_copy(name);
let ref_ = p.new_symbol(js_ast::symbol::Kind::Other, name);
// current_scope is the FunctionBody of the function being compiled.
VecExt::append(&mut p.current_scope_mut().generated, ref_);
ref_
}

fn new_import_item(&mut self, name: &[u8]) -> js_ast::Ref {
let p = &mut *self.p;
let name = p.arena.alloc_slice_copy(name);
Expand Down Expand Up @@ -150,6 +159,34 @@ impl<'a, const TS: bool, const SCAN_ONLY: bool> bun_react_compiler::Host
}

impl<'a, const TS: bool, const SCAN_ONLY: bool> P<'a, TS, SCAN_ONLY> {
/// Call when the React Compiler replaced the parameters and the body of the
/// function whose FunctionBody scope is `current_scope`. The new ones declare
/// only symbols from `Host::new_local`, which are in this scope's `generated`.
/// Of the symbols that the parser declared for the old ones, the output still
/// prints `arguments` and `name`: a function expression declares its own name
/// in its FunctionArgs scope. Nothing prints the others. If they stay, the
/// renamer numbers each new local around the old symbol of the same name
/// (`count` prints as `count2`).
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn drop_symbols_of_replaced_function(&mut self, name: Option<js_ast::Ref>) {
let mut body = self.current_scope;
debug_assert!(body.kind == js_ast::scope::Kind::FunctionBody);
body.members = js_ast::scope::Members::EMPTY;
body.children.clear();
if let Some(mut args) = body.parent {
debug_assert!(args.kind == js_ast::scope::Kind::FunctionArgs);
let mut kept = js_ast::scope::Members::EMPTY;
for (key, member) in args.members.iter() {
let kind = self.symbols[member.ref_.inner_index() as usize].kind;
if kind == js_ast::symbol::Kind::Arguments || Some(member.ref_) == name {
// SAFETY: `key` is the key of a member of a live scope.
unsafe { kept.put(key, *member) };
}
}
args.members = kept;
args.children.retain(|child| *child == body);
}
}

/// Sets `react_compiler_may_replace_body` for the visit of the pending candidate. Returns the old value.
pub(crate) fn enter_react_compiler_candidate(
&mut self,
Expand Down
5 changes: 5 additions & 0 deletions src/js_parser/visit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1778,6 +1778,8 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
.binding
.filter(|r| *r != js_ast::Ref::NONE)
.map(|r| p.load_name_from_ref(r));
// `Host::new_local` appends the locals of the compiled function here.
let generated_len = p.current_scope().generated.len();
let compiled = {
let host = &mut crate::react_compiler_host::ReactCompilerHost::new(p);
bun_react_compiler::maybe_compile_pending(
Expand All @@ -1793,6 +1795,9 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
stmts.clear();
stmts.extend(new_body);
p.react_compiler_result = Some(result);
p.drop_symbols_of_replaced_function(pending.binding);
} else {
p.current_scope_mut().generated.truncate(generated_len);
}
}

Expand Down
8 changes: 8 additions & 0 deletions src/react_compiler/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,14 @@ New symbols (`$`, `t0`, `c`, `_c`) are minted via the `Host` trait
implemented by the parser's `P`; the import of `react/compiler-runtime` is
registered via `Host::add_import_record`.

Every local of a compiled function is a new symbol, also one the source
declared. `Host::new_local` registers it in the body scope of that function
(`Scope::generated`), and once the body is replaced the parser drops the
symbols it declared for the old one (all but `arguments` and the own name of a
function expression). The bundler's renamer then numbers the new symbols like
the locals of any other function. `Host::new_generated` is for a name declared
at module level, such as an outlined `_temp`.

### Bail-out semantics

Any `bun_ast` node the port cannot lower (bundler-only synthetics: `ESpecial`,
Expand Down
38 changes: 24 additions & 14 deletions src/react_compiler/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ impl<'h> Codegen<'h> {
}
}

/// The symbol for a name declared at module level ([`Host::new_generated`]).
fn ref_for_name(&mut self, name: StoreStr) -> Ref {
if let Some(&r) = self.name_to_ref.get(&name) {
self.host.record_usage(r);
Expand All @@ -135,12 +136,23 @@ impl<'h> Codegen<'h> {
r
}

/// The symbol for a name the compiled function declares ([`Host::new_local`]).
fn ref_for_local(&mut self, name: StoreStr) -> Ref {
if let Some(&r) = self.name_to_ref.get(&name) {
self.host.record_usage(r);
return r;
}
let r = self.host.new_local(name.slice());
self.name_to_ref.insert(name, r);
r
}

fn well_known(&mut self, w: WellKnown, name: &[u8]) -> Ref {
if let Some(r) = self.well_known[w as usize] {
self.host.record_usage(r);
return r;
}
let r = self.host.new_generated(name);
let r = self.host.new_local(name);
self.well_known[w as usize] = Some(r);
r
}
Expand Down Expand Up @@ -201,7 +213,7 @@ impl<'h> Codegen<'h> {
let mut cursor = std::io::Cursor::new(&mut buf[..]);
write!(cursor, "bb{}", id.0).unwrap();
let len = cursor.position() as usize;
let r = self.host.new_generated(&buf[..len]);
let r = self.host.new_local(&buf[..len]);
self.label_to_ref.insert(id, r);
r
}
Expand Down Expand Up @@ -355,7 +367,13 @@ pub(crate) fn codegen_function(

let identifiers = rename_variables(&mut reactive_fn_mut, cx.env);
let mut outlined_cx = Context::new(cx.env, cx.cg, identifiers);
let codegen = codegen_reactive_function(&mut outlined_cx, &reactive_fn_mut)?;
let mut codegen = codegen_reactive_function(&mut outlined_cx, &reactive_fn_mut)?;
// The declaration is hoisted to module level. The same name gives the
// `Ref` that the `LoadGlobal` at the use site printed.
Comment thread
robobun marked this conversation as resolved.
Resolved
codegen.id = reactive_fn_mut.id.as_ref().map(|name| LocRef {
loc: convert_loc(reactive_fn_mut.loc),
ref_: cx.cg.ref_for_name(store_str(name.as_bytes())),
});
outlined.push(OutlinedFunction {
func: codegen,
#[cfg(any(debug_assertions, bun_asan, feature = "fixtures"))]
Expand Down Expand Up @@ -448,7 +466,7 @@ impl<'a, 'h> Context<'a, 'h> {
return Err(unnamed_identifier_err(id.0));
};
let (IdentifierName::Named(s) | IdentifierName::Promoted(s)) = name;
let r = self.cg.ref_for_name(*s);
let r = self.cg.ref_for_local(*s);
self.cg.id_to_ref.insert(id, r);
Ok(r)
}
Expand Down Expand Up @@ -502,16 +520,8 @@ fn codegen_reactive_function(
let (memo_blocks, memo_values, pruned_memo_blocks, pruned_memo_values) =
count_memo_blocks(func, cx.env);

let id = func.id.as_ref().map(|name| {
let r = cx.cg.ref_for_name(store_str(name.as_bytes()));
LocRef {
loc: convert_loc(func.loc),
ref_: r,
}
});

Ok(CodegenFunction {
id,
id: None,
#[cfg(any(debug_assertions, bun_asan, feature = "fixtures"))]
name_hint: func.name_hint.clone(),
params,
Expand Down Expand Up @@ -2338,7 +2348,7 @@ fn codegen_function_expression(
fn_flags |= flags::Function::HasRestArg;
}
let fn_name = name.as_ref().map(|n| {
let r = cx.cg.ref_for_name(*n);
let r = cx.cg.ref_for_local(*n);
LocRef { loc, ref_: r }
});
Expr::init(
Expand Down
4 changes: 3 additions & 1 deletion src/react_compiler/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,13 +317,15 @@ pub(crate) fn compile_outlined_fn(
let (reactive_fn, unique_identifiers) = run_hir_passes(&mut hir, &mut env, context)?;

let mut cg = Codegen::new(host, arena);
let codegen_result =
let mut codegen_result =
codegen::codegen_function(&reactive_fn, &mut env, &mut cg, context, unique_identifiers)?;

if env.has_errors() {
return Err(env.take_errors());
}

// The `Ref` that the use site in the component printed.
codegen_result.id = codegen_fn.id;
Ok(codegen_result)
}

Expand Down
9 changes: 9 additions & 0 deletions src/react_compiler/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,17 @@ pub trait Host {
/// resolved from the current scope the way the visit pass resolves it.
fn jsx_classic_factory(&mut self, loc: Loc) -> Expr;

/// A new symbol declared at module level: the name of an outlined
/// function, or of a binding the compiler imports.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn new_generated(&mut self, name: &[u8]) -> Ref;

/// A new symbol declared by the function being compiled (or by a function
/// outlined from it): a local, a parameter, a label, or the name of a
/// nested function expression. The host registers it with that function's
/// scope, so the renamer keeps it apart from each top-level name the
/// function reads.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn new_local(&mut self, name: &[u8]) -> Ref;

fn new_import_item(&mut self, name: &[u8]) -> Ref {
self.new_generated(name)
}
Expand Down
7 changes: 7 additions & 0 deletions test/bundler/transpiler/react-compiler-fixtures.test.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading