Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
219 changes: 76 additions & 143 deletions packages/@stylexjs/rust-plugin/Cargo.lock

Large diffs are not rendered by default.

13 changes: 7 additions & 6 deletions packages/@stylexjs/rust-plugin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ stylex_css = { path = "crates/stylex-css" }
stylex_css_parser = { path = "crates/stylex-css-parser" }
stylex_evaluator = { path = "crates/stylex-evaluator" }
stylex_diagnostics = { path = "crates/stylex-diagnostics" }
stylex_utils = { path = "crates/stylex-utils" }
rustc-hash = { workspace = true }
log = { workspace = true }
napi = { version = "3.9.0", default-features = false, features = ["napi8", "serde-json"], optional = true }
Expand Down Expand Up @@ -142,16 +143,16 @@ smallvec = { version = "1.15.1" }
# reason: a recursive walk over a nested expression must not be bounded by the
# thread's stack. Named here so the evaluator can depend on it directly.
stacker = "0.1.24"
swc_compiler_base = { version = "67.0.0" }
swc_config = { version = "6.0.0" }
swc_core = { version = "84.0.3" }
swc_ecma_parser = { version = "47.0.1" }
swc_compiler_base = { version = "68.0.0" }
swc_config = { version = "7.0.0" }
swc_core = { version = "85.1.1" }
swc_ecma_parser = { version = "48.1.0" }
url = "2.5.8"
# The Node addon's global allocator (root `node` feature): mimalloc where SWC's
# own Node bindings use it, the system allocator elsewhere.
swc_malloc = { version = "1.2.5" }
swc_sourcemap = { version = "10.0.2" }
testing = "28.0.1"
swc_sourcemap = { version = "10.0.4" }
testing = "29.0.0"
thiserror = "2.0.18"
# The structural key's hasher. 128-bit output in one pass, where two salted
# `DefaultHasher` states cost two -- see `stylex-utils/src/hash.rs`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use std::{
cell::Cell,
fs,
panic::{self, AssertUnwindSafe, UnwindSafe},
path::Path,
sync::{Arc, Once, OnceLock},
};
use stylex_ast::ast::convertors::{convert_concat_to_tpl_expr, convert_simple_tpl_to_str_expr};
Expand All @@ -25,7 +24,7 @@ use swc_core::{
use crate::{declaration_span::find_declaration_span, state::DiagnosticState};
use stylex_regex::regex::URL_REGEX;
use stylex_state_index::key_span_index::{CallLookup, NamespaceKeyQuery};
use stylex_utils::{hash::stable_hash_wide, swc::syntax_for_file};
use stylex_utils::{hash::stable_hash_wide, swc::module_syntax_for_file};

/// One diagnostic's view of a file: the source map that the frame quotes from,
/// and the handler that draws the caret.
Expand Down Expand Up @@ -883,7 +882,7 @@ fn parse_and_normalize_program(
source_file.clone(),
&code_frame.handler,
EsVersion::EsNext,
syntax_for_file(Path::new(filename)),
module_syntax_for_file(filename),
IsModule::Bool(true),
None,
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ default = []

[dependencies]
anyhow.workspace = true
hstr = "4.0.0"
hstr = "5.1.0"
indexmap.workspace = true
log.workspace = true
rustc-hash.workspace = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -740,6 +740,11 @@ pub struct StateManager {
kept_function_maps: Vec<Rc<FunctionMap>>,
/// Addresses of `kept_function_maps`, so keeping a map is O(1).
kept_function_map_addresses: FxHashSet<usize>,
/// What each theme import resolved to in this transform, by importing file and specifier.
/// Every reference to an imported theme value asks, and each answer costs file-system probes
/// and `package.json` reads (or a host round trip); the answer cannot change while one module
/// compiles.
import_resolutions: std::cell::RefCell<FxHashMap<(String, String), ImportPathResolution>>,
}

impl Default for StateManager {
Expand All @@ -757,6 +762,7 @@ impl StateManager {
evaluation_heap: Rc::default(),
kept_function_maps: Vec::new(),
kept_function_map_addresses: FxHashSet::default(),
import_resolutions: std::cell::RefCell::default(),
input_source_file: None,
imports: ImportState::default(),
existing_import_sources: vec![],
Expand Down Expand Up @@ -1765,6 +1771,23 @@ impl StateManager {
&self,
import_path: &str,
package_json_seen: &mut FxHashMap<String, PackageJsonExtended>,
) -> ImportPathResolution {
let key = (self.get_filename().to_owned(), import_path.to_owned());
if let Some(resolution) = self.import_resolutions.borrow().get(&key) {
return resolution.clone();
}
let resolution = self.resolve_import_path(import_path, package_json_seen);
self
.import_resolutions
.borrow_mut()
.insert(key, resolution.clone());
resolution
}

fn resolve_import_path(
&self,
import_path: &str,
package_json_seen: &mut FxHashMap<String, PackageJsonExtended>,
) -> ImportPathResolution {
let source_file_path = self.get_filename();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -719,3 +719,42 @@ mod file_suffix {
assert!(matches_file_suffix("", ""));
}
}

// Every reference to an imported theme value asks for the import's path; within one transform
// the answer is fixed, so the resolver (file-system probes, or a host round trip) runs once per
// specifier.
#[test]
fn a_theme_import_is_resolved_once_per_transform() {
#[derive(Debug, Default)]
struct Counting(std::cell::Cell<usize>);
impl stylex_structures::import_resolver::ImportResolver for Counting {
fn resolve_theme_import(
&self,
import_path: &str,
_source_file_path: &str,
) -> Result<Option<String>, String> {
self.0.set(self.0.get() + 1);
Ok(Some(format!("/repo/{import_path}")))
}
}
let resolver = std::rc::Rc::new(Counting::default());
let mut state = state_for(
real("/repo/src/app.js"),
CheckModuleResolution::Custom {
theme_file_extension: None,
},
);
state.options.core.import_resolver = Some(resolver.clone());

for _ in 0..3 {
assert!(matches!(
state.import_path_resolver("./vars.stylex.js", &mut FxHashMap::default()),
ImportPathResolution::Resolved { path } if path == "/repo/./vars.stylex.js"
));
}
assert_eq!(resolver.0.get(), 1);

// Another specifier is its own question.
state.import_path_resolver("./other.stylex.js", &mut FxHashMap::default());
assert_eq!(resolver.0.get(), 2);
}
Original file line number Diff line number Diff line change
Expand Up @@ -366,8 +366,23 @@ fn evaluate_partial_object_recursively(
return Box::new(EvaluateResult::refused(result.deopt, None));
}
// `Object.assign(obj, result.value)` upstream (`visitors/parse-stylex-create-arg.js:146`,
// 0.19.0), via the shared spread/assign helpers.
let Some(new_props) = result.value.and_then(spread_own_properties) else {
// 0.19.0), via the shared spread/assign helpers. With a JavaScript host the evaluator
// keeps objects and arrays as typed heap values (identity matters there), so a spread
// of a local constant arrives typed: read its own properties through the same
// materialization the style values use.
let value = match result.value {
Some(
value @ (EvaluateResultValue::Object(_)
| EvaluateResultValue::SharedArray(_)
| EvaluateResultValue::NativeArray(_)
| EvaluateResultValue::Host(_)),
) => match stylex_evaluator::evaluate::materialize_result(&value, traversal_state) {
Ok(Some(expr)) => Some(EvaluateResultValue::Expr(expr)),
_ => None,
},
value => value,
};
let Some(new_props) = value.and_then(spread_own_properties) else {
// No own properties (number, boolean, callback): refuse.
stylex_unimplemented!("{}", SPREAD_NOT_SUPPORTED);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use std::rc::Rc;
use swc_core::{
atoms::Atom,
ecma::{
ast::{Expr, Lit, MemberExpr, ObjectLit, PropOrSpread},
visit::{Visit, noop_visit_type},
ast::{Expr, Lit, MemberExpr, ObjectLit, OptChainBase, OptChainExpr, PropOrSpread},
visit::{Visit, VisitWith, noop_visit_type},
},
};

Expand Down Expand Up @@ -123,6 +123,24 @@ pub(crate) struct MemberTransform<'a> {
impl Visit for MemberTransform<'_> {
noop_visit_type!();

// An optional link (`a?.b`, the `.c` of `a?.b.c`, `a?.b()`) is not a `MemberExpression` to
// Babel, whose visitor here matches only plain member expressions: only the link's object,
// computed key, callee and arguments are walked, as Babel walks them. Counting the link would
// treat a non-style read such as `p?.view` as an unknown style and keep every `null` reset
// after it.
fn visit_opt_chain_expr(&mut self, chain: &OptChainExpr) {
match chain.base.as_ref() {
OptChainBase::Member(member) => {
member.obj.visit_with(self);
member.prop.visit_with(self);
},
OptChainBase::Call(call) => {
call.callee.visit_with(self);
call.args.visit_with(self);
},
}
}

// Don't walk children: a nested member expression would count twice.
fn visit_member_expr(&mut self, member: &MemberExpr) {
member_expression(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -910,6 +910,18 @@ impl Visit for ModuleBindingsCollector {
}
}

/// Records every JSX spread expression of the module with [`StateManager::seed_jsx_spread_expr`].
struct JsxSpreadSeeds<'a>(&'a mut stylex_state::state_manager::StateManager);

impl Visit for JsxSpreadSeeds<'_> {
fn visit_jsx_attr_or_spread(&mut self, attribute: &swc_core::ecma::ast::JSXAttrOrSpread) {
if let swc_core::ecma::ast::JSXAttrOrSpread::SpreadElement(spread) = attribute {
self.0.seed_jsx_spread_expr(spread.expr.as_ref());
}
attribute.visit_children_with(self);
}
}

fn module_root_bindings(module: &Module) -> FxHashSet<Id> {
#[derive(Default)]
struct PatternBindings(FxHashSet<Id>);
Expand Down Expand Up @@ -1106,6 +1118,11 @@ where
/// body. Runtime helpers need `runtime_injection`; hoisted dynamic-style consts always emit.
pub(crate) fn transform_consumers(&mut self, module: &mut Module) {
self.state.cycle = TransformationCycle::TransformConsumers;
// Discovery recorded each JSX spread as written; the producer pass may since have rewritten
// calls inside one (`{...stylex.props(s.a, stylex.defaultMarker())}`), and the consumer pass
// finds a spread by its current shape. Record the current shapes too, so such a spread still
// compiles to static attributes.
module.visit_with(&mut JsxSpreadSeeds(&mut self.state));
module.visit_mut_children_with(self);

let runtime_injection = self.state.options.runtime_injection.is_some();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ radix_fmt.workspace = true
rustc-hash.workspace = true
serde_json.workspace = true
swc_core = { workspace = true, features = ["common", "ecma_ast", "ecma_utils"] }
swc_ecma_parser.workspace = true
swc_ecma_parser = { workspace = true, features = ["flow"] }
xxhash-rust.workspace = true

[dev-dependencies]
Expand Down
29 changes: 28 additions & 1 deletion packages/@stylexjs/rust-plugin/crates/stylex-utils/src/swc.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::path::Path;

use swc_core::ecma::ast::{BinaryOp, Decl, Expr, Lit, OptChainBase, Stmt};
use swc_ecma_parser::{Syntax, TsSyntax};
use swc_ecma_parser::{FlowSyntax, Syntax, TsSyntax};

/// Returns the ESTree node kind of an expression for diagnostics, e.g. `"CallExpression"`.
/// Logical operators, optional chains and `super.x` follow ESTree rather than SWC's node shapes.
Expand Down Expand Up @@ -109,6 +109,33 @@ pub fn syntax_for_file(path: &Path) -> Syntax {
})
}

/// Returns the syntax the compiler parses a module named `filename` with: TypeScript for
/// `.ts`, `.tsx`, `.mts` and `.cts`, Flow with JSX and Flow's runtime syntax for anything else.
/// Passes that parse the module again, such as code frames, must use this so a module that
/// compiled also parses there.
pub fn module_syntax_for_file(filename: &str) -> Syntax {
if [".ts", ".tsx", ".mts", ".cts"]
.iter()
.any(|extension| filename.ends_with(extension))
{
Syntax::Typescript(TsSyntax {
tsx: filename.ends_with(".tsx"),
decorators: true,
..Default::default()
})
} else {
Syntax::Flow(FlowSyntax {
jsx: true,
all: true,
decorators: true,
enums: true,
components: true,
pattern_matching: true,
..Default::default()
})
}
}

/// Whether an angle bracket in a module at `path` may open a JSX element.
fn admits_jsx(path: &Path) -> bool {
!path
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,33 @@ mod file_syntax {
}
}

fn parses_as_module(file: &str, source: &str) -> bool {
let cm: Lrc<SourceMap> = Default::default();
let fm = cm.new_source_file(
Lrc::new(FileName::Custom(file.to_string())),
source.to_string(),
);
let mut parser = Parser::new_from(Lexer::new(
crate::swc::module_syntax_for_file(file),
Default::default(),
StringInput::from(&*fm),
None,
));

parser.parse_module().is_ok() && parser.take_errors().is_empty()
}

#[test]
fn the_compiler_syntax_reads_flow_runtime_syntax_in_javascript() {
let flow = "import typeof T from 'x';\ncomponent C(x: number) { return <div />; }\nconst s = match (x) { 1 => 'a', _ => 'b' };\n";
for file in ["App.js", "App.jsx", "App.mjs", "App.cjs"] {
assert!(parses_as_module(file, flow), "{file} must read Flow");
}
assert!(parses_as_module("styles.ts", TYPESCRIPT_WITHOUT_JSX));
assert!(parses_as_module("App.tsx", JSX));
assert!(!parses_as_module("styles.ts", flow));
}

#[test]
fn every_answer_is_typescript() {
for file in [
Expand Down
1 change: 1 addition & 0 deletions packages/@stylexjs/rust-plugin/scripts/test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const nodeSuites = [
'memo_parameter_identity_current',
'hole_spread_diagnostics_current',
'benchmark_current',
'flow_syntax_current',
];
const cargoTest = [
'cargo',
Expand Down
22 changes: 2 additions & 20 deletions packages/@stylexjs/rust-plugin/src/utils/parser_limits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,11 @@ use swc_ecma_parser::{
error::{Error, SyntaxError},
input::Tokens,
unstable::{Token, TokenAndSpan, TokenFlags, TokenValue},
Context, FlowSyntax, Lexer, PResult, Parser, StringInput, Syntax, SyntaxFlags, TsSyntax,
Context, Lexer, PResult, Parser, StringInput, Syntax, SyntaxFlags,
};

pub(crate) fn syntax_for_filename(filename: &str) -> Syntax {
if [".ts", ".tsx", ".mts", ".cts"]
.iter()
.any(|extension| filename.ends_with(extension))
{
Syntax::Typescript(TsSyntax {
tsx: filename.ends_with(".tsx"),
decorators: true,
..Default::default()
})
} else {
Syntax::Flow(FlowSyntax {
jsx: true,
all: true,
decorators: true,
enums: true,
components: true,
..Default::default()
})
}
stylex_utils::swc::module_syntax_for_file(filename)
}

/// Expressions of any kind on one path, including chains (`a.b().c`, `a + b + c`, casts).
Expand Down
1 change: 1 addition & 0 deletions packages/@stylexjs/rust-plugin/src/utils/parser_modes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ pub(crate) fn supported_syntax(mut syntax: Syntax) -> Syntax {
flow.decorators = true;
flow.enums = true;
flow.components = true;
flow.pattern_matching = true;
}
}
syntax
Expand Down
Loading
Loading