Commit Graph

521 Commits

Author SHA1 Message Date
Alex Crichton
68c5233f80 First refactor for WebIDL bindings
This commit starts the `wasm-bindgen` CLI tool down the road to being a
true polyfill for WebIDL bindings. This refactor is probably the first
of a few, but is hopefully the largest and most sprawling and everything
will be a bit more targeted from here on out.

The goal of this refactoring is to separate out the massive
`crates/cli-support/src/js/mod.rs` into a number of separate pieces of
functionality. It currently takes care of basically everything
including:

* Binding intrinsics
* Handling anyref transformations
* Generating all JS for imports/exports
* All the logic for how to import and how to name imports
* Execution and management of wasm-bindgen closures

Many of these are separable concerns and most overlap with WebIDL
bindings. The internal refactoring here is intended to make it more
clear who's responsible for what as well as making some existing
operations much more straightforward. At a high-level, the following
changes are done:

1. A `src/webidl.rs` module is introduced. The purpose of this module is
   to take all of the raw wasm-bindgen custom sections from the module
   and transform them into a WebIDL bindings section.

  This module has a placeholder `WebidlCustomSection` which is nowhere
  near the actual custom section but if you squint is in theory very
  similar. It's hoped that this will eventually become the true WebIDL
  custom section, currently being developed in an external crate.

  Currently, however, the WebIDL bindings custom section only covers a
  subset of the functionality we export to wasm-bindgen users. To avoid
  leaving them high and dry this module also contains an auxiliary
  custom section named `WasmBindgenAux`. This custom section isn't
  intended to have a binary format, but is intended to represent a
  theoretical custom section necessary to couple with WebIDL bindings to
  achieve all our desired functionality in `wasm-bindgen`. It'll never
  be standardized, but it'll also never be serialized :)

2. The `src/webidl.rs` module now takes over quite a bit of
   functionality from `src/js/mod.rs`. Namely it handles synthesis of an
   `export_map` and an `import_map` mapping export/import IDs to exactly
   what's expected to be hooked up there. This does not include type
   information (as that's in the bindings section) but rather includes
   things like "this is the method of class A" or "this import is from
   module `foo`" and things like that. These could arguably be subsumed
   by future JS features as well, but that's for another time!

3. All handling of wasm-bindgen "descriptor functions" now happens in a
   dedicated `src/descriptors.rs` module. The output of this module is
   its own custom section (intended to be immediately consumed by the
   WebIDL module) which is in theory what we want to ourselves emit one
   day but rustc isn't capable of doing so right now.

4. Invocations and generations of imports are completely overhauled.
   Using the `import_map` generated in the WebIDL step all imports are
   now handled much more precisely in one location rather than
   haphazardly throughout the module. This means we have precise
   information about each import of the module and we only modify
   exactly what we're looking at. This also vastly simplifies intrinsic
   generation since it's all simply a codegen part of the `rust2js.rs`
   module now.

5. Handling of direct imports which don't have a JS shim generated is
   slightly different from before and is intended to be
   future-compatible with WebIDL bindings in its full glory, but we'll
   need to update it to handle cases for constructors and method calls
   eventually as well.

6. Intrinsic definitions now live in their own file (`src/intrinsic.rs`)
   and have a separated definition for their symbol name and signature.
   The actual implementation of each intrinsic lives in `rust2js.rs`

There's a number of TODO items to finish before this merges. This
includes reimplementing the anyref pass and actually implementing import
maps for other targets. Those will come soon in follow-up commits, but
the entire `tests/wasm/main.rs` suite is currently passing and this
seems like a good checkpoint.
2019-06-05 07:52:14 -07:00
Alex Crichton
c876bd6268
Merge pull request #1570 from DiamondLovesYou/master
Support 8 argument closures.
2019-06-03 09:36:41 -05:00
Richard Diamond
03218d9d3c Support 8 argument closures. 2019-06-01 04:19:26 -05:00
Gus Caplan
2cc40a27d2
Run fmt and clippy 2019-05-28 09:52:44 -05:00
Alex Crichton
a68cdc594d Add a test that Callback::forget works 2019-05-20 09:32:37 -07:00
Nick Fitzgerald
c504c381ca
Merge pull request #1530 from alexcrichton/drop-glue-closures
Protect against segfaults calling destroyed closures
2019-05-13 09:43:32 -07:00
Alex Crichton
15defcfd3a Add a debug assert and more tests 2019-05-13 08:12:32 -07:00
Alex Crichton
542076d658 Protect against segfaults calling destroyed closures
This commit updates the drop glue generated for closures to simply
ignore null pointers. The drop glue can be called in erroneous
situations such as when a closure is invoked after it's been destroyed.
In these cases we don't want to segfault and/or corrupt memory but
instead let the normal error message from the invoke glue continue to
get propagated.

Closes #1526
2019-05-13 07:22:33 -07:00
Nick Fitzgerald
450c9234ad Add the anyref_heap_live_count function
This is useful for debugging and writing tests that assert various operations do
not leak `JsValue`s.
2019-05-09 15:57:21 -07:00
Alex Crichton
3d43d6e5e8 Fix importing and exporting the same name
Run exports through the same identifier generation as imports to ensure
that everything gets a unique identifier and then just make sure all the
appropriate wires are hooked up when dealing with exports and imports.

Closes #1496
2019-05-03 07:15:20 -07:00
Alex Crichton
22eb34d9ab Fix direct imports in --target web
Currently the import object constructed for the `--target web` output
only ever includes the current module as an one of the modules included.
With `wasm-bindgen`'s optimization to import directly from modules,
however, it's possible to have more modules imported from in the
generated wasm file. This commit ensures that the imports are hooked up
in the `--target web` es6 emulation mode, ensuring there aren't
extraneous errors about import objects.
2019-05-01 13:53:59 -07:00
Alex Crichton
c70ed36be4 Add some tests which do computation in getters/setters 2019-04-30 10:02:11 -07:00
Caio
470eea9fb0 Getters/Setters for fields 2019-04-30 10:26:03 -03:00
Ingvar Stepanyan
3a7d384dc8 Generate bindings for indexed struct properties
This allows to export fields of tuple-like structs as indexed JS properties.
2019-04-17 12:56:14 +01:00
Alex Crichton
ff1addbbaa Run cargo fmt 2019-04-16 10:52:27 -07:00
alexlapa
00c4dd9b6f Merge branch 'master' into add-wasm-bindgen-skip-attr 2019-04-14 23:43:21 +03:00
Alex Crichton
e39404e633 Add support for isize/usize arrays
Closes #1426
2019-04-12 08:56:36 -07:00
Alex Crichton
7e5e401076 Add an accessor for the function table
This commit adds an intrinsics to the `wasm_bindgen` crate which
accesses the `WebAssembly.Table` which is the function table of the
module. Eventually the thinking is that a module would import its own
function table via native wasm functionality (via `anyref` and such),
but until that's implemented let's add a binding for it ourselves!

Closes #1427
2019-04-08 10:40:46 -07:00
Alex Crichton
f48fdec21e Fix imported usage of wasm_bindgen macro
Make sure it refers to `__wasm_bindgen_class_marker` via an absolute
path!

Closes #1422
2019-04-04 09:56:16 -07:00
Alex Crichton
d48f4995e5 Support 1-reference argument closures
This is work towards #1399, although it's just for one-argument closures
where the first argument is a reference. No other closures with
references in argument position are supported yet
2019-04-01 14:31:21 -07:00
alexlapa
1dcf468c9d add wasm_bindgen(skip) attr to disable getters and setters exposure of pub fields 2019-03-30 05:09:02 +02:00
Sam Day
1914bba0be Implement Debug on Closures
resolves #1387
2019-03-29 09:07:48 +01:00
Alex Crichton
0160f6af45 Fix handling of u32 between Rust and JS
All numbers in WebAssembly are signed and then each operation on them
may optionally have an unsigned version. This means that when we pass
large signed numbers to JS they actually show up as large negative
numbers even though JS numbers can faithfully represent the type.

This is fixed by adding `>>>0` in a few locations in the generated
bindings to coerce the JS value into an unsigned value.

Closes #1388
2019-03-27 13:37:14 -07:00
Alex Crichton
a6fe0cefa8 Migrate all crates to the 2018 edition
Most of the CLI crates were already in the 2018 edition, and it turns
out that one of the macro crates was already in the 2018 edition so we
may as well move everything to the 2018 edition!

Always nice to remove those `extern crate` statements nowadays!

This commit also does a `cargo fmt --all` to make sure we're conforming
with style again.
2019-03-26 08:10:53 -07:00
Caio
70f5373348 Preserve argument names 2019-03-14 08:46:42 -03:00
Alex Crichton
7e62aff1ce Fix a case where snippet is specified twice
When importing a file across multiple locations in a module make sure it
doesn't trip an assert and it works as expected.
2019-03-05 08:00:47 -08:00
Alex Crichton
b762948456 Implement the local JS snippets RFC
This commit is an implementation of [RFC 6] which enables crates to
inline local JS snippets into the final output artifact of
`wasm-bindgen`. This is accompanied with a few minor breaking changes
which are intended to be relatively minor in practice:

* The `module` attribute disallows paths starting with `./` and `../`.
  It requires paths starting with `/` to actually exist on the filesystem.
* The `--browser` flag no longer emits bundler-compatible code, but
  rather emits an ES module that can be natively loaded into a browser.

Otherwise be sure to check out [the RFC][RFC 6] for more details, and
otherwise this should implement at least the MVP version of the RFC!
Notably at this time JS snippets with `--nodejs` or `--no-modules` are
not supported and will unconditionally generate an error.

[RFC 6]: https://github.com/rustwasm/rfcs/pull/6

Closes #1311
2019-03-05 08:00:47 -08:00
Nick Fitzgerald
2ce57a7fa1 Add support for FnOnce to Closure 2019-03-01 13:18:48 -08:00
Alex Crichton
f831711f5d Support Option<RustStruct> in arguments/returns
Add all the necessary support in a few locations and we should be good
to go!

Closes #1252
2019-02-19 09:08:37 -08:00
Alex Crichton
894b479213 Migrate wasm-bindgen to using walrus
This commit moves `wasm-bindgen` the CLI tool from internally using
`parity-wasm` for wasm parsing/serialization to instead use `walrus`.
The `walrus` crate is something we've been working on recently with an
aim to replace the usage of `parity-wasm` in `wasm-bindgen` to make the
current CLI tool more maintainable as well as more future-proof.

The `walrus` crate provides a much nicer AST to work with as well as a
structured `Module`, whereas `parity-wasm` provides a very raw interface
to the wasm module which isn't really appropriate for our use case. The
many transformations and tweaks that wasm-bindgen does have a huge
amount of ad-hoc index management to carefully craft a final wasm
binary, but this is all entirely taken care for us with the `walrus`
crate.

Additionally, `wasm-bindgen` will ingest and rewrite the wasm file,
often changing the binary offsets of functions. Eventually with DWARF
debug information we'll need to be sure to preserve the debug
information throughout the transformations that `wasm-bindgen` does
today. This is practically impossible to do with the `parity-wasm`
architecture, but `walrus` was designed from the get-go to solve this
problem transparently in the `walrus` crate itself. (it doesn't today,
but this is planned work)

It is the intention that this does not end up regressing any
`wasm-bindgen` use cases, neither in functionality or in speed. As a
large change and refactoring, however, it's likely that at least
something will arise! We'll want to continue to remain vigilant to any
issues that come up with this commit.

Note that the `gc` crate has been deleted as part of this change, as the
`gc` crate is no longer necessary since `walrus` does it automatically.
Additionally the `gc` crate was one of the main problems with preserving
debug information as it often deletes wasm items!

Finally, this also starts moving crates to the 2018 edition where
necessary since `walrus` requires the 2018 edition, and in general it's
more pleasant to work within the 2018 edition!
2019-02-12 07:25:53 -08:00
Nick Fitzgerald
11eeeb8fc8 Use textContent instead of innerHTML for extracting logs from headless browser tests
Easier to maintain fidelity and less likely to be sabotaged by XSS and
`<script>` tags.

Fixes #1232
2019-02-08 10:35:19 +01:00
Nick Fitzgerald
0e11e4a3bd Add the UnwrapThrowExt<T> trait
An extension trait for `Option<T>` and `Result<T, E>` for unwraping the `T`
value, or throwing a JS error if it is not available.

These methods should have a smaller code size footprint than the normal
`Option::unwrap` and `Option::expect` methods, but they are specific to
working with wasm and JS.

On non-wasm32 targets, defaults to the normal unwrap/expect calls.
2019-01-31 13:26:21 -08:00
Alex Crichton
9224455077 Support Option with custom enums in JS
Find a hole automatically to use a sentinel value for `None`, and then
just wire everything up!

Closes #1198
2019-01-28 14:27:57 -08:00
Alex Crichton
c35d6f4b0a Fix conditional #[wasm_bindgen] in impls
Reported in #1191 the fix requires us to get a bit creative I think. The
general gist is that a block like this:

    #[wasm_bindgen]
    impl Foo {
        pub fn foo() {}
    }

was previously expanded all in one go. Now, however, it's expanded into:

    impl Foo {
        #[__wasm_bindgen_class_marker(Foo = "Foo")]
        pub fn foo() {}
    }

    // goop generated by orginal #[wasm_bindgen]

This method of expansion takes advantage of rustc's recursive expansion
feature. It also allows us to expand `impl` blocks and allow inner items
to not be fully expanded yet, such as still having `#[cfg]` attributes
(like in the original bug report).

We use theinternal `__wasm_bindgen_class_marker` to indicate that we're
parsing an `ImplItemMethod` unconditionally, and then generation
proceeds as usual. The only final catch is that when we're expanding in
an `impl` block we have to generate tokens for the `Program`
(wasm-bindgen injected goop like the custom section) inside the body
of the function itself instead of next to it. Otherwise we'd get syntax
errors inside of impl blocks!

Closes #1191
2019-01-28 12:29:01 -08:00
Richard Dodd
5bffc28631 Add a proper test.
And fix loads of bugs.
2019-01-16 10:16:29 +00:00
Richard Dodd
72765757ef Fix tests again. 2019-01-16 10:16:29 +00:00
Richard Dodd
126efd5a95 Redo as js function + fix tests 2019-01-16 10:16:29 +00:00
Alex Crichton
20e871f676 Fix an issue where closure rewriting required class internals
Surfaced through previous sanity-checking commits, this reorders some
internal operations to...

Closes #1174
2019-01-14 15:53:29 -08:00
mvlabat
371e864509 Add support for importing default exports 2018-12-11 21:00:00 +02:00
Alex Crichton
a2aa28e4d3 Add a #[wasm_bindgen(start)] attribute
This commit adds a new attribute to `#[wasm_bindgen]`: `start`. The
`start` attribute can be used to indicate that a function should be
executed when the module is loaded, configuring the `start` function of
the wasm executable. While this doesn't necessarily literally configure
the `start` section, it does its best!

Only one crate in a crate graph may indicate `#[wasm_bindgen(start)]`,
so it's not recommended to be used in libraries but only end-user
applications. Currently this still must be used with the `crate-type =
["cdylib"]` annotation in `Cargo.toml`.

The implementation here is somewhat tricky because of the circular
dependency between our generated JS and the wasm file that we emit. This
circular dependency makes running initialization routines (like the
`start` shim) particularly fraught with complications because one may
need to run before the other but bundlers may not necessarily respect
it. Workarounds have been implemented for various emission strategies,
for example calling the start function directly after exports are wired
up with `--no-modules` and otherwise working around what appears to be
a Webpack bug with initializers running in a different order than we'd
like. In any case, this in theory doesn't show up to the end user!

Closes #74
2018-11-28 22:11:15 -08:00
Alex Crichton
c8a352189b Assert all attributes are used by default
This commit implements a system that will assert that all
`#[wasm_bindgen]` attributes are actually used during compilation. This
should help ensure that we don't sneak in stray attributes that don't
actually end up having any meaning, and hopefully make it a bit easier
to learn `#[wasm_bindgen]`!
2018-11-28 11:42:48 -08:00
Alex Crichton
151ed58b69 Consistently use extern "C"
This is what rustfmt favors, so let's favor it too!

Closes #1042
2018-11-27 12:27:00 -08:00
Alex Crichton
48f4adfa8c Run rustfmt over everything 2018-11-27 12:07:59 -08:00
Alex Crichton
68537b9649 Add an optimization to directly wire up imported functions
This commit adds an optimization to `wasm-bindgen` to directly import
and invoke other modules' functions from the wasm module, rather than
going through a shim in the imported bindings. This will be an important
optimization in the future for the host bindings proposal, but for now
it's largely just a proof-of-concept to show that we can do it and is
unlikely to bring about many performance benefits.

The implementation in this commit is largely refactoring to reorganize a
bit how functions are imported, but the implementation happens in
`generate_import_function`.

With this commit, 71/287 imports in the `tests/wasm/main.rs` suite get
hooked up directly to the ES modules, no shims needed!
2018-11-13 13:16:38 -08:00
Alex Crichton
dc4e78550a
Merge pull request #1019 from alexcrichton/rfc-5
Implement rustwasm/rfcs#5, implement `Deref` for imports and `structural` by default
2018-11-12 10:59:46 -06:00
Alex Crichton
cb246e38fb Rename host_binding to final 2018-11-09 08:00:41 -08:00
Nick Fitzgerald
75c18f0916 Only emit JS glue assertions for move arguments in debug mode 2018-11-08 15:08:46 -08:00
Alex Crichton
4c42aba007 Switch all imports to structural by default
This commit switches all imports of JS methods to `structural` by
default. Proposed in [RFC 5] this should increase the performance of
bindings today while also providing future-proofing for possible
confusion with the recent addition of the `Deref` trait for all imported
types by default as well.

A new attribute, `host_binding`, is introduced in this PR as well to
recover the old behavior of binding directly to an imported function
which will one day be the precise function on the prototype. Eventually
`web-sys` will switcsh over entirely to being driven via `host_binding`
methods, but for now it's been measured to be not quite as fast so we're
not making that switch yet.

Note that `host_binding` differs from the proposed name of `final` due
to the controversy, and its hoped that `host_binding` is a good
middle-ground!

[RFC 5]: https://rustwasm.github.io/rfcs/005-structural-and-deref.html
2018-11-08 13:52:18 -08:00
Alex Crichton
58c3a99f94 Fix a test to actually test the right property
This was a copy/paste typo!
2018-11-08 12:30:40 -08:00
Alex Crichton
64a6241960 Fix tagging static methods as structural 2018-11-08 11:50:34 -08:00