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

Support raw identifiers for enums and enum variants #4323

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions crates/backend/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -475,8 +475,10 @@ pub struct Enum {
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
#[derive(Clone)]
pub struct Variant {
/// The name of this variant
pub name: Ident,
/// The name of this variant in Rust
pub rust_name: Ident,
/// The name of this variant in JS
pub js_name: String,
daxpedda marked this conversation as resolved.
Show resolved Hide resolved
/// The backing value of this variant
pub value: u32,
/// The doc comments on this variant, if any
Expand Down
2 changes: 1 addition & 1 deletion crates/backend/src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1543,7 +1543,7 @@ impl ToTokens for ast::Enum {
quote! { u32 }
};
let cast_clauses = self.variants.iter().map(|variant| {
let variant_name = &variant.name;
let variant_name = &variant.rust_name;
quote! {
if js == #enum_name::#variant_name as #underlying {
#enum_name::#variant_name
Expand Down
14 changes: 5 additions & 9 deletions crates/backend/src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ fn shared_program<'a>(
.iter()
.map(|a| shared_struct(a, intern))
.collect(),
enums: prog.enums.iter().map(|a| shared_enum(a, intern)).collect(),
enums: prog.enums.iter().map(|a| shared_enum(a)).collect(),
imports: prog
.imports
.iter()
Expand Down Expand Up @@ -236,23 +236,19 @@ fn shared_function<'a>(func: &'a ast::Function, _intern: &'a Interner) -> Functi
}
}

fn shared_enum<'a>(e: &'a ast::Enum, intern: &'a Interner) -> Enum<'a> {
fn shared_enum(e: &ast::Enum) -> Enum {
Enum {
name: &e.js_name,
signed: e.signed,
variants: e
.variants
.iter()
.map(|v| shared_variant(v, intern))
.collect(),
variants: e.variants.iter().map(shared_variant).collect(),
comments: e.comments.iter().map(|s| &**s).collect(),
generate_typescript: e.generate_typescript,
}
}

fn shared_variant<'a>(v: &'a ast::Variant, intern: &'a Interner) -> EnumVariant<'a> {
fn shared_variant(v: &ast::Variant) -> EnumVariant {
EnumVariant {
name: intern.intern(&v.name),
name: v.js_name.as_str(),
RunDevelopment marked this conversation as resolved.
Show resolved Hide resolved
value: v.value,
comments: v.comments.iter().map(|s| &**s).collect(),
}
Expand Down
3 changes: 3 additions & 0 deletions crates/cli/tests/reference/raw.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
/* tslint:disable */
/* eslint-disable */
export function test1(test: number): number;
export enum Enum {
A = 0,
}
export class Test {
private constructor();
free(): void;
Expand Down
7 changes: 7 additions & 0 deletions crates/cli/tests/reference/raw.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ export function test1(test) {
return ret >>> 0;
}

/**
* @enum {0}
*/
export const Enum = Object.freeze({
A: 0, "0": "A",
});

const TestFinalization = (typeof FinalizationRegistry === 'undefined')
? { register: () => {}, unregister: () => {} }
: new FinalizationRegistry(ptr => wasm.__wbg_test_free(ptr >>> 0, 1));
Expand Down
5 changes: 5 additions & 0 deletions crates/cli/tests/reference/raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,8 @@ impl r#Test {
extern "C" {
fn r#test2() -> JsValue;
}

#[wasm_bindgen]
pub enum r#Enum {
r#A,
}
63 changes: 24 additions & 39 deletions crates/macro-support/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,20 @@ impl BindgenAttrs {
Ok(thread_local)
}

/// Returns the JS name from the given attributes, or the Rust name if not present.
fn js_name_or_ident(&self, ident: &Ident) -> String {
self.js_name()
.map(|(n, _)| n.to_string())
.unwrap_or_else(|| ident.unraw().to_string())
}

/// Returns the JS class from the given attributes, or the Rust name if not present.
fn js_class_or_ident(&self, ident: &Ident) -> String {
self.js_class()
.map(|(n, _)| n.to_string())
.unwrap_or_else(|| ident.unraw().to_string())
}

attrgen!(methods);
}

Expand Down Expand Up @@ -437,10 +451,7 @@ impl ConvertToAst<(&ast::Program, BindgenAttrs)> for &mut syn::ItemStruct {
);
}
let mut fields = Vec::new();
let js_name = attrs
.js_name()
.map(|s| s.0.to_string())
.unwrap_or(self.ident.unraw().to_string());
let js_name = attrs.js_name_or_ident(&self.ident);
let is_inspectable = attrs.inspectable().is_some();
let getter_with_clone = attrs.getter_with_clone();
for (i, field) in self.fields.iter_mut().enumerate() {
Expand Down Expand Up @@ -573,11 +584,7 @@ impl<'a> ConvertToAst<(&ast::Program, BindgenAttrs, &'a Option<ast::ImportModule
}) => path,
_ => bail_span!(class, "first argument of method must be a path"),
};
let class_name = extract_path_ident(class_name)?;
let class_name = opts
.js_class()
.map(|p| p.0.into())
.unwrap_or_else(|| class_name.to_string());
let class_name = opts.js_class_or_ident(&extract_path_ident(class_name)?);

let kind = ast::MethodKind::Operation(ast::Operation {
is_static: false,
Expand All @@ -590,10 +597,7 @@ impl<'a> ConvertToAst<(&ast::Program, BindgenAttrs, &'a Option<ast::ImportModule
kind,
}
} else if let Some(cls) = opts.static_method_of() {
let class = opts
.js_class()
.map(|p| p.0.into())
.unwrap_or_else(|| cls.to_string());
let class = opts.js_class_or_ident(cls);
let ty = ident_ty(cls.clone());

let kind = ast::MethodKind::Operation(ast::Operation {
Expand All @@ -614,11 +618,7 @@ impl<'a> ConvertToAst<(&ast::Program, BindgenAttrs, &'a Option<ast::ImportModule
}) => path,
_ => bail_span!(self, "return value of constructor must be a bare path"),
};
let class_name = extract_path_ident(class_name)?;
let class_name = opts
.js_class()
.map(|p| p.0.into())
.unwrap_or_else(|| class_name.to_string());
let class_name = opts.js_class_or_ident(&extract_path_ident(class_name)?);

ast::ImportFunctionKind::Method {
class: class_name,
Expand Down Expand Up @@ -718,10 +718,7 @@ impl ConvertToAst<(&ast::Program, BindgenAttrs)> for syn::ForeignItemType {
self,
(program, attrs): (&ast::Program, BindgenAttrs),
) -> Result<Self::Target, Diagnostic> {
let js_name = attrs
.js_name()
.map(|s| s.0)
.map_or_else(|| self.ident.to_string(), |s| s.to_string());
let js_name = attrs.js_name_or_ident(&self.ident);
let typescript_type = attrs.typescript_type().map(|s| s.0.to_string());
let is_type_of = attrs.is_type_of().cloned();
let shim = format!(
Expand Down Expand Up @@ -783,12 +780,7 @@ impl<'a> ConvertToAst<(&ast::Program, BindgenAttrs, &'a Option<ast::ImportModule
));
}

let default_name = self.ident.to_string();
let js_name = opts
.js_name()
.map(|p| p.0)
.unwrap_or(&default_name)
.to_string();
let js_name = opts.js_name_or_ident(&self.ident);
let shim = format!(
"__wbg_static_accessor_{}_{}",
self.ident,
Expand Down Expand Up @@ -1285,12 +1277,7 @@ fn prepare_for_impl_recursion(
other => bail_span!(other, "failed to parse this item as a known item"),
};

let ident = extract_path_ident(class)?;

let js_class = impl_opts
.js_class()
.map(|s| s.0.to_string())
.unwrap_or(ident.to_string());
let js_class = impl_opts.js_class_or_ident(&extract_path_ident(class)?);

let wasm_bindgen = &program.wasm_bindgen;
let wasm_bindgen_futures = &program.wasm_bindgen_futures;
Expand Down Expand Up @@ -1481,10 +1468,7 @@ impl<'a> MacroParse<(&'a mut TokenStream, BindgenAttrs)> for syn::ItemEnum {
}

let generate_typescript = opts.skip_typescript().is_none();
let js_name = opts
.js_name()
.map(|s| s.0)
.map_or_else(|| self.ident.to_string(), |s| s.to_string());
let js_name = opts.js_name_or_ident(&self.ident);
let comments = extract_doc_comments(&self.attrs);

opts.check_used();
Expand Down Expand Up @@ -1588,7 +1572,8 @@ impl<'a> MacroParse<(&'a mut TokenStream, BindgenAttrs)> for syn::ItemEnum {

let comments = extract_doc_comments(&v.attrs);
Ok(ast::Variant {
name: v.ident.clone(),
rust_name: v.ident.clone(),
js_name: v.ident.unraw().to_string(),
// due to the above checks, we know that the value fits
// within 32 bits, so this cast doesn't lose any information
value: value as u32,
Expand Down
Loading