diff --git a/packages/@stylexjs/rust-plugin/Cargo.lock b/packages/@stylexjs/rust-plugin/Cargo.lock index 97e3383a9..cf9c9e71a 100644 --- a/packages/@stylexjs/rust-plugin/Cargo.lock +++ b/packages/@stylexjs/rust-plugin/Cargo.lock @@ -8,18 +8,6 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" -[[package]] -name = "ahash" -version = "0.8.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" -dependencies = [ - "cfg-if", - "once_cell", - "version_check", - "zerocopy", -] - [[package]] name = "aho-corasick" version = "1.1.5" @@ -94,9 +82,9 @@ checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" [[package]] name = "ast_node" -version = "7.0.0" +version = "8.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edf54a7a1bf98e127c22e9e2b9d19619092c74283fdc14e4d67da69780f90db6" +checksum = "34b122e4595000b5d0ffa612edeb5e56a6d5a5df8f348d6a66b328ac25358ef1" dependencies = [ "quote", "swc_macros_common", @@ -127,9 +115,9 @@ dependencies = [ [[package]] name = "better_scoped_tls" -version = "1.0.1" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd228125315b132eed175bf47619ac79b945b26e56b848ba203ae4ea8603609" +checksum = "4a3be58af5656af939642a7953f8f890c7038604bb7c8b79ec787f2d531c9d66" dependencies = [ "scoped-tls", ] @@ -839,9 +827,9 @@ dependencies = [ [[package]] name = "from_variant" -version = "3.0.0" +version = "4.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5ff35a391aef949120a0340d690269b3d9f63460a6106e99bd07b961f345ea9" +checksum = "4bff1743d3da24557b54444a7ac6bb7b5730401a7ce6553d65bfee4665d81cfa" dependencies = [ "swc_macros_common", "syn 2.0.119", @@ -1006,7 +994,6 @@ version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" dependencies = [ - "ahash", "allocator-api2", ] @@ -1053,9 +1040,9 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "hstr" -version = "4.0.3" +version = "5.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b904c58532ecdbf77f46013daec3ecfa9aec83ec17cf4c8053be80a9c1d8d15" +checksum = "931c3fce5dec69eacf7a22bf9f3c7ebf950406b0b0ed942083ddd5af88075cd7" dependencies = [ "hashbrown 0.14.5", "new_debug_unreachable", @@ -1422,23 +1409,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" dependencies = [ "cfg-if", - "miette-derive", "owo-colors", "textwrap", "unicode-width 0.1.14", ] -[[package]] -name = "miette-derive" -version = "7.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "mimalloc" version = "0.1.52" @@ -2378,9 +2353,9 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "string_enum" -version = "1.0.2" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae36a4951ca7bd1cfd991c241584a9824a70f6aff1e7d4f693fb3f2465e4030e" +checksum = "a4a16d4a157a0ad540a3c17dcc5d5c078c58213f095017792db227148d4cb915" dependencies = [ "quote", "swc_macros_common", @@ -2623,6 +2598,7 @@ dependencies = [ "stylex_structures", "stylex_transform", "stylex_types", + "stylex_utils", "swc_core", "swc_ecma_parser", "swc_malloc", @@ -2776,9 +2752,9 @@ dependencies = [ [[package]] name = "swc_allocator" -version = "5.0.1" +version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f2e587c2b183333ba3547a916d180b7caaaa90610f1be5699710837bb635b8a" +checksum = "c95e61d933ac4c44456f38a17b387fcc3f8c7398d3291cfdc360ebb0d1e02616" dependencies = [ "allocator-api2", "bumpalo", @@ -2788,9 +2764,9 @@ dependencies = [ [[package]] name = "swc_atoms" -version = "10.0.1" +version = "11.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50bb5f0ddb3d05cf1d46368de41dd82db7401fdd53f4b8271612be91573308a3" +checksum = "4dc7367819a76b11456cdc06373f393dfb514fd7fb8e10819e17c8592cba9532" dependencies = [ "cbor4ii", "hstr", @@ -2800,9 +2776,9 @@ dependencies = [ [[package]] name = "swc_common" -version = "27.0.0" +version = "28.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1953f0e786c305582e21ef5a093cfe16cfeaa4231f56f780db82e4952b7ef5b2" +checksum = "4362316d2865a917e6f9915cb32fede122761f5c605d559ea380730e591c0e1e" dependencies = [ "anyhow", "ast_node", @@ -2829,9 +2805,9 @@ dependencies = [ [[package]] name = "swc_compiler_base" -version = "67.0.0" +version = "68.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282a86e0d04822c445b00567d4fcdfca4ff9afdd5a428051b07e27237136eb9e" +checksum = "d22484d38b924eefbea53e492f7c6fbc0c7ed97e0f97a629919fc87f35464f48" dependencies = [ "anyhow", "base64", @@ -2854,9 +2830,9 @@ dependencies = [ [[package]] name = "swc_config" -version = "6.0.1" +version = "7.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf6924ef781f1f8af3dfdac9674e94f0ab0c20af6b88b2e116af57b1e755b591" +checksum = "90d3236f524081811d7e6b97d2a515842e8a214b4f39680eecbc8d5a9f285d39" dependencies = [ "anyhow", "bytes-str", @@ -2875,9 +2851,9 @@ dependencies = [ [[package]] name = "swc_config_macro" -version = "1.0.1" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b416e8ce6de17dc5ea496e10c7012b35bbc0e3fef38d2e065eed936490db0b3" +checksum = "41d45cf971042540deca60c09daf6dfad2be616a88291273f16826e592333acb" dependencies = [ "proc-macro2", "quote", @@ -2887,9 +2863,9 @@ dependencies = [ [[package]] name = "swc_core" -version = "84.0.3" +version = "85.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e46e978a10163a1f7dc48174fa003262f8d675a1a87e7c35b2887e273edeb0d" +checksum = "c01e72d102fae0fae1f55acac8bf41604b589606a45fc9dd9acbd927c0668658" dependencies = [ "swc_allocator", "swc_atoms", @@ -2910,9 +2886,9 @@ dependencies = [ [[package]] name = "swc_ecma_ast" -version = "30.0.2" +version = "31.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86bef17958307218ffee375556423bd47a82deb8f6ef8b54bc5a4086958cd1d1" +checksum = "b1d3a9541fb51e6b8112991f219af1d2e23c656a0f1d5343a9f0c10389cdd2dc" dependencies = [ "bitflags", "cbor4ii", @@ -2931,9 +2907,9 @@ dependencies = [ [[package]] name = "swc_ecma_codegen" -version = "33.0.0" +version = "34.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bb171b30bb7f179894e985085be5561cfef4b035a58d4ea51a2310570d4d9bc" +checksum = "65e203a8b3d4c4f082e8bf5b601ed5cc62b8232bfb91a8a73fef6775cf09ec91" dependencies = [ "ascii", "compact_str 0.7.1", @@ -2955,9 +2931,9 @@ dependencies = [ [[package]] name = "swc_ecma_codegen_macros" -version = "2.0.2" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e276dc62c0a2625a560397827989c82a93fd545fcf6f7faec0935a82cc4ddbb8" +checksum = "46745e175b2d544dfeaa689c921f91f29239f4b8d7171cfd3d7da85c598907f1" dependencies = [ "proc-macro2", "swc_macros_common", @@ -2966,9 +2942,9 @@ dependencies = [ [[package]] name = "swc_ecma_hooks" -version = "2.0.0" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af2927f285c88c51f7fed0a07316389ca1311a02761fbd31c0f3d29d53774a1a" +checksum = "e37d534ee2286e0d52b567ce5b6a208b112bcb64e2ec6ea8630ad8d2a016fe64" dependencies = [ "swc_atoms", "swc_common", @@ -2978,9 +2954,9 @@ dependencies = [ [[package]] name = "swc_ecma_minifier" -version = "64.0.4" +version = "65.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6470574261933520880ddc497cfba99b91ddba6ef537003277d49c863d3c67e" +checksum = "6f8d5f87d4612460e1eaa8be027c9999f75400c9e16e6c9803b7c35fbf09dc33" dependencies = [ "arrayvec", "bitflags", @@ -3013,9 +2989,9 @@ dependencies = [ [[package]] name = "swc_ecma_parser" -version = "47.0.1" +version = "48.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2df5fd9367abbe9d4d2db5608df599b1d9f425a690e4ca61b304f7a23961410" +checksum = "1aeb93c8091af3f8347661a835cfb8f2e76d7da25b3e7d8c7341692c4dea6525" dependencies = [ "bitflags", "either", @@ -3034,9 +3010,9 @@ dependencies = [ [[package]] name = "swc_ecma_testing" -version = "28.0.0" +version = "29.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e93e2aa69a4dd8c6e9dd99f335d095421b5d5e1a4bd8798579c5862970b67198" +checksum = "7ae91542fcff9f988df719e86746d2ec52fa852a9f8d2c3745509cc66300cc4f" dependencies = [ "anyhow", "hex", @@ -3047,9 +3023,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_base" -version = "51.0.1" +version = "52.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc5dc7a85486a27483a9eb19737fd91cc31f74409e896ff950df522d5ce6179c" +checksum = "a897146308d1765cbb3759337750ce517729738498b6f8a12c8007a886251e6e" dependencies = [ "better_scoped_tls", "indexmap", @@ -3069,9 +3045,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_optimization" -version = "54.0.1" +version = "55.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64c11dd8ba1393d4636cf4a7cd9697927f06957acdf78f663ccd97129db91245" +checksum = "557cc3efd5c1ea79fbee92a9e29e34c52c45db358cffa575569e6b25aa6f1222" dependencies = [ "bytes-str", "dashmap", @@ -3094,9 +3070,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_react" -version = "57.0.2" +version = "58.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "976dc553655e405a6879d9c2d5977bb76165a7a2ab249d5687768632ffb86c66" +checksum = "90063f7e63001501347e58f79628677206cddadb4434d2e1d0648827eebb9ea6" dependencies = [ "base64", "bytes-str", @@ -3119,9 +3095,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_testing" -version = "55.1.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff7cfb087e85d7fa40ac6070c132b1ce0f71f93b2cb4a9abb4ef2ee354c13ca3" +checksum = "95a229f858fc44fba8c1be4b7865f81af81fc7a569906dff35baa4ae39c251ac" dependencies = [ "ansi_term", "anyhow", @@ -3145,9 +3121,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_typescript" -version = "57.0.3" +version = "58.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ec0a0850a03db3a20d2950f8217f27edab0cab6bf941a4f5d15ec944fab88c2" +checksum = "8f11ef8893bad1cabd307e03bae3bbdc943b390b26fa100f8cf4ba2c562138d0" dependencies = [ "bytes-str", "rustc-hash", @@ -3163,9 +3139,9 @@ dependencies = [ [[package]] name = "swc_ecma_utils" -version = "36.1.0" +version = "37.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b59b32185a6e5dabfc087ab27fbab048f64dfd73e8290aa339a4aaffcb8fb439" +checksum = "b7ff65050ce973959f01dc773b671b2156b154b93f5b0bea60f33a6ec4a3f920" dependencies = [ "dragonbox_ecma", "hashbrown 0.14.5", @@ -3183,9 +3159,9 @@ dependencies = [ [[package]] name = "swc_ecma_visit" -version = "30.0.0" +version = "31.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc14fd3354020d23d7d4bbe37136c01f9887e84f106967e965ea2c03c002b6ea" +checksum = "4136cfa9751a439b5d229b86d1655efb90eee76fb2b718b235ccd8733ed1d7b8" dependencies = [ "new_debug_unreachable", "num-bigint", @@ -3198,9 +3174,9 @@ dependencies = [ [[package]] name = "swc_eq_ignore_macros" -version = "1.0.1" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c16ce73424a6316e95e09065ba6a207eba7765496fed113702278b7711d4b632" +checksum = "9de7905c0881b7f3a0d2385a072e1ebb92b290581680bb9ea6f8f7defb900de5" dependencies = [ "proc-macro2", "quote", @@ -3209,22 +3185,23 @@ dependencies = [ [[package]] name = "swc_error_reporters" -version = "29.0.0" +version = "30.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "363cea95ecf19a832de77ea0e68308cf176a504ad852aff7f5d5cafadc068b27" +checksum = "28974d739223b596742235c26c9d014b461424de97baa2687bf89589ae1e3597" dependencies = [ "anyhow", "miette", "once_cell", "serde", "swc_common", + "unicode-width 0.1.14", ] [[package]] name = "swc_macros_common" -version = "1.0.1" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aae1efbaa74943dc5ad2a2fb16cbd78b77d7e4d63188f3c5b4df2b4dcd2faaae" +checksum = "2012b2e2cbfba9a6ec7c4c8fefbaa01152e08cd4cde61c82b5d898ccaaa81c25" dependencies = [ "proc-macro2", "quote", @@ -3243,18 +3220,18 @@ dependencies = [ [[package]] name = "swc_plugin" -version = "1.0.1" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92b27449420554de6ad8d49004ad3d36e6ac64ecb51d1b0fe1002afcd7a45d85" +checksum = "782016ffa8f2295a9e88275077ce66677f8abfaa7a44aef7400315192393bb29" dependencies = [ "once_cell", ] [[package]] name = "swc_plugin_macro" -version = "2.0.0" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "584f7e74ca311c843d67e143331d9fb17bd5468f6216f3feac0b012d7cc268c0" +checksum = "0049e5d266a0ca8de3d63d039d77019adaa7b508452a182c011dfe81302baae9" dependencies = [ "proc-macro2", "quote", @@ -3263,9 +3240,9 @@ dependencies = [ [[package]] name = "swc_plugin_proxy" -version = "31.0.0" +version = "32.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e831b57ed002a2abeee0bc2f20752ee3302f2b931980e3e5ddfa4f6d9653567" +checksum = "b26ce7263169c34b0f45a887e28a844bc171318e9d83ae5e714c8df06f64a22d" dependencies = [ "better_scoped_tls", "cbor4ii", @@ -3277,9 +3254,9 @@ dependencies = [ [[package]] name = "swc_sourcemap" -version = "10.0.3" +version = "10.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df9ce7c46dc9730284761c88b34d15a8cfbaf40884705f3deec65b9493765ac8" +checksum = "21f150474e1a309c34abef7be75923685428bc4eca455709365cde05c7446072" dependencies = [ "base64-simd", "bitvec", @@ -3296,9 +3273,9 @@ dependencies = [ [[package]] name = "swc_transform_common" -version = "21.0.0" +version = "22.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5e4b5dbedb2078bfec90855e49ffd8cda0c6d78b7f6f8d75c7a765d5de97b58" +checksum = "db0aaa01c5ede4a5d8ed13069a9ce63e3fc2c65fff05b7c52c961bc50b3d7dc3" dependencies = [ "better_scoped_tls", "rustc-hash", @@ -3308,9 +3285,9 @@ dependencies = [ [[package]] name = "swc_visit" -version = "2.0.2" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7df72a1be54e379864cebf04f26abb4d7ee637977f62f8ec8387233f7a27e88" +checksum = "2590162a5acb3a8c1957cbb3fe560e95fae68d1ace8268ca35b644777ba05004" dependencies = [ "either", ] @@ -3378,9 +3355,9 @@ dependencies = [ [[package]] name = "testing" -version = "28.0.1" +version = "29.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b16c4ded13bda542f4c5164c4a39b05377f1a4c0cc342cda0c885108b9008b86" +checksum = "0357f2b1ab1f27548d0a03f1358158eec1b547b64ad46854b5b24ceb33cf28a3" dependencies = [ "cargo_metadata", "difference", @@ -3399,9 +3376,9 @@ dependencies = [ [[package]] name = "testing_macros" -version = "2.0.0" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "971a7561e3787ce2eb1768b900c385e797395037fecc56aadb2ed8230a4ba774" +checksum = "8cd90fd288b2b6d2225ceb2777dfb93849d6d2d2414b06210242eb373fe41caa" dependencies = [ "anyhow", "glob", @@ -3542,18 +3519,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", - "valuable", -] - -[[package]] -name = "tracing-log" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" -dependencies = [ - "log", - "once_cell", - "tracing-core", ] [[package]] @@ -3567,11 +3532,9 @@ dependencies = [ "once_cell", "regex-automata", "sharded-slab", - "smallvec", "thread_local", "tracing", "tracing-core", - "tracing-log", ] [[package]] @@ -3579,10 +3542,6 @@ name = "triomphe" version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d15f4f5898bcfc5d8a8e45ed30b2f108d710c1a2e5489dbf80e078f707181bc" -dependencies = [ - "serde", - "stable_deref_trait", -] [[package]] name = "typenum" @@ -3678,12 +3637,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "valuable" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" - [[package]] name = "value-trait" version = "0.12.1" @@ -4075,26 +4028,6 @@ dependencies = [ "synstructure", ] -[[package]] -name = "zerocopy" -version = "0.8.63" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.63" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "zerofrom" version = "0.1.8" diff --git a/packages/@stylexjs/rust-plugin/Cargo.toml b/packages/@stylexjs/rust-plugin/Cargo.toml index 9d0715447..20d9f4a37 100644 --- a/packages/@stylexjs/rust-plugin/Cargo.toml +++ b/packages/@stylexjs/rust-plugin/Cargo.toml @@ -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 } @@ -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`. diff --git a/packages/@stylexjs/rust-plugin/crates/stylex-diagnostics/src/code_frame.rs b/packages/@stylexjs/rust-plugin/crates/stylex-diagnostics/src/code_frame.rs index f201b9c28..a2fa0ecda 100644 --- a/packages/@stylexjs/rust-plugin/crates/stylex-diagnostics/src/code_frame.rs +++ b/packages/@stylexjs/rust-plugin/crates/stylex-diagnostics/src/code_frame.rs @@ -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}; @@ -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. @@ -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, ); diff --git a/packages/@stylexjs/rust-plugin/crates/stylex-evaluator/Cargo.toml b/packages/@stylexjs/rust-plugin/crates/stylex-evaluator/Cargo.toml index c21cfc76a..87e4cd6a8 100644 --- a/packages/@stylexjs/rust-plugin/crates/stylex-evaluator/Cargo.toml +++ b/packages/@stylexjs/rust-plugin/crates/stylex-evaluator/Cargo.toml @@ -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 diff --git a/packages/@stylexjs/rust-plugin/crates/stylex-state/src/state_manager.rs b/packages/@stylexjs/rust-plugin/crates/stylex-state/src/state_manager.rs index 40ad4db57..b0074ec40 100644 --- a/packages/@stylexjs/rust-plugin/crates/stylex-state/src/state_manager.rs +++ b/packages/@stylexjs/rust-plugin/crates/stylex-state/src/state_manager.rs @@ -740,6 +740,11 @@ pub struct StateManager { kept_function_maps: Vec>, /// Addresses of `kept_function_maps`, so keeping a map is O(1). kept_function_map_addresses: FxHashSet, + /// 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>, } impl Default for StateManager { @@ -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![], @@ -1765,6 +1771,23 @@ impl StateManager { &self, import_path: &str, package_json_seen: &mut FxHashMap, + ) -> 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, ) -> ImportPathResolution { let source_file_path = self.get_filename(); diff --git a/packages/@stylexjs/rust-plugin/crates/stylex-state/src/tests/file_and_options_test.rs b/packages/@stylexjs/rust-plugin/crates/stylex-state/src/tests/file_and_options_test.rs index 55d2704f1..80fedb93b 100644 --- a/packages/@stylexjs/rust-plugin/crates/stylex-state/src/tests/file_and_options_test.rs +++ b/packages/@stylexjs/rust-plugin/crates/stylex-state/src/tests/file_and_options_test.rs @@ -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); + impl stylex_structures::import_resolver::ImportResolver for Counting { + fn resolve_theme_import( + &self, + import_path: &str, + _source_file_path: &str, + ) -> Result, 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); +} diff --git a/packages/@stylexjs/rust-plugin/crates/stylex-transform/src/shared/utils/core/evaluate_stylex_create_arg.rs b/packages/@stylexjs/rust-plugin/crates/stylex-transform/src/shared/utils/core/evaluate_stylex_create_arg.rs index 163b873e6..e353b48ce 100644 --- a/packages/@stylexjs/rust-plugin/crates/stylex-transform/src/shared/utils/core/evaluate_stylex_create_arg.rs +++ b/packages/@stylexjs/rust-plugin/crates/stylex-transform/src/shared/utils/core/evaluate_stylex_create_arg.rs @@ -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); }; diff --git a/packages/@stylexjs/rust-plugin/crates/stylex-transform/src/shared/utils/core/member_expression.rs b/packages/@stylexjs/rust-plugin/crates/stylex-transform/src/shared/utils/core/member_expression.rs index 2620410db..72b4d97be 100644 --- a/packages/@stylexjs/rust-plugin/crates/stylex-transform/src/shared/utils/core/member_expression.rs +++ b/packages/@stylexjs/rust-plugin/crates/stylex-transform/src/shared/utils/core/member_expression.rs @@ -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}, }, }; @@ -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( diff --git a/packages/@stylexjs/rust-plugin/crates/stylex-transform/src/transform/visit_mut/visit_mut_module.rs b/packages/@stylexjs/rust-plugin/crates/stylex-transform/src/transform/visit_mut/visit_mut_module.rs index 87e7b408e..08b669cb8 100644 --- a/packages/@stylexjs/rust-plugin/crates/stylex-transform/src/transform/visit_mut/visit_mut_module.rs +++ b/packages/@stylexjs/rust-plugin/crates/stylex-transform/src/transform/visit_mut/visit_mut_module.rs @@ -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 { #[derive(Default)] struct PatternBindings(FxHashSet); @@ -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(); diff --git a/packages/@stylexjs/rust-plugin/crates/stylex-utils/Cargo.toml b/packages/@stylexjs/rust-plugin/crates/stylex-utils/Cargo.toml index 24410264f..aca0fa1d6 100644 --- a/packages/@stylexjs/rust-plugin/crates/stylex-utils/Cargo.toml +++ b/packages/@stylexjs/rust-plugin/crates/stylex-utils/Cargo.toml @@ -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] diff --git a/packages/@stylexjs/rust-plugin/crates/stylex-utils/src/swc.rs b/packages/@stylexjs/rust-plugin/crates/stylex-utils/src/swc.rs index a8accf1af..79e5e95ef 100644 --- a/packages/@stylexjs/rust-plugin/crates/stylex-utils/src/swc.rs +++ b/packages/@stylexjs/rust-plugin/crates/stylex-utils/src/swc.rs @@ -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. @@ -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 diff --git a/packages/@stylexjs/rust-plugin/crates/stylex-utils/src/tests/swc_test.rs b/packages/@stylexjs/rust-plugin/crates/stylex-utils/src/tests/swc_test.rs index c4214dc3a..bf434de52 100644 --- a/packages/@stylexjs/rust-plugin/crates/stylex-utils/src/tests/swc_test.rs +++ b/packages/@stylexjs/rust-plugin/crates/stylex-utils/src/tests/swc_test.rs @@ -566,6 +566,33 @@ mod file_syntax { } } + fn parses_as_module(file: &str, source: &str) -> bool { + let cm: Lrc = 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
; }\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 [ diff --git a/packages/@stylexjs/rust-plugin/scripts/test.cjs b/packages/@stylexjs/rust-plugin/scripts/test.cjs index f8d39dd04..f00b013b2 100644 --- a/packages/@stylexjs/rust-plugin/scripts/test.cjs +++ b/packages/@stylexjs/rust-plugin/scripts/test.cjs @@ -28,6 +28,7 @@ const nodeSuites = [ 'memo_parameter_identity_current', 'hole_spread_diagnostics_current', 'benchmark_current', + 'flow_syntax_current', ]; const cargoTest = [ 'cargo', diff --git a/packages/@stylexjs/rust-plugin/src/utils/parser_limits.rs b/packages/@stylexjs/rust-plugin/src/utils/parser_limits.rs index 0cfd56efa..8d7e6f11a 100644 --- a/packages/@stylexjs/rust-plugin/src/utils/parser_limits.rs +++ b/packages/@stylexjs/rust-plugin/src/utils/parser_limits.rs @@ -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). diff --git a/packages/@stylexjs/rust-plugin/src/utils/parser_modes.rs b/packages/@stylexjs/rust-plugin/src/utils/parser_modes.rs index fe94aaa98..ce58fbfa1 100644 --- a/packages/@stylexjs/rust-plugin/src/utils/parser_modes.rs +++ b/packages/@stylexjs/rust-plugin/src/utils/parser_modes.rs @@ -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 diff --git a/packages/@stylexjs/rust-plugin/src/utils/source_compare.rs b/packages/@stylexjs/rust-plugin/src/utils/source_compare.rs index ec4170315..aadc2262d 100644 --- a/packages/@stylexjs/rust-plugin/src/utils/source_compare.rs +++ b/packages/@stylexjs/rust-plugin/src/utils/source_compare.rs @@ -83,12 +83,13 @@ where // The comparison below ignores hygiene contexts, which is the same as // clearing them on both sides, so only parentheses need rewriting: in place // on an owned side, on a copy of a borrowed one. - if normalize_actual.parens { - actual.to_mut().visit_mut_with(&mut Normalize); + let renames = normalize_actual.match_subjects || normalize_expected.match_subjects; + if normalize_actual.parens || renames { + actual.to_mut().visit_mut_with(&mut Normalize::default()); } let mut expected = Cow::Borrowed(expected); - if normalize_expected.parens { - expected.to_mut().visit_mut_with(&mut Normalize); + if normalize_expected.parens || renames { + expected.to_mut().visit_mut_with(&mut Normalize::default()); } SyntaxContext::within_ignored_ctxt(|| actual.as_ref().eq_ignore_span(expected.as_ref())) && !contains_nan(actual.as_ref()) @@ -118,14 +119,30 @@ fn contains_nan>(value: &T) -> bool { struct NormalizationNeeded { parens: bool, contexts: bool, + match_subjects: bool, } impl NormalizationNeeded { fn any(&self) -> bool { - self.parens || self.contexts + self.parens || self.contexts || self.match_subjects } } +/// SWC lowers a Flow `match` while parsing, into code that keeps the subject in a constant +/// named after the byte offset of `match` (`__match_subject_`). The same source text +/// parsed at another offset gets another name, so the names are compared by order of +/// appearance instead. +const MATCH_SUBJECT_PREFIX: &str = "__match_subject_"; + +fn is_match_subject(identifier: &Ident) -> bool { + identifier + .sym + .strip_prefix(MATCH_SUBJECT_PREFIX) + .is_some_and(|offset| { + !offset.is_empty() && offset.bytes().all(|byte| byte.is_ascii_digit()) + }) +} + impl Visit for NormalizationNeeded { fn visit_expr(&mut self, expression: &Expr) { if !self.parens { @@ -150,6 +167,11 @@ impl Visit for NormalizationNeeded { fn visit_syntax_context(&mut self, context: &SyntaxContext) { self.contexts |= *context != SyntaxContext::empty(); } + + fn visit_ident(&mut self, identifier: &Ident) { + self.match_subjects |= is_match_subject(identifier); + identifier.visit_children_with(self); + } } fn normalization_needed>(value: &T) -> NormalizationNeeded { @@ -158,13 +180,34 @@ fn normalization_needed>(value: &T) -> Normali visitor } -struct Normalize; +#[derive(Default)] +struct Normalize { + match_subjects: Vec, +} impl VisitMut for Normalize { fn visit_mut_syntax_context(&mut self, context: &mut SyntaxContext) { *context = SyntaxContext::empty(); } + fn visit_mut_ident(&mut self, identifier: &mut Ident) { + if is_match_subject(identifier) { + let ordinal = match self + .match_subjects + .iter() + .position(|name| *name == identifier.sym) + { + Some(ordinal) => ordinal, + None => { + self.match_subjects.push(identifier.sym.clone()); + self.match_subjects.len() - 1 + } + }; + identifier.sym = format!("{MATCH_SUBJECT_PREFIX}{ordinal}").into(); + } + identifier.visit_mut_children_with(self); + } + fn visit_mut_expr(&mut self, expression: &mut Expr) { while matches!(expression, Expr::Paren(_)) { let Expr::Paren(parenthesized) = expression.take() else { diff --git a/packages/@stylexjs/rust-plugin/src/utils/source_edits.rs b/packages/@stylexjs/rust-plugin/src/utils/source_edits.rs index 2a3d49b1f..4e48baf90 100644 --- a/packages/@stylexjs/rust-plugin/src/utils/source_edits.rs +++ b/packages/@stylexjs/rust-plugin/src/utils/source_edits.rs @@ -71,19 +71,34 @@ pub fn source_range(file: &SourceFile, span: Span) -> Result> { /// Prints `transformed` by editing the text of `original`, so untouched source keeps its /// formatting and comments. +// The transform calls the `_with_options` form; the source-preservation suite calls this one. +#[allow(dead_code)] pub fn emit_source_preserving_with_syntax( file: &SourceFile, original: &Module, transformed: &Module, comments: &SingleThreadedComments, grammar: impl Into, +) -> Result { + emit_source_preserving_with_options(file, original, transformed, comments, grammar, true) +} + +/// [`emit_source_preserving_with_syntax`] that builds the source map only when `with_map` is +/// set; `map` is `null` otherwise. +pub fn emit_source_preserving_with_options( + file: &SourceFile, + original: &Module, + transformed: &Module, + comments: &SingleThreadedComments, + grammar: impl Into, + with_map: bool, ) -> Result { let mut grammar = grammar.into(); grammar.syntax = parser_modes::supported_syntax(grammar.syntax); stacker::maybe_grow( parser_limits::PARSER_STACK_RED_ZONE, parser_limits::PARSER_STACK_SIZE, - || source_typed::emit(file, original, transformed, comments, grammar), + || source_typed::emit(file, original, transformed, comments, grammar, with_map), ) } @@ -473,11 +488,12 @@ fn finish_source_output( original_comments: &[Range], mut edits: Vec, grammar: ParseOptions, + with_map: bool, ) -> Result { edits.sort_by_key(|edit| (edit.start, edit.end)); let changes = annotation_changes(file, original, original_comments, &edits); if changes.is_empty() { - let output = apply_source_edits(file, edits)?; + let output = apply_source_edits_with(file, edits, with_map)?; verify_output_typed( &output.code, file, @@ -488,7 +504,7 @@ fn finish_source_output( )?; return Ok(output); } - let first = apply_source_edits(file, edits.clone())?; + let first = apply_source_edits_with(file, edits.clone(), false)?; let map = SourceMap::default(); let parsed_file = map.new_source_file( FileName::Custom(file.name.to_string()).into(), @@ -585,7 +601,7 @@ fn finish_source_output( edits[index].new_text = replacement; } edits.extend(outside); - let output = apply_source_edits(file, edits)?; + let output = apply_source_edits_with(file, edits, with_map)?; verify_output_typed( &output.code, file, @@ -670,8 +686,18 @@ fn verify_output_typed( Ok(()) } pub fn apply_source_edits( + file: &SourceFile, + edits: Vec, +) -> Result { + apply_source_edits_with(file, edits, true) +} + +/// Applies `edits`. Without `with_map`, `map` is `null` and no mapping is computed: the mapping +/// walk visits every character of the file and writes a segment for each. +pub fn apply_source_edits_with( file: &SourceFile, mut edits: Vec, + with_map: bool, ) -> Result { edits.sort_by_key(|edit| (edit.start, edit.end)); let mut previous_end = 0; @@ -688,6 +714,21 @@ pub fn apply_source_edits( } previous_end = edit.end; } + if !with_map { + let mut code = String::with_capacity(file.src.len()); + let mut cursor = 0; + for edit in &edits { + code.push_str(&file.src[cursor..edit.start]); + code.push_str(&edit.new_text); + cursor = edit.end; + } + code.push_str(&file.src[cursor..]); + return Ok(SourcePreservingOutput { + code, + edits, + map: Value::Null, + }); + } // Keep positions only at edit boundaries; identity chunks advance their own. let mut needed = vec![0, file.src.len()]; for edit in &edits { diff --git a/packages/@stylexjs/rust-plugin/src/utils/source_regions.rs b/packages/@stylexjs/rust-plugin/src/utils/source_regions.rs index 7a32b46c3..4a7d1df9b 100644 --- a/packages/@stylexjs/rust-plugin/src/utils/source_regions.rs +++ b/packages/@stylexjs/rust-plugin/src/utils/source_regions.rs @@ -766,7 +766,10 @@ where }; self.before.visit_with(&mut finder); if let Some(range) = finder.found { - let parenthesize = !any_expression_slot || matches!(node, Expr::Seq(_)); + // A primary expression (a name, `this`, a literal) needs no grouping anywhere. + let primary = matches!(node, Expr::Ident(_) | Expr::This(_) | Expr::Lit(_)); + let parenthesize = + !primary && (!any_expression_slot || matches!(node, Expr::Seq(_))); *node = Expr::Ident(self.placeholder(range, parenthesize)); return; } @@ -776,10 +779,50 @@ where fn visit_mut_expr_or_spread(&mut self, node: &mut ExprOrSpread) { self.visit_any_expression_slot(&mut node.expr); } + /// The callee or object of an optional chain link. Parentheses around a reused optional + /// chain there would end the chain early (`(a?.b.map)(f)` throws where `a?.b.map(f)` + /// short-circuits), so reused chain text goes in bare, where it parses back as the same + /// chain. + fn visit_mut_opt_chain_base(&mut self, node: &mut OptChainBase) { + let head = |this: &mut Self, expr: &mut Expr| { + if matches!(expr, Expr::OptChain(_)) { + this.visit_any_expression_slot(expr) + } else { + this.visit_mut_expr(expr) + } + }; + match node { + OptChainBase::Call(call) => { + head(self, &mut call.callee); + call.args.visit_mut_with(self); + call.type_args.visit_mut_with(self); + } + OptChainBase::Member(member) => { + head(self, &mut member.obj); + member.prop.visit_mut_with(self); + } + } + } fn visit_mut_key_value_prop(&mut self, node: &mut KeyValueProp) { node.key.visit_mut_with(self); self.visit_any_expression_slot(&mut node.value); } + fn visit_mut_class_prop(&mut self, node: &mut ClassProp) { + node.key.visit_mut_with(self); + node.decorators.visit_mut_with(self); + node.type_ann.visit_mut_with(self); + if let Some(value) = &mut node.value { + self.visit_any_expression_slot(value); + } + } + fn visit_mut_private_prop(&mut self, node: &mut PrivateProp) { + node.key.visit_mut_with(self); + node.decorators.visit_mut_with(self); + node.type_ann.visit_mut_with(self); + if let Some(value) = &mut node.value { + self.visit_any_expression_slot(value); + } + } fn visit_mut_var_declarator(&mut self, node: &mut VarDeclarator) { node.name.visit_mut_with(self); if let Some(init) = &mut node.init { diff --git a/packages/@stylexjs/rust-plugin/src/utils/source_typed.rs b/packages/@stylexjs/rust-plugin/src/utils/source_typed.rs index c0a785696..0ca040190 100644 --- a/packages/@stylexjs/rust-plugin/src/utils/source_typed.rs +++ b/packages/@stylexjs/rust-plugin/src/utils/source_typed.rs @@ -2,7 +2,8 @@ use super::*; use swc_core::common::{comments::SingleThreadedComments, EqIgnoreSpan, SourceFile, Span, Spanned}; use swc_core::ecma::ast::{ - Decl, Expr, ExprStmt, Lit, Module, ModuleDecl, ModuleItem, Prop, PropOrSpread, Stmt, TsType, + Class, ClassMember, ClassMethod, Constructor, Decl, Expr, ExprStmt, Lit, Module, ModuleDecl, + ModuleItem, PrivateMethod, Prop, PropOrSpread, Stmt, TsType, }; use swc_core::ecma::parser::Syntax; use swc_core::ecma::visit::{Visit, VisitWith}; @@ -181,6 +182,51 @@ impl Visit for TypedAnchors<'_> { } } +/// Looks for a leaf of the modified item that is an anchor of the original item, as +/// [`TypedAnchors`] would record it, without copying the modified item's leaves. +struct TypedAnchorMatch<'a> { + file: &'a SourceFile, + before: &'a HashMap<(u32, u32, &'static str), Vec>, + found: bool, +} +impl TypedAnchorMatch<'_> { + fn check(&mut self, span: Span, kind: &'static str, node: impl FnOnce() -> TypedAnchor) { + if self.found || source_range(self.file, span).is_err() { + return; + } + if let Some(old) = self.before.get(&(span.lo.0, span.hi.0, kind)) { + let node = node(); + self.found = old.iter().any(|old| old.same(&node)); + } + } +} +impl Visit for TypedAnchorMatch<'_> { + fn visit_ident(&mut self, node: &Ident) { + self.check(node.span, "identifier", || TypedAnchor::Ident(node.clone())); + } + fn visit_ident_name(&mut self, node: &IdentName) { + self.check(node.span, "name", || TypedAnchor::Name(node.clone())); + } + fn visit_str(&mut self, node: &Str) { + self.check(node.span, "string", || TypedAnchor::String(node.clone())); + } + fn visit_number(&mut self, node: &Number) { + self.check(node.span, "number", || TypedAnchor::Number(node.clone())); + } + fn visit_big_int(&mut self, node: &BigInt) { + self.check(node.span, "bigint", || TypedAnchor::BigInt(node.clone())); + } + fn visit_bool(&mut self, node: &Bool) { + self.check(node.span, "bool", || TypedAnchor::Bool(*node)); + } + fn visit_null(&mut self, node: &Null) { + self.check(node.span, "null", || TypedAnchor::Null(*node)); + } + fn visit_private_name(&mut self, node: &PrivateName) { + self.check(node.span, "private", || TypedAnchor::Private(node.clone())); + } +} + /// Pairs retained keyword wrappers whose operand is generated or the same authored node. fn keyword_operands<'a, 'b>( before: &'a Expr, @@ -223,6 +269,151 @@ fn arrow_header(arrow: &ArrowExpr) -> ArrowExpr { } } +/// Whether two classes differ only in their members. Compares the header fields in place, so the +/// members are not copied. +fn same_class_header(before: &Class, after: &Class) -> bool { + // Lists every header field, so a new upstream field fails to compile here. + let Class { + span, + ctxt, + decorators, + body, + super_class, + is_abstract, + type_params, + super_type_params, + implements, + } = before; + *span == after.span + && *ctxt == after.ctxt + && body.len() == after.body.len() + && *is_abstract == after.is_abstract + && *decorators == after.decorators + && decorators.eq_ignore_span(&after.decorators) + && *super_class == after.super_class + && super_class.eq_ignore_span(&after.super_class) + && *type_params == after.type_params + && type_params.eq_ignore_span(&after.type_params) + && *super_type_params == after.super_type_params + && super_type_params.eq_ignore_span(&after.super_type_params) + && *implements == after.implements + && implements.eq_ignore_span(&after.implements) +} + +/// Whether two methods differ only in their function bodies. +fn same_method_header(before: &ClassMethod, after: &ClassMethod) -> bool { + let ClassMethod { + span, + key, + function, + kind, + is_static, + accessibility, + is_abstract, + is_optional, + is_override, + } = before; + *span == after.span + && *key == after.key + && key.eq_ignore_span(&after.key) + && *kind == after.kind + && *is_static == after.is_static + && *accessibility == after.accessibility + && *is_abstract == after.is_abstract + && *is_optional == after.is_optional + && *is_override == after.is_override + && same_function_header(function, &after.function) +} + +/// [`same_method_header`] for a `#private` method. +fn same_private_method_header(before: &PrivateMethod, after: &PrivateMethod) -> bool { + let PrivateMethod { + span, + key, + function, + kind, + is_static, + accessibility, + is_abstract, + is_optional, + is_override, + } = before; + *span == after.span + && *key == after.key + && *kind == after.kind + && *is_static == after.is_static + && *accessibility == after.accessibility + && *is_abstract == after.is_abstract + && *is_optional == after.is_optional + && *is_override == after.is_override + && same_function_header(function, &after.function) +} + +/// Whether two constructors differ only in their body statements. +fn same_constructor_header(before: &Constructor, after: &Constructor) -> bool { + let Constructor { + span, + ctxt, + key, + params, + body, + accessibility, + is_optional, + } = before; + *span == after.span + && *ctxt == after.ctxt + && *key == after.key + && *params == after.params + && params.eq_ignore_span(&after.params) + && *accessibility == after.accessibility + && *is_optional == after.is_optional + && matches!((body, &after.body), (Some(old), Some(new)) if old.span == new.span) +} + +/// Whether two class fields differ only in their initializers. +fn same_field_header( + before: &T, + after: &T, + without_value: impl Fn(&mut T), +) -> bool { + let (mut before, mut after) = (before.clone(), after.clone()); + without_value(&mut before); + without_value(&mut after); + before == after && before.eq_ignore_span(&after) +} + +/// Whether two functions differ only in their bodies. Compares the header fields in place, so +/// the body (the whole function, for a component) is not copied at every nesting level. +fn same_function_header(before: &Function, after: &Function) -> bool { + // Lists every header field, so a new upstream field fails to compile here. + let Function { + params, + this_param, + decorators, + span, + ctxt, + body: _, + is_generator, + is_async, + type_params, + return_type, + } = before; + *span == after.span + && *ctxt == after.ctxt + && *is_generator == after.is_generator + && *is_async == after.is_async + && *params == after.params + && params.eq_ignore_span(&after.params) + && *this_param == after.this_param + && this_param.eq_ignore_span(&after.this_param) + && *decorators == after.decorators + && decorators.eq_ignore_span(&after.decorators) + && *type_params == after.type_params + && type_params.eq_ignore_span(&after.type_params) + && *return_type == after.return_type + && return_type.eq_ignore_span(&after.return_type) +} + fn import_literal_only_changed(before: &ImportDecl, after: &ImportDecl) -> bool { if before.src.span.is_dummy() || before.src.span != after.src.span { return false; @@ -239,6 +430,7 @@ pub(super) fn emit( transformed: &Module, comments: &SingleThreadedComments, grammar: ParseOptions, + with_map: bool, ) -> Result { if original.shebang != transformed.shebang { bail!("source-preserving emission cannot rewrite a shebang"); @@ -259,11 +451,20 @@ pub(super) fn emit( grammar: grammar.syntax, comments: &ranges, used_source_roots: HashSet::new(), + assignment_slot: false, }; let before: Vec<_> = original.body.iter().map(Root::Module).collect(); let after: Vec<_> = transformed.body.iter().map(Root::Module).collect(); let edits = planner.list(&before, &after, file.src.len())?; - finish_source_output(file, original, transformed, &ranges, edits, grammar) + finish_source_output( + file, + original, + transformed, + &ranges, + edits, + grammar, + with_map, + ) } struct TypedPlanner<'a> { @@ -273,6 +474,11 @@ struct TypedPlanner<'a> { grammar: Syntax, comments: &'a [Range], used_source_roots: HashSet<(u32, u32, &'static str)>, + /// The next [`Self::expr`] call edits an expression in a slot that takes any assignment + /// expression (an initializer, argument, element, property value, JSX container, + /// conditional branch, assigned value, or a parenthesized, returned or tested expression). + /// A replacement there needs no parentheses unless it is a sequence. + assignment_slot: bool, } impl TypedPlanner<'_> { fn source_prefix(&self) -> &str { @@ -320,10 +526,16 @@ impl TypedPlanner<'_> { let mut values = Vec::new(); for argument in &new[old.len()..] { let code = emit_node(&*argument.expr)?; + // An argument takes any assignment expression; only a sequence needs grouping. + let code = code.trim(); values.push(format!( - "{}({})", + "{}{}", if argument.spread.is_some() { "..." } else { "" }, - code.trim() + if matches!(&*argument.expr, Expr::Seq(_)) { + format!("({code})") + } else { + code.to_owned() + } )); } Ok(vec![TextEdit { @@ -353,7 +565,7 @@ impl TypedPlanner<'_> { } let mut edits = Vec::new(); for (old, new) in before.exprs.iter().zip(&after.exprs) { - edits.extend(self.expr(old, new)?); + edits.extend(self.slot_expr(old, new)?); } for (old, new) in before.quasis.iter().zip(&after.quasis) { if old.raw != new.raw { @@ -535,7 +747,7 @@ impl TypedPlanner<'_> { (JSXAttrOrSpread::SpreadElement(old), JSXAttrOrSpread::SpreadElement(new)) if old.dot3_token == new.dot3_token => { - edits.extend(self.expr(&old.expr, &new.expr)?) + edits.extend(self.slot_expr(&old.expr, &new.expr)?) } (JSXAttrOrSpread::JSXAttr(old), JSXAttrOrSpread::JSXAttr(new)) if old.name == new.name => @@ -546,7 +758,7 @@ impl TypedPlanner<'_> { Some(JSXAttrValue::JSXExprContainer(new)), ) => match (&old.expr, &new.expr) { (JSXExpr::Expr(old), JSXExpr::Expr(new)) => { - edits.extend(self.expr(old, new)?) + edits.extend(self.slot_expr(old, new)?) } _ => bail!("JSX expression kind changed without a source boundary"), }, @@ -627,13 +839,15 @@ impl TypedPlanner<'_> { JSXElementChild::JSXExprContainer(old), JSXElementChild::JSXExprContainer(new), ) if old.span == new.span => match (&old.expr, &new.expr) { - (JSXExpr::Expr(old), JSXExpr::Expr(new)) => edits.extend(self.expr(old, new)?), + (JSXExpr::Expr(old), JSXExpr::Expr(new)) => { + edits.extend(self.slot_expr(old, new)?) + } _ => bail!("JSX child expression kind changed"), }, (JSXElementChild::JSXSpreadChild(old), JSXElementChild::JSXSpreadChild(new)) if old.span == new.span => { - edits.extend(self.expr(&old.expr, &new.expr)?) + edits.extend(self.slot_expr(&old.expr, &new.expr)?) } _ => bail!("JSX child changed without an owned matching lexical container"), } @@ -659,7 +873,13 @@ impl TypedPlanner<'_> { .any(|comment| range.start <= comment.start && comment.end <= range.end) }) } + /// [`Self::expr`] for an expression in an assignment-expression slot. + fn slot_expr(&mut self, before: &Expr, after: &Expr) -> Result> { + self.assignment_slot = true; + self.expr(before, after) + } fn expr(&mut self, before: &Expr, after: &Expr) -> Result> { + let slot = std::mem::take(&mut self.assignment_slot); if before == after && before.eq_ignore_span(after) { return Ok(Vec::new()); } @@ -685,7 +905,7 @@ impl TypedPlanner<'_> { (ArrowFunctionBody::Expr(old), ArrowFunctionBody::Expr(new)) => { self.expr(old, new) } - _ => self.legacy_expr(before, after), + _ => self.legacy_expr(before, after, slot), } } (Expr::Fn(old), Expr::Fn(new)) @@ -719,7 +939,7 @@ impl TypedPlanner<'_> { // Rewrites only the argument, keeping separators and comments. let mut edits = Vec::new(); for (old, new) in old.args.iter().zip(&new.args) { - edits.extend(self.expr(&old.expr, &new.expr)?); + edits.extend(self.slot_expr(&old.expr, &new.expr)?); } Ok(edits) } @@ -743,7 +963,7 @@ impl TypedPlanner<'_> { { self.append_arguments(old.span, &old.args, &new.args) } - _ => self.legacy_expr(before, after), + _ => self.legacy_expr(before, after, slot), } } (Expr::Array(before), Expr::Array(after)) @@ -754,19 +974,44 @@ impl TypedPlanner<'_> { match (old, new) { (None, None) => {} (Some(old), Some(new)) if old.spread == new.spread => { - edits.extend(self.expr(&old.expr, &new.expr)?) + edits.extend(self.slot_expr(&old.expr, &new.expr)?) } _ => { return self.legacy_expr( &Expr::Array(before.clone()), &Expr::Array(after.clone()), + slot, ) } } } Ok(edits) } - (Expr::Paren(before), Expr::Paren(after)) => self.expr(&before.expr, &after.expr), + (Expr::Paren(before), Expr::Paren(after)) => self.slot_expr(&before.expr, &after.expr), + // Operators keep their source text and edit each operand, so comments between + // operands stay where they are. A replaced operand is parenthesized + // (`legacy_expr`), so precedence cannot change. + (Expr::Cond(old), Expr::Cond(new)) if !old.span.is_dummy() && old.span == new.span => { + let mut edits = self.expr(&old.test, &new.test)?; + edits.extend(self.slot_expr(&old.cons, &new.cons)?); + edits.extend(self.slot_expr(&old.alt, &new.alt)?); + Ok(edits) + } + (Expr::Bin(old), Expr::Bin(new)) + if !old.span.is_dummy() && old.span == new.span && old.op == new.op => + { + let mut edits = self.expr(&old.left, &new.left)?; + edits.extend(self.expr(&old.right, &new.right)?); + Ok(edits) + } + (Expr::Assign(old), Expr::Assign(new)) + if !old.span.is_dummy() + && old.span == new.span + && old.op == new.op + && old.left == new.left => + { + self.slot_expr(&old.right, &new.right) + } (Expr::TsAs(before), Expr::TsAs(after)) if before.type_ann == after.type_ann => { self.expr(&before.expr, &after.expr) } @@ -789,13 +1034,18 @@ impl TypedPlanner<'_> { (Prop::KeyValue(old), Prop::KeyValue(new)) if old.key == new.key => { - edits.extend(self.expr(&old.value, &new.value)?) + edits.extend(self.slot_expr(&old.value, &new.value)?) + } + // A method edits its body, like a function declaration. + (Prop::Method(old), Prop::Method(new)) if old.key == new.key => { + edits.extend(self.function_body(&old.function, &new.function)?) } _ if old == new => {} _ => { return self.legacy_expr( &Expr::Object(before.clone()), &Expr::Object(after.clone()), + slot, ) } } @@ -805,26 +1055,31 @@ impl TypedPlanner<'_> { return self.legacy_expr( &Expr::Object(before.clone()), &Expr::Object(after.clone()), + slot, ) } } } Ok(edits) } - _ => self.legacy_expr(before, after), + _ => self.legacy_expr(before, after, slot), } } - fn legacy_expr(&mut self, before: &Expr, after: &Expr) -> Result> { + fn legacy_expr(&mut self, before: &Expr, after: &Expr, slot: bool) -> Result> { let range = source_range(self.file, before.span())?; let region = emit_region_from_source_cached(self.source_prefix(), self.file, before, after)?; - let code = retain_expression_comments( - self.file, - self.comments, - &range, - ®ion.reused, - format!("({})", region.code.trim()), - )?; + let code = region.code.trim(); + // Elsewhere the replacement's precedence may differ from the original's, so it is + // grouped. Babel prints no such parentheses, and minifiers keep them around functions + // as an eager-compile hint. + let code = if slot && !matches!(after, Expr::Seq(_)) { + code.to_owned() + } else { + format!("({code})") + }; + let code = + retain_expression_comments(self.file, self.comments, &range, ®ion.reused, code)?; Ok(vec![TextEdit { start: range.start, end: range.end, @@ -901,6 +1156,24 @@ impl TypedPlanner<'_> { Root::Module(ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(old))), Root::Module(ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(new))), ) => self.decl(&old.decl, &new.decl), + ( + Root::Module(ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(old))), + Root::Module(ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(new))), + ) => match (&old.decl, &new.decl) { + // `export default function` edits its body statement by statement, as a + // function declaration does, so comments between statements stay in place. + (DefaultDecl::Fn(old), DefaultDecl::Fn(new)) if old.ident == new.ident => { + self.function_body(&old.function, &new.function) + } + // `export default class` edits member by member, as a class declaration does. + (DefaultDecl::Class(old), DefaultDecl::Class(new)) if old.ident == new.ident => { + match self.class_members(&old.class, &new.class)? { + Some(edits) => Ok(edits), + None => self.typed_root_region(before, after), + } + } + _ => self.typed_root_region(before, after), + }, ( Root::Module(ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(old))), Root::Module(ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(new))), @@ -909,10 +1182,70 @@ impl TypedPlanner<'_> { (Some(Stmt::Decl(old)), Some(Stmt::Decl(new))) => self.decl(old, new), (Some(Stmt::Expr(old)), Some(Stmt::Expr(new))) => self.expr(&old.expr, &new.expr), (Some(Stmt::Return(old)), Some(Stmt::Return(new))) => match (&old.arg, &new.arg) { - (Some(old), Some(new)) => self.expr(old, new), + (Some(old), Some(new)) => self.slot_expr(old, new), _ => self.typed_root_region(before, after), }, - (Some(Stmt::Throw(old)), Some(Stmt::Throw(new))) => self.expr(&old.arg, &new.arg), + (Some(Stmt::Throw(old)), Some(Stmt::Throw(new))) => { + self.slot_expr(&old.arg, &new.arg) + } + (Some(Stmt::If(old)), Some(Stmt::If(new))) + if old.span == new.span && old.alt.is_some() == new.alt.is_some() => + { + let mut edits = self.slot_expr(&old.test, &new.test)?; + edits + .extend(self.root(Root::Statement(&old.cons), Root::Statement(&new.cons))?); + if let (Some(old), Some(new)) = (&old.alt, &new.alt) { + edits.extend(self.root(Root::Statement(old), Root::Statement(new))?); + } + Ok(edits) + } + (Some(Stmt::Switch(old)), Some(Stmt::Switch(new))) + if old.span == new.span + && old.cases.len() == new.cases.len() + && old.cases.iter().zip(&new.cases).all(|(old, new)| { + old.span == new.span && old.test.is_some() == new.test.is_some() + }) => + { + let mut edits = self.slot_expr(&old.discriminant, &new.discriminant)?; + for (old, new) in old.cases.iter().zip(&new.cases) { + if let (Some(old), Some(new)) = (&old.test, &new.test) { + edits.extend(self.slot_expr(old, new)?); + } + edits.extend(self.list( + &old.cons.iter().map(Root::Statement).collect::>(), + &new.cons.iter().map(Root::Statement).collect::>(), + source_range(self.file, old.span)?.end, + )?); + } + Ok(edits) + } + // Loops whose header is unchanged edit only their body. + (Some(Stmt::For(old)), Some(Stmt::For(new))) + if old.span == new.span + && old.init == new.init + && old.test == new.test + && old.update == new.update => + { + self.root(Root::Statement(&old.body), Root::Statement(&new.body)) + } + (Some(Stmt::ForOf(old)), Some(Stmt::ForOf(new))) + if old.span == new.span + && old.is_await == new.is_await + && old.left == new.left + && old.right == new.right => + { + self.root(Root::Statement(&old.body), Root::Statement(&new.body)) + } + (Some(Stmt::ForIn(old)), Some(Stmt::ForIn(new))) + if old.span == new.span && old.left == new.left && old.right == new.right => + { + self.root(Root::Statement(&old.body), Root::Statement(&new.body)) + } + (Some(Stmt::While(old)), Some(Stmt::While(new))) + if old.span == new.span && old.test == new.test => + { + self.root(Root::Statement(&old.body), Root::Statement(&new.body)) + } (Some(Stmt::Block(old)), Some(Stmt::Block(new))) if old.ctxt == new.ctxt => self .list( &old.stmts.iter().map(Root::Statement).collect::>(), @@ -924,11 +1257,7 @@ impl TypedPlanner<'_> { } } fn function_body(&mut self, before: &Function, after: &Function) -> Result> { - let mut old_header = before.clone(); - old_header.body = None; - let mut new_header = after.clone(); - new_header.body = None; - if old_header != new_header || !old_header.eq_ignore_span(&new_header) { + if !same_function_header(before, after) { bail!("source preserving emission cannot rewrite an unsupported function header"); } match (&before.body, &after.body) { @@ -937,6 +1266,72 @@ impl TypedPlanner<'_> { _ => bail!("source preserving emission cannot replace a function body without a retained source container"), } } + /// Edits a class member by member, so a change inside one method keeps the rest of the class, + /// its formatting and its comments in place. `None` when a header or a member's shape changed + /// and the class has to be printed as a whole. + fn class_members(&mut self, before: &Class, after: &Class) -> Result>> { + if !same_class_header(before, after) { + return Ok(None); + } + let mut edits = Vec::new(); + for (old, new) in before.body.iter().zip(&after.body) { + if old == new { + continue; + } + match (old, new) { + (ClassMember::Method(old), ClassMember::Method(new)) + if same_method_header(old, new) => + { + edits.extend(self.function_body(&old.function, &new.function)?); + } + (ClassMember::PrivateMethod(old), ClassMember::PrivateMethod(new)) + if same_private_method_header(old, new) => + { + edits.extend(self.function_body(&old.function, &new.function)?); + } + (ClassMember::Constructor(old), ClassMember::Constructor(new)) + if same_constructor_header(old, new) => + { + let (Some(old_body), Some(new_body)) = (&old.body, &new.body) else { + return Ok(None); + }; + edits.extend( + self.list( + &old_body + .stmts + .iter() + .map(Root::Statement) + .collect::>(), + &new_body + .stmts + .iter() + .map(Root::Statement) + .collect::>(), + source_range(self.file, old_body.span)?.end - 1, + )?, + ); + } + (ClassMember::ClassProp(old), ClassMember::ClassProp(new)) + if same_field_header(old, new, |prop| prop.value = None) => + { + match (&old.value, &new.value) { + (Some(old), Some(new)) => edits.extend(self.slot_expr(old, new)?), + _ => return Ok(None), + } + } + (ClassMember::PrivateProp(old), ClassMember::PrivateProp(new)) + if same_field_header(old, new, |prop| prop.value = None) => + { + match (&old.value, &new.value) { + (Some(old), Some(new)) => edits.extend(self.slot_expr(old, new)?), + _ => return Ok(None), + } + } + _ => return Ok(None), + } + } + Ok(Some(edits)) + } fn typed_decl_region(&mut self, before: &Decl, after: &Decl) -> Result> { let range = source_range(self.file, before.span())?; let region = @@ -966,6 +1361,14 @@ impl TypedPlanner<'_> { { self.function_body(&old.function, &new.function) } + (Decl::Class(old), Decl::Class(new)) + if old.ident == new.ident && old.declare == new.declare => + { + match self.class_members(&old.class, &new.class)? { + Some(edits) => Ok(edits), + None => self.typed_decl_region(before, after), + } + } (Decl::Var(old), Decl::Var(new)) if old.kind == new.kind && old.declare == new.declare @@ -980,7 +1383,7 @@ impl TypedPlanner<'_> { let mut edits = Vec::new(); for (old, new) in old.decls.iter().zip(&new.decls) { match (&old.init, &new.init) { - (Some(old), Some(new)) => edits.extend(self.expr(old, new)?), + (Some(old), Some(new)) => edits.extend(self.slot_expr(old, new)?), (None, None) => {} _ => return self.typed_decl_region(before, after), } @@ -990,10 +1393,8 @@ impl TypedPlanner<'_> { _ => self.typed_decl_region(before, after), } } + /// Whether a modified list item (`!before.same(after)`) still owns its original's source. fn provenance(&self, before: Root<'_>, after: Root<'_>) -> Result { - if before.same(after) { - return Ok(true); - } if let ( Root::Module(ModuleItem::ModuleDecl(ModuleDecl::Import(old))), Root::Module(ModuleItem::ModuleDecl(ModuleDecl::Import(new))), @@ -1054,15 +1455,13 @@ impl TypedPlanner<'_> { // Anchors are typed source-owned leaves, not coincident spans. let mut before_anchors = TypedAnchors::new(self.file); before.visit(&mut before_anchors); - let mut after_anchors = TypedAnchors::new(self.file); - after.visit(&mut after_anchors); - Ok(after_anchors.nodes.iter().any(|(key, nodes)| { - before_anchors.nodes.get(key).is_some_and(|old| { - nodes - .iter() - .any(|node| old.iter().any(|old| old.same(node))) - }) - })) + let mut matcher = TypedAnchorMatch { + file: self.file, + before: &before_anchors.nodes, + found: false, + }; + after.visit(&mut matcher); + Ok(matcher.found) } fn statement_range(&self, root: Root<'_>, limit: usize) -> Result> { let mut range = source_range(self.file, root.span())?; @@ -1121,6 +1520,9 @@ impl TypedPlanner<'_> { } } let mut matched = Vec::new(); + // Whether each matched item is its original unchanged, compared once here: the + // comparison walks the whole item, and an unchanged item needs no edit. + let mut unchanged = Vec::new(); let mut previous = None; for item in after { let span = item.span(); @@ -1131,7 +1533,8 @@ impl TypedPlanner<'_> { let index = *roots .get(&(span.lo.0, span.hi.0, item.kind())) .context("new list item has an untrusted snippet span; mark its root DUMMY_SP")?; - if !self.provenance(before[index], *item)? { + let same = before[index].same(*item); + if !same && !self.provenance(before[index], *item)? { bail!("ambiguous modified list-item provenance at {:?}; numeric snippet spans are not origins",span) } let key = (span.lo.0, span.hi.0, item.kind()); @@ -1144,7 +1547,8 @@ impl TypedPlanner<'_> { bail!("source-preserving emission does not reorder original statements/attributes") } previous = Some(index); - matched.push(Some(index)) + matched.push(Some(index)); + unchanged.push(same); } let directive_count = before .iter() @@ -1222,13 +1626,16 @@ impl TypedPlanner<'_> { } } let mut pending = Vec::new(); + let mut unchanged = unchanged.into_iter(); for (item, matched) in after.iter().zip(matched) { if let Some(i) = matched { if !pending.is_empty() { edits.push(self.insert(ranges[i].start, &pending)?); pending.clear() } - edits.extend(self.root(before[i], *item)?) + if unchanged.next() != Some(true) { + edits.extend(self.root(before[i], *item)?) + } } else { pending.push(*item) } @@ -1312,6 +1719,7 @@ mod tests { &changed, &parsed.comments, parsed.syntax.into(), + true, ) .unwrap(); assert!(output.code.contains("generated")); @@ -1323,6 +1731,7 @@ mod tests { &parsed.module, &parsed.comments, parsed.syntax.into(), + true, ) .unwrap(); assert_eq!(super::super::source_regions::prefix_scans(), scans); @@ -1345,6 +1754,7 @@ mod tests { &transformed, &parsed.comments, parsed.syntax.into(), + true, ) .unwrap_err(); assert!(error.to_string().contains("provenance"), "{error}"); @@ -1364,7 +1774,7 @@ mod tests { let original_range=source_range(&parsed.file,import.src.span).unwrap(); import.src.value="./theme/tokens.stylex".into(); import.src.raw=None; - let output=emit(&parsed.file,&parsed.module,&transformed,&parsed.comments,parsed.syntax.into()).unwrap(); + let output=emit(&parsed.file,&parsed.module,&transformed,&parsed.comments,parsed.syntax.into(),true).unwrap(); let expected=format!("{}\"./theme/tokens.stylex\"{}",&source[..original_range.start],&source[original_range.end..]); assert_eq!(output.code,expected); assert_eq!(output.edits.len(),1); @@ -1455,6 +1865,7 @@ mod tests { &transformed, &parsed.comments, parsed.syntax.into(), + true, ) .unwrap(); assert!(output.code.starts_with("import stylex from 'stylex';")); @@ -1495,6 +1906,7 @@ mod tests { &transformed, &parsed.comments, parsed.syntax.into(), + true, ) .unwrap(); assert!(output @@ -1517,6 +1929,7 @@ mod tests { &transformed, &parsed.comments, parsed.syntax.into(), + true, ) .unwrap_err(); assert!(error.to_string().contains("provenance")); diff --git a/packages/@stylexjs/rust-plugin/src/utils/transform/mod.rs b/packages/@stylexjs/rust-plugin/src/utils/transform/mod.rs index 46dc2f6ad..f0599d459 100644 --- a/packages/@stylexjs/rust-plugin/src/utils/transform/mod.rs +++ b/packages/@stylexjs/rust-plugin/src/utils/transform/mod.rs @@ -518,19 +518,19 @@ fn transform_on_stack( rewrite_alias_imports(&mut parsed.module, filename, rewriter)?; } - let emitted = emit_module_with_origins(&parsed, &original_module)?; + let input_map = options + .additional_options + .get("inputSourceMap") + .filter(|map| map.is_object()); + let maps = options.bool_option("sourceMaps", false); + // The map costs a pass over every character; build it only when it is returned or + // composed. + let emitted = + emit_module_with_origins(&parsed, &original_module, maps || input_map.is_some())?; // A map from an earlier transform of this file composes with ours, so // the result maps to the original source. - let emitted = render::compose_input_source_map( - emitted, - options - .additional_options - .get("inputSourceMap") - .filter(|map| map.is_object()), - )?; - let source_map = options - .bool_option("sourceMaps", false) - .then_some(emitted.map); + let emitted = render::compose_input_source_map(emitted, input_map)?; + let source_map = maps.then_some(emitted.map); Ok(TransformOutput { code: emitted.code, metadata_stylex, diff --git a/packages/@stylexjs/rust-plugin/src/utils/transform/render.rs b/packages/@stylexjs/rust-plugin/src/utils/transform/render.rs index 849f8d828..c3b06885e 100644 --- a/packages/@stylexjs/rust-plugin/src/utils/transform/render.rs +++ b/packages/@stylexjs/rust-plugin/src/utils/transform/render.rs @@ -28,8 +28,9 @@ pub(super) fn emit_verbatim( pub(super) fn emit_module_with_origins( parsed: &ParsedModule, original: &Module, + with_map: bool, ) -> Result { - source_edits::emit_source_preserving_with_syntax( + source_edits::emit_source_preserving_with_options( &parsed.file, original, &parsed.module, @@ -38,6 +39,7 @@ pub(super) fn emit_module_with_origins( syntax: parsed.syntax, source_type: parsed.source_type, }, + with_map, ) } diff --git a/packages/@stylexjs/rust-plugin/src/utils/transform/render_tests.rs b/packages/@stylexjs/rust-plugin/src/utils/transform/render_tests.rs index 80175289b..a8e645585 100644 --- a/packages/@stylexjs/rust-plugin/src/utils/transform/render_tests.rs +++ b/packages/@stylexjs/rust-plugin/src/utils/transform/render_tests.rs @@ -339,7 +339,7 @@ fn actual_public_core_dynamic_binary_expressions_reproduce_the_transformed_ast() core.state.set_input_source_file(parsed.file.clone()); parsed.module.visit_mut_with(&mut core); drop(core); - let output = emit_module_with_origins(&parsed, &original).unwrap(); + let output = emit_module_with_origins(&parsed, &original, true).unwrap(); assert!(!output.code.contains("stylex.create")); assert!(output.code.contains("width+100") || output.code.contains("width + 100")); }); diff --git a/packages/@stylexjs/rust-plugin/tests/creation_current.rs b/packages/@stylexjs/rust-plugin/tests/creation_current.rs index ebd8a287a..9a744819d 100644 --- a/packages/@stylexjs/rust-plugin/tests/creation_current.rs +++ b/packages/@stylexjs/rust-plugin/tests/creation_current.rs @@ -436,6 +436,15 @@ fn creation_current_dynamic_null_undefined_and_parameter_identity() { "import * as stylex from '@stylexjs/stylex'; export const styles=stylex.create({root:(value)=>({opacity:value>0,width:value||0,height:value&&1})});", ] { differential(source, "/tmp/creation-current/app.js", json!({})); } } +// With a host the evaluator keeps a local object as a typed heap value; a spread of it inside a +// dynamic style must still read its own properties, as Babel's `Object.assign` does. +#[test] +fn creation_current_dynamic_style_spreads_a_local_constant_with_a_host() { + for source in [ + "import * as stylex from '@stylexjs/stylex'; const base={'--text-size':'12px',color:'red'}; export const styles=stylex.create({popup:(width)=>({...base,width})});", + "import * as stylex from '@stylexjs/stylex'; const base={color:'red'}; export const styles=stylex.create({root:{...base,width:'100%'},popup:(width)=>({...base,margin:'-1px',width})});", + ] { differential(source, "/tmp/creation-current/app.js", json!({})); } +} #[test] fn creation_current_dynamic_complete_units_class_paths_and_pseudo_inheritance() { for source in [ diff --git a/packages/@stylexjs/rust-plugin/tests/emitter_current.rs b/packages/@stylexjs/rust-plugin/tests/emitter_current.rs new file mode 100644 index 000000000..2ecd1d0d6 --- /dev/null +++ b/packages/@stylexjs/rust-plugin/tests/emitter_current.rs @@ -0,0 +1,144 @@ +//! Source-preserving emission of module shapes from real apps, against live Babel. +use serde_json::json; +use stylex_swc_plugin::{transform_source, StyleXTransformOptions}; +// Only `transform` is used here. +#[allow(dead_code)] +#[path = "support/current_babel.rs"] +mod current_babel; + +const HEADER: &str = "import * as stylex from '@stylexjs/stylex';\nconst s = stylex.create({ a: { color: 'red' }, b: { color: 'blue' } });\n"; + +fn options() -> StyleXTransformOptions { + serde_json::from_value(json!({"styleResolution":"application-order","sxPropName":"sx"})) + .unwrap() +} + +fn compile(body: &str) -> stylex_swc_plugin::TransformOutput { + let source = format!("{HEADER}{body}"); + current_babel::transform(&source, "/tmp/emitter-current/app.tsx", &options()) +} + +/// Every comment of `body` survives, in source order. +fn keeps_comments(body: &str, output: &str) { + let mut cursor = 0; + for comment in ["/* kept */", "// moved"] + .into_iter() + .filter(|comment| body.contains(comment)) + { + let at = output[cursor..] + .find(comment) + .unwrap_or_else(|| panic!("{comment} lost or reordered:\n{output}")); + cursor += at + comment.len(); + } +} + +// Each module below edits a JSX `sx` prop inside a construct the emitter used to re-emit whole. +// A re-emitted region keeps only the comments of the source it reuses and moves the others in +// front of it; when a reused comment came first, the emitter refused the module ("cannot +// preserve the relative order of comments"). Babel compiles all of them. +#[test] +fn export_default_function_edits_statement_by_statement() { + let body = "export default function A({ n }: { /* kept */ n: number }) {\n const x = n;\n // moved\n return
{x}
;\n}\n"; + keeps_comments(body, &compile(body).code); +} + +#[test] +fn conditional_and_logical_operands_are_edited_in_place() { + for body in [ + "export const A = ({ on }: { on: boolean }) => (\n
\n {on ? {/* kept */} : (\n // moved\n \n )}\n
\n);\n", + "declare function ready(n: number): boolean;\nexport const A = () => (\n
\n {ready(/* kept */ 1) && (\n // moved\n \n )}\n
\n);\n", + ] { + keeps_comments(body, &compile(body).code); + } +} + +#[test] +fn if_switch_and_loop_bodies_are_edited_statement_by_statement() { + for body in [ + "declare function log(n: number): void;\nexport function B({ n }: { n: number }) {\n if (n > 0) {\n log(/* kept */ n);\n // moved\n return ;\n }\n return null;\n}\n", + "declare function log(n: number): void;\nexport function B({ n }: { n: number }) {\n switch (n) {\n case 1:\n log(/* kept */ n);\n // moved\n return ;\n default:\n return null;\n }\n}\n", + "declare function log(n: number): void;\nexport function B({ ns }: { ns: number[] }) {\n const out = [];\n for (const n of ns) {\n log(/* kept */ n);\n // moved\n out.push();\n }\n return out;\n}\n", + ] { + keeps_comments(body, &compile(body).code); + } +} + +#[test] +fn object_methods_and_assignments_are_edited_in_place() { + for body in [ + "declare function log(n: number): void;\nexport const renderers = {\n row(n: number) {\n log(/* kept */ n);\n // moved\n return ;\n },\n};\n", + "declare function ready(n: number): boolean;\nlet content: unknown;\ncontent = ready(/* kept */ 1) ? null : (\n // moved\n \n);\nexport { content };\n", + ] { + keeps_comments(body, &compile(body).code); + } +} + +// A reused optional chain in callee position used to be parenthesized, which ends the chain +// early (`(p?.items.map)(f)` throws where `p?.items.map(f)` short-circuits); the postflight +// check then refused the module as a lossy emission. +#[test] +fn a_reused_optional_chain_callee_keeps_its_chain() { + let output = compile( + "export const L = ({ p }: { p?: { items: number[] } }) => (\n
    {p?.items.map((i) =>
  • )}
\n);\n", + ); + assert!(output.code.contains("p?.items.map("), "{}", output.code); +} + +// Building the source map costs a walk over every character of the module, so it is built only +// when it is returned; the code is the same either way. +#[test] +fn the_code_does_not_depend_on_source_maps() { + let source = format!("{HEADER}export const A = () =>
;\n"); + let mut with_maps = options(); + with_maps + .additional_options + .insert("sourceMaps".into(), json!(true)); + let mapped = transform_source(&source, "/tmp/emitter-current/app.tsx", &with_maps).unwrap(); + let plain = transform_source(&source, "/tmp/emitter-current/app.tsx", &options()).unwrap(); + assert_eq!(mapped.code, plain.code); + assert!(mapped.source_map.is_some()); + assert!(plain.source_map.is_none()); +} + +// A rewritten arrow or function needs no parentheses in an initializer, argument, property +// value or JSX container. Babel prints none, and minifiers keep parentheses around functions +// as a hint to compile them eagerly. +#[test] +fn rewritten_functions_are_not_parenthesized() { + for body in [ + "export const A = () =>
;\n", + "export const B = function () { return
; };\n", + "declare function memo(f: T): T;\nexport const C = memo(() =>
);\n", + "export const D = { render: () =>
};\n", + ] { + let output = compile(body); + // The emitter prints `()=>`; a grouped function shows as `(()` or `(function` right + // after its slot's opening token. + for parenthesized in ["= (()", "= (function", "memo((()", ": (()"] { + assert!( + !output.code.contains(parenthesized), + "{parenthesized} in:\n{}", + output.code + ); + } + } +} + +// `null` resets of an expanded shorthand are kept only where an earlier style of a runtime +// `stylex.props` call may set the key. An optional read such as `p?.view` is not a style; Babel's +// member visitor does not match it, so it does not keep every reset after it. +#[test] +fn an_optional_read_does_not_keep_null_resets() { + let source = "import * as stylex from '@stylexjs/stylex';\nconst s = stylex.create({ host: { display: 'flex' }, fill: { inset: 0 }, at: (v: number) => ({ left: v }) });\nexport const A = (p: any) =>
;\n"; + let output = current_babel::transform(source, "/tmp/emitter-current/app.tsx", &options()); + assert!(!output.code.contains(": null"), "{}", output.code); +} + +// With `stylex.defaultMarker()` among the styles, the producer pass rewrites the marker call +// inside the JSX spread before the consumer pass compiles it; the spread must still become a +// static `className` attribute, as Babel writes it. +#[test] +fn a_static_sx_with_the_default_marker_becomes_attributes() { + let output = compile("export const A = () =>
;\n"); + assert!(!output.code.contains("{...{"), "{}", output.code); +} diff --git a/packages/@stylexjs/rust-plugin/tests/flow_syntax_current.cjs b/packages/@stylexjs/rust-plugin/tests/flow_syntax_current.cjs new file mode 100644 index 000000000..125cd008d --- /dev/null +++ b/packages/@stylexjs/rust-plugin/tests/flow_syntax_current.cjs @@ -0,0 +1,122 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +// Flow files compile like the Babel plugin behind hermes-parser, and the output keeps the +// authored Flow syntax, formatting and comments around what StyleX rewrote. + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const path = require('node:path'); +const babel = require('@babel/core'); +const { transformSync } = require('..'); + +const filename = path.join(__dirname, 'fixtures', 'flow-syntax', 'Component.js'); +const options = { + unstable_moduleResolution: { type: 'commonJS', rootDir: path.dirname(filename) }, + runtimeInjection: false, +}; +const header = `// @flow +import * as stylex from '@stylexjs/stylex'; +const styles = stylex.create({a: {color: 'red'}, b: {color: 'blue'}}); +`; + +function babelMetadata(code, extra = {}) { + return babel.transformSync(code, { + filename, + babelrc: false, + configFile: false, + plugins: [ + require.resolve('babel-plugin-syntax-hermes-parser'), + [require('@stylexjs/babel-plugin'), { ...options, ...extra }], + ], + }).metadata.stylex; +} + +function compile(body, extra = {}) { + const code = header + body; + const native = transformSync(code, { ...options, ...extra, filename }); + assert.deepEqual(native.metadata.stylex, babelMetadata(code, extra)); + return native.code; +} + +test('match expressions and statements compile and stay in the output', () => { + const props = compile(`export function f(x: string) { + return stylex.props(match (x) { 'a' => styles.a, _ => styles.b }); +} +`); + assert.match(props, /match \(x\) \{ 'a' => /); + const nearby = compile(`export function f(x: string) { + match (x) { 'a' => { g(); } _ => {} } + return stylex.props(styles.a); +} +`); + assert.match(nearby, /match \(x\) \{ 'a' => \{ g\(\); \} _ => \{\} \}/); +}); + +test('function types with unnamed params and inline interfaces parse', () => { + const code = compile(`type Rtl = {[key: string]: ( + $ReadOnly<[string, string]>, + options: Options, +) => ?string}; +type Container = interface extends Element {_root?: mixed} | Document; +export const p = stylex.props(styles.a); +`); + assert.match(code, /type Container = interface extends Element/); +}); + +test('component, hook and enum declarations keep their syntax', () => { + const code = compile(`enum Size {Small, Large} +export component Box(size: Size) renders? Inner { + return
; +} +hook useStyles(): mixed { return stylex.props(styles.a); } +export {useStyles}; +`); + assert.match(code, /^enum Size \{Small, Large\}$/m); + assert.match(code, /^export component Box\(size: Size\) renders\? Inner \{$/m); + assert.match(code, /^hook useStyles\(\): mixed \{/m); +}); + +test('a class is edited member by member', () => { + const code = compile(`export default class Footer extends React.PureComponent { + #ready(): boolean { + // first + f(); + // second + return true; + } + label: string = 'x'; + render(): React.Node { + // before + const content = ( +
+
+ ); + // after + return content; + } +} +`); + assert.match(code, /^export default class Footer extends React\.PureComponent \{$/m); + assert.match(code, /^ {2}#ready\(\): boolean \{\n {4}\/\/ first\n {4}f\(\);\n {4}\/\/ second\n/m); + assert.match(code, /^ {4}\/\/ before\n {4}const content = \(\n {6}/m); + assert.match(code, /^ {4}\/\/ after\n {4}return content;$/m); +}); + +test('dev line numbers come from the Flow parse', () => { + const code = compile( + `import typeof T from 'react'; +export function C(): React.Node { + return
; +} +`, + { dev: true, debug: true }, + ); + assert.match(code, /data-style-src="[^"]*Component\.js:3"/); +});