Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace all Self identifiers in method argument and return types #4155

Merged
merged 9 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
* Added `unsupported` crate to `wasm_bindgen_test(unsupported = test)` as a way of running tests on non-Wasm targets as well.
[#4150](https://github.com/rustwasm/wasm-bindgen/pull/4150)

* Added support for `Self` in complex type expressions in methods.
[#4155](https://github.com/rustwasm/wasm-bindgen/pull/4155)

### Changed

* Implicitly enable reference type and multivalue transformations if the module already makes use of the corresponding target features.
Expand Down
48 changes: 24 additions & 24 deletions crates/cli/tests/reference/raw.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,6 @@ export function __wbg_set_wasm(val) {
}


const lTextDecoder = typeof TextDecoder === 'undefined' ? (0, module.require)('util').TextDecoder : TextDecoder;

let cachedTextDecoder = new lTextDecoder('utf-8', { ignoreBOM: true, fatal: true });

cachedTextDecoder.decode();

let cachedUint8ArrayMemory0 = null;

function getUint8ArrayMemory0() {
if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
}
return cachedUint8ArrayMemory0;
}

function getStringFromWasm0(ptr, len) {
ptr = ptr >>> 0;
return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
}

const heap = new Array(128).fill(undefined);

heap.push(undefined, null, true, false);
Expand All @@ -45,6 +25,26 @@ function takeObject(idx) {
dropObject(idx);
return ret;
}

const lTextDecoder = typeof TextDecoder === 'undefined' ? (0, module.require)('util').TextDecoder : TextDecoder;

let cachedTextDecoder = new lTextDecoder('utf-8', { ignoreBOM: true, fatal: true });

cachedTextDecoder.decode();

let cachedUint8ArrayMemory0 = null;

function getUint8ArrayMemory0() {
if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
}
return cachedUint8ArrayMemory0;
}

function getStringFromWasm0(ptr, len) {
ptr = ptr >>> 0;
return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
}
/**
* @param {number} test
* @returns {number}
Expand Down Expand Up @@ -109,11 +109,11 @@ export function __wbg_test2_39fe629b9aa739cf() {
return addHeapObject(ret);
};

export function __wbindgen_throw(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};

export function __wbindgen_object_drop_ref(arg0) {
takeObject(arg0);
};

export function __wbindgen_throw(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};

2 changes: 1 addition & 1 deletion crates/macro-support/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@ strict-macro = []
[dependencies]
proc-macro2 = "1.0"
quote = '1.0'
syn = { version = '2.0', features = ['visit', 'full'] }
syn = { version = '2.0', features = ['visit', 'visit-mut', 'full'] }
wasm-bindgen-backend = { path = "../backend", version = "=0.2.93" }
wasm-bindgen-shared = { path = "../shared", version = "=0.2.93" }
28 changes: 14 additions & 14 deletions crates/macro-support/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use quote::ToTokens;
use syn::ext::IdentExt;
use syn::parse::{Parse, ParseStream, Result as SynResult};
use syn::spanned::Spanned;
use syn::visit_mut::VisitMut;
use syn::{ItemFn, Lit, MacroDelimiter, ReturnType};

use crate::ClassMarker;
Expand Down Expand Up @@ -884,6 +885,15 @@ pub(crate) fn is_js_keyword(keyword: &str, skip: Option<&[&str]>) -> bool {
.any(|this| *this == keyword)
}

struct SelfReplace(Ident);
impl VisitMut for SelfReplace {
fn visit_ident_mut(&mut self, i: &mut proc_macro2::Ident) {
if i == "Self" {
*i = self.0.clone();
}
}
}

/// Construct a function (and gets the self type if appropriate) for our AST from a syn function.
#[allow(clippy::too_many_arguments)]
fn function_from_decl(
Expand Down Expand Up @@ -911,24 +921,14 @@ fn function_from_decl(

let syn::Signature { inputs, output, .. } = sig;

let replace_self = |t: syn::Type| {
let replace_self = |mut t: syn::Type| {
let self_ty = match self_ty {
Some(i) => i,
None => return t,
};
let path = match get_ty(&t) {
syn::Type::Path(syn::TypePath { qself: None, path }) => path.clone(),
other => return other.clone(),
};
let new_path = if path.segments.len() == 1 && path.segments[0].ident == "Self" {
self_ty.clone().into()
} else {
path
};
syn::Type::Path(syn::TypePath {
qself: None,
path: new_path,
})
let mut replace = SelfReplace(self_ty.clone());
replace.visit_type_mut(&mut t);
t
};

let replace_colliding_arg = |i: &mut syn::PatType| {
Expand Down
28 changes: 28 additions & 0 deletions tests/wasm/inner_self.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//! This tests that the `wasm_bindgen` macro produces code that compiles for these use cases.
//! `cargo test --target wasm32-unknown-unknown` will not run if any of these tests breaks.
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub struct A;

#[wasm_bindgen]
pub struct SelfPortrait;

#[wasm_bindgen]
impl A {
pub fn test_only_self() -> Self {
A
}
pub fn test_option_self() -> Option<Self> {
None
}
pub fn test_nested_self() -> Result<Option<Self>, String> {
Ok(None)
}
pub fn test_self_slice() -> Box<[Self]> {
Box::new([])
}
pub fn test_selfish() -> Result<Self, SelfPortrait> {
Ok(A)
}
}
1 change: 1 addition & 0 deletions tests/wasm/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ pub mod getters_and_setters;
pub mod ignore;
pub mod import_class;
pub mod imports;
pub mod inner_self;
pub mod intrinsics;
pub mod js_keywords;
pub mod js_objects;
Expand Down