Commit Graph

497 Commits

Author SHA1 Message Date
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
Alex Crichton
16d5243362 Implement support for js_class on exported types
Allow defining types which have different names in Rust than they have
in JS! (just like can be done with imported types)

Closes #1010
2018-11-05 12:29:14 -08:00
Alex Crichton
13cac2d0c4 Fix generated shims if APIs don't exist
This commit fixes instantiation of the wasm module even if some of the
improted APIs don't exist. This extends the functionality initially
added in #409 to attempt to gracefully allow importing values from the
environment which don't actually exist in all contexts. In addition to
nonexistent methods being handled now entire nonexistent types are now
also handled.

I suspect that eventually we'll add a CLI flag to `wasm-bindgen` to say
"I assert everything exists, don't check it" to trim out the extra JS
glue generated here. In the meantime though this'll pave the way for a
wasm-bindgen shim to be instantiated in both a web worker and the main
thread, while using DOM-like APIs only on the main thread.
2018-10-10 17:46:51 -07:00
Alex Crichton
4993e45fd9 Squash a few warnings that snuck in by accident 2018-10-10 16:09:24 -07:00
Alex Crichton
f6cb73442a Fix bindings for classes only referenced through struct fields
The bindings generation for a class would accidentally omit the `__wrap`
function if it was only discovered very late in the process that
`__wrap` was needed, after we'd already passed the point where we needed
to have decided that.

This commit moves struct field generation of bindings much earlier in
the binding generation process which should ensure everything is all
hooked up by the time we generate the classes themselves.

Closes #949
2018-10-10 10:21:19 -07:00
Alex Crichton
b868185637 Add tests for internal imports now working
These compiler bugs have now been fixed on nightly, so we just need to
wait for the bug fixes to ride the trains to be available to everyone!

Closes #201
2018-10-08 09:47:17 -07:00
Alex Crichton
84bda02bbf
Merge pull request #923 from alexcrichton/extends-path
Parse `Path`s in `extends` attributes
2018-10-03 10:38:50 -07:00
Alex Crichton
5df8e20815 Parse Paths in extends attributes
Closes #916
2018-10-03 09:14:23 -07:00
Alex Crichton
32b62b4358 Fix exporting structs with BorrowMut in scope
Apparently the codegen wasn't precise enough such that a trait import
could cause method resolution to go awry!

Closes #919
2018-10-02 23:56:15 -07:00
Alex Crichton
9c085dc0f5
Merge pull request #914 from alexcrichton/rename-polyfill
Rename `polyfill` to `vendor_prefix`
2018-10-01 14:47:07 -07:00
Alex Crichton
f75349262a Rename polyfill to vendor_prefix
cc #906
2018-10-01 14:45:30 -07:00
Alex Crichton
a7e9da0a81
Merge pull request #879 from alexcrichton/closure-zst
Improve codegen for `Closure<T>`
2018-10-01 14:41:13 -07:00
Alex Crichton
8ba41cce6e Improve codegen for Closure<T>
This commit improves the codegen for `Closure<T>`, primarily for ZST
where the closure doesn't actually capture anything. Previously
`wasm-bindgen` would unconditionally allocate an `Rc` for a fat pointer,
meaning that it would always hit the allocator even when the `Box<T>`
didn't actually contain an allocation. Now the reference count for the
closure is stored on the JS object rather than in Rust.

Some more advanced tests were added along the way to ensure that
functionality didn't regress, and otherwise the calling convention for
`Closure` changed a good deal but should still be the same user-facing.
The primary change was that the reference count reaching zero may cause
JS to need to run the destructor. It simply returns this information in
`Drop for Closure` and otherwise when calling it now also retains a
function pointer that runs the destructor.

Closes #874
2018-09-29 07:00:53 -07:00
Alex Crichton
3c14f7a6eb Implement a polyfill attribute for imports
Allow using imported APIs under alternative names, such as prefixed
names, for web APIs when the exact API differs across browsers.
2018-09-28 13:43:00 -07:00
Alex Crichton
7ecf4aae87 cargo +nightly fmt --all
Rustfmt all the things!
2018-09-26 08:26:00 -07:00
Alex Crichton
7b495468f6 Implement support for Uint8ClampedArray
This commit implements support for binding APIs that take
`Uint8ClampedArray` in JS. This is pretty rare but comes up in a
`web-sys` binding or two, and we're now able to bind these APIs instead
of having to omit the bindings.

The `Uint8ClampedArray` type is bound by using the `Clamped` marker
struct in Rust. For example this is declaring a JS API that takes
`Uint8ClampedArray`:

    use wasm_bindgen::Clamped;

    #[wasm_bindgen]
    extern {
        fn takes_clamped(a: Clamped<&[u8]>);
    }

The `Clamped` type currently only works when wrapping the `&[u8]`, `&mut
[u8]`, and `Vec<u8>` types. Everything else will produce an error at
`wasm-bindgen` time.

Closes #421
2018-09-24 13:58:37 -07:00
Alex Crichton
9a1fa5a81b
Merge pull request #870 from alexcrichton/no-constructor-token
Remove the need for a `ConstructorToken`
2018-09-21 21:40:08 -07:00
Alex Crichton
75f005be23 Support #[wasm_bindgen(setter, js_name = ...)]
Previously we'd require the explicit `js_name` to *also* start with
`set_`, but when explicitly specified it shouldn't be mangled at all!

Closes #584
2018-09-21 17:54:26 -07:00
Alex Crichton
3f85d7db9f Remove the need for a ConstructorToken
This commit removes the need for an injected `ConstructorToken` type and
also cleans up the story we have for generating constructors a bit.
After this commit a `constructor()` is omitted entirely if we're in
non-debug mode and there's no actual listed constructor. Additionally we
don't deal with splat arguments and rerouting constructors, Nick was
kind enough to enlighten me about `Object.create` which is creating an
instance without running the constructor!

Instances of an exported type are now created through one of two
methods:

* If `#[wasm_bindgen(constructor)]` is present, then a `constructor` is
  generated with the appropriate signature. If a constructor is not
  present and we're in debug mode, a throwing constructor is generated.
  If we're in release mode and there's no constructor, no constructor is
  generated.

* Otherwise if a binding returns an instance of a type (or otherwise
  needs to manfuacture an instance, then it will cause an internal
  `__wrap` function to be generated. This function will use
  `Object.create` to create an instance without running the constructor.

This should ideally clean up our generated JS for classes quite a bit,
making it much more lean-and-mean!
2018-09-21 17:42:06 -07:00
Alex Crichton
ab3688d01a Only generate JS null checks in debug mode
In non-debug mode Rust is already checking these pointers, so let's only
generate the relevant code in debug mode.
2018-09-21 16:10:02 -07:00
Alex Crichton
3efe51eb8b Reorganize and rewrite examples
This commit is a large-ish scale reorganization of our examples. The
main goal here is to have a dedicated section of the guide for example,
and all examples will be listed there. Each example's `README` is now
just boilerplate pointing at the guide along with a blurb about how to
run it.

Some examples like `math` and `smorgasboard` have been deleted as they
didn't really serve much purpose, and others like `closures` have been
rewritten with `web-sys` instead of hand-bound bindings.

Overall it's hoped that this puts us in a good and consistent state for
our examples, with all of them being described in the guide, excerpts
are in the guide, and they're all relatively idiomatically using
`web-sys`.
2018-09-20 16:45:30 -07:00
Alex Crichton
7cf4213283 Allow returning Result from functions
This commit adds support for exporting a function defined in Rust that returns a
`Result`, translating the `Ok` variant to the actual return value and the `Err`
variant to an exception that's thrown in JS.

The support for return types and descriptors was rejiggered a bit to be a bit
more abstract and more well suited for this purpose. We no longer distinguish
between functions with a return value and those without a return value.
Additionally a new trait, `ReturnWasmAbi`, is used for converting return values.
This trait is an internal implementation detail, however, and shouldn't surface
itself to users much (if at all).

Closes #841
2018-09-18 13:13:59 -07:00
Richard Dodd
7d5d845608 Add docs and remove typecheck from variadic attribute 2018-09-01 13:55:35 +01:00
Richard Dodd
ce1cb84327 Merge branch 'master' into variadic_js_functions 2018-08-31 10:08:53 +01:00
Alex Crichton
e1474110d4 Add an accessor for wasm's own memory as a JS object
In addition to closing #495 this'll be useful eventually when instantiating
multiple wasm modules from Rust as you'd now be able to acquire a reference to
the current module in Rust itself.
2018-08-27 11:05:55 -07:00