Skip to content

Support variadic javascript function parameters #726

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

Merged
merged 15 commits into from
Sep 3, 2018
Merged
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
2 changes: 2 additions & 0 deletions crates/backend/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ pub struct ImportFunction {
pub rust_name: Ident,
pub js_ret: Option<syn::Type>,
pub catch: bool,
pub variadic: bool,
pub structural: bool,
pub kind: ImportFunctionKind,
pub shim: Ident,
Expand Down Expand Up @@ -463,6 +464,7 @@ impl ImportFunction {
shared::ImportFunction {
shim: self.shim.to_string(),
catch: self.catch,
variadic: self.variadic,
method,
structural: self.structural,
function: self.function.shared(),
Expand Down
4 changes: 2 additions & 2 deletions crates/cli-support/src/js/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1733,7 +1733,6 @@ impl<'a> Context<'a> {
}

fn global(&mut self, s: &str) {
let s = s;
let s = s.trim();

// Ensure a blank line between adjacent items, and ensure everything is
Expand Down Expand Up @@ -1963,8 +1962,9 @@ impl<'a, 'b> SubContext<'a, 'b> {

let js = Rust2Js::new(self.cx)
.catch(import.catch)
.variadic(import.variadic)
.process(descriptor.unwrap_function())?
.finish(&target);
.finish(&target)?;
self.cx.export(&import.shim, &js, None);
Ok(())
}
Expand Down
42 changes: 35 additions & 7 deletions crates/cli-support/src/js/rust2js.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use failure::Error;
use failure::{self, Error};

use super::{Context, Js2Rust};
use descriptor::{Descriptor, Function};
Expand Down Expand Up @@ -36,6 +36,9 @@ pub struct Rust2Js<'a, 'b: 'a> {

/// Whether or not we're catching JS exceptions
catch: bool,

/// Whether or not the last argument is a slice representing variadic arguments.
variadic: bool,
}

impl<'a, 'b> Rust2Js<'a, 'b> {
Expand All @@ -50,6 +53,7 @@ impl<'a, 'b> Rust2Js<'a, 'b> {
arg_idx: 0,
ret_expr: String::new(),
catch: false,
variadic: false,
}
}

Expand All @@ -62,6 +66,15 @@ impl<'a, 'b> Rust2Js<'a, 'b> {
self
}

pub fn variadic(&mut self, variadic: bool) -> &mut Self {
if variadic {
self.cx.expose_uint32_memory();
self.cx.expose_add_heap_object();
}
self.variadic = variadic;
self
}

/// Generates all bindings necessary for the signature in `Function`,
/// creating necessary argument conversions and return value processing.
pub fn process(&mut self, function: &Function) -> Result<&mut Self, Error> {
Expand All @@ -72,6 +85,7 @@ impl<'a, 'b> Rust2Js<'a, 'b> {
Ok(self)
}

/// Get a generated name for an argument.
fn shim_argument(&mut self) -> String {
let s = format!("arg{}", self.arg_idx);
self.arg_idx += 1;
Expand Down Expand Up @@ -515,7 +529,7 @@ impl<'a, 'b> Rust2Js<'a, 'b> {
Ok(())
}

pub fn finish(&self, invoc: &str) -> String {
pub fn finish(&self, invoc: &str) -> Result<String, Error> {
let mut ret = String::new();
ret.push_str("function(");
ret.push_str(&self.shim_arguments.join(", "));
Expand All @@ -528,10 +542,24 @@ impl<'a, 'b> Rust2Js<'a, 'b> {
ret.push_str(") {\n");
ret.push_str(&self.prelude);

let mut invoc = self.ret_expr.replace(
"JS",
&format!("{}({})", invoc, self.js_arguments.join(", ")),
);
let mut invoc = if self.variadic {
if self.js_arguments.is_empty() {
return Err(failure::err_msg("a function with no arguments cannot be variadic"));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stylistically I think this could just be bail!("...")

}
let last_arg = self.js_arguments.len() - 1; // check implies >= 0
self.ret_expr.replace(
"JS",
&format!("{}({}, ...{})",
invoc,
self.js_arguments[..last_arg].join(", "),
self.js_arguments[last_arg])
)
} else {
self.ret_expr.replace(
"JS",
&format!("{}({})", invoc, self.js_arguments.join(", ")),
)
};
if self.catch {
let catch = "\
const view = getUint32Memory();\n\
Expand Down Expand Up @@ -566,7 +594,7 @@ impl<'a, 'b> Rust2Js<'a, 'b> {
ret.push_str(&invoc);

ret.push_str("\n}\n");
return ret;
Ok(ret)
}

fn global_idx(&mut self) -> usize {
Expand Down
27 changes: 27 additions & 0 deletions crates/macro-support/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,14 @@ impl BindgenAttrs {
_ => None,
})
}

/// Whether the variadic attributes is present
fn variadic(&self) -> bool {
self.attrs.iter().any(|a| match *a {
BindgenAttr::Variadic => true,
_ => false,
})
}
}

impl syn::synom::Synom for BindgenAttrs {
Expand Down Expand Up @@ -219,6 +227,7 @@ pub enum BindgenAttr {
JsName(String),
JsClass(String),
Extends(Ident),
Variadic,
}

impl syn::synom::Synom for BindgenAttr {
Expand Down Expand Up @@ -304,6 +313,8 @@ impl syn::synom::Synom for BindgenAttr {
ns: call!(term2ident) >>
(ns)
)=> { BindgenAttr::Extends }
|
call!(term, "variadic") => { |_| BindgenAttr::Variadic }
));
}

Expand Down Expand Up @@ -365,6 +376,7 @@ impl<'a> ConvertToAst<()> for &'a mut syn::ItemStruct {
let getter = shared::struct_field_get(&ident, &name_str);
let setter = shared::struct_field_set(&ident, &name_str);
let opts = BindgenAttrs::find(&mut field.attrs)?;
assert_not_variadic(&opts, &field)?;
let comments = extract_doc_comments(&field.attrs);
fields.push(ast::StructField {
name: name.clone(),
Expand Down Expand Up @@ -395,6 +407,7 @@ impl<'a> ConvertToAst<(BindgenAttrs, &'a Option<String>)> for syn::ForeignItemFn
) -> Result<Self::Target, Diagnostic> {
let default_name = self.ident.to_string();
let js_name = opts.js_name().unwrap_or(&default_name);

let wasm = function_from_decl(
js_name,
self.decl.clone(),
Expand All @@ -404,6 +417,7 @@ impl<'a> ConvertToAst<(BindgenAttrs, &'a Option<String>)> for syn::ForeignItemFn
None,
)?.0;
let catch = opts.catch();
let variadic = opts.variadic();
let js_ret = if catch {
// TODO: this assumes a whole bunch:
//
Expand Down Expand Up @@ -533,6 +547,7 @@ impl<'a> ConvertToAst<(BindgenAttrs, &'a Option<String>)> for syn::ForeignItemFn
kind,
js_ret,
catch,
variadic,
structural: opts.structural(),
rust_name: self.ident.clone(),
shim: Ident::new(&shim, Span::call_site()),
Expand All @@ -545,6 +560,7 @@ impl ConvertToAst<BindgenAttrs> for syn::ForeignItemType {
type Target = ast::ImportKind;

fn convert(self, attrs: BindgenAttrs) -> Result<Self::Target, Diagnostic> {
assert_not_variadic(&attrs, &self)?;
let js_name = attrs
.js_name()
.map_or_else(|| self.ident.to_string(), |s| s.to_string());
Expand All @@ -570,6 +586,7 @@ impl<'a> ConvertToAst<(BindgenAttrs, &'a Option<String>)> for syn::ForeignItemSt
if self.mutability.is_some() {
bail_span!(self.mutability, "cannot import mutable globals yet")
}
assert_not_variadic(&opts, &self)?;
let default_name = self.ident.to_string();
let js_name = opts.js_name().unwrap_or(&default_name);
let shim = format!(
Expand Down Expand Up @@ -604,6 +621,7 @@ impl ConvertToAst<BindgenAttrs> for syn::ItemFn {
if self.unsafety.is_some() {
bail_span!(self.unsafety, "can only #[wasm_bindgen] safe functions");
}
assert_not_variadic(&attrs, &self)?;

let default_name = self.ident.to_string();
let name = attrs.js_name().unwrap_or(&default_name);
Expand Down Expand Up @@ -1074,6 +1092,15 @@ fn assert_no_lifetimes(decl: &syn::FnDecl) -> Result<(), Diagnostic> {
Diagnostic::from_vec(walk.diagnostics)
}

/// This method always fails if the BindgenAttrs contain variadic
fn assert_not_variadic(attrs: &BindgenAttrs, span: &dyn ToTokens) -> Result<(), Diagnostic> {
if attrs.variadic() {
bail_span!(span, "the `variadic` attribute can only be applied to imported \
(`extern`) functions")
}
Ok(())
}

/// If the path is a single ident, return it.
fn extract_path_ident(path: &syn::Path) -> Result<Ident, Diagnostic> {
if path.leading_colon.is_some() {
Expand Down
1 change: 1 addition & 0 deletions crates/shared/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ pub enum ImportKind {
pub struct ImportFunction {
pub shim: String,
pub catch: bool,
pub variadic: bool,
pub method: Option<MethodData>,
pub structural: bool,
pub function: Function,
Expand Down
1 change: 1 addition & 0 deletions crates/webidl/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ impl<'src> FirstPassRecord<'src> {
},
rust_name: rust_ident(rust_name),
js_ret: js_ret.clone(),
variadic: false,
catch,
structural,
shim:{
Expand Down
1 change: 1 addition & 0 deletions guide/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
- [`module = "blah"`](./reference/attributes/on-js-imports/module.md)
- [`static_method_of = Blah`](./reference/attributes/on-js-imports/static_method_of.md)
- [`structural`](./reference/attributes/on-js-imports/structural.md)
- [variadic](./reference/attributes/on-js-imports/variadic.md)
- [On Rust Exports](./reference/attributes/on-rust-exports/index.md)
- [`constructor`](./reference/attributes/on-rust-exports/constructor.md)
- [`js_name = Blah`](./reference/attributes/on-rust-exports/js_name.md)
Expand Down
38 changes: 38 additions & 0 deletions guide/src/reference/attributes/on-js-imports/variadic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Variadic Parameters

In javascript, both the types of function arguments, and the number of function arguments are
dynamic. For example

```js
function sum(...rest) {
let i;
// the old way
let old_way = 0;
for (i=0; i<arguments.length; i++) {
old_way += arguments[i];
}
// the new way
let new_way = 0;
for (i=0; i<rest.length; i++) {
new_way += rest[i];
}
// both give the same answer
assert(old_way === new_way);
return new_way;
}
```

This function doesn't translate directly into rust, since we don't currently support variadic
arguments on the wasm target. To bind to it, we use a slice as the last argument, and annotate the
function as variadic:

```rust
#[wasm_bindgen]
extern {
#[wasm_bindgen(variadic)]
fn sum(args: &[i32]) -> i32;
}
```

when we call this function, the last argument will be expanded as the javascript expects.

12 changes: 12 additions & 0 deletions guide/src/whirlwind-tour/what-else-can-we-do.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ extern {
fn new() -> Awesome;
#[wasm_bindgen(method)]
fn get_internal(this: &Awesome) -> u32;
// We can call javascript functions that have a dynamic number of arguments,
// e.g. rust `sum(&[1, 2, 3])` will be called like `sum(1, 2, 3)`
#[wasm_bindgen(variadic)]
fn sum(vals: &[u32]) -> u32;
}

#[wasm_bindgen]
Expand Down Expand Up @@ -143,5 +147,13 @@ export class Awesome {
}
}

export function sum(...args) {
let answer = 0;
for(var i=0; i<args.length; i++) {
answer += args[i];
}
return answer;
}

booted.then(main);
```
1 change: 1 addition & 0 deletions tests/wasm/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,4 @@ pub mod slice;
pub mod structural;
pub mod u64;
pub mod validate_prt;
pub mod variadic;
59 changes: 59 additions & 0 deletions tests/wasm/variadic.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const assert = require('assert');

// a function for testing numbers
function variadic_sum(...args) {
let answer = 0;
for(var i=0; i<args.length; i++) {
answer += args[i];
}
return answer;
}

exports.variadic_sum_u8 = variadic_sum;
exports.variadic_sum_u16 = variadic_sum;
exports.variadic_sum_u32 = variadic_sum;
exports.variadic_sum_u64 = variadic_sum;
exports.variadic_sum_i8 = variadic_sum;
exports.variadic_sum_i16 = variadic_sum;
exports.variadic_sum_i32 = variadic_sum;
exports.variadic_sum_i64 = variadic_sum;
exports.variadic_sum_f32 = variadic_sum;
exports.variadic_sum_f64 = variadic_sum;
exports.variadic_sum_rest_vec = variadic_sum;

// a function for testing nullable numbers
function variadic_sum_opt(...args) {
let answer = 0;
for(var i=0; i<args.length; i++) {
if(args[i] != null) {
answer += args[i];
}
}
return answer;
}

exports.variadic_sum_opt = variadic_sum_opt;

// a function for testing strings
function variadic_concat(...args) {
let answer = "";
for(var i=0; i<args.length; i++) {
answer = `${answer}${args[i]}`;
}
return answer;
}

exports.variadic_concat_str = variadic_concat;
exports.variadic_concat_string = variadic_concat;

// a test that takes any type of arguments (for testing JsValue).
function variadic_compare_pairs(...args) {
assert(args.length % 2 == 0, "args must be sequence of pairs");
for(var i=0; i<args.length; i++) {
const first = args[i++];
const second = args[i];
assert.equal(first, second);
}
}

exports.variadic_compare_pairs = variadic_compare_pairs;
Loading