From 6a5412304a22e0bf3334d18b16145339fdb7e411 Mon Sep 17 00:00:00 2001 From: Noz Wu Date: Mon, 10 Aug 2026 15:07:53 +0800 Subject: [PATCH] Remove pre-generation --- .github/workflows/ci.yaml | 35 -- client/Cargo.toml | 1 - client/js-sys/Cargo.toml | 5 +- client/js-sys/build.rs | 66 ---- client/js-sys/src/array/array.gen.rs | 366 ----------------- client/js-sys/src/array/array.js-sys.rs | 37 -- client/js-sys/src/array/mod.rs | 67 +++- client/js-sys/src/bigint/bigint.gen.rs | 47 --- client/js-sys/src/bigint/bigint.js-sys.rs | 4 - client/js-sys/src/bigint/mod.rs | 9 +- client/js-sys/src/lib.rs | 1 - client/js-sys/src/number/mod.rs | 9 +- client/js-sys/src/number/number.gen.rs | 54 --- client/js-sys/src/number/number.js-sys.rs | 4 - client/js-sys/src/string/mod.rs | 45 ++- client/js-sys/src/string/string.gen.rs | 299 -------------- client/js-sys/src/string/string.js-sys.rs | 26 -- client/js-sys/src/value/mod.rs | 12 +- client/js-sys/src/value/value.gen.rs | 57 --- client/js-sys/src/value/value.js-sys.rs | 8 - client/test/Cargo.toml | 2 +- client/web-sys/build.rs | 66 ---- client/web-sys/src/console.gen.rs | 124 ------ .../src/{console.js-sys.rs => console.rs} | 2 +- client/web-sys/src/lib.rs | 2 - host/Cargo.toml | 3 - host/cargo-js-sys/Cargo.toml | 35 -- host/cargo-js-sys/src/js_sys.rs | 370 ------------------ host/cargo-js-sys/src/main.rs | 57 --- host/dev/src/check.rs | 8 +- host/dev/src/client/check.rs | 89 +---- host/dev/src/client/mod.rs | 2 +- host/js-sys-bindgen/Cargo.toml | 2 - host/js-sys-bindgen/src/file.rs | 92 ----- host/js-sys-bindgen/src/function.rs | 4 +- host/js-sys-bindgen/src/lib.rs | 6 - host/js-sys-bindgen/src/macro.rs | 23 +- .../src/tests/macro/function.rs | 18 +- host/js-sys-bindgen/src/tests/macro/member.rs | 6 +- host/js-sys-bindgen/src/tests/macro/mod.rs | 4 +- host/js-sys-bindgen/src/tests/mod.rs | 1 - host/js-sys-macro/Cargo.toml | 2 +- host/js-sys-macro/src/lib.rs | 2 +- 43 files changed, 138 insertions(+), 1934 deletions(-) delete mode 100644 client/js-sys/build.rs delete mode 100644 client/js-sys/src/array/array.gen.rs delete mode 100644 client/js-sys/src/array/array.js-sys.rs delete mode 100644 client/js-sys/src/bigint/bigint.gen.rs delete mode 100644 client/js-sys/src/bigint/bigint.js-sys.rs delete mode 100644 client/js-sys/src/number/number.gen.rs delete mode 100644 client/js-sys/src/number/number.js-sys.rs delete mode 100644 client/js-sys/src/string/string.gen.rs delete mode 100644 client/js-sys/src/string/string.js-sys.rs delete mode 100644 client/js-sys/src/value/value.gen.rs delete mode 100644 client/js-sys/src/value/value.js-sys.rs delete mode 100644 client/web-sys/build.rs delete mode 100644 client/web-sys/src/console.gen.rs rename client/web-sys/src/{console.js-sys.rs => console.rs} (90%) delete mode 100644 host/cargo-js-sys/Cargo.toml delete mode 100644 host/cargo-js-sys/src/js_sys.rs delete mode 100644 host/cargo-js-sys/src/main.rs delete mode 100644 host/js-sys-bindgen/src/file.rs diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 54173e2a..fbb6a272 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -83,11 +83,6 @@ jobs: cache-bin: false - name: Prepare Output Directory run: mkdir ${{ runner.temp }}/host-tools - - name: Build `cargo-js-sys` - working-directory: host - run: | - cargo ${{ matrix.os.sub-command }} build -p cargo-js-sys ${{ matrix.os.args }} --release - cp target/${{ matrix.os.path }}release/cargo-js-sys${{ matrix.os.exe }} ${{ runner.temp }}/host-tools/ - name: Build `js-bindgen-ld` working-directory: host run: | @@ -521,33 +516,3 @@ jobs: - name: Test working-directory: host run: js-bindgen-dev host test -v - - cargo-js-sys: - name: Check `cargo-js-sys` - - needs: host-tools - - runs-on: ubuntu-latest - - timeout-minutes: 20 - - env: - JBG_DEV_TOOLS: 1 - - steps: - - name: Checkout - uses: actions/checkout@v7 - with: - persist-credentials: false - - name: Download Host Tools - uses: actions/download-artifact@v8 - with: - name: host-tools-linux - path: ${{ runner.temp }}/host-tools/ - - name: Install Host Tools - run: | - chmod +x ${{ runner.temp }}/host-tools/* - echo "${{ runner.temp }}/host-tools" >> $GITHUB_PATH - - name: Check - working-directory: client - run: cargo-js-sys js-sys -c --workspace -v diff --git a/client/Cargo.toml b/client/Cargo.toml index 408a38b1..7cb7bb03 100644 --- a/client/Cargo.toml +++ b/client/Cargo.toml @@ -13,7 +13,6 @@ edition = "2024" rust-version = "1.85" license = "MIT OR Apache-2.0" include = [ - "!/src/**/*.js-sys.rs", "!/src/**/tests/**", "/Cargo.toml", "/LICENSE-APACHE", diff --git a/client/js-sys/Cargo.toml b/client/js-sys/Cargo.toml index 3ed0d20b..508d7690 100644 --- a/client/js-sys/Cargo.toml +++ b/client/js-sys/Cargo.toml @@ -12,15 +12,12 @@ test = false [dependencies] js-bindgen = { workspace = true } -js-sys-macro = { workspace = true, optional = true } +js-sys-macro = { workspace = true } [dev-dependencies] js-bindgen-test = { workspace = true } paste = { workspace = true } web-sys = { workspace = true } -[features] -macro = ["dep:js-sys-macro"] - [lints] workspace = true diff --git a/client/js-sys/build.rs b/client/js-sys/build.rs deleted file mode 100644 index d058f7a8..00000000 --- a/client/js-sys/build.rs +++ /dev/null @@ -1,66 +0,0 @@ -//! This file is not shipped to Crates.io, but it is present when depending on -//! `js-sys` via `git` or `path`. - -use std::io::ErrorKind; -use std::path::Path; -use std::process::Command; -use std::{env, fs, panic, process}; - -fn main() { - if option_env!("JBG_DEV").is_none_or(|value| value != "1") - || option_env!("CI").is_some_and(|value| value == "true") - { - return; - } - - if search_dir(&env::current_dir().unwrap(), false) { - let status = Command::new("cargo") - .env_remove("CARGO_ENCODED_RUSTFLAGS") - .current_dir("../../host") - .arg("+stable") - .arg("run") - .args(["-p", "cargo-js-sys"]) - .arg("--") - .arg("-q") - .arg("js-sys") - .args(["--manifest-path", "../client/js-sys/Cargo.toml"]) - .status() - .unwrap(); - - if !status.success() { - process::exit(status.code().unwrap_or(1)) - } - } -} - -fn search_dir(dir: &Path, mut any: bool) -> bool { - for entry in fs::read_dir(dir).unwrap() { - let entry = entry.unwrap(); - let path = entry.path(); - - if path.is_file() && path.as_os_str().as_encoded_bytes().ends_with(b".js-sys.rs") { - println!("cargo::rerun-if-changed={}", path.display()); - - if !any { - let r#gen = path.with_extension("").with_extension("gen.rs"); - - match fs::metadata(r#gen) { - Ok(meta) => { - let gen_mtime = meta.modified().unwrap(); - let js_sys_mtime = fs::metadata(&path).unwrap().modified().unwrap(); - - if gen_mtime < js_sys_mtime { - any = true; - } - } - Err(error) if error.kind() == ErrorKind::NotFound => any = true, - Err(error) => panic::panic_any(error), - } - } - } else if path.is_dir() { - any |= search_dir(&path, any); - } - } - - any -} diff --git a/client/js-sys/src/array/array.gen.rs b/client/js-sys/src/array/array.gen.rs deleted file mode 100644 index c36a2307..00000000 --- a/client/js-sys/src/array/array.gen.rs +++ /dev/null @@ -1,366 +0,0 @@ -//! This file was generated by `js-sys-bindgen`. - -#![allow(warnings)] - -use core::marker::PhantomData; -use crate::{js_bindgen, r#macro, JsValue}; -use crate::hazard::{InputJsConv, OutputJsConv, OutputWatConv, Input, InputWatConv, Output, JsCast}; -use crate::util::{PtrConst, PtrLength, PtrMut}; - -#[repr(transparent)] -pub struct JsArray { - value: JsValue, - _type: PhantomData, -} - -impl AsRef for JsArray { - fn as_ref(&self) -> &JsValue { - &self.value - } -} - -impl From> for JsValue { - fn from(value: JsArray) -> Self { - value.value - } -} - -unsafe impl Input for &JsArray { - const WAT_TYPE: &'static str = <&JsValue as Input>::WAT_TYPE; - const WAT_CONV: Option = <&JsValue as Input>::WAT_CONV; - const JS_CONV: Option = <&JsValue as Input>::JS_CONV; - - type Type = <&'static JsValue as Input>::Type; - - fn into_raw(self) -> Self::Type { - Input::into_raw(&self.value) - } -} - -unsafe impl JsCast for JsArray {} - -unsafe impl Output for JsArray { - const WAT_TYPE: &str = ::WAT_TYPE; - const WAT_CONV: Option = ::WAT_CONV; - const JS_CONV: Option = ::JS_CONV; - - type Type = ::Type; - - fn from_raw(raw: Self::Type) -> Self { - Self { - value: Output::from_raw(raw), - _type: PhantomData, - } - } -} - -impl JsArray { - pub fn length(self: &JsArray) -> u32 { - js_bindgen::unsafe_global_wat! { - "(import \"js_sys\" \"length\" (func $js_sys.import.length (@sym (name \"js_sys.import.length\")) (param {}) (result {}))){}", - "(func $js_sys.length (@sym) (param {}) (param $self {}) (result {})", - " local.get $self{}", " call $js_sys.import.length (@reloc){}", ")", interpolate - r#macro::wat_input_import_type:: < & JsValue > (), interpolate - r#macro::wat_output_import_type:: < u32 > (), interpolate r#macro::wat_imports!((& - JsValue), u32), interpolate r#macro::wat_indirect!(u32), interpolate < & JsValue as - Input > ::WAT_TYPE, interpolate r#macro::wat_direct:: < u32 > (), interpolate - r#macro::wat_input!(& JsValue), interpolate r#macro::wat_output!(u32), - } - - js_bindgen::import_js! { - module = "js_sys", - name = "length", - required_embeds = [ - r#macro::js_input_embed::<&JsValue>(), - r#macro::js_output_embed::(), - ], - "{}{}{}", - interpolate r#macro::js_select!("(self) => ", "(self) => {\n", (&JsValue), u32), - interpolate r#macro::js_parameter!("self", &JsValue), - interpolate r#macro::js_output!( - "\treturn ", - "self.length", - "self.length", - u32, - &JsValue, - ), - } - - unsafe extern "C" { - #[link_name = "js_sys.length"] - fn length(this: <&JsValue as Input>::Type) -> ::Type; - } - - Output::from_raw(unsafe { length(Input::into_raw(self)) }) - } -} - -pub(super) unsafe fn array_js_value_decode( - array: PtrConst, - len: PtrLength, -) -> JsArray { - js_bindgen::unsafe_global_wat! { - "(import \"js_sys\" \"array_js_value_decode\" (func $js_sys.import.array_js_value_decode (@sym (name \"js_sys.import.array_js_value_decode\")) (param {} {}) (result {}))){}", - "(func $js_sys.array_js_value_decode (@sym) (param {}) (param $array {}) (param $len {}) (result {})", - " local.get $array{}", " local.get $len{}", - " call $js_sys.import.array_js_value_decode (@reloc){}", ")", interpolate - r#macro::wat_input_import_type:: < PtrConst < JsValue > > (), interpolate - r#macro::wat_input_import_type:: < PtrLength < JsValue > > (), interpolate - r#macro::wat_output_import_type:: < JsArray < JsValue > > (), interpolate - r#macro::wat_imports!((PtrConst < JsValue >, PtrLength < JsValue >), JsArray < JsValue >), - interpolate r#macro::wat_indirect!(JsArray < JsValue >), interpolate < PtrConst < JsValue > - as Input > ::WAT_TYPE, interpolate < PtrLength < JsValue > as Input > ::WAT_TYPE, - interpolate r#macro::wat_direct:: < JsArray < JsValue > > (), interpolate - r#macro::wat_input!(PtrConst < JsValue >), interpolate r#macro::wat_input!(PtrLength < - JsValue >), interpolate r#macro::wat_output!(JsArray < JsValue >), - } - - js_bindgen::import_js! { - module = "js_sys", - name = "array_js_value_decode", - required_embeds = [ - ("js_sys", "array.js_value.decode"), - r#macro::js_input_embed::>(), - r#macro::js_input_embed::>(), - r#macro::js_output_embed::>(), - ], - "{}{}{}{}", - interpolate r#macro::js_select!( - "", - "(array, len) => {\n", - (PtrConst, PtrLength), - JsArray, - ), - interpolate r#macro::js_parameter!("array", PtrConst), - interpolate r#macro::js_parameter!("len", PtrLength), - interpolate r#macro::js_output!( - "\treturn ", - "this.#jsEmbed.js_sys['array.js_value.decode']", - "this.#jsEmbed.js_sys['array.js_value.decode'](array, len)", - JsArray, - PtrConst, - PtrLength, - ), - } - - unsafe extern "C" { - #[link_name = "js_sys.array_js_value_decode"] - fn array_js_value_decode( - array: as Input>::Type, - len: as Input>::Type, - ) -> as Output>::Type; - } - - Output::from_raw(unsafe { array_js_value_decode(Input::into_raw(array), Input::into_raw(len)) }) -} - -pub(super) unsafe fn array_js_value_encode( - array: &JsArray, - array_ptr: PtrMut, - array_len: PtrLength, - externref_ptr: PtrConst, - externref_len: i32, -) -> bool { - js_bindgen::unsafe_global_wat! { - "(import \"js_sys\" \"array_js_value_encode\" (func $js_sys.import.array_js_value_encode (@sym (name \"js_sys.import.array_js_value_encode\")) (param {} {} {} {} {}) (result {}))){}", - "(func $js_sys.array_js_value_encode (@sym) (param {}) (param $array {}) (param $array_ptr {}) (param $array_len {}) (param $externref_ptr {}) (param $externref_len {}) (result {})", - " local.get $array{}", " local.get $array_ptr{}", " local.get $array_len{}", - " local.get $externref_ptr{}", " local.get $externref_len{}", - " call $js_sys.import.array_js_value_encode (@reloc){}", ")", interpolate - r#macro::wat_input_import_type:: < & JsArray > (), interpolate - r#macro::wat_input_import_type:: < PtrMut < JsValue > > (), interpolate - r#macro::wat_input_import_type:: < PtrLength < JsValue > > (), interpolate - r#macro::wat_input_import_type:: < PtrConst < i32 > > (), interpolate - r#macro::wat_input_import_type:: < i32 > (), interpolate r#macro::wat_output_import_type:: < - bool > (), interpolate r#macro::wat_imports!((& JsArray, PtrMut < JsValue >, PtrLength < - JsValue >, PtrConst < i32 >, i32), bool), interpolate r#macro::wat_indirect!(bool), - interpolate < & JsArray as Input > ::WAT_TYPE, interpolate < PtrMut < JsValue > as Input > - ::WAT_TYPE, interpolate < PtrLength < JsValue > as Input > ::WAT_TYPE, interpolate < - PtrConst < i32 > as Input > ::WAT_TYPE, interpolate < i32 as Input > ::WAT_TYPE, interpolate - r#macro::wat_direct:: < bool > (), interpolate r#macro::wat_input!(& JsArray), interpolate - r#macro::wat_input!(PtrMut < JsValue >), interpolate r#macro::wat_input!(PtrLength < JsValue - >), interpolate r#macro::wat_input!(PtrConst < i32 >), interpolate r#macro::wat_input!(i32), - interpolate r#macro::wat_output!(bool), - } - - js_bindgen::import_js! { - module = "js_sys", - name = "array_js_value_encode", - required_embeds = [ - ("js_sys", "array.js_value.encode"), - r#macro::js_input_embed::<&JsArray>(), - r#macro::js_input_embed::>(), - r#macro::js_input_embed::>(), - r#macro::js_input_embed::>(), - r#macro::js_input_embed::(), - r#macro::js_output_embed::(), - ], - "{}{}{}{}{}{}{}", - interpolate r#macro::js_select!( - "", - "(array, array_ptr, array_len, externref_ptr, externref_len) => {\n", - (&JsArray, PtrMut, PtrLength, PtrConst, i32), - bool, - ), - interpolate r#macro::js_parameter!("array", &JsArray), - interpolate r#macro::js_parameter!("array_ptr", PtrMut), - interpolate r#macro::js_parameter!("array_len", PtrLength), - interpolate r#macro::js_parameter!("externref_ptr", PtrConst), - interpolate r#macro::js_parameter!("externref_len", i32), - interpolate r#macro::js_output!( - "\treturn ", - "this.#jsEmbed.js_sys['array.js_value.encode']", - "this.#jsEmbed.js_sys['array.js_value.encode'](array, array_ptr, array_len, externref_ptr, externref_len)", - bool, - &JsArray, - PtrMut, - PtrLength, - PtrConst, - i32, - ), - } - - unsafe extern "C" { - #[link_name = "js_sys.array_js_value_encode"] - fn array_js_value_encode( - array: <&JsArray as Input>::Type, - array_ptr: as Input>::Type, - array_len: as Input>::Type, - externref_ptr: as Input>::Type, - externref_len: ::Type, - ) -> ::Type; - } - - Output::from_raw(unsafe { - array_js_value_encode( - Input::into_raw(array), - Input::into_raw(array_ptr), - Input::into_raw(array_len), - Input::into_raw(externref_ptr), - Input::into_raw(externref_len), - ) - }) -} - -pub(super) unsafe fn array_u32_decode(array: PtrConst, len: PtrLength) -> JsArray { - js_bindgen::unsafe_global_wat! { - "(import \"js_sys\" \"array_u32_decode\" (func $js_sys.import.array_u32_decode (@sym (name \"js_sys.import.array_u32_decode\")) (param {} {}) (result {}))){}", - "(func $js_sys.array_u32_decode (@sym) (param {}) (param $array {}) (param $len {}) (result {})", - " local.get $array{}", " local.get $len{}", - " call $js_sys.import.array_u32_decode (@reloc){}", ")", interpolate - r#macro::wat_input_import_type:: < PtrConst < u32 > > (), interpolate - r#macro::wat_input_import_type:: < PtrLength < u32 > > (), interpolate - r#macro::wat_output_import_type:: < JsArray < u32 > > (), interpolate - r#macro::wat_imports!((PtrConst < u32 >, PtrLength < u32 >), JsArray < u32 >), interpolate - r#macro::wat_indirect!(JsArray < u32 >), interpolate < PtrConst < u32 > as Input > - ::WAT_TYPE, interpolate < PtrLength < u32 > as Input > ::WAT_TYPE, interpolate - r#macro::wat_direct:: < JsArray < u32 > > (), interpolate r#macro::wat_input!(PtrConst < u32 - >), interpolate r#macro::wat_input!(PtrLength < u32 >), interpolate - r#macro::wat_output!(JsArray < u32 >), - } - - js_bindgen::import_js! { - module = "js_sys", - name = "array_u32_decode", - required_embeds = [ - ("js_sys", "view.getUint32"), - r#macro::js_input_embed::>(), - r#macro::js_input_embed::>(), - r#macro::js_output_embed::>(), - ], - "{}{}{}{}", - interpolate r#macro::js_select!( - "", - "(array, len) => {\n", - (PtrConst, PtrLength), - JsArray, - ), - interpolate r#macro::js_parameter!("array", PtrConst), - interpolate r#macro::js_parameter!("len", PtrLength), - interpolate r#macro::js_output!( - "\treturn ", - "this.#jsEmbed.js_sys['view.getUint32']", - "this.#jsEmbed.js_sys['view.getUint32'](array, len)", - JsArray, - PtrConst, - PtrLength, - ), - } - - unsafe extern "C" { - #[link_name = "js_sys.array_u32_decode"] - fn array_u32_decode( - array: as Input>::Type, - len: as Input>::Type, - ) -> as Output>::Type; - } - - Output::from_raw(unsafe { array_u32_decode(Input::into_raw(array), Input::into_raw(len)) }) -} - -pub(super) unsafe fn array_u32_encode( - array: &JsArray, - ptr: PtrMut, - len: PtrLength, -) -> bool { - js_bindgen::unsafe_global_wat! { - "(import \"js_sys\" \"array_u32_encode\" (func $js_sys.import.array_u32_encode (@sym (name \"js_sys.import.array_u32_encode\")) (param {} {} {}) (result {}))){}", - "(func $js_sys.array_u32_encode (@sym) (param {}) (param $array {}) (param $ptr {}) (param $len {}) (result {})", - " local.get $array{}", " local.get $ptr{}", " local.get $len{}", - " call $js_sys.import.array_u32_encode (@reloc){}", ")", interpolate - r#macro::wat_input_import_type:: < & JsArray < u32 > > (), interpolate - r#macro::wat_input_import_type:: < PtrMut < u32 > > (), interpolate - r#macro::wat_input_import_type:: < PtrLength < u32 > > (), interpolate - r#macro::wat_output_import_type:: < bool > (), interpolate r#macro::wat_imports!((& JsArray - < u32 >, PtrMut < u32 >, PtrLength < u32 >), bool), interpolate - r#macro::wat_indirect!(bool), interpolate < & JsArray < u32 > as Input > ::WAT_TYPE, - interpolate < PtrMut < u32 > as Input > ::WAT_TYPE, interpolate < PtrLength < u32 > as Input - > ::WAT_TYPE, interpolate r#macro::wat_direct:: < bool > (), interpolate - r#macro::wat_input!(& JsArray < u32 >), interpolate r#macro::wat_input!(PtrMut < u32 >), - interpolate r#macro::wat_input!(PtrLength < u32 >), interpolate r#macro::wat_output!(bool), - } - - js_bindgen::import_js! { - module = "js_sys", - name = "array_u32_encode", - required_embeds = [ - ("js_sys", "array.u32.encode"), - r#macro::js_input_embed::<&JsArray>(), - r#macro::js_input_embed::>(), - r#macro::js_input_embed::>(), - r#macro::js_output_embed::(), - ], - "{}{}{}{}{}", - interpolate r#macro::js_select!( - "", - "(array, ptr, len) => {\n", - (&JsArray, PtrMut, PtrLength), - bool, - ), - interpolate r#macro::js_parameter!("array", &JsArray), - interpolate r#macro::js_parameter!("ptr", PtrMut), - interpolate r#macro::js_parameter!("len", PtrLength), - interpolate r#macro::js_output!( - "\treturn ", - "this.#jsEmbed.js_sys['array.u32.encode']", - "this.#jsEmbed.js_sys['array.u32.encode'](array, ptr, len)", - bool, - &JsArray, - PtrMut, - PtrLength, - ), - } - - unsafe extern "C" { - #[link_name = "js_sys.array_u32_encode"] - fn array_u32_encode( - array: <&JsArray as Input>::Type, - ptr: as Input>::Type, - len: as Input>::Type, - ) -> ::Type; - } - - Output::from_raw(unsafe { - array_u32_encode(Input::into_raw(array), Input::into_raw(ptr), Input::into_raw(len)) - }) -} diff --git a/client/js-sys/src/array/array.js-sys.rs b/client/js-sys/src/array/array.js-sys.rs deleted file mode 100644 index 3ce568db..00000000 --- a/client/js-sys/src/array/array.js-sys.rs +++ /dev/null @@ -1,37 +0,0 @@ -use crate::util::{PtrConst, PtrLength, PtrMut}; - -#[js_sys] -extern "js-sys" { - pub type JsArray; - - #[js_sys(property)] - pub fn length(self: &JsArray) -> u32; - - #[js_sys(js_embed = "array.js_value.decode")] - pub(super) unsafe fn array_js_value_decode( - array: PtrConst, - len: PtrLength, - ) -> JsArray; - - #[js_sys(js_embed = "array.js_value.encode")] - pub(super) unsafe fn array_js_value_encode( - array: &JsArray, - array_ptr: PtrMut, - array_len: PtrLength, - externref_ptr: PtrConst, - externref_len: i32, - ) -> bool; - - #[js_sys(js_embed = "view.getUint32")] - pub(super) unsafe fn array_u32_decode( - array: PtrConst, - len: PtrLength, - ) -> JsArray; - - #[js_sys(js_embed = "array.u32.encode")] - pub(super) unsafe fn array_u32_encode( - array: &JsArray, - ptr: PtrMut, - len: PtrLength, - ) -> bool; -} diff --git a/client/js-sys/src/array/mod.rs b/client/js-sys/src/array/mod.rs index c3862d45..97b6a9e5 100644 --- a/client/js-sys/src/array/mod.rs +++ b/client/js-sys/src/array/mod.rs @@ -1,18 +1,57 @@ -#[rustfmt::skip] -#[path ="array.gen.rs"] -mod array; - use core::error::Error; use core::fmt::{self, Display, Formatter}; use core::mem::MaybeUninit; use core::ptr; -pub use self::array::JsArray; use crate::JsValue; use crate::externref::ExternrefTable; use crate::hazard::{Input, InputJsConv, InputWatConv, JsCast}; use crate::util::{ExternSlice, PtrConst, PtrLength, PtrMut}; +#[crate::js_sys(js_sys = crate)] +extern "js-sys" { + pub type JsArray; + + #[must_use] + #[js_sys(property)] + pub fn length(self: &JsArray) -> u32; + + /// # Safety + /// + /// `array` must be readable for `len` values. + #[js_sys(js_embed = "array.js_value.decode")] + unsafe fn array_js_value_decode( + array: PtrConst, + len: PtrLength, + ) -> JsArray; + + /// # Safety + /// + /// `array_ptr` must be writable for `array_len` values, and `externref_ptr` + /// must be readable for `externref_len` values. + #[js_sys(js_embed = "array.js_value.encode")] + unsafe fn array_js_value_encode( + array: &JsArray, + array_ptr: PtrMut, + array_len: PtrLength, + externref_ptr: PtrConst, + externref_len: i32, + ) -> bool; + + /// # Safety + /// + /// `array` must be readable for `len` values. + #[js_sys(js_embed = "view.getUint32")] + unsafe fn array_u32_decode(array: PtrConst, len: PtrLength) -> JsArray; + + /// # Safety + /// + /// `ptr` must be writable for `len` values. + #[js_sys(js_embed = "array.u32.encode")] + unsafe fn array_u32_encode(array: &JsArray, ptr: PtrMut, len: PtrLength) + -> bool; +} + impl JsArray { #[must_use] pub fn as_any(&self) -> &JsArray { @@ -69,7 +108,7 @@ impl JsArray { // SAFETY: Parameters are correct. let result = unsafe { - array::array_js_value_encode( + array_js_value_encode( self.as_any(), PtrMut::new(slice), PtrLength::new(slice), @@ -95,7 +134,7 @@ impl JsArray { // SAFETY: Parameters are correct. let result = unsafe { - array::array_js_value_encode( + array_js_value_encode( self.as_any(), PtrMut::from_uninit_slice(js_slice), PtrLength::from_uninit_slice(js_slice), @@ -120,7 +159,7 @@ impl JsArray { // SAFETY: Parameters are correct. let result = unsafe { - array::array_js_value_encode( + array_js_value_encode( self.as_any(), PtrMut::from_uninit_array(js_array), PtrLength::from_uninit_array(js_array), @@ -193,8 +232,7 @@ impl From<&[T]> for JsArray { let slice = JsValue::from_slice(value); // SAFETY: Parameters are correct. - let result = - unsafe { array::array_js_value_decode(PtrConst::new(slice), PtrLength::new(slice)) }; + let result = unsafe { array_js_value_decode(PtrConst::new(slice), PtrLength::new(slice)) }; Self::unchecked_from(result.into()) } @@ -233,8 +271,7 @@ unsafe impl Input for &[T] { impl JsArray { pub fn to_slice(&self, slice: &mut [u32]) -> Result<(), TryFromJsArrayError> { // SAFETY: Parameters are correct. - let result = - unsafe { array::array_u32_encode(self, PtrMut::new(slice), PtrLength::new(slice)) }; + let result = unsafe { array_u32_encode(self, PtrMut::new(slice), PtrLength::new(slice)) }; if result { Ok(()) @@ -249,7 +286,7 @@ impl JsArray { ) -> Result<&'slice mut [u32], TryFromJsArrayError> { // SAFETY: Parameters are correct. let result = unsafe { - array::array_u32_encode( + array_u32_encode( self, PtrMut::from_uninit_slice(slice), PtrLength::from_uninit_slice(slice), @@ -270,7 +307,7 @@ impl JsArray { // SAFETY: Parameters are correct. let result = unsafe { - array::array_u32_encode( + array_u32_encode( self, PtrMut::from_uninit_array(&mut array), PtrLength::from_uninit_array(&array), @@ -301,7 +338,7 @@ js_bindgen::embed_js!( impl From<&[u32]> for JsArray { fn from(value: &[u32]) -> Self { // SAFETY: Parameters are correct. - unsafe { array::array_u32_decode(PtrConst::new(value), PtrLength::new(value)) } + unsafe { array_u32_decode(PtrConst::new(value), PtrLength::new(value)) } } } diff --git a/client/js-sys/src/bigint/bigint.gen.rs b/client/js-sys/src/bigint/bigint.gen.rs deleted file mode 100644 index 9cb49c10..00000000 --- a/client/js-sys/src/bigint/bigint.gen.rs +++ /dev/null @@ -1,47 +0,0 @@ -//! This file was generated by `js-sys-bindgen`. - -#![allow(warnings)] - -use crate::JsValue; -use crate::hazard::{Input, InputWatConv, InputJsConv, OutputJsConv, Output, JsCast, OutputWatConv}; - -#[repr(transparent)] -pub struct JsBigInt(JsValue); - -impl AsRef for JsBigInt { - fn as_ref(&self) -> &JsValue { - &self.0 - } -} - -impl From for JsValue { - fn from(value: JsBigInt) -> Self { - value.0 - } -} - -unsafe impl Input for &JsBigInt { - const WAT_TYPE: &'static str = <&JsValue as Input>::WAT_TYPE; - const WAT_CONV: Option = <&JsValue as Input>::WAT_CONV; - const JS_CONV: Option = <&JsValue as Input>::JS_CONV; - - type Type = <&'static JsValue as Input>::Type; - - fn into_raw(self) -> Self::Type { - Input::into_raw(&self.0) - } -} - -unsafe impl JsCast for JsBigInt {} - -unsafe impl Output for JsBigInt { - const WAT_TYPE: &str = ::WAT_TYPE; - const WAT_CONV: Option = ::WAT_CONV; - const JS_CONV: Option = ::JS_CONV; - - type Type = ::Type; - - fn from_raw(raw: Self::Type) -> Self { - Self(Output::from_raw(raw)) - } -} diff --git a/client/js-sys/src/bigint/bigint.js-sys.rs b/client/js-sys/src/bigint/bigint.js-sys.rs deleted file mode 100644 index eadff82e..00000000 --- a/client/js-sys/src/bigint/bigint.js-sys.rs +++ /dev/null @@ -1,4 +0,0 @@ -#[js_sys] -extern "js-sys" { - pub type JsBigInt; -} diff --git a/client/js-sys/src/bigint/mod.rs b/client/js-sys/src/bigint/mod.rs index 2fc8c829..40d2e235 100644 --- a/client/js-sys/src/bigint/mod.rs +++ b/client/js-sys/src/bigint/mod.rs @@ -1,5 +1,4 @@ -#[rustfmt::skip] -#[path ="bigint.gen.rs"] -mod bigint; - -pub use self::bigint::JsBigInt; +#[crate::js_sys(js_sys = crate)] +extern "js-sys" { + pub type JsBigInt; +} diff --git a/client/js-sys/src/lib.rs b/client/js-sys/src/lib.rs index d9d71b84..d7933c98 100644 --- a/client/js-sys/src/lib.rs +++ b/client/js-sys/src/lib.rs @@ -22,7 +22,6 @@ mod string; mod value; pub use js_bindgen; -#[cfg(feature = "macro")] pub use js_sys_macro::js_sys; pub use crate::array::{JsArray, TryFromJsArrayError}; diff --git a/client/js-sys/src/number/mod.rs b/client/js-sys/src/number/mod.rs index 0ffba725..c192336d 100644 --- a/client/js-sys/src/number/mod.rs +++ b/client/js-sys/src/number/mod.rs @@ -1,5 +1,4 @@ -#[rustfmt::skip] -#[path ="number.gen.rs"] -mod number; - -pub use self::number::JsNumber; +#[crate::js_sys(js_sys = crate)] +extern "js-sys" { + pub type JsNumber; +} diff --git a/client/js-sys/src/number/number.gen.rs b/client/js-sys/src/number/number.gen.rs deleted file mode 100644 index dc460790..00000000 --- a/client/js-sys/src/number/number.gen.rs +++ /dev/null @@ -1,54 +0,0 @@ -//! This file was generated by `js-sys-bindgen`. - -#![allow(warnings)] - -use core::marker::PhantomData; -use crate::JsValue; -use crate::hazard::{Input, InputWatConv, InputJsConv, OutputJsConv, Output, JsCast, OutputWatConv}; - -#[repr(transparent)] -pub struct JsNumber { - value: JsValue, - _type: PhantomData, -} - -impl AsRef for JsNumber { - fn as_ref(&self) -> &JsValue { - &self.value - } -} - -impl From> for JsValue { - fn from(value: JsNumber) -> Self { - value.value - } -} - -unsafe impl Input for &JsNumber { - const WAT_TYPE: &'static str = <&JsValue as Input>::WAT_TYPE; - const WAT_CONV: Option = <&JsValue as Input>::WAT_CONV; - const JS_CONV: Option = <&JsValue as Input>::JS_CONV; - - type Type = <&'static JsValue as Input>::Type; - - fn into_raw(self) -> Self::Type { - Input::into_raw(&self.value) - } -} - -unsafe impl JsCast for JsNumber {} - -unsafe impl Output for JsNumber { - const WAT_TYPE: &str = ::WAT_TYPE; - const WAT_CONV: Option = ::WAT_CONV; - const JS_CONV: Option = ::JS_CONV; - - type Type = ::Type; - - fn from_raw(raw: Self::Type) -> Self { - Self { - value: Output::from_raw(raw), - _type: PhantomData, - } - } -} diff --git a/client/js-sys/src/number/number.js-sys.rs b/client/js-sys/src/number/number.js-sys.rs deleted file mode 100644 index 3cf3c262..00000000 --- a/client/js-sys/src/number/number.js-sys.rs +++ /dev/null @@ -1,4 +0,0 @@ -#[js_sys] -extern "js-sys" { - pub type JsNumber; -} diff --git a/client/js-sys/src/string/mod.rs b/client/js-sys/src/string/mod.rs index 74378bff..f7f5b2e0 100644 --- a/client/js-sys/src/string/mod.rs +++ b/client/js-sys/src/string/mod.rs @@ -1,20 +1,45 @@ -#[rustfmt::skip] -#[path ="string.gen.rs"] -mod string; - use alloc::string::String; use alloc::vec::Vec; use core::fmt::{self, Display, Formatter}; -pub use self::string::JsString; use crate::JsValue; use crate::hazard::{Input, InputJsConv, InputWatConv}; use crate::util::{ExternSlice, PtrConst, PtrLength, PtrMut}; +#[crate::js_sys(js_sys = crate)] +extern "js-sys" { + #[derive(Clone, Debug)] + pub type JsString; + + #[js_sys(js_name = "String")] + fn string_constructor(value: &JsValue) -> JsString; + + /// # Safety + /// + /// `array` must be readable for `len` bytes. + #[js_sys(js_embed = "string.eq")] + unsafe fn string_eq(string: &JsString, array: PtrConst, len: PtrLength) -> bool; + + /// # Safety + /// + /// `array` must be readable for `len` bytes. + #[js_sys(js_embed = "string.decode")] + unsafe fn string_decode(array: PtrConst, len: PtrLength) -> JsString; + + #[js_sys(js_embed = "string.utf8_length")] + fn string_utf8_length(string: &JsString) -> f64; + + /// # Safety + /// + /// `array` must be writable for `len` bytes. + #[js_sys(js_embed = "string.encode")] + unsafe fn string_encode(string: &JsString, array: PtrMut, len: PtrLength); +} + impl JsString { #[must_use] pub fn new(value: &JsValue) -> Self { - string::string_constructor(value) + string_constructor(value) } } @@ -38,7 +63,7 @@ impl PartialEq<&str> for JsString { // SAFETY: Parameters are correct. unsafe { - string::string_eq( + string_eq( self, PtrConst::new(other.as_bytes()), PtrLength::new(other.as_bytes()), @@ -93,7 +118,7 @@ impl From<&str> for JsString { // SAFETY: Parameters are correct. unsafe { - string::string_decode( + string_decode( PtrConst::new(value.as_bytes()), PtrLength::new(value.as_bytes()), ) @@ -135,7 +160,7 @@ impl From<&JsString> for String { "}}", ); - let len = string::string_utf8_length(value); + let len = string_utf8_length(value); #[cfg(target_arch = "wasm32")] assert!( len < f64::from(u32::MAX), @@ -151,7 +176,7 @@ impl From<&JsString> for String { let mut vec = Vec::with_capacity(len); // SAFETY: Parameters are correct. unsafe { - string::string_encode( + string_encode( value, PtrMut::new(&mut vec), PtrLength::from_uninit_slice(vec.spare_capacity_mut()), diff --git a/client/js-sys/src/string/string.gen.rs b/client/js-sys/src/string/string.gen.rs deleted file mode 100644 index b88ed367..00000000 --- a/client/js-sys/src/string/string.gen.rs +++ /dev/null @@ -1,299 +0,0 @@ -//! This file was generated by `js-sys-bindgen`. - -#![allow(warnings)] - -use crate::{js_bindgen, r#macro, JsValue}; -use crate::hazard::{InputJsConv, OutputJsConv, OutputWatConv, Input, InputWatConv, Output, JsCast}; -use crate::util::{PtrConst, PtrLength, PtrMut}; - -#[derive(Clone, Debug)] -#[repr(transparent)] -pub struct JsString(JsValue); - -impl AsRef for JsString { - fn as_ref(&self) -> &JsValue { - &self.0 - } -} - -impl From for JsValue { - fn from(value: JsString) -> Self { - value.0 - } -} - -unsafe impl Input for &JsString { - const WAT_TYPE: &'static str = <&JsValue as Input>::WAT_TYPE; - const WAT_CONV: Option = <&JsValue as Input>::WAT_CONV; - const JS_CONV: Option = <&JsValue as Input>::JS_CONV; - - type Type = <&'static JsValue as Input>::Type; - - fn into_raw(self) -> Self::Type { - Input::into_raw(&self.0) - } -} - -unsafe impl JsCast for JsString {} - -unsafe impl Output for JsString { - const WAT_TYPE: &str = ::WAT_TYPE; - const WAT_CONV: Option = ::WAT_CONV; - const JS_CONV: Option = ::JS_CONV; - - type Type = ::Type; - - fn from_raw(raw: Self::Type) -> Self { - Self(Output::from_raw(raw)) - } -} - -pub(super) fn string_constructor(value: &JsValue) -> JsString { - js_bindgen::unsafe_global_wat! { - "(import \"js_sys\" \"string_constructor\" (func $js_sys.import.string_constructor (@sym (name \"js_sys.import.string_constructor\")) (param {}) (result {}))){}", - "(func $js_sys.string_constructor (@sym) (param {}) (param $value {}) (result {})", - " local.get $value{}", " call $js_sys.import.string_constructor (@reloc){}", ")", - interpolate r#macro::wat_input_import_type:: < & JsValue > (), interpolate - r#macro::wat_output_import_type:: < JsString > (), interpolate r#macro::wat_imports!((& - JsValue), JsString), interpolate r#macro::wat_indirect!(JsString), interpolate < & JsValue - as Input > ::WAT_TYPE, interpolate r#macro::wat_direct:: < JsString > (), interpolate - r#macro::wat_input!(& JsValue), interpolate r#macro::wat_output!(JsString), - } - - js_bindgen::import_js! { - module = "js_sys", - name = "string_constructor", - required_embeds = [ - r#macro::js_input_embed::<&JsValue>(), - r#macro::js_output_embed::(), - ], - "{}{}{}", - interpolate r#macro::js_select!("", "(value) => {\n", (&JsValue), JsString), - interpolate r#macro::js_parameter!("value", &JsValue), - interpolate r#macro::js_output!( - "\treturn ", - "globalThis.String", - "globalThis.String(value)", - JsString, - &JsValue, - ), - } - - unsafe extern "C" { - #[link_name = "js_sys.string_constructor"] - fn string_constructor(value: <&JsValue as Input>::Type) -> ::Type; - } - - Output::from_raw(unsafe { string_constructor(Input::into_raw(value)) }) -} - -pub(super) unsafe fn string_eq(string: &JsString, array: PtrConst, len: PtrLength) -> bool { - js_bindgen::unsafe_global_wat! { - "(import \"js_sys\" \"string_eq\" (func $js_sys.import.string_eq (@sym (name \"js_sys.import.string_eq\")) (param {} {} {}) (result {}))){}", - "(func $js_sys.string_eq (@sym) (param {}) (param $string {}) (param $array {}) (param $len {}) (result {})", - " local.get $string{}", " local.get $array{}", " local.get $len{}", - " call $js_sys.import.string_eq (@reloc){}", ")", interpolate - r#macro::wat_input_import_type:: < & JsString > (), interpolate - r#macro::wat_input_import_type:: < PtrConst < u8 > > (), interpolate - r#macro::wat_input_import_type:: < PtrLength < u8 > > (), interpolate - r#macro::wat_output_import_type:: < bool > (), interpolate r#macro::wat_imports!((& - JsString, PtrConst < u8 >, PtrLength < u8 >), bool), interpolate - r#macro::wat_indirect!(bool), interpolate < & JsString as Input > ::WAT_TYPE, interpolate < - PtrConst < u8 > as Input > ::WAT_TYPE, interpolate < PtrLength < u8 > as Input > ::WAT_TYPE, - interpolate r#macro::wat_direct:: < bool > (), interpolate r#macro::wat_input!(& JsString), - interpolate r#macro::wat_input!(PtrConst < u8 >), interpolate r#macro::wat_input!(PtrLength - < u8 >), interpolate r#macro::wat_output!(bool), - } - - js_bindgen::import_js! { - module = "js_sys", - name = "string_eq", - required_embeds = [ - ("js_sys", "string.eq"), - r#macro::js_input_embed::<&JsString>(), - r#macro::js_input_embed::>(), - r#macro::js_input_embed::>(), - r#macro::js_output_embed::(), - ], - "{}{}{}{}{}", - interpolate r#macro::js_select!( - "", - "(string, array, len) => {\n", - (&JsString, PtrConst, PtrLength), - bool, - ), - interpolate r#macro::js_parameter!("string", &JsString), - interpolate r#macro::js_parameter!("array", PtrConst), - interpolate r#macro::js_parameter!("len", PtrLength), - interpolate r#macro::js_output!( - "\treturn ", - "this.#jsEmbed.js_sys['string.eq']", - "this.#jsEmbed.js_sys['string.eq'](string, array, len)", - bool, - &JsString, - PtrConst, - PtrLength, - ), - } - - unsafe extern "C" { - #[link_name = "js_sys.string_eq"] - fn string_eq( - string: <&JsString as Input>::Type, - array: as Input>::Type, - len: as Input>::Type, - ) -> ::Type; - } - - Output::from_raw(unsafe { - string_eq(Input::into_raw(string), Input::into_raw(array), Input::into_raw(len)) - }) -} - -pub(super) unsafe fn string_decode(array: PtrConst, len: PtrLength) -> JsString { - js_bindgen::unsafe_global_wat! { - "(import \"js_sys\" \"string_decode\" (func $js_sys.import.string_decode (@sym (name \"js_sys.import.string_decode\")) (param {} {}) (result {}))){}", - "(func $js_sys.string_decode (@sym) (param {}) (param $array {}) (param $len {}) (result {})", - " local.get $array{}", " local.get $len{}", - " call $js_sys.import.string_decode (@reloc){}", ")", interpolate - r#macro::wat_input_import_type:: < PtrConst < u8 > > (), interpolate - r#macro::wat_input_import_type:: < PtrLength < u8 > > (), interpolate - r#macro::wat_output_import_type:: < JsString > (), interpolate - r#macro::wat_imports!((PtrConst < u8 >, PtrLength < u8 >), JsString), interpolate - r#macro::wat_indirect!(JsString), interpolate < PtrConst < u8 > as Input > ::WAT_TYPE, - interpolate < PtrLength < u8 > as Input > ::WAT_TYPE, interpolate r#macro::wat_direct:: < - JsString > (), interpolate r#macro::wat_input!(PtrConst < u8 >), interpolate - r#macro::wat_input!(PtrLength < u8 >), interpolate r#macro::wat_output!(JsString), - } - - js_bindgen::import_js! { - module = "js_sys", - name = "string_decode", - required_embeds = [ - ("js_sys", "string.decode"), - r#macro::js_input_embed::>(), - r#macro::js_input_embed::>(), - r#macro::js_output_embed::(), - ], - "{}{}{}{}", - interpolate r#macro::js_select!( - "", - "(array, len) => {\n", - (PtrConst, PtrLength), - JsString, - ), - interpolate r#macro::js_parameter!("array", PtrConst), - interpolate r#macro::js_parameter!("len", PtrLength), - interpolate r#macro::js_output!( - "\treturn ", - "this.#jsEmbed.js_sys['string.decode']", - "this.#jsEmbed.js_sys['string.decode'](array, len)", - JsString, - PtrConst, - PtrLength, - ), - } - - unsafe extern "C" { - #[link_name = "js_sys.string_decode"] - fn string_decode( - array: as Input>::Type, - len: as Input>::Type, - ) -> ::Type; - } - - Output::from_raw(unsafe { string_decode(Input::into_raw(array), Input::into_raw(len)) }) -} - -pub(super) fn string_utf8_length(string: &JsString) -> f64 { - js_bindgen::unsafe_global_wat! { - "(import \"js_sys\" \"string_utf8_length\" (func $js_sys.import.string_utf8_length (@sym (name \"js_sys.import.string_utf8_length\")) (param {}) (result {}))){}", - "(func $js_sys.string_utf8_length (@sym) (param {}) (param $string {}) (result {})", - " local.get $string{}", " call $js_sys.import.string_utf8_length (@reloc){}", ")", - interpolate r#macro::wat_input_import_type:: < & JsString > (), interpolate - r#macro::wat_output_import_type:: < f64 > (), interpolate r#macro::wat_imports!((& - JsString), f64), interpolate r#macro::wat_indirect!(f64), interpolate < & JsString as Input - > ::WAT_TYPE, interpolate r#macro::wat_direct:: < f64 > (), interpolate - r#macro::wat_input!(& JsString), interpolate r#macro::wat_output!(f64), - } - - js_bindgen::import_js! { - module = "js_sys", - name = "string_utf8_length", - required_embeds = [ - ("js_sys", "string.utf8_length"), - r#macro::js_input_embed::<&JsString>(), - r#macro::js_output_embed::(), - ], - "{}{}{}", - interpolate r#macro::js_select!("", "(string) => {\n", (&JsString), f64), - interpolate r#macro::js_parameter!("string", &JsString), - interpolate r#macro::js_output!( - "\treturn ", - "this.#jsEmbed.js_sys['string.utf8_length']", - "this.#jsEmbed.js_sys['string.utf8_length'](string)", - f64, - &JsString, - ), - } - - unsafe extern "C" { - #[link_name = "js_sys.string_utf8_length"] - fn string_utf8_length(string: <&JsString as Input>::Type) -> ::Type; - } - - Output::from_raw(unsafe { string_utf8_length(Input::into_raw(string)) }) -} - -pub(super) unsafe fn string_encode(string: &JsString, array: PtrMut, len: PtrLength) { - js_bindgen::unsafe_global_wat! { - "(import \"js_sys\" \"string_encode\" (func $js_sys.import.string_encode (@sym (name \"js_sys.import.string_encode\")) (param {} {} {}))){}", - "(func $js_sys.string_encode (@sym) (param $string {}) (param $array {}) (param $len {})", - " local.get $string{}", " local.get $array{}", " local.get $len{}", - " call $js_sys.import.string_encode (@reloc)", ")", interpolate - r#macro::wat_input_import_type:: < & JsString > (), interpolate - r#macro::wat_input_import_type:: < PtrMut < u8 > > (), interpolate - r#macro::wat_input_import_type:: < PtrLength < u8 > > (), interpolate - r#macro::wat_imports!((& JsString, PtrMut < u8 >, PtrLength < u8 >),), interpolate < & - JsString as Input > ::WAT_TYPE, interpolate < PtrMut < u8 > as Input > ::WAT_TYPE, - interpolate < PtrLength < u8 > as Input > ::WAT_TYPE, interpolate r#macro::wat_input!(& - JsString), interpolate r#macro::wat_input!(PtrMut < u8 >), interpolate - r#macro::wat_input!(PtrLength < u8 >), - } - - js_bindgen::import_js! { - module = "js_sys", - name = "string_encode", - required_embeds = [ - ("js_sys", "string.encode"), - r#macro::js_input_embed::<&JsString>(), - r#macro::js_input_embed::>(), - r#macro::js_input_embed::>(), - ], - "{}{}{}{}{}", - interpolate r#macro::js_select!( - "", - "(string, array, len) => {\n", - (&JsString, PtrMut, PtrLength), - ), - interpolate r#macro::js_parameter!("string", &JsString), - interpolate r#macro::js_parameter!("array", PtrMut), - interpolate r#macro::js_parameter!("len", PtrLength), - interpolate r#macro::js_select!( - "this.#jsEmbed.js_sys['string.encode']", - "this.#jsEmbed.js_sys['string.encode'](string, array, len)\n}", - (&JsString, PtrMut, PtrLength), - ), - } - - unsafe extern "C" { - #[link_name = "js_sys.string_encode"] - fn string_encode( - string: <&JsString as Input>::Type, - array: as Input>::Type, - len: as Input>::Type, - ); - } - - unsafe { string_encode(Input::into_raw(string), Input::into_raw(array), Input::into_raw(len)) }; -} diff --git a/client/js-sys/src/string/string.js-sys.rs b/client/js-sys/src/string/string.js-sys.rs deleted file mode 100644 index 26f75f0b..00000000 --- a/client/js-sys/src/string/string.js-sys.rs +++ /dev/null @@ -1,26 +0,0 @@ -use crate::util::{PtrConst, PtrLength, PtrMut}; - -#[js_sys] -extern "js-sys" { - #[derive(Clone, Debug)] - pub type JsString; - - #[js_sys(js_name = "String")] - pub(super) fn string_constructor(value: &JsValue) -> JsString; - - #[js_sys(js_embed = "string.eq")] - pub(super) unsafe fn string_eq( - string: &JsString, - array: PtrConst, - len: PtrLength, - ) -> bool; - - #[js_sys(js_embed = "string.decode")] - pub(super) unsafe fn string_decode(array: PtrConst, len: PtrLength) -> JsString; - - #[js_sys(js_embed = "string.utf8_length")] - pub(super) fn string_utf8_length(string: &JsString) -> f64; - - #[js_sys(js_embed = "string.encode")] - pub(super) unsafe fn string_encode(string: &JsString, array: PtrMut, len: PtrLength); -} diff --git a/client/js-sys/src/value/mod.rs b/client/js-sys/src/value/mod.rs index d5f122a2..60fbbe68 100644 --- a/client/js-sys/src/value/mod.rs +++ b/client/js-sys/src/value/mod.rs @@ -1,7 +1,3 @@ -#[rustfmt::skip] -#[path ="value.gen.rs"] -mod value; - use core::marker::PhantomData; use core::mem::MaybeUninit; use core::slice; @@ -16,6 +12,12 @@ pub struct JsValue { _local: PhantomData<*const ()>, } +#[crate::js_sys(js_sys = crate)] +extern "js-sys" { + #[js_sys(js_embed = "js_value.partial_eq")] + fn js_value_partial_eq(value1: &JsValue, value2: &JsValue) -> bool; +} + impl JsValue { pub const UNDEFINED: Self = Self::new(0); pub const NULL: Self = Self::new(1); @@ -143,6 +145,6 @@ impl PartialEq for JsValue { "(value1, value2) => value1 === value2", ); - value::js_value_partial_eq(self, other) + js_value_partial_eq(self, other) } } diff --git a/client/js-sys/src/value/value.gen.rs b/client/js-sys/src/value/value.gen.rs deleted file mode 100644 index cc646c88..00000000 --- a/client/js-sys/src/value/value.gen.rs +++ /dev/null @@ -1,57 +0,0 @@ -//! This file was generated by `js-sys-bindgen`. - -#![allow(warnings)] - -use crate::{js_bindgen, r#macro}; -use crate::hazard::{Input, Output}; -use super::JsValue; -use crate::util::PtrLength; - -pub(super) fn js_value_partial_eq(value1: &JsValue, value2: &JsValue) -> bool { - js_bindgen::unsafe_global_wat! { - "(import \"js_sys\" \"js_value_partial_eq\" (func $js_sys.import.js_value_partial_eq (@sym (name \"js_sys.import.js_value_partial_eq\")) (param {} {}) (result {}))){}", - "(func $js_sys.js_value_partial_eq (@sym) (param {}) (param $value1 {}) (param $value2 {}) (result {})", - " local.get $value1{}", " local.get $value2{}", - " call $js_sys.import.js_value_partial_eq (@reloc){}", ")", interpolate - r#macro::wat_input_import_type:: < & JsValue > (), interpolate - r#macro::wat_input_import_type:: < & JsValue > (), interpolate - r#macro::wat_output_import_type:: < bool > (), interpolate r#macro::wat_imports!((& - JsValue), bool), interpolate r#macro::wat_indirect!(bool), interpolate < & JsValue as Input - > ::WAT_TYPE, interpolate < & JsValue as Input > ::WAT_TYPE, interpolate - r#macro::wat_direct:: < bool > (), interpolate r#macro::wat_input!(& JsValue), interpolate - r#macro::wat_input!(& JsValue), interpolate r#macro::wat_output!(bool), - } - - js_bindgen::import_js! { - module = "js_sys", - name = "js_value_partial_eq", - required_embeds = [ - ("js_sys", "js_value.partial_eq"), - r#macro::js_input_embed::<&JsValue>(), - r#macro::js_output_embed::(), - ], - "{}{}{}{}", - interpolate r#macro::js_select!("", "(value1, value2) => {\n", (&JsValue), bool), - interpolate r#macro::js_parameter!("value1", &JsValue), - interpolate r#macro::js_parameter!("value2", &JsValue), - interpolate r#macro::js_output!( - "\treturn ", - "this.#jsEmbed.js_sys['js_value.partial_eq']", - "this.#jsEmbed.js_sys['js_value.partial_eq'](value1, value2)", - bool, - &JsValue, - ), - } - - unsafe extern "C" { - #[link_name = "js_sys.js_value_partial_eq"] - fn js_value_partial_eq( - value1: <&JsValue as Input>::Type, - value2: <&JsValue as Input>::Type, - ) -> ::Type; - } - - Output::from_raw(unsafe { - js_value_partial_eq(Input::into_raw(value1), Input::into_raw(value2)) - }) -} diff --git a/client/js-sys/src/value/value.js-sys.rs b/client/js-sys/src/value/value.js-sys.rs deleted file mode 100644 index 02549c38..00000000 --- a/client/js-sys/src/value/value.js-sys.rs +++ /dev/null @@ -1,8 +0,0 @@ -use super::JsValue; -use crate::util::PtrLength; - -#[js_sys] -extern "js-sys" { - #[js_sys(js_embed = "js_value.partial_eq")] - pub(super) fn js_value_partial_eq(value1: &JsValue, value2: &JsValue) -> bool; -} diff --git a/client/test/Cargo.toml b/client/test/Cargo.toml index bd30282f..2aeb4de4 100644 --- a/client/test/Cargo.toml +++ b/client/test/Cargo.toml @@ -12,7 +12,7 @@ test = false [target.'cfg(all(target_family = "wasm", any(target_os = "none", target_os = "unknown")))'.dependencies] js-bindgen-test-macro = { workspace = true } -js-sys = { workspace = true, features = ["macro"] } +js-sys = { workspace = true } [lints] workspace = true diff --git a/client/web-sys/build.rs b/client/web-sys/build.rs deleted file mode 100644 index 0c567cc0..00000000 --- a/client/web-sys/build.rs +++ /dev/null @@ -1,66 +0,0 @@ -//! This file is not shipped to Crates.io, but it is present when depending on -//! `web-sys` via `git` or `path`. - -use std::io::ErrorKind; -use std::path::Path; -use std::process::Command; -use std::{env, fs, panic, process}; - -fn main() { - if option_env!("JBG_DEV").is_none_or(|value| value != "1") - || option_env!("CI").is_some_and(|value| value == "true") - { - return; - } - - if search_dir(&env::current_dir().unwrap(), false) { - let status = Command::new("cargo") - .env_remove("CARGO_ENCODED_RUSTFLAGS") - .current_dir("../../host") - .arg("+stable") - .arg("run") - .args(["-p", "cargo-js-sys"]) - .arg("--") - .arg("-q") - .arg("js-sys") - .args(["--manifest-path", "../client/web-sys/Cargo.toml"]) - .status() - .unwrap(); - - if !status.success() { - process::exit(status.code().unwrap_or(1)) - } - } -} - -fn search_dir(dir: &Path, mut any: bool) -> bool { - for entry in fs::read_dir(dir).unwrap() { - let entry = entry.unwrap(); - let path = entry.path(); - - if path.is_file() && path.as_os_str().as_encoded_bytes().ends_with(b".js-sys.rs") { - println!("cargo::rerun-if-changed={}", path.display()); - - if !any { - let r#gen = path.with_extension("").with_extension("gen.rs"); - - match fs::metadata(r#gen) { - Ok(meta) => { - let gen_mtime = meta.modified().unwrap(); - let js_sys_mtime = fs::metadata(&path).unwrap().modified().unwrap(); - - if gen_mtime < js_sys_mtime { - any = true; - } - } - Err(error) if error.kind() == ErrorKind::NotFound => any = true, - Err(error) => panic::panic_any(error), - } - } - } else if path.is_dir() { - any |= search_dir(&path, any); - } - } - - any -} diff --git a/client/web-sys/src/console.gen.rs b/client/web-sys/src/console.gen.rs deleted file mode 100644 index e6d01ee6..00000000 --- a/client/web-sys/src/console.gen.rs +++ /dev/null @@ -1,124 +0,0 @@ -//! This file was generated by `js-sys-bindgen`. - -#![allow(warnings)] - -use js_sys::{js_bindgen, r#macro}; -use js_sys::hazard::{Input, Output}; -use js_sys::JsValue; -use js_sys::hazard::JsCast; - -pub fn log0() { - js_bindgen::unsafe_global_wat! { - "(import \"web_sys\" \"console.log0\" (func $web_sys.import.console.log0 (@sym (name \"web_sys.import.console.log0\"))))", - "(func $web_sys.console.log0 (@sym)", " call $web_sys.import.console.log0 (@reloc)", ")", - } - - js_bindgen::import_js! (module = "web_sys", name = "console.log0", "globalThis.console.log"); - - unsafe extern "C" { - #[link_name = "web_sys.console.log0"] - fn log0(); - } - - unsafe { log0() }; -} - -pub fn log(data: &[T]) { - js_bindgen::unsafe_global_wat! { - "(import \"web_sys\" \"console.log\" (func $web_sys.import.console.log (@sym (name \"web_sys.import.console.log\")) (param {}))){}", - "(func $web_sys.console.log (@sym) (param $data {})", " local.get $data{}", - " call $web_sys.import.console.log (@reloc)", ")", interpolate - r#macro::wat_input_import_type:: < & [JsValue] > (), interpolate r#macro::wat_imports!((& - [JsValue]),), interpolate < & [JsValue] as Input > ::WAT_TYPE, interpolate - r#macro::wat_input!(& [JsValue]), - } - - js_bindgen::import_js! { - module = "web_sys", - name = "console.log", - required_embeds = [r#macro::js_input_embed::<&[JsValue]>()], - "{}{}{}", - interpolate r#macro::js_select!("", "(data) => {\n", (&[JsValue])), - interpolate r#macro::js_parameter!("data", &[JsValue]), - interpolate r#macro::js_select!( - "globalThis.console.log", - "globalThis.console.log(data)\n}", - (&[JsValue]), - ), - } - - unsafe extern "C" { - #[link_name = "web_sys.console.log"] - fn log(data: <&[JsValue] as Input>::Type); - } - - unsafe { log(Input::into_raw(data)) }; -} - -pub fn log2(data1: &JsValue, data2: &JsValue) { - js_bindgen::unsafe_global_wat! { - "(import \"web_sys\" \"console.log2\" (func $web_sys.import.console.log2 (@sym (name \"web_sys.import.console.log2\")) (param {} {}))){}", - "(func $web_sys.console.log2 (@sym) (param $data1 {}) (param $data2 {})", - " local.get $data1{}", " local.get $data2{}", - " call $web_sys.import.console.log2 (@reloc)", ")", interpolate - r#macro::wat_input_import_type:: < & JsValue > (), interpolate - r#macro::wat_input_import_type:: < & JsValue > (), interpolate r#macro::wat_imports!((& - JsValue),), interpolate < & JsValue as Input > ::WAT_TYPE, interpolate < & JsValue as Input - > ::WAT_TYPE, interpolate r#macro::wat_input!(& JsValue), interpolate r#macro::wat_input!(& - JsValue), - } - - js_bindgen::import_js! { - module = "web_sys", - name = "console.log2", - required_embeds = [r#macro::js_input_embed::<&JsValue>()], - "{}{}{}{}", - interpolate r#macro::js_select!("", "(data1, data2) => {\n", (&JsValue)), - interpolate r#macro::js_parameter!("data1", &JsValue), - interpolate r#macro::js_parameter!("data2", &JsValue), - interpolate r#macro::js_select!( - "globalThis.console.log", - "globalThis.console.log(data1, data2)\n}", - (&JsValue), - ), - } - - unsafe extern "C" { - #[link_name = "web_sys.console.log2"] - fn log2(data1: <&JsValue as Input>::Type, data2: <&JsValue as Input>::Type); - } - - unsafe { log2(Input::into_raw(data1), Input::into_raw(data2)) }; -} - -pub fn error(data: &JsValue) { - js_bindgen::unsafe_global_wat! { - "(import \"web_sys\" \"console.error\" (func $web_sys.import.console.error (@sym (name \"web_sys.import.console.error\")) (param {}))){}", - "(func $web_sys.console.error (@sym) (param $data {})", " local.get $data{}", - " call $web_sys.import.console.error (@reloc)", ")", interpolate - r#macro::wat_input_import_type:: < & JsValue > (), interpolate r#macro::wat_imports!((& - JsValue),), interpolate < & JsValue as Input > ::WAT_TYPE, interpolate r#macro::wat_input!(& - JsValue), - } - - js_bindgen::import_js! { - module = "web_sys", - name = "console.error", - required_embeds = [r#macro::js_input_embed::<&JsValue>()], - "{}{}{}", - interpolate r#macro::js_select!("", "(data) => {\n", (&JsValue)), - interpolate r#macro::js_parameter!("data", &JsValue), - interpolate r#macro::js_select!( - "globalThis.console.error", - "globalThis.console.error(data)\n}", - (&JsValue), - ), - } - - unsafe extern "C" { - #[link_name = "web_sys.console.error"] - fn error(data: <&JsValue as Input>::Type); - } - - unsafe { error(Input::into_raw(data)) }; -} diff --git a/client/web-sys/src/console.js-sys.rs b/client/web-sys/src/console.rs similarity index 90% rename from client/web-sys/src/console.js-sys.rs rename to client/web-sys/src/console.rs index 278353b6..bda90ba4 100644 --- a/client/web-sys/src/console.js-sys.rs +++ b/client/web-sys/src/console.rs @@ -1,5 +1,5 @@ -use js_sys::JsValue; use js_sys::hazard::JsCast; +use js_sys::{JsValue, js_sys}; #[js_sys(namespace = "console")] extern "js-sys" { diff --git a/client/web-sys/src/lib.rs b/client/web-sys/src/lib.rs index fd8ddd60..75faf108 100644 --- a/client/web-sys/src/lib.rs +++ b/client/web-sys/src/lib.rs @@ -1,7 +1,5 @@ #![no_std] -#[rustfmt::skip] -#[path ="console.gen.rs"] pub mod console; pub use js_sys; diff --git a/host/Cargo.toml b/host/Cargo.toml index 8e7a6f94..544116c8 100644 --- a/host/Cargo.toml +++ b/host/Cargo.toml @@ -1,7 +1,6 @@ [workspace] resolver = "3" members = [ - "cargo-js-sys", "cargo-shim", "cli-lib", "dev", @@ -35,14 +34,12 @@ include = [ ] [workspace.dependencies] -annotate-snippets = { version = "0.12", default-features = false } anstyle = { version = "1", default-features = false } anyhow = "1" argfile = { version = "1", features = ["response"] } axum = { version = "0.8", default-features = false, features = ["http1", "http2", "json", "tokio"] } cargo_metadata = "0.23" clap = { version = "4", features = ["derive"] } -clap-cargo = { version = "0.18", features = ["cargo_metadata"] } dtor = { version = "1", default-features = false, features = ["proc_macro"] } fantoccini = { version = "0.22", default-features = false, features = ["rustls-tls"] } foldhash = { version = "0.2", default-features = false } diff --git a/host/cargo-js-sys/Cargo.toml b/host/cargo-js-sys/Cargo.toml deleted file mode 100644 index bf04187b..00000000 --- a/host/cargo-js-sys/Cargo.toml +++ /dev/null @@ -1,35 +0,0 @@ -[package] -name = "cargo-js-sys" -version = "0.1.0" -edition = { workspace = true } -rust-version = "1.91" -license = { workspace = true } -include = { workspace = true } - -[package.metadata.dev] -require-feature = true - -[[bin]] -bench = false -name = "cargo-js-sys" -test = false - -[dependencies] -annotate-snippets = { workspace = true, optional = true } -anstyle = { workspace = true } -anyhow = { workspace = true } -cargo_metadata = { workspace = true } -clap = { workspace = true } -clap-cargo = { workspace = true } -js-bindgen-shared = { workspace = true, features = ["memmap"] } -js-sys-bindgen = { workspace = true } -prettyplease = { workspace = true } -proc-macro2 = { workspace = true, features = ["span-locations"] } -similar-asserts = { workspace = true } - -[features] -default = ["js-sys"] -js-sys = ["dep:annotate-snippets", "js-sys-bindgen/file"] - -[lints] -workspace = true diff --git a/host/cargo-js-sys/src/js_sys.rs b/host/cargo-js-sys/src/js_sys.rs deleted file mode 100644 index 57ce436f..00000000 --- a/host/cargo-js-sys/src/js_sys.rs +++ /dev/null @@ -1,370 +0,0 @@ -use std::ops::{ControlFlow, Deref}; -use std::path::Path; -use std::str::FromStr; -use std::{fs, process, str}; - -use annotate_snippets::renderer::DecorStyle; -use annotate_snippets::{AnnotationKind, Level, Renderer, Snippet}; -use anstyle::{AnsiColor, Style}; -use anyhow::Result; -use clap::Args; -use clap_cargo::{Manifest, Workspace}; -use js_bindgen_shared::ReadFile; -use js_sys_bindgen::syn::{self, Error, parse_quote}; -use similar_asserts::SimpleDiff; - -use crate::GlobalArgs; - -#[derive(Args)] -pub(crate) struct JsSys { - #[command(flatten)] - manifest: Manifest, - #[command(flatten)] - workspace: Workspace, - path: Option, -} - -#[derive(Clone)] -struct PathWrapper(String); - -impl JsSys { - pub(crate) fn run(self, global_args: GlobalArgs) -> Result<()> { - let mut summary = Summary::new(); - let mut success = true; - - let metadata = self.manifest.metadata(); - let metadata = metadata.exec()?; - let (packages, _) = self.workspace.partition_packages(&metadata); - let num_packages = packages.len(); - - for package in packages { - let js_sys: Option = - if let Some(path) = self.path.as_ref().map(PathWrapper::path) { - Some(path) - } else if package.name == "js-sys" { - Some(parse_quote!(crate)) - } else if let Some(package) = package - .dependencies - .iter() - .find(|dependency| dependency.name == "js-sys") - { - Some( - syn::parse_str( - &package - .rename - .as_ref() - .unwrap_or(&package.name) - .replace('-', "_"), - ) - .unwrap(), - ) - } else if let Some(package) = package - .dependencies - .iter() - .find(|dependency| dependency.name == "web-sys") - { - let web_sys = package - .rename - .as_ref() - .unwrap_or(&package.name) - .replace('-', "_"); - Some(syn::parse_str(&format!("{web_sys}::js_sys")).unwrap()) - } else { - None - }; - - let crate_ = package.name.replace('-', "_"); - - let base = if num_packages > 1 { - metadata.workspace_root.as_std_path() - } else { - package - .manifest_path - .parent() - .expect("package manifest should be in a directory") - .as_std_path() - }; - - for target in package - .targets - .iter() - .filter(|target| !target.is_custom_build()) - { - let dir = target - .src_path - .parent() - .expect("target source file should be in a directory") - .as_std_path(); - - let mut state = State { - summary: &mut summary, - base, - global_args, - package: &package.name, - crate_: &crate_, - js_sys: js_sys.as_ref(), - }; - - match state.process(dir)? { - ControlFlow::Continue(value) => success &= value, - ControlFlow::Break(()) => { - success = false; - break; - } - } - } - } - - if !global_args.quiet { - println!(); - - let style = Style::new().bold(); - println!( - "{style}{:>9}:{style:#} Total {}, {} {}, Unchanged {}, Errors {}", - "Summary", - summary.generated + summary.unchanged + summary.errors, - if global_args.check { - "Checked" - } else if global_args.dry_run { - "Planned" - } else { - "Generated" - }, - summary.generated, - summary.unchanged, - summary.errors - ); - } - - if !success { - process::exit(1); - } - - Ok(()) - } -} - -struct State<'a> { - summary: &'a mut Summary, - base: &'a Path, - global_args: GlobalArgs, - package: &'a str, - crate_: &'a str, - js_sys: Option<&'a syn::Path>, -} - -struct Summary { - generated: usize, - unchanged: usize, - errors: usize, -} - -impl Summary { - fn new() -> Self { - Self { - generated: 0, - unchanged: 0, - errors: 0, - } - } -} - -impl State<'_> { - fn process(&mut self, dir: &Path) -> Result> { - let mut success = true; - - for entry in fs::read_dir(dir)? { - let entry = entry?.path(); - let relative_entry = entry.strip_prefix(self.base).unwrap_or(&entry); - - if entry.is_file() - && let Some(file) = entry.file_name() - && file.as_encoded_bytes().ends_with(b".js-sys.rs") - { - let Some(js_sys) = self.js_sys else { - let style = Style::new().bold().fg_color(Some(AnsiColor::Red.into())); - eprintln!( - "{style}Error:{style:#} can't find `js-sys` in dependencies for `{}`, \ - provide it manually via `--path`", - self.package - ); - return Ok(ControlFlow::Break(())); - }; - let Some(output) = self.generate(js_sys, &entry, relative_entry)? else { - success = false; - continue; - }; - - success &= self.output(&entry, relative_entry, &output)?; - } else if entry.is_dir() { - match self.process(&entry)? { - ControlFlow::Continue(value) => success &= value, - ControlFlow::Break(()) => return Ok(ControlFlow::Break(())), - } - } - } - - Ok(ControlFlow::Continue(success)) - } - - fn generate( - &mut self, - js_sys: &syn::Path, - entry: &Path, - relative_entry: &Path, - ) -> Result> { - let input = ReadFile::new(entry)?; - let input = str::from_utf8(&input)?; - let output = match js_sys_bindgen::file(input, self.crate_, Some(js_sys.clone())) { - Ok(output) => output, - Err(error) => { - let path = relative_entry.to_string_lossy(); - let style = Style::new().bold().fg_color(Some(AnsiColor::Red.into())); - - let errors: Vec<_> = error - .into_iter() - .map(|error| { - Level::ERROR - .no_name() - .secondary_title(format!("{style}{:>9}:{style:#} {error}", "Error")) - .element( - Snippet::source(input) - .line_start(error.span().start().line) - .path(&path) - .annotation( - AnnotationKind::Primary.span(error.span().byte_range()), - ), - ) - }) - .collect(); - - let output = Renderer::styled() - .decor_style(DecorStyle::Unicode) - .render(&errors); - eprintln!("{output}"); - - self.summary.errors += 1; - - return Ok(None); - } - }; - - Ok(Some(prettyplease::unparse(&output))) - } - - fn output(&mut self, entry: &Path, relative_entry: &Path, output: &str) -> Result { - let output_file = entry.with_extension("").with_extension("gen.rs"); - let relative_output_file = output_file.strip_prefix(self.base).unwrap_or(&output_file); - let exists = output_file.exists(); - - if exists && !output_file.is_file() { - let style = Style::new().bold().fg_color(Some(AnsiColor::Red.into())); - eprintln!( - "{style}{:>9}:{style:#} output file exists but is not a file: {}", - "Error", - relative_output_file.display() - ); - - self.summary.errors += 1; - - return Ok(false); - } - - let current = exists.then(|| ReadFile::new(&output_file)).transpose()?; - let current = if let Some(current) = ¤t { - match str::from_utf8(current.deref()) { - Ok(current) => Some(current), - Err(error) => { - let style = Style::new().bold().fg_color(Some(AnsiColor::Red.into())); - eprintln!( - "{style}{:>9}:{style:#} output file exists but is not UTF-8: {}\n\t{error}", - "Error", - relative_output_file.display(), - ); - - self.summary.errors += 1; - - return Ok(false); - } - } - } else { - None - }; - - let feedback = |color: AnsiColor, text: &str| { - let style = Style::new().fg_color(Some(color.into())); - println!( - "{style}{:>9}:{style:#} {} -> {}", - text, - relative_entry.display(), - relative_output_file.display() - ); - }; - - if self.global_args.check { - let Some(current) = current else { - feedback(AnsiColor::Red, "Missing"); - self.summary.errors += 1; - return Ok(false); - }; - - if current == output { - if self.global_args.verbose { - feedback(AnsiColor::Green, "Checked"); - } - - self.summary.generated += 1; - Ok(true) - } else { - feedback(AnsiColor::Red, "Different"); - eprintln!( - "{}", - SimpleDiff::from_str(current, output, "current", "expected") - ); - - self.summary.errors += 1; - Ok(false) - } - } else if current.is_none_or(|current| current != output) { - if !self.global_args.dry_run { - fs::write(&output_file, output)?; - } - - if !self.global_args.quiet || self.global_args.check { - feedback( - AnsiColor::Green, - if self.global_args.dry_run { - "Planned" - } else { - "Generated" - }, - ); - } - - self.summary.generated += 1; - Ok(true) - } else { - if self.global_args.verbose { - feedback(AnsiColor::BrightBlack, "Unchanged"); - } - - self.summary.unchanged += 1; - Ok(true) - } - } -} - -impl FromStr for PathWrapper { - type Err = Error; - - fn from_str(s: &str) -> Result { - syn::parse_str::(s)?; - Ok(Self(s.to_owned())) - } -} - -impl PathWrapper { - fn path(&self) -> syn::Path { - syn::parse_str::(&self.0).unwrap() - } -} diff --git a/host/cargo-js-sys/src/main.rs b/host/cargo-js-sys/src/main.rs deleted file mode 100644 index 945f07b0..00000000 --- a/host/cargo-js-sys/src/main.rs +++ /dev/null @@ -1,57 +0,0 @@ -#[cfg(feature = "js-sys")] -mod js_sys; - -use anyhow::Result; -use clap::builder::ArgPredicate; -use clap::{Args, Parser, Subcommand}; -use clap_cargo::style::CLAP_STYLING; - -#[cfg(feature = "js-sys")] -use crate::js_sys::JsSys; - -#[cfg(not(any(feature = "js-sys")))] -compile_error!("pick at least one crate feature"); - -#[derive(Parser)] -#[command(name = "cargo", bin_name = "cargo", version, about, long_about = None, styles = CLAP_STYLING)] -struct Cli { - #[command(flatten)] - global_args: GlobalArgs, - #[command(subcommand)] - commands: Commands, -} - -#[derive(Args, Clone, Copy)] -struct GlobalArgs { - #[arg(global = true, short, long, conflicts_with = "verbose")] - quiet: bool, - #[arg(global = true, short, long)] - verbose: bool, - #[arg( - global = true, - short = 'n', - long, - conflicts_with = "check", - default_value_if("check", ArgPredicate::IsPresent, Some("true")) - )] - dry_run: bool, - #[arg(global = true, short = 'c', long)] - check: bool, -} - -#[derive(Subcommand)] -enum Commands { - #[cfg(feature = "js-sys")] - JsSys(JsSys), -} - -fn main() -> Result<()> { - let cli = Cli::parse(); - - match cli.commands { - #[cfg(feature = "js-sys")] - Commands::JsSys(js_sys) => js_sys.run(cli.global_args)?, - } - - Ok(()) -} diff --git a/host/dev/src/check.rs b/host/dev/src/check.rs index 9c563eda..ecc46bc4 100644 --- a/host/dev/src/check.rs +++ b/host/dev/src/check.rs @@ -9,7 +9,7 @@ use clap::builder::PossibleValue; use clap::{Args, ValueEnum}; use strum::{EnumIter, IntoEnumIterator}; -use crate::client::{self, Client, ClientTool}; +use crate::client::Client; use crate::command; use crate::host::{self, Host, HostTool}; @@ -26,7 +26,6 @@ enum_with_all!(enum Tools, Tool(Tool), "tools"); #[derive(Clone, Copy, Eq, PartialEq)] enum Tool { Shared(CheckTool), - Client(ClientTool), Host(HostTool), Zizmor, } @@ -75,14 +74,13 @@ impl Check { match tool { Tool::Shared(tool) => match tool { CheckTool::Clippy | CheckTool::RustSec => { - client_tools.push(client::Tool::Shared(tool)); + client_tools.push(tool); host_tools.push(host::Tool::Shared(tool)); } CheckTool::Tombi => root_tools.push(RootTool::Tombi), CheckTool::CargoSpellcheck => root_tools.push(RootTool::CargoSpellcheck), CheckTool::Typos => root_tools.push(RootTool::Typos), }, - Tool::Client(tool) => client_tools.push(client::Tool::Client(tool)), Tool::Host(tool) => host_tools.push(host::Tool::Host(tool)), Tool::Zizmor => root_tools.push(RootTool::Zizmor), } @@ -150,7 +148,6 @@ impl ValueEnum for Tool { static VALUES: LazyLock> = LazyLock::new(|| { CheckTool::iter() .map(Tool::Shared) - .chain(ClientTool::iter().map(Tool::Client)) .chain(HostTool::iter().map(Tool::Host)) .chain(iter::once(Tool::Zizmor)) .collect() @@ -162,7 +159,6 @@ impl ValueEnum for Tool { fn to_possible_value(&self) -> Option { match self { Self::Shared(tool) => tool.to_possible_value(), - Self::Client(tool) => tool.to_possible_value(), Self::Host(tool) => tool.to_possible_value(), Self::Zizmor => Some(PossibleValue::new("zizmor")), } diff --git a/host/dev/src/client/check.rs b/host/dev/src/client/check.rs index 9a9978f2..209d03d8 100644 --- a/host/dev/src/client/check.rs +++ b/host/dev/src/client/check.rs @@ -1,14 +1,8 @@ -use std::env; -use std::iter::Copied; use std::process::Command; -use std::slice::Iter; -use std::sync::LazyLock; use std::time::Instant; use anyhow::Result; -use clap::builder::PossibleValue; -use clap::{Args, ValueEnum}; -use strum::{EnumIter, IntoEnumIterator}; +use clap::Args; use super::permutation::Profile; use super::{ClientArgs, metadata}; @@ -25,16 +19,7 @@ pub struct Check { enum_with_all!(pub enum Tools, Tool(Tool), "tools"); -#[derive(Clone, Copy, Eq, PartialEq)] -pub enum Tool { - Shared(CheckTool), - Client(ClientTool), -} - -#[derive(Clone, Copy, EnumIter, Eq, PartialEq, ValueEnum)] -pub enum ClientTool { - CargoJsSys, -} +pub type Tool = CheckTool; impl Default for Check { fn default() -> Self { @@ -51,12 +36,12 @@ impl Check { } pub fn execute(self, verbose: bool) -> Result<()> { - let tools = Tool::from_tools(self.tools)?; + let tools = CheckTool::from_tools(self.tools)?; let start = Instant::now(); for tool in tools { match tool { - Tool::Shared(CheckTool::Clippy) => { + CheckTool::Clippy => { let commands = [ CargoCommand { title: "Check", @@ -79,50 +64,26 @@ impl Check { ]; metadata::run(self.args.clone(), &commands, Profile::Dev, verbose)?; } - Tool::Client(ClientTool::CargoJsSys) => { - let mut command = - if env::var_os("JBG_DEV_TOOLS").is_some_and(|value| value == "1") { - Command::new("cargo-js-sys") - } else { - let mut command = Command::new("cargo"); - command.arg("build").args(["-p", "cargo-js-sys"]); - - command::run("Build `cargo-js-sys`", command, verbose)?; - - let mut command = Command::new("cargo"); - command.arg("run").args(["-p", "cargo-js-sys"]).arg("--"); - command - }; - - command - .arg("js-sys") - .args(["--manifest-path", "../client/Cargo.toml"]) - .arg("--workspace") - .arg("-c") - .arg("-v"); - - command::run("Check `cargo-js-sys`", command, verbose)?; - } - Tool::Shared(CheckTool::RustSec) => { + CheckTool::RustSec => { let mut command = Command::new("cargo"); command.current_dir("../client").arg("audit"); command::run("RustSec", command, verbose)?; } - Tool::Shared(CheckTool::Tombi) => { + CheckTool::Tombi => { let mut command = Command::new("tombi"); command .current_dir("../client") .args(["lint", "--error-on-warnings", "."]); command::run("Tombi Lint", command, verbose)?; } - Tool::Shared(CheckTool::CargoSpellcheck) => { + CheckTool::CargoSpellcheck => { let mut command = Command::new("cargo"); command .current_dir("../client") .args(["spellcheck", "-m", "1"]); command::run("`cargo-spellcheck`", command, verbose)?; } - Tool::Shared(CheckTool::Typos) => { + CheckTool::Typos => { let mut command = Command::new("typos"); command.current_dir("../client"); command::run("Typos", command, verbose)?; @@ -136,37 +97,3 @@ impl Check { Ok(()) } } - -impl Default for Tool { - fn default() -> Self { - Self::Shared(CheckTool::default()) - } -} - -impl IntoEnumIterator for Tool { - type Iterator = Copied>; - - fn iter() -> Self::Iterator { - Self::value_variants().iter().copied() - } -} - -impl ValueEnum for Tool { - fn value_variants<'a>() -> &'a [Self] { - static VALUES: LazyLock> = LazyLock::new(|| { - CheckTool::iter() - .map(Tool::Shared) - .chain(ClientTool::iter().map(Tool::Client)) - .collect() - }); - - &VALUES - } - - fn to_possible_value(&self) -> Option { - match self { - Self::Shared(tool) => tool.to_possible_value(), - Self::Client(tool) => tool.to_possible_value(), - } - } -} diff --git a/host/dev/src/client/mod.rs b/host/dev/src/client/mod.rs index c99997eb..4701e223 100644 --- a/host/dev/src/client/mod.rs +++ b/host/dev/src/client/mod.rs @@ -12,8 +12,8 @@ use anyhow::Result; use clap::{Args, Subcommand, ValueEnum}; use strum::EnumIter; +pub use self::check::Tool; use self::check::{Check, Tools}; -pub use self::check::{ClientTool, Tool}; use self::fmt::Fmt; use self::permutation::{Profile, Toolchain}; use self::test::Test; diff --git a/host/js-sys-bindgen/Cargo.toml b/host/js-sys-bindgen/Cargo.toml index d33df660..86158689 100644 --- a/host/js-sys-bindgen/Cargo.toml +++ b/host/js-sys-bindgen/Cargo.toml @@ -37,8 +37,6 @@ tempfile = { workspace = true } wasmparser = { workspace = true } [features] -file = ["macro"] -macro = [] web-idl = ["dep:weedle2"] [lints] diff --git a/host/js-sys-bindgen/src/file.rs b/host/js-sys-bindgen/src/file.rs deleted file mode 100644 index 47682d37..00000000 --- a/host/js-sys-bindgen/src/file.rs +++ /dev/null @@ -1,92 +0,0 @@ -use std::mem; - -use proc_macro2::TokenStream; -use syn::{Error, File, Item, ItemMod, Meta, Path, Result, parse_quote}; - -use crate::ImportManager; -use crate::r#macro::{self, ErrorStack}; - -pub fn file(input: &str, crate_: &str, js_sys: Option) -> Result { - let mut file: File = syn::parse_str(input)?; - let mut imports = ImportManager::new(js_sys); - let mut error = ErrorStack::new(); - process_items( - mem::take(&mut file.items), - &mut file.items, - crate_, - &mut imports, - &mut error, - ); - - file.items = imports.iter().map(Item::from).chain(file.items).collect(); - - file.attrs = [ - parse_quote!(#![doc = " This file was generated by `js-sys-bindgen`."]), - parse_quote!(#![allow(warnings)]), - ] - .into_iter() - .chain(file.attrs) - .collect(); - - if let Some(error) = error.resolve() { - Err(error) - } else { - Ok(file) - } -} - -fn process_items( - items: Vec, - output: &mut Vec, - crate_: &str, - imports: &mut ImportManager, - error: &mut ErrorStack, -) { - for item in items { - match item { - item @ (Item::ExternCrate(_) | Item::Use(_)) => output.push(item), - Item::ForeignMod(mut foreign_mod) => { - let js_sys = foreign_mod - .attrs - .extract_if(.., |attr| attr.path().is_ident("js_sys")) - .next(); - - if let Some(js_sys) = js_sys { - let attr = match js_sys.meta { - Meta::Path(_) => TokenStream::new(), - Meta::List(list) => list.tokens, - Meta::NameValue(name_value) => { - error.push(Error::new_spanned( - name_value, - "found unsupported `js_sys` attribute syntax", - )); - continue; - } - }; - - match r#macro::internal(attr, foreign_mod, Some(crate_), Some(imports)) { - Ok(mut items) => output.append(&mut items), - Err((_, e)) => { - error.push(e); - } - } - } else { - error.push(Error::new_spanned( - foreign_mod, - "`js_sys` attribute not found", - )); - } - } - Item::Mod( - mut r#mod @ ItemMod { - content: Some(_), .. - }, - ) => { - let items = &mut r#mod.content.as_mut().unwrap().1; - process_items(mem::take(items), items, crate_, imports, error); - output.push(r#mod.into()); - } - item => error.push(Error::new_spanned(item, "item not supported")), - } - } -} diff --git a/host/js-sys-bindgen/src/function.rs b/host/js-sys-bindgen/src/function.rs index b543ade8..3b1072bb 100644 --- a/host/js-sys-bindgen/src/function.rs +++ b/host/js-sys-bindgen/src/function.rs @@ -127,9 +127,7 @@ impl Function { let mut foreign_call = quote_spanned!(span=> unsafe { #ident(#(#input::into_raw(#intern_input_names)),*) }); - if output_ty.is_empty() { - foreign_call.extend(quote_spanned!(span=> ;)); - } else { + if !output_ty.is_empty() { foreign_call = quote_spanned! (span=> #output::from_raw(#foreign_call)); } diff --git a/host/js-sys-bindgen/src/lib.rs b/host/js-sys-bindgen/src/lib.rs index 2a513783..5edca8ff 100644 --- a/host/js-sys-bindgen/src/lib.rs +++ b/host/js-sys-bindgen/src/lib.rs @@ -1,8 +1,5 @@ -#[cfg(feature = "file")] -mod file; mod function; mod hygiene; -#[cfg(feature = "macro")] mod r#macro; #[cfg(test)] mod tests; @@ -14,11 +11,8 @@ pub use proc_macro2; pub use quote; pub use syn; -#[cfg(feature = "file")] -pub use crate::file::file; pub use crate::function::{Function, FunctionJsOutput}; pub use crate::hygiene::{Hygiene, ImportManager}; -#[cfg(feature = "macro")] pub use crate::r#macro::r#macro; pub use crate::r#type::Type; #[cfg(feature = "web-idl")] diff --git a/host/js-sys-bindgen/src/macro.rs b/host/js-sys-bindgen/src/macro.rs index bdcb5821..a696fdc1 100644 --- a/host/js-sys-bindgen/src/macro.rs +++ b/host/js-sys-bindgen/src/macro.rs @@ -5,16 +5,12 @@ use quote::ToTokens; use syn::parse::Parser; use syn::{Error, ForeignItem, Item, ItemForeignMod, LitStr, Path, meta}; -use crate::{Function, FunctionJsOutput, Hygiene, ImportManager, Type}; +use crate::{Function, FunctionJsOutput, Hygiene, Type}; -pub fn r#macro( - attr: TokenStream, - item: TokenStream, - imports: Option<&mut ImportManager>, -) -> Result { +pub fn r#macro(attr: TokenStream, item: TokenStream) -> Result { let foreign_mod: ItemForeignMod = syn::parse2(item).map_err(Error::into_compile_error)?; - internal(attr, foreign_mod, None, imports) + internal(attr, foreign_mod, None) .map(|items| items.into_iter().map(Item::into_token_stream).collect()) .map_err(|(output, error)| { let error = error.into_compile_error(); @@ -34,7 +30,6 @@ pub(crate) fn internal( attr: TokenStream, mut foreign_mod: ItemForeignMod, crate_: Option<&str>, - imports: Option<&mut ImportManager>, ) -> Result, (Option>, Error)> { let mut error = ErrorStack::new(); @@ -43,9 +38,7 @@ pub(crate) fn internal( if let Err(e) = meta::parser(|meta| { if meta.path.is_ident("js_sys") { - if imports.is_some() { - Err(meta.error("`js_sys` attribute only allowed with proc-macro hygiene")) - } else if js_sys.is_some() { + if js_sys.is_some() { Err(meta.error("duplicate attribute")) } else { js_sys = Some(meta.value()?.parse()?); @@ -67,12 +60,8 @@ pub(crate) fn internal( error.push(e); } - let mut hygiene = if let Some(imports) = imports { - Hygiene::Imports(imports) - } else { - Hygiene::Hygiene { - js_sys: js_sys.as_ref(), - } + let mut hygiene = Hygiene::Hygiene { + js_sys: js_sys.as_ref(), }; for attr in foreign_mod diff --git a/host/js-sys-bindgen/src/tests/macro/function.rs b/host/js-sys-bindgen/src/tests/macro/function.rs index cc52a3bb..af5d08c1 100644 --- a/host/js-sys-bindgen/src/tests/macro/function.rs +++ b/host/js-sys-bindgen/src/tests/macro/function.rs @@ -37,7 +37,7 @@ fn basic() { fn log(data: <&JsValue as ::js_sys::hazard::Input>::Type); } - unsafe { log(::js_sys::hazard::Input::into_raw(data)) }; + unsafe { log(::js_sys::hazard::Input::into_raw(data)) } } }, "(import \"test_crate\" \"log\" (func $test_crate.import.log (@sym (name \ @@ -92,7 +92,7 @@ fn namespace() { fn log(data: <&JsValue as ::js_sys::hazard::Input>::Type); } - unsafe { log(::js_sys::hazard::Input::into_raw(data)) }; + unsafe { log(::js_sys::hazard::Input::into_raw(data)) } } }, "(import \"test_crate\" \"console.log\" (func $test_crate.import.console.log (@sym (name \ @@ -147,7 +147,7 @@ fn js_sys() { fn log(data: <&JsValue as js_sys::hazard::Input>::Type); } - unsafe { log(js_sys::hazard::Input::into_raw(data)) }; + unsafe { log(js_sys::hazard::Input::into_raw(data)) } } }, "(import \"test_crate\" \"log\" (func $test_crate.import.log (@sym (name \ @@ -214,7 +214,7 @@ fn two_parameters() { ::js_sys::hazard::Input::into_raw(data1), ::js_sys::hazard::Input::into_raw(data2), ) - }; + } } }, "(import \"test_crate\" \"log\" (func $test_crate.import.log (@sym (name \ @@ -259,7 +259,7 @@ fn empty() { fn log(); } - unsafe { log() }; + unsafe { log() } } }, "(import \"test_crate\" \"log\" (func $test_crate.import.log (@sym (name \ @@ -311,7 +311,7 @@ fn js_name() { fn logx(data: <&JsValue as ::js_sys::hazard::Input>::Type); } - unsafe { logx(::js_sys::hazard::Input::into_raw(data)) }; + unsafe { logx(::js_sys::hazard::Input::into_raw(data)) } } }, "(import \"test_crate\" \"logx\" (func $test_crate.import.logx (@sym (name \ @@ -353,7 +353,7 @@ fn js_import() { fn log(data: <&JsValue as ::js_sys::hazard::Input>::Type); } - unsafe { log(::js_sys::hazard::Input::into_raw(data)) }; + unsafe { log(::js_sys::hazard::Input::into_raw(data)) } } }, "(import \"test_crate\" \"log\" (func $test_crate.import.log (@sym (name \ @@ -412,7 +412,7 @@ fn js_embed() { fn log(data: <&JsValue as ::js_sys::hazard::Input>::Type); } - unsafe { log(::js_sys::hazard::Input::into_raw(data)) }; + unsafe { log(::js_sys::hazard::Input::into_raw(data)) } } }, "(import \"test_crate\" \"log\" (func $test_crate.import.log (@sym (name \ @@ -513,7 +513,7 @@ fn cfg() { fn log(); } - unsafe { log() }; + unsafe { log() } } }, "(import \"test_crate\" \"log\" (func $test_crate.import.log (@sym (name \ diff --git a/host/js-sys-bindgen/src/tests/macro/member.rs b/host/js-sys-bindgen/src/tests/macro/member.rs index 2233224e..a9cff861 100644 --- a/host/js-sys-bindgen/src/tests/macro/member.rs +++ b/host/js-sys-bindgen/src/tests/macro/member.rs @@ -43,7 +43,7 @@ fn method() { fn test(this: <&::js_sys::JsValue as ::js_sys::hazard::Input>::Type); } - unsafe { test(::js_sys::hazard::Input::into_raw(self)) }; + unsafe { test(::js_sys::hazard::Input::into_raw(self)) } } } }, @@ -126,7 +126,7 @@ fn method_par() { ::js_sys::hazard::Input::into_raw(par1), ::js_sys::hazard::Input::into_raw(par2), ) - }; + } } } }, @@ -288,7 +288,7 @@ fn setter() { ::js_sys::hazard::Input::into_raw(self), ::js_sys::hazard::Input::into_raw(value), ) - }; + } } } }, diff --git a/host/js-sys-bindgen/src/tests/macro/mod.rs b/host/js-sys-bindgen/src/tests/macro/mod.rs index ad739296..6ae771a9 100644 --- a/host/js-sys-bindgen/src/tests/macro/mod.rs +++ b/host/js-sys-bindgen/src/tests/macro/mod.rs @@ -32,8 +32,7 @@ macro_rules! test { let input = quote! $input; let foreign_mod = syn::parse2(input.clone()).unwrap(); - let output = - r#macro::internal(attr.clone(), foreign_mod, Some("test_crate"), None).unwrap(); + let output = r#macro::internal(attr.clone(), foreign_mod, Some("test_crate")).unwrap(); let output = prettyplease::unparse(&File { shebang: None, attrs: Vec::new(), @@ -100,7 +99,6 @@ fn inner(tmp: &Path, source: &str) -> Result<(Option, Option)> { TokenStream::new(), parse_quote! { extern "js-sys" { pub type JsTest; } }, Some("test_crate"), - None, ) .unwrap(); let js_test: TokenStream = js_test.into_iter().fold(TokenStream::new(), |mut acc, x| { diff --git a/host/js-sys-bindgen/src/tests/mod.rs b/host/js-sys-bindgen/src/tests/mod.rs index a9150b6d..d542a73d 100644 --- a/host/js-sys-bindgen/src/tests/mod.rs +++ b/host/js-sys-bindgen/src/tests/mod.rs @@ -7,7 +7,6 @@ macro_rules! test { }; } -#[cfg(feature = "macro")] mod r#macro; mod r#type; #[cfg(feature = "web-idl")] diff --git a/host/js-sys-macro/Cargo.toml b/host/js-sys-macro/Cargo.toml index 2e203f94..14d8be81 100644 --- a/host/js-sys-macro/Cargo.toml +++ b/host/js-sys-macro/Cargo.toml @@ -13,7 +13,7 @@ proc-macro = true test = false [dependencies] -js-sys-bindgen = { workspace = true, features = ["macro"] } +js-sys-bindgen = { workspace = true } proc-macro2 = { workspace = true, features = ["proc-macro"] } [lints] diff --git a/host/js-sys-macro/src/lib.rs b/host/js-sys-macro/src/lib.rs index e6c12fd9..feedcd8b 100644 --- a/host/js-sys-macro/src/lib.rs +++ b/host/js-sys-macro/src/lib.rs @@ -2,7 +2,7 @@ use proc_macro::TokenStream; #[proc_macro_attribute] pub fn js_sys(attr: TokenStream, item: TokenStream) -> TokenStream { - js_sys_bindgen::r#macro(attr.into(), item.into(), None) + js_sys_bindgen::r#macro(attr.into(), item.into()) .unwrap_or_else(|e| e) .into() }