From 10ee2acdd26a7f1298c6f6d6b7af9b469fe29b87 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sat, 4 May 2024 14:41:41 +0200 Subject: Merging upstream version 1.70.0+dfsg2. Signed-off-by: Daniel Baumann --- vendor/wasm-bindgen/.cargo-checksum.json | 1 + vendor/wasm-bindgen/CHANGELOG.md | 1862 ++++++++++++++++++++ vendor/wasm-bindgen/CONTRIBUTING.md | 4 + vendor/wasm-bindgen/Cargo.toml | 79 + vendor/wasm-bindgen/LICENSE-APACHE | 201 +++ vendor/wasm-bindgen/LICENSE-MIT | 25 + vendor/wasm-bindgen/README.md | 113 ++ vendor/wasm-bindgen/_package.json | 14 + vendor/wasm-bindgen/build.rs | 4 + vendor/wasm-bindgen/examples/README.md | 7 + vendor/wasm-bindgen/examples/import_js/README.md | 15 + vendor/wasm-bindgen/examples/import_js/index.html | 8 + .../wasm-bindgen/examples/import_js/package.json | 14 + vendor/wasm-bindgen/publish.rs | 221 +++ vendor/wasm-bindgen/releases/friends.sh | 19 + .../releases/release-announcement-template.md | 39 + vendor/wasm-bindgen/src/cache/intern.rs | 103 ++ vendor/wasm-bindgen/src/cache/mod.rs | 1 + vendor/wasm-bindgen/src/cast.rs | 160 ++ vendor/wasm-bindgen/src/closure.rs | 885 ++++++++++ vendor/wasm-bindgen/src/convert/closures.rs | 225 +++ vendor/wasm-bindgen/src/convert/impls.rs | 378 ++++ vendor/wasm-bindgen/src/convert/mod.rs | 11 + vendor/wasm-bindgen/src/convert/slices.rs | 311 ++++ vendor/wasm-bindgen/src/convert/traits.rs | 131 ++ vendor/wasm-bindgen/src/describe.rs | 192 ++ vendor/wasm-bindgen/src/externref.rs | 184 ++ vendor/wasm-bindgen/src/lib.rs | 1800 +++++++++++++++++++ .../tests/headless/externref_heap_live_count.rs | 20 + vendor/wasm-bindgen/tests/headless/main.js | 2 + vendor/wasm-bindgen/tests/headless/main.rs | 61 + vendor/wasm-bindgen/tests/headless/modules.js | 3 + vendor/wasm-bindgen/tests/headless/modules.rs | 12 + vendor/wasm-bindgen/tests/headless/snippets.rs | 58 + vendor/wasm-bindgen/tests/headless/snippets1.js | 9 + vendor/wasm-bindgen/tests/headless/strings.js | 21 + vendor/wasm-bindgen/tests/headless/strings.rs | 16 + vendor/wasm-bindgen/tests/must_use.rs | 10 + vendor/wasm-bindgen/tests/non_wasm.rs | 50 + vendor/wasm-bindgen/tests/std-crate-no-std-dep.rs | 29 + vendor/wasm-bindgen/tests/unwrap_throw.rs | 23 + vendor/wasm-bindgen/tests/wasm/api.js | 75 + vendor/wasm-bindgen/tests/wasm/api.rs | 199 +++ vendor/wasm-bindgen/tests/wasm/arg_names.js | 16 + vendor/wasm-bindgen/tests/wasm/arg_names.rs | 15 + vendor/wasm-bindgen/tests/wasm/bigint.js | 53 + vendor/wasm-bindgen/tests/wasm/bigint.rs | 118 ++ vendor/wasm-bindgen/tests/wasm/char.js | 17 + vendor/wasm-bindgen/tests/wasm/char.rs | 43 + vendor/wasm-bindgen/tests/wasm/classes.js | 239 +++ vendor/wasm-bindgen/tests/wasm/classes.rs | 610 +++++++ vendor/wasm-bindgen/tests/wasm/closures.js | 164 ++ vendor/wasm-bindgen/tests/wasm/closures.rs | 645 +++++++ vendor/wasm-bindgen/tests/wasm/comments.js | 19 + vendor/wasm-bindgen/tests/wasm/comments.rs | 73 + vendor/wasm-bindgen/tests/wasm/duplicate_deps.js | 17 + vendor/wasm-bindgen/tests/wasm/duplicate_deps.rs | 18 + vendor/wasm-bindgen/tests/wasm/duplicates.rs | 57 + vendor/wasm-bindgen/tests/wasm/duplicates_a.js | 2 + vendor/wasm-bindgen/tests/wasm/duplicates_b.js | 2 + vendor/wasm-bindgen/tests/wasm/duplicates_c.js | 2 + vendor/wasm-bindgen/tests/wasm/enums.js | 40 + vendor/wasm-bindgen/tests/wasm/enums.rs | 97 + vendor/wasm-bindgen/tests/wasm/final.js | 25 + vendor/wasm-bindgen/tests/wasm/final.rs | 40 + vendor/wasm-bindgen/tests/wasm/futures.js | 44 + vendor/wasm-bindgen/tests/wasm/futures.rs | 166 ++ .../wasm-bindgen/tests/wasm/getters_and_setters.js | 107 ++ .../wasm-bindgen/tests/wasm/getters_and_setters.rs | 348 ++++ vendor/wasm-bindgen/tests/wasm/import_class.js | 170 ++ vendor/wasm-bindgen/tests/wasm/import_class.rs | 263 +++ vendor/wasm-bindgen/tests/wasm/imports.js | 143 ++ vendor/wasm-bindgen/tests/wasm/imports.rs | 323 ++++ vendor/wasm-bindgen/tests/wasm/imports_2.js | 5 + vendor/wasm-bindgen/tests/wasm/intrinsics.rs | 113 ++ vendor/wasm-bindgen/tests/wasm/js_keywords.js | 24 + vendor/wasm-bindgen/tests/wasm/js_keywords.rs | 55 + vendor/wasm-bindgen/tests/wasm/js_objects.js | 112 ++ vendor/wasm-bindgen/tests/wasm/js_objects.rs | 184 ++ vendor/wasm-bindgen/tests/wasm/jscast.js | 28 + vendor/wasm-bindgen/tests/wasm/jscast.rs | 88 + vendor/wasm-bindgen/tests/wasm/main.rs | 56 + vendor/wasm-bindgen/tests/wasm/math.js | 37 + vendor/wasm-bindgen/tests/wasm/math.rs | 142 ++ vendor/wasm-bindgen/tests/wasm/no_shims.rs | 152 ++ vendor/wasm-bindgen/tests/wasm/node.js | 37 + vendor/wasm-bindgen/tests/wasm/node.rs | 105 ++ vendor/wasm-bindgen/tests/wasm/option.js | 28 + vendor/wasm-bindgen/tests/wasm/option.rs | 61 + .../wasm-bindgen/tests/wasm/optional_primitives.js | 102 ++ .../wasm-bindgen/tests/wasm/optional_primitives.rs | 442 +++++ vendor/wasm-bindgen/tests/wasm/result.js | 126 ++ vendor/wasm-bindgen/tests/wasm/result.rs | 190 ++ vendor/wasm-bindgen/tests/wasm/result_jserror.js | 54 + vendor/wasm-bindgen/tests/wasm/result_jserror.rs | 118 ++ vendor/wasm-bindgen/tests/wasm/rethrow.js | 14 + vendor/wasm-bindgen/tests/wasm/rethrow.rs | 28 + vendor/wasm-bindgen/tests/wasm/simple.js | 107 ++ vendor/wasm-bindgen/tests/wasm/simple.rs | 227 +++ vendor/wasm-bindgen/tests/wasm/slice.js | 197 +++ vendor/wasm-bindgen/tests/wasm/slice.rs | 240 +++ vendor/wasm-bindgen/tests/wasm/structural.js | 13 + vendor/wasm-bindgen/tests/wasm/structural.rs | 32 + vendor/wasm-bindgen/tests/wasm/truthy_falsy.rs | 28 + vendor/wasm-bindgen/tests/wasm/usize.js | 39 + vendor/wasm-bindgen/tests/wasm/usize.rs | 79 + vendor/wasm-bindgen/tests/wasm/validate_prt.js | 43 + vendor/wasm-bindgen/tests/wasm/validate_prt.rs | 44 + vendor/wasm-bindgen/tests/wasm/variadic.js | 59 + vendor/wasm-bindgen/tests/wasm/variadic.rs | 134 ++ vendor/wasm-bindgen/tests/wasm/vendor_prefix.js | 11 + vendor/wasm-bindgen/tests/wasm/vendor_prefix.rs | 48 + 112 files changed, 15073 insertions(+) create mode 100644 vendor/wasm-bindgen/.cargo-checksum.json create mode 100644 vendor/wasm-bindgen/CHANGELOG.md create mode 100644 vendor/wasm-bindgen/CONTRIBUTING.md create mode 100644 vendor/wasm-bindgen/Cargo.toml create mode 100644 vendor/wasm-bindgen/LICENSE-APACHE create mode 100644 vendor/wasm-bindgen/LICENSE-MIT create mode 100644 vendor/wasm-bindgen/README.md create mode 100644 vendor/wasm-bindgen/_package.json create mode 100644 vendor/wasm-bindgen/build.rs create mode 100644 vendor/wasm-bindgen/examples/README.md create mode 100644 vendor/wasm-bindgen/examples/import_js/README.md create mode 100644 vendor/wasm-bindgen/examples/import_js/index.html create mode 100644 vendor/wasm-bindgen/examples/import_js/package.json create mode 100644 vendor/wasm-bindgen/publish.rs create mode 100755 vendor/wasm-bindgen/releases/friends.sh create mode 100644 vendor/wasm-bindgen/releases/release-announcement-template.md create mode 100644 vendor/wasm-bindgen/src/cache/intern.rs create mode 100644 vendor/wasm-bindgen/src/cache/mod.rs create mode 100644 vendor/wasm-bindgen/src/cast.rs create mode 100644 vendor/wasm-bindgen/src/closure.rs create mode 100644 vendor/wasm-bindgen/src/convert/closures.rs create mode 100644 vendor/wasm-bindgen/src/convert/impls.rs create mode 100644 vendor/wasm-bindgen/src/convert/mod.rs create mode 100644 vendor/wasm-bindgen/src/convert/slices.rs create mode 100644 vendor/wasm-bindgen/src/convert/traits.rs create mode 100644 vendor/wasm-bindgen/src/describe.rs create mode 100644 vendor/wasm-bindgen/src/externref.rs create mode 100644 vendor/wasm-bindgen/src/lib.rs create mode 100644 vendor/wasm-bindgen/tests/headless/externref_heap_live_count.rs create mode 100644 vendor/wasm-bindgen/tests/headless/main.js create mode 100644 vendor/wasm-bindgen/tests/headless/main.rs create mode 100644 vendor/wasm-bindgen/tests/headless/modules.js create mode 100644 vendor/wasm-bindgen/tests/headless/modules.rs create mode 100644 vendor/wasm-bindgen/tests/headless/snippets.rs create mode 100644 vendor/wasm-bindgen/tests/headless/snippets1.js create mode 100644 vendor/wasm-bindgen/tests/headless/strings.js create mode 100644 vendor/wasm-bindgen/tests/headless/strings.rs create mode 100644 vendor/wasm-bindgen/tests/must_use.rs create mode 100644 vendor/wasm-bindgen/tests/non_wasm.rs create mode 100644 vendor/wasm-bindgen/tests/std-crate-no-std-dep.rs create mode 100644 vendor/wasm-bindgen/tests/unwrap_throw.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/api.js create mode 100644 vendor/wasm-bindgen/tests/wasm/api.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/arg_names.js create mode 100644 vendor/wasm-bindgen/tests/wasm/arg_names.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/bigint.js create mode 100644 vendor/wasm-bindgen/tests/wasm/bigint.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/char.js create mode 100644 vendor/wasm-bindgen/tests/wasm/char.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/classes.js create mode 100644 vendor/wasm-bindgen/tests/wasm/classes.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/closures.js create mode 100644 vendor/wasm-bindgen/tests/wasm/closures.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/comments.js create mode 100644 vendor/wasm-bindgen/tests/wasm/comments.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/duplicate_deps.js create mode 100644 vendor/wasm-bindgen/tests/wasm/duplicate_deps.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/duplicates.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/duplicates_a.js create mode 100644 vendor/wasm-bindgen/tests/wasm/duplicates_b.js create mode 100644 vendor/wasm-bindgen/tests/wasm/duplicates_c.js create mode 100644 vendor/wasm-bindgen/tests/wasm/enums.js create mode 100644 vendor/wasm-bindgen/tests/wasm/enums.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/final.js create mode 100644 vendor/wasm-bindgen/tests/wasm/final.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/futures.js create mode 100644 vendor/wasm-bindgen/tests/wasm/futures.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/getters_and_setters.js create mode 100644 vendor/wasm-bindgen/tests/wasm/getters_and_setters.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/import_class.js create mode 100644 vendor/wasm-bindgen/tests/wasm/import_class.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/imports.js create mode 100644 vendor/wasm-bindgen/tests/wasm/imports.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/imports_2.js create mode 100644 vendor/wasm-bindgen/tests/wasm/intrinsics.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/js_keywords.js create mode 100644 vendor/wasm-bindgen/tests/wasm/js_keywords.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/js_objects.js create mode 100644 vendor/wasm-bindgen/tests/wasm/js_objects.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/jscast.js create mode 100644 vendor/wasm-bindgen/tests/wasm/jscast.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/main.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/math.js create mode 100644 vendor/wasm-bindgen/tests/wasm/math.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/no_shims.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/node.js create mode 100644 vendor/wasm-bindgen/tests/wasm/node.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/option.js create mode 100644 vendor/wasm-bindgen/tests/wasm/option.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/optional_primitives.js create mode 100644 vendor/wasm-bindgen/tests/wasm/optional_primitives.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/result.js create mode 100644 vendor/wasm-bindgen/tests/wasm/result.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/result_jserror.js create mode 100644 vendor/wasm-bindgen/tests/wasm/result_jserror.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/rethrow.js create mode 100644 vendor/wasm-bindgen/tests/wasm/rethrow.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/simple.js create mode 100644 vendor/wasm-bindgen/tests/wasm/simple.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/slice.js create mode 100644 vendor/wasm-bindgen/tests/wasm/slice.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/structural.js create mode 100644 vendor/wasm-bindgen/tests/wasm/structural.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/truthy_falsy.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/usize.js create mode 100644 vendor/wasm-bindgen/tests/wasm/usize.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/validate_prt.js create mode 100644 vendor/wasm-bindgen/tests/wasm/validate_prt.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/variadic.js create mode 100644 vendor/wasm-bindgen/tests/wasm/variadic.rs create mode 100644 vendor/wasm-bindgen/tests/wasm/vendor_prefix.js create mode 100644 vendor/wasm-bindgen/tests/wasm/vendor_prefix.rs (limited to 'vendor/wasm-bindgen') diff --git a/vendor/wasm-bindgen/.cargo-checksum.json b/vendor/wasm-bindgen/.cargo-checksum.json new file mode 100644 index 000000000..74bb7190f --- /dev/null +++ b/vendor/wasm-bindgen/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"0df8b3bc12566111f27195b3a6e24210b2d974efdd1e46dec1980e743feef97c","CONTRIBUTING.md":"aa138d76f5cb25bba1a6942a230373aaed6be73c619f945cc4657e13ba69f897","Cargo.toml":"df86a1e4cac62cccd0de6ab815246906866c54f1a12a355f1047e8796759c3a6","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"378f5840b258e2779c39418f3f2d7b2ba96f1c7917dd6be0713f88305dbda397","README.md":"8e0075aceb58e5db84b7debf46f7a3fde437573f46fe9aad6421a3a081575cbe","_package.json":"64c943903ffc064a2c5506e46fce690d7f566589d0d8e71804ec1638d1aabad5","build.rs":"95d57e593c411b82bf88819765d6422db2a65c1bf489b63f87e0aefeb721fc41","examples/README.md":"e5396e95d8130948e48b767ab505c46bc69f6ff3ebfe0d9709068cf42c250818","examples/import_js/README.md":"bb53d4a264e9a084effdc7a22ca7d5acca0207b411478b98782d881b7fcade51","examples/import_js/index.html":"f4825d155bfe0059aa182a506d6d076d1ba5f118e46365ac902b12f27a6c8c0d","examples/import_js/index.js":"d425b7b0636dc5c5046bc96e6bfe6ef3bb1503fa91c54f40ecb457a1b060ee5c","examples/import_js/package.json":"bbbfbfa1a62779e38ba30c920d27aefaaf10bf6add3a89a65b7d2b093c1fe017","examples/import_js/webpack.config.js":"fc314556d2f0c6266cde7c47afaceebe474be97c0401985a23d822ad9dd0105a","guide/book.toml":"d8cae5ae5fbeaab5b6852c64b975d37f51592a8e9eedba22c898672d9b11e9be","guide/src/SUMMARY.md":"073b7bf40c1979cf3e6215581fcbe9be49800a676a0fd60ea2b89fe9c555b200","guide/src/_headers":"401cee68df5967f0aa509a1b978a83f06e8e830deca1433964703e7a1ac2c646","guide/src/contributing/design/describe.md":"3186f9795be894708788e50d2ee745b9bd73bc94fb3dce67f3f1fd5e7fbd3659","guide/src/contributing/design/exporting-rust-struct.md":"24c6f2417797db6125484ae1bacfdfc058c0dbfa28638cbaa58ff5dbecc9b5d3","guide/src/contributing/design/exporting-rust.md":"4dd822967bf2fc111ad69c1dc4619715b692349208e8780dd8f54b571fb57e2e","guide/src/contributing/design/importing-js-struct.md":"848d0b144b28a5ae1ca3760438e71b938cfb2ee350f5b902fd08c38a0a64e27b","guide/src/contributing/design/importing-js.md":"c949c8921c213ba21b08f705d4611304acba47b68c35484fe968a80194f3a9ab","guide/src/contributing/design/index.md":"3bcd35bfadc3fa81d26dcac23f2e2ab5c3e2874cb6a88d0d892c5effe535fb04","guide/src/contributing/design/js-objects-in-rust.md":"0a18922b509ed8a6cc6724b81af6e6d469b75b3796dba770949a8b59d8067455","guide/src/contributing/design/rust-type-conversions.md":"efd7ddcc55770b5a2b68d542fd6aa128a9d4f60eaa5477481a1827c11b17dec0","guide/src/contributing/index.md":"e5115ccd2403b929d65acb9626bff8d66e10d1eb625a023ea017f2271a3e49c6","guide/src/contributing/js-sys/adding-more-apis.md":"d6626d530fa5b73f045a20bf123d5e261ac2ca3bd64cbb80b655612f9b9a6276","guide/src/contributing/js-sys/index.md":"9c0864ca52e8699148e789c2a6ba2d3044ba2358d7106a1b7fd725d3720dbb54","guide/src/contributing/js-sys/testing.md":"d1f613c88793ffce61b2d77aa40e3a91a1de3c73ab9f8eaedfc39da16c93ad07","guide/src/contributing/publishing.md":"012c31c7037ca084d0c2a65c2dfc0be6fcbe5c118307e9efbb4f6f781ae48e43","guide/src/contributing/team.md":"a3f993cb1afeee767e85077d135b1ea08850c433a69c436ebe6b7a48124ed945","guide/src/contributing/testing.md":"b6d45f2a177525e1fd9b7c8a0d47f0bc156a9327795bcb4d96716851f94ff2db","guide/src/contributing/web-sys/index.md":"6b4d5e00cbbcaab29295a3bd60e90b7f72b118758966622a307d9222488707c1","guide/src/contributing/web-sys/logging.md":"ee960ec9adc174183fb349acdbf5fc647b6f9a290022be9b118b9de37b8b5687","guide/src/contributing/web-sys/overview.md":"e6179317f75aa8e836e3c803f5d814e87119763709eea47b04cebc86c089d80a","guide/src/contributing/web-sys/supporting-more-web-apis.md":"984efae9c4241a105a1f5d6574cff7202f378c90ac648c4da815d97517da2b28","guide/src/contributing/web-sys/testing.md":"77f8e4b45bd0e27676dd503474bc32f91672b23c6ab7127a4f5b828dc8ea40e4","guide/src/examples/2d-canvas.md":"44a0eb82ec3398ee63a6df5aab103f1b002082eac2d129f656d8519cbc0829e7","guide/src/examples/2d-canvas.png":"b202cd79b20c00d49c40d71225eefea99306015858a432ceb7592d53c15300f7","guide/src/examples/add.md":"8dac740d6a4c499d868c29d8426d113da9cdd6ef22bf8084b8cf8c1de513b09c","guide/src/examples/char.md":"93f94a1b670322d0dc21b46d749909c414f9f254e2dd97afd8afe8cb0e5ab908","guide/src/examples/closures.md":"669dfc47a670271d7ce7a3bd2c08620b698b01ea8b2a7b1cc2047a77e7617130","guide/src/examples/console-log.md":"6552f4d766291cddc0eade75e4f64de9f10e00b89a0bedb1b15dcf7baa90b6e0","guide/src/examples/dom.md":"44ad74370b3727ec98f958273c639e767f2ae5b75e96ef53e74be1833a630272","guide/src/examples/fetch.md":"0f9d08e240bc5ced13ab154182aedef7fa7b00cba784c65727aa15be27f86d7c","guide/src/examples/hello-world.md":"d5f4d830c316a91e951cdaeab5cb23ae47dbc910b05de849e67bef1ea709564f","guide/src/examples/import-js.md":"0480a6aa32b1fdc1347cb3d0c4f2a006caeb33c75ed21eb78ad800f012cbc2c6","guide/src/examples/index.md":"4e629f42d7bfb52bc35856b6e21c3aa7433563482697212d7b54f1bf619b56ed","guide/src/examples/julia.md":"0cd4ae1de24d657d7869c984dec61cc8b796621365be633212bdb2a6d57ce727","guide/src/examples/paint.md":"06c6c04f121080e0e5600b4ad300df9e93b5d4b6342f42c421e6dec1f2955ced","guide/src/examples/performance.md":"de888713cf0a047bd4a28a1ca890be51d99b6aaabc9a2b134280b768a7148377","guide/src/examples/raytrace.md":"6769cf3b7bd14e9814e751927fde8c5acb443c5e82758285a1ee4f91e577a870","guide/src/examples/request-animation-frame.md":"26eef6b203acc0b2667d9c4380c39a44eb4b97991efeded9ca32cc9ab454e993","guide/src/examples/synchronous-instantiation.md":"c2f887e4754535c453d22438c3179d71d2468d8994a61330a362132c73157ef1","guide/src/examples/todomvc.md":"b872c5631eae969368d147342fca16dadb6f0412f8922230c27271370e9d3d97","guide/src/examples/wasm-audio-worklet.md":"dda392cb5beb75423bd402661d0de85de7acf5098e38ecf167533774b5b9977a","guide/src/examples/wasm-in-wasm.md":"5439a690e7107736e6f8b92e475f0a45e83ab9a1e5a0fe02e8f6dd93372590c6","guide/src/examples/wasm-in-web-worker.md":"8877a952ba93bbf52d85acb7a6a38d318e5638c36b86338156c4881cc704394f","guide/src/examples/wasm2js.md":"48f953dfa1b17b68e5d983231e991797e32e9bc22b9c3db72c2d055e08449a00","guide/src/examples/weather_report.md":"184bf64d58820b032a80c738050e7b2cd0042eb722f61c7e8a3c531239f72db2","guide/src/examples/web-audio.md":"32bb18c9e4f167614ce3fb61d1d04265449f88da40949834b50baf9e37063fbd","guide/src/examples/webgl.md":"15570a0a081c2301981a1fbca0bd39dfcf35221c64ddfb8e8f4477660658cb08","guide/src/examples/webrtc_datachannel.md":"47b06b1b00c41f048fad3c2206399cae2d8dbd90b6d83953c138826f11677eb5","guide/src/examples/websockets.md":"704f9d5c1d13426e6e64e132cb0204be3c10a54dbfa5f1c834adc4efb4a1b8d2","guide/src/examples/without-a-bundler.md":"1e5155e4cb042c4a8f561287b5ab09d3179b6dbcbfabfc540bbdfb9240f16865","guide/src/introduction.md":"057e81f8f62d8647e51d1269bdb5788654be2e22fea23d155ec5a15bbf8bae1d","guide/src/reference/accessing-properties-of-untyped-js-values.md":"a91e3eb706ddd15628072978906e2faca31560de616c0630316d9f6eff6b55bf","guide/src/reference/arbitrary-data-with-serde.md":"b281146412f6bda893f146e84721677f003cad57af941552c2faf534b61b2d98","guide/src/reference/attributes/index.md":"12b57ebbd0c9ba42d9f10d752c9943d9beec90d659d1b1ff9e9bfea02572a2c8","guide/src/reference/attributes/on-js-imports/catch.md":"da230e6986ca29f1e82313b82275ab9c3b2144906271cf82b27772541d781d84","guide/src/reference/attributes/on-js-imports/constructor.md":"89f8be11c567b4611c84209b34351238553d5360d7f7665ea25332e1544c5b99","guide/src/reference/attributes/on-js-imports/extends.md":"84ece37398ba0df66f890982315f082c52b5f027e03c20527755abe610c2567c","guide/src/reference/attributes/on-js-imports/final.md":"8d32d5053e9c1bc5df6fa7fe286a378895e47dea5ca067c8dddf99efe0aa5172","guide/src/reference/attributes/on-js-imports/getter-and-setter.md":"27f3c2738688a43e611524e5e3ab7174a1993026a69098b75780a388aeb5e745","guide/src/reference/attributes/on-js-imports/index.md":"2219a4514fe9597cbbe6c46014b57c38f1e85f3d0775a8a7880f50858cb13633","guide/src/reference/attributes/on-js-imports/indexing-getter-setter-deleter.md":"11d5c03f922294894fe0147fae96e04b26a5adb36ce91296e52729a9fe5931c2","guide/src/reference/attributes/on-js-imports/js_class.md":"d51c5f05b71bbf6b6ec8e0c36314ae299fd7eb07be989e721b79b599405b3486","guide/src/reference/attributes/on-js-imports/js_name.md":"12457466f3510256a51a78f52b09f7cb1c0b0ce3ef636e028cd2c372fa9e8738","guide/src/reference/attributes/on-js-imports/js_namespace.md":"e523dffa8b3110f1a17390d6bcc6c9c41c23e0a1e549f68a0aaec153ee2d228d","guide/src/reference/attributes/on-js-imports/method.md":"d54246efce5d7a104702439ba509bcc5bfbb0b57253edebdb696617daca80bcd","guide/src/reference/attributes/on-js-imports/module.md":"b47cd5ccbb69955f1d47101accc96fcd562abecbf7e34826f7f3c585d6b9dad0","guide/src/reference/attributes/on-js-imports/no_deref.md":"7d58bb3b6f768e38b949727abd1ee621ad09ebc537f83a8a20d0eeddf3771b95","guide/src/reference/attributes/on-js-imports/raw_module.md":"f363e5f3bc401b7e350eeec49cffde85dfb2346d597f38d98993fe5bfb9ff649","guide/src/reference/attributes/on-js-imports/static_method_of.md":"d5a5d9623ee55097f26e190b478e75f2e7d2ffc30e51ec647f39933d3d4e3b18","guide/src/reference/attributes/on-js-imports/structural.md":"364e01a5792029e9a5fa582375736efcee006352834ee273d218da89b77dd8bf","guide/src/reference/attributes/on-js-imports/typescript_type.md":"9cae454e9134ca1d14e2af3c732f370335332c615bf03ac49e525ff6f1877cbc","guide/src/reference/attributes/on-js-imports/variadic.md":"1ecf00149be472e3111f188c053092f3274fb33453414516a305084d8e92c4df","guide/src/reference/attributes/on-js-imports/vendor_prefix.md":"47a8d47e0cd745cca697f6d944e145f02695ca422255c3d6e1c9b2b719994b1b","guide/src/reference/attributes/on-rust-exports/constructor.md":"d3878fdb36174e5662ccfdf0fb027ef8175a7f8ca14ccca875217e03f5d5be1d","guide/src/reference/attributes/on-rust-exports/getter-and-setter.md":"464a2d41a791bd8ba5a8b1c4aa64b2f865c42b98a2d1289bb65e766e98a1b56a","guide/src/reference/attributes/on-rust-exports/getter_with_clone.md":"11a04dba4d66c19be0e234014d21ccf9cd0b76169b723e90ceb81d719478f283","guide/src/reference/attributes/on-rust-exports/index.md":"9fe778a0dd013a874db484cb22b1d9867bfe6d69cfbbe5cfeaa8ab78cf19daab","guide/src/reference/attributes/on-rust-exports/inspectable.md":"52fbcfdb83c426430a95692d566a4709255e25b24be5704d7378a4196a8c5908","guide/src/reference/attributes/on-rust-exports/js_class.md":"f4c0d8e8021001578f7d300e88c438d1a7806c17cc0d8acc3b4134922a75affc","guide/src/reference/attributes/on-rust-exports/js_name.md":"77f035b6391b9e44f254a411ba18687c5fa6110e276be73b5ea347701c8dad42","guide/src/reference/attributes/on-rust-exports/readonly.md":"a5da847ad36557f03b1c79a83d14c219dce914021266133c204260bc041b9b89","guide/src/reference/attributes/on-rust-exports/skip.md":"b9972241b8d473d1a46ef3c2861065ca296cdc923883c404f19f1d859bf914a6","guide/src/reference/attributes/on-rust-exports/skip_typescript.md":"1622c29b0d93a884bd0b5b2a62107a594e2919758c80592566e7786efe788b89","guide/src/reference/attributes/on-rust-exports/start.md":"00acf5bcc40abea6ba89a20dab20e2cb17396ce07fc75d15bba0351dd9b7de81","guide/src/reference/attributes/on-rust-exports/typescript_custom_section.md":"9b96a30f81dd5e218953b85d823e429356723e8a6cd8aff3be0869b10d849a0a","guide/src/reference/attributes/on-rust-exports/typescript_type.md":"ffbacc6b690912ea085831d855ad37c495b483fdf27444f2988e69591e0edabb","guide/src/reference/browser-support.md":"aac94e3609d89a23dc274756be11cf2a87409070fae30a161cc61230dbfabd22","guide/src/reference/cli.md":"5a3fe5530842b32ec949568e923afd15adfede266f20863c1f69e45a2c02742c","guide/src/reference/deployment.md":"0e03b847ffc4adcd9285cf5c8cbbd3917898e763b985a65a73893bd7c2ebe430","guide/src/reference/index.md":"c603c3a7f265afb7c7b5eb391b32f6115f8842f3f422fd3730be4f90c4796bc4","guide/src/reference/iterating-over-js-values.md":"ec00f09516eb7de98bf7296f44b6aa9ceee3fae1dcdb7cdf8f36963d45b7ebeb","guide/src/reference/js-promises-and-rust-futures.md":"5f0c0b990f5b55c8d9485f7cc66a617f79cc232705562f306af97785c7ed1f79","guide/src/reference/js-snippets.md":"dff5adcbf66f06322e606c672ef070c2a0375f1ae592ca8a9da36a50324735cc","guide/src/reference/optimize-size.md":"c10abc1ea0902c9a57b74808bcf75bf092c0c2bb4082962b85d18df7593602c1","guide/src/reference/passing-rust-closures-to-js.md":"aa18f75ffd4b7779a2699b1bf969245ec0e1a70b24abe61e8877c2eb65f6ef60","guide/src/reference/receiving-js-closures-in-rust.md":"fc9c80ba5e1a5f243a66f68caba27e8103652aeac3765a9fad2d0e16113fede3","guide/src/reference/reference-types.md":"91d178b7fe2ec82eec4d8926a08b39ac16898172d6f65aee84347c6918033c67","guide/src/reference/rust-targets.md":"467d5cf7eaa1d4b89f9f5b2248cdd1a10340ca1db263ffff5c483ce10dcfbf54","guide/src/reference/types.md":"859123f51fa932fa37d7e47cd5c46956929793bd3accea050d3be516080ed78f","guide/src/reference/types/bool.md":"e954d93ec5096837d4dd2db3f23e71c14483279e347ca8908ecb49aded6e497a","guide/src/reference/types/boxed-jsvalue-slice.md":"634e51ce92770e6078ca3303be946272af3f092f2703c90601ed8f9092c69a53","guide/src/reference/types/boxed-number-slices.md":"1a217a68ff549f4208f99863d6616521c9d466542c1156bcc2be7d3a73e4edd4","guide/src/reference/types/char.md":"01f2f7bdb25a9a52edd93dcbbca6a29269a8d5adf6cb94dcadea29a7aace22f4","guide/src/reference/types/exported-rust-types.md":"d2f601d7d39ae92326c5624e1e2a2795f1f47accb92ec030c987b6c709681906","guide/src/reference/types/imported-js-types.md":"e12807f46bb55f4ad9dfde4cd683b3e7f9ee79302e5a0250ef24a52bd7ef71a3","guide/src/reference/types/jsvalue.md":"46d74da47f8a517249de4dd096351c10d658d9c3535950a34c1fc5d5b42eb2f7","guide/src/reference/types/number-slices.md":"f380258fc058527c7dd6f49664a4e9dff69f0b03d626071aeb61efefb2a0b646","guide/src/reference/types/numbers.md":"cce95c07be08c1f16327fd4c7e79b7c480db9cc95e2b07514d31e51bd6122101","guide/src/reference/types/pointers.md":"3710b736f790a97a325b1883d5fa8104c16365446ef702e9dd29bda74699043e","guide/src/reference/types/result.md":"78be87e86c35d2bbc1b863217c1a7592af9f2c699902f44e22d1bc4b1c0664c0","guide/src/reference/types/str.md":"6cc086b02ae3d3565678e69d91dbf105f1f310009097a37fad4c812e25d4b7c0","guide/src/reference/types/string.md":"9e42298135e0aec11bb924e3a2b5002335cfe290240b48db12dc981156177cd0","guide/src/reference/weak-references.md":"8dc6ca26c478fceff12e374e11e2f01fdf5b6a88b7302d449d4336859f4efe8a","guide/src/reference/working-with-duck-typed-interfaces.md":"a23f1f98019fed2060e1fbce954ec457e77a3a17524f34ca861d256d2ad4b6ef","guide/src/wasm-bindgen-test/asynchronous-tests.md":"c24c381b719b4bd7b0c181da1db59170e822c142eb22f95c4a6eeb8fd36df3ab","guide/src/wasm-bindgen-test/browsers.md":"d8619911d57d56eb027cb040f3456a55d0f14f670c50e4eb2e58c1331206dde4","guide/src/wasm-bindgen-test/continuous-integration.md":"5865990ef231b3c99a9c1bc18f7b7f054a29b77ac7b671fcf1cd6bb4f4304ae8","guide/src/wasm-bindgen-test/index.md":"64fbcd222c3c597109d2717a3574abf2041ff325c26ee07d58c4cd7ba1c1f8ad","guide/src/wasm-bindgen-test/usage.md":"a1da64eaaf8fe9bea366724e08a4ba63dc984f86a28cc393fe00dc394ab244d6","guide/src/web-sys/cargo-features.md":"0e50067a7a46cee3d1b21a2690aabc539379cb1452de377ebaa0eaa4e5e587b2","guide/src/web-sys/function-overloads.md":"90a08bb955f7c79e573f83c31d5e7431ae1e3ad7001792ff8ff52e4299364fcd","guide/src/web-sys/index.md":"345499d0840fd23a2e5eb5ac497665decbb3f836fe9f4f88301ae4b5fbd8d44f","guide/src/web-sys/inheritance.md":"8f18af20b930497e2fae4a266dd27e317d1ea3510266c21b32f351354b495ff2","guide/src/web-sys/type-translations.md":"687ef5e4a3961fddcb94d24f69abec0ea64f6df306f4593974b69589215980b1","guide/src/web-sys/unstable-apis.md":"e74c3e72136d6906dd60258a27f34e1ea4612e7c8e95662596475dc557151cfb","guide/src/web-sys/using-web-sys.md":"523e16af6e27703a4a0582568bc97710350222af20801907268d2d8c197fb667","publish.rs":"6352715cf06a9e373a141e34991fa97ec5bdeb0ce7d623a4fbbe9448ef1bea35","releases/friends.sh":"f896ccdcb8445d29ed6dd0d9a360f94d4f33af2f1cc9965e7bb38b156c45949d","releases/release-announcement-template.md":"fcb3c75cdb8d5d6ce8a198f5570c967313f751d1eef0790b34a518772b2e8a38","src/cache/intern.rs":"b78abd7502ad069bbeb61073d1972c717a469849222037565b50514192c187a9","src/cache/mod.rs":"8989143b55160dbc142cb20c6e066cf0a3f70d6c97fbc9aa0fac59bd62bd865b","src/cast.rs":"195cb94e25bcfc2116472272baf1345b3ca2657280daf49d724defd3886cac52","src/closure.rs":"877179da24fbe510bad3959761b239a2a41c1eabec613b24449009c60f93838e","src/convert/closures.rs":"06679377bca9e6853033572b6a8dc2620381b1607deabc20cc55d17fe59da6b3","src/convert/impls.rs":"8e2caeb0d9e62eb98bdcf5383865e42b350afdb82812a2b8b1c4631edb068123","src/convert/mod.rs":"566ffd1f546afdb8d24c6c0d6faa00a28596a67ca6f2f39e9485add54400443c","src/convert/slices.rs":"3a6bdd428d8b844eb81f4682d462a322d9e28a6b780aa9cb44ac823b0fa9d28a","src/convert/traits.rs":"1505d64b0ca0b5d7e81f8e1f04a259bc70a7ab39131fcb461b59170e85d82b3d","src/describe.rs":"677c2f516a701264830cfbef2cba40371c0cbf4204b9cf62d7b7fb6d1cffbfe9","src/externref.rs":"cc1883fd0e0a2c64421fd12326908c0fd9aa73bba618c89cf17cc2efacd3fe70","src/lib.rs":"32c2b51e11c73921cc7c8c3be42c372b2c472a0afe37052206e0c25a8c18ac67","tests/headless/externref_heap_live_count.rs":"41b2758762c91bd2d05995b1b8989651a6bf2e586ffad5597ff63f6d2dc6d755","tests/headless/main.js":"6de0a19b91330e9bc68334c4f1fa11c1cd6bf273f5ea3e470933ad800c962679","tests/headless/main.rs":"d86245fdd476cb6c275c0649d76fd348ab55b7952ece325c1ed4ec00051a1f73","tests/headless/modules.js":"a407c81d2670309ed484adf98a2e522f6ea031b1286416eb7bf184df7433d5da","tests/headless/modules.rs":"74f77f88bb5280862c06087d78c48ba930736e58db9a1e6c80450bb0e032b789","tests/headless/snippets.rs":"baf9d3c68e1b567fcba4e073cc0d24a8f039955e10dd1275e4a389574ff556d7","tests/headless/snippets1.js":"8bd0c367fdbc61f509728255750094bb36200a1aea74079611ad7cfa9c5f3f28","tests/headless/strings.js":"fca2d7a1afae31663607f956134a4f447aaee0f85d828addc3c4c1440f2e18e5","tests/headless/strings.rs":"4a64d8a4f9329a282d0f87408c0645ded71a7d023eaad40a32eaf60886a08375","tests/must_use.rs":"cae67a8740cd2c969a6b33316cd5036639048d9bbfecf55a5f45faaa624de1d0","tests/non_wasm.rs":"fbc7f10d3604f3c867f031cd218c2b29af2b42b1225495837ad5560878930ab9","tests/std-crate-no-std-dep.rs":"47f0e32bad7b9b11ca77d66d904eb3408c3528732899479039fb6db4c6e9ed9e","tests/unwrap_throw.rs":"79f05fa37249cea08689592d53d856019a90fd1b72c41413f7fcda5cf5913356","tests/wasm/api.js":"daf4b7e2b76b718431235eda5e221dd53037fb6bebbec6023c7e3fd2b806f763","tests/wasm/api.rs":"7b0894f72025088d586597f4b6e5a745b74406afde8998f3012e30191247f37d","tests/wasm/arg_names.js":"0d7de3801257e18756a974bdd2950d2fb06755f7c0d1c681e03b56d97e828e34","tests/wasm/arg_names.rs":"decd8f71a58ebf662a586b7f19e41f6666782df0da74a8a2c69b7a504661dd79","tests/wasm/bigint.js":"b6d045afbbb7d5e8723b41ee2e9c22357c8c4c4aed804bbca2a9b42a19906354","tests/wasm/bigint.rs":"5a7e0e6e6753a5ce08c199334fd89f1cfeabc1305301d988d6f748e001ccfa2c","tests/wasm/char.js":"6f307035f2689f0827726503f201f8fd591100ff051a55bda23ddcaeaa2902f1","tests/wasm/char.rs":"44dc134f9057e6c91da32c7fdba5ba10785507ced161c07267548ee08308e6c0","tests/wasm/classes.js":"62e5b31ca25d1a9678f85f0c4aff8380c5d1a8d4a7ddfea01abc1adbb8b3c880","tests/wasm/classes.rs":"5a0267be5cf432f892e8e24f1f6558ddbe9a88298096ffd82998348e852062f3","tests/wasm/closures.js":"b2f4cad6f16c394c9ff47d29335d31a37011b2dccc5aee4a8757c5b1d90e4de0","tests/wasm/closures.rs":"903a049000cc47bb8623c0de9f79b626830f1cdde5b69ebf2185ea6fa54d71c3","tests/wasm/comments.js":"2c3bf2e79ecc33f0fba33d13a91a1ae9390f9f7a466af8eb215636662e20462a","tests/wasm/comments.rs":"5a0068fe3e214c07da92a46b6e45a2771fbd8e04f14cb7802f32082b87a459a0","tests/wasm/duplicate_deps.js":"2226e4f65525c545ab45109879b16b2a92341b440178e75d3a9efb3ed10f7b03","tests/wasm/duplicate_deps.rs":"3a91569e54f56e178dc164f2d2b8537ec6a10b3161c23e1cc8e552805cd868f4","tests/wasm/duplicates.rs":"a2b4a7960e8a7c9b3fda943e8aadb7cbc0ba8fa1a6956baf40ba2f129bd591ee","tests/wasm/duplicates_a.js":"d3d685e95a54b911c2b9a64f7c0f245e3e492491368355044ae2cd12c3332044","tests/wasm/duplicates_b.js":"cd6c87905a5c5514239bba52a03e6c151d79a57a477f52a073b61ef18c98f642","tests/wasm/duplicates_c.js":"93399409996d182b5fe02548d3c5c3e1681939629e0261d6f19f8c1ee3b08dfc","tests/wasm/enums.js":"7b37ce390aba76477e4d54c5214624cfc5eec49e0f88ef6f535f06f23527864f","tests/wasm/enums.rs":"1537fda37a051340722c29cb5aadc9e1819a2e609f2569ca4fd972308d03fc7f","tests/wasm/final.js":"cfa7c496291f08b98f0406190ee4deaab9ade890d65ada4c223a76135e66f619","tests/wasm/final.rs":"25b0a85e87686e3f7a7a44e3ac25402d504eec7f9813a74ffd63c5f4428ee0ff","tests/wasm/futures.js":"bbf23eeef87e1d6d59ae62c5bddd9d8b77bf76fc08886332f7f140b207b3cb22","tests/wasm/futures.rs":"7418487a8a706675753ee65e1fc24c49d1743ff5dac7f8a165b527d928138c96","tests/wasm/getters_and_setters.js":"8ba2d939aab232074860cdf1e01d1c58faee49a31ef35b585c962aceccb870a5","tests/wasm/getters_and_setters.rs":"e25a2d026375adda68b4591f2802ad941e0a212fca8d7ff6cf020eb5da5fa5c7","tests/wasm/import_class.js":"16e8269479a1354598901f38bd3ec4ee2a8847df59932b55999e9923e369db03","tests/wasm/import_class.rs":"5ce1419eb5342d377578ea1eac60fe31502f32eb8579625496cc4883e5210daf","tests/wasm/imports.js":"0d38ba5259f2dd19575394400ba0cbf9ef7a5f3e61ea19d43b87f46b52065391","tests/wasm/imports.rs":"0e4f38e6b3113cb3ba7c732a3c3ac36ff7cdd318764789d2deabe8de982a4810","tests/wasm/imports_2.js":"ab251fc0a0a1921c60d316160bc120fd97da3c3753804174cfda2f08ff43208d","tests/wasm/intrinsics.rs":"cc8da8e3ee50e5c8e2adf210bdf624d7a2c27becc615cd8ab560f30f1b983641","tests/wasm/js_keywords.js":"d247be675cc73540fea4b2e50bb2b7fcedb2b0d511d85be6fb646876d3025562","tests/wasm/js_keywords.rs":"8a8d619c2930686ce1130034273d248f7f86f4bcc8fb202bee07d240e711baf6","tests/wasm/js_objects.js":"a2be00dab58716e4cbbaeba4da8512ba924c39d3f1cb405ba769ab8a780ed7fc","tests/wasm/js_objects.rs":"86725cea9aec227e562409b9f3f96ff70cf57f21eb4ccdbe96de7ec64504244e","tests/wasm/jscast.js":"d678058645d2d370c45ec5fd5bc9b94612b1e70035a9e0f524c134369f06fe1d","tests/wasm/jscast.rs":"f9abd0442be8f5b28e135c7d6a671a65939d0ff0ba993537c06b2be968145bcd","tests/wasm/main.rs":"07641dcc4d3280529b963abba0a75c80379b793879c8cbd68a23a1fe31147c5c","tests/wasm/math.js":"9deb196ab7ad3d5d1f98d7d0b6ee60cb125212a4a1281ba0141cc3713fdea892","tests/wasm/math.rs":"be9000d84c6b6b091455e3b20ee7f5a88dbcfc0d38db97fad3dd167970c4b4a3","tests/wasm/no_shims.rs":"83636fee1ae0ae5b98d76b7f62f637824e77edd7a55fb27749b1a88b3910d6f6","tests/wasm/node.js":"ec3a9500773c7f07a7bcf002e23aa3848be5208147c3d750281a1e1f6d899af1","tests/wasm/node.rs":"fe140900d7048353ce0e518a1e67dedb1928f0cf34c02514498184fd8aef10cc","tests/wasm/option.js":"0d0cba722045698e9621f2565acf854bf3085c8739622798085aaa6b58e3edbe","tests/wasm/option.rs":"d82123f7349e22873e636341a52e99e256213e77d4d7ab8450ba6379be2128b7","tests/wasm/optional_primitives.js":"37484639631e1c50bdc055a08babff18d4be9f7a9291f0f3395e1a7c519e5cac","tests/wasm/optional_primitives.rs":"502803cf27b78dd8a6c1d75ae954b71cc017f803486867a87c0474e5d53a6567","tests/wasm/result.js":"78212259f886d864885eca7599199434bd7abec915a2e7fa3b73dfe63284e15c","tests/wasm/result.rs":"2aab9c8a7c05b44bbd99b40800fb6fd08dd2cb498740219c9defec059cd4a637","tests/wasm/result_jserror.js":"3ea04e68937f15d869535b3bb119d8886dfcde3c16c12c4a18a995f358552154","tests/wasm/result_jserror.rs":"d168239fc71078f23a820e8959050e15965b86be047ab17c19c1befa35a82b4e","tests/wasm/rethrow.js":"0a495a8d1b735277e18cc3fc3edf8bd2a72586441d3884134182e5052786ab84","tests/wasm/rethrow.rs":"59dcf192c9e85b0d98031c135d2aa2eda4902a2bc5b740a9ddf1e75dc9cdd23e","tests/wasm/simple.js":"3890fa19585d031821e8db80de06593e8e5ce83c9ba8214fe1cef319e9c14fbb","tests/wasm/simple.rs":"5487804ed159538fa8722444c9c2db8929b6056692ae67991d72489f90194849","tests/wasm/slice.js":"2e3c42c6ebeb832f42e99e4f251817bd13083eff0b7c45c46fb4d7ab2aa740cd","tests/wasm/slice.rs":"511eb693d0ac56bde149c37039fb207ee4f0b1b92db2a809306f5ac80d578dbd","tests/wasm/structural.js":"ac504a1dbb7222c70270530a284eec56ace0bc47b95e8f9331f4b2df1d28c3f9","tests/wasm/structural.rs":"dda0e9cea09b94dd84ae39d6cf0949aa305062b7a466fdcb53370f5ee9e3dff5","tests/wasm/truthy_falsy.rs":"b54206b376f7413c9cce1792df65f57ed1e97660b4be8d9486e9c6af00f6893f","tests/wasm/usize.js":"521714b75033d9e18117de2cae2cd690c477faa88daefbbc82a09e60f4e901a8","tests/wasm/usize.rs":"b97455844d1f7acfbae7fcc69ec0bd8de871201281e802173a62574b8f3d7983","tests/wasm/validate_prt.js":"a726a85f4805648d9e69c804a266bbedaed942228a1b3a46274a91bcb83eafe9","tests/wasm/validate_prt.rs":"cea3db07f10d2bf057af99b90655179371bccf1db67e7364d476b00ecbf24a93","tests/wasm/variadic.js":"30d3bb656c0eb29b69c7e653f3201b5210b8a78e962b4678336c4d9889182adb","tests/wasm/variadic.rs":"1cabd34ad64475cc705853a2b9a8f619f6aed6ee3f3d8179793f8198df1ac178","tests/wasm/vendor_prefix.js":"1424c7fea77fea13179a50030afeffdf4b277dcb6d7b1e5ce3eea681ec2c47f4","tests/wasm/vendor_prefix.rs":"eabd627e14e09ec637d7e7a5b0bccced7e3370203351e4ce8610a5c66fac502b"},"package":"eaf9f5aceeec8be17c128b2e93e031fb8a4d469bb9c4ae2d7dc1888b26887268"} \ No newline at end of file diff --git a/vendor/wasm-bindgen/CHANGELOG.md b/vendor/wasm-bindgen/CHANGELOG.md new file mode 100644 index 000000000..2c9061bc7 --- /dev/null +++ b/vendor/wasm-bindgen/CHANGELOG.md @@ -0,0 +1,1862 @@ +# `wasm-bindgen` Change Log +-------------------------------------------------------------------------------- + +## 0.2.81 + +Released 2022-06-14. + +[changes](https://github.com/rustwasm/wasm-bindgen/compare/0.2.80...0.2.81) + +-------------------------------------------------------------------------------- + +## 0.2.80 + +Released 2022-04-04. + +[changes](https://github.com/rustwasm/wasm-bindgen/compare/0.2.79...0.2.80) + +-------------------------------------------------------------------------------- + +## 0.2.79 + +Released 2022-01-19. + +[changes](https://github.com/rustwasm/wasm-bindgen/compare/0.2.78...0.2.79) + +-------------------------------------------------------------------------------- + +## 0.2.78 + +Released 2021-09-15. + +[changes](https://github.com/rustwasm/wasm-bindgen/compare/0.2.77...0.2.78) + +-------------------------------------------------------------------------------- + +## 0.2.77 + +Released 2021-09-08. + +[changes](https://github.com/rustwasm/wasm-bindgen/compare/0.2.76...0.2.77) + +-------------------------------------------------------------------------------- + +## 0.2.76 + +Released 2021-08-19. + +[changes](https://github.com/rustwasm/wasm-bindgen/compare/0.2.75...0.2.76) + +-------------------------------------------------------------------------------- + +## 0.2.75 + +Released 2021-08-02. + +[changes](https://github.com/rustwasm/wasm-bindgen/compare/0.2.74...0.2.75) + +-------------------------------------------------------------------------------- + +## 0.2.74 + +Released 2021-05-10. + +[changes](https://github.com/rustwasm/wasm-bindgen/compare/0.2.73...0.2.74) + +-------------------------------------------------------------------------------- + +## 0.2.73 + +Released 2021-03-29. + +[changes](https://github.com/rustwasm/wasm-bindgen/compare/0.2.72...0.2.73) + +-------------------------------------------------------------------------------- + +## 0.2.72 + +Released 2021-03-18. + +[changes](https://github.com/rustwasm/wasm-bindgen/compare/0.2.71...0.2.72) + +-------------------------------------------------------------------------------- + +## 0.2.71 + +Released 2021-02-26. + +[changes](https://github.com/rustwasm/wasm-bindgen/compare/0.2.70...0.2.71) + +-------------------------------------------------------------------------------- + +## 0.2.70 + +Released 2021-01-25. + +[changes](https://github.com/rustwasm/wasm-bindgen/compare/0.2.69...0.2.70) + +-------------------------------------------------------------------------------- + +## 0.2.69 + +Released 2020-11-30. + +### Added + +* Unstable bindings for WebBluetooth have been added. + [#2311](https://github.com/rustwasm/wasm-bindgen/pull/2311) + +* Unstable bindings for WebUSB have been added. + [#2345](https://github.com/rustwasm/wasm-bindgen/pull/2345) + +* Renaming a struct field with `js_name` is now supported. + [#2360](https://github.com/rustwasm/wasm-bindgen/pull/2360) + +* The WebGPU WebIDL has been updated. + [#2353](https://github.com/rustwasm/wasm-bindgen/pull/2353) + +### Fixed + +* The ImageCapture APIs of web-sys have been moved to unstable and were fixed. + [#2348](https://github.com/rustwasm/wasm-bindgen/pull/2348) + +* Bindings for `waitAsync` have been updated. + [#2362](https://github.com/rustwasm/wasm-bindgen/pull/2362) + +-------------------------------------------------------------------------------- + +## 0.2.68 + +Released 2020-09-08. + +### Added + +* Add userVisibleOnly property to PushSubscriptionOptionsInit. + [#2288](https://github.com/rustwasm/wasm-bindgen/pull/2288) + +### Fixed + +* TypeScript files now import `*.wasm` instead of bare files. + [#2283](https://github.com/rustwasm/wasm-bindgen/pull/2283) + +* Usage of `externref` now appropriately resizes the table by using 2x the + previous capacity, fixing a performance issue with lots of externref objects. + [#2294](https://github.com/rustwasm/wasm-bindgen/pull/2294) + +* Compatibility with the latest Firefox WebDriver has been fixed. + [#2301](https://github.com/rustwasm/wasm-bindgen/pull/2301) + +* Non deterministic output with closures has been fixed. + [#2304](https://github.com/rustwasm/wasm-bindgen/pull/2304) + +### Updated + +* The WebGPU WebIDL was updated. + [#2267](https://github.com/rustwasm/wasm-bindgen/pull/2267) + +-------------------------------------------------------------------------------- + +## 0.2.67 + +Released 2020-07-28. + +### Added + +* A `--reference-types` flag was added to the CLI. + [#2257](https://github.com/rustwasm/wasm-bindgen/pull/2257) + +### Fixed + +* Breakage with `Closure::forget` in 0.2.66 was fixed. + [#2258](https://github.com/rustwasm/wasm-bindgen/pull/2258) + +-------------------------------------------------------------------------------- + +## 0.2.66 + +Released 2020-07-28. + +### Added + +* Reverse mappings from value to name are now available in JS bindings of enums. + [#2240](https://github.com/rustwasm/wasm-bindgen/pull/2240) + +### Fixed + +* Functions using a return pointer in threaded programs now correctly load and + store return values in a way that doesn't interfere with other threads. + [#2249](https://github.com/rustwasm/wasm-bindgen/pull/2249) + +* Support for weak references has been updated and a `--weak-refs` flag is now + available in the CLI for enabling weak references. + [#2248](https://github.com/rustwasm/wasm-bindgen/pull/2248) + +-------------------------------------------------------------------------------- + +## 0.2.65 + +Released 2020-07-15. + +### Added + +* Functions from JS can now be natively imported as `async` and will use + promises under the hood. + [#2196](https://github.com/rustwasm/wasm-bindgen/pull/2196) + +### Changed + +* Encoding for the reference types proposal has been updated to the latest + version of the spec. + [#2234](https://github.com/rustwasm/wasm-bindgen/pull/2234) + +-------------------------------------------------------------------------------- + +## 0.2.64 + +Released 2020-06-29. + +### Added + +* Nested namespaces for imports can now be specified. + [#2105](https://github.com/rustwasm/wasm-bindgen/pull/2105) + +* A `deno` target has been added. + [#2176](https://github.com/rustwasm/wasm-bindgen/pull/2176) + +### Fixed + +* Getters/setters that consume the original object have been fixed to invalidate + the object correctly. + [#2172](https://github.com/rustwasm/wasm-bindgen/pull/2172) + +* Compatibility with nightly threading in LLVM has been fixed. + [#2183](https://github.com/rustwasm/wasm-bindgen/pull/2183) + +* Trailing space in generated doc comments is now removed. + [#2210](https://github.com/rustwasm/wasm-bindgen/pull/2210) + +-------------------------------------------------------------------------------- + +## 0.2.63 + +Released 2020-05-27. + +### Added + +* A new example about using WebRTC has been added. + [#2131](https://github.com/rustwasm/wasm-bindgen/pull/2131) + +* The `Blob.stream()` method has been added. + [#2140](https://github.com/rustwasm/wasm-bindgen/pull/2140) + [#2142](https://github.com/rustwasm/wasm-bindgen/pull/2142) + +### Changed + +* The encoding and implementation of WebAssembly reference types has been sync'd + with the latest upstream specification. + [#2125](https://github.com/rustwasm/wasm-bindgen/pull/2125) + +### Fixed + +* Test functions names will no longer collide with test intrinsic names. + [#2123](https://github.com/rustwasm/wasm-bindgen/pull/2123) + +* Fixed warnings with `#[must_use]` types in generated code. + [#2144](https://github.com/rustwasm/wasm-bindgen/pull/2144) + +* Fixed compatibility with latest Rust nightlies. + [#2159](https://github.com/rustwasm/wasm-bindgen/pull/2159) + +-------------------------------------------------------------------------------- + +## 0.2.62 + +Released 2020-05-01. + +### Fixed + +* Usage of `require` has been fixed with Webpack 5. + [#2115](https://github.com/rustwasm/wasm-bindgen/pull/2115) + +-------------------------------------------------------------------------------- + +## 0.2.61 + +Released 2020-04-29. + +### Added + +* Exported Rust `enum` types can now be renamed with `js_name`. + [#2071](https://github.com/rustwasm/wasm-bindgen/pull/2071) + +* More comments are copied to JS/TS files, and comments should no longer + accidentally have escape sequences in them. + [#2070](https://github.com/rustwasm/wasm-bindgen/pull/2070) + +* Experimental bindings for the Clipboard browser APIs have been added. + [#2100](https://github.com/rustwasm/wasm-bindgen/pull/2100) + +### Changed + +* WebGPU bindings have been updated. + [#2080](https://github.com/rustwasm/wasm-bindgen/pull/2080) + +* `setBindGroup` methods for WebIDL now take immutable slices instead of mutable + slices. + [#2087](https://github.com/rustwasm/wasm-bindgen/pull/2087) + +* JS code generation for `catch` functions has been improved. + [#2098](https://github.com/rustwasm/wasm-bindgen/pull/2098) + +* Usage of NPM dependencies with the `web` target is no longer an error. + [#2103](https://github.com/rustwasm/wasm-bindgen/pull/2103) + +### Fixed + +* Combining `js_name` with `getter` and `setter` has now been fixed. + [#2074](https://github.com/rustwasm/wasm-bindgen/pull/2074) + +* Importing global names which conflict with other namespaces should now work + correctly. + [#2057](https://github.com/rustwasm/wasm-bindgen/pull/2057) + +* Acquiring the global JS object has been fixed for Firefox extension content + scripts. + [#2099](https://github.com/rustwasm/wasm-bindgen/pull/2099) + +* The output of `wasm-bindgen` is now compatible with Webpack 5 and the updated + version of the wasm ESM integration specification. + [#2110](https://github.com/rustwasm/wasm-bindgen/pull/2099) + +-------------------------------------------------------------------------------- + +## 0.2.60 + +Released 2020-03-25. + +### Added + +* The `js_sys` types are now more accurately reflected in TypeScript. + [#2028](https://github.com/rustwasm/wasm-bindgen/pull/2028) + +* The timeout in `wasm-bindgen-test-runner`'s timeout can now be configured via + `WASM_BINDGEN_TEST_TIMEOUT`. + [#2036](https://github.com/rustwasm/wasm-bindgen/pull/2036) + +* WebIDL for WebXR has been added. + [#2000](https://github.com/rustwasm/wasm-bindgen/pull/2000) + +### Changed + +* The WebIDL for WebGPU has been updated. + [#2037](https://github.com/rustwasm/wasm-bindgen/pull/2037) + +-------------------------------------------------------------------------------- + +## 0.2.59 + +Released 2020-03-03. + +### Added + +* The `js_sys::Number` type now has a number of JS-number associated constants + on it now. + [#1965](https://github.com/rustwasm/wasm-bindgen/pull/1965) + +* The `getTransform` method on `CanvasRenderingContext2D` has been added. + [#1966](https://github.com/rustwasm/wasm-bindgen/pull/1966) + +* Initial experimental support was added for electron targets with a new + `--omit-imports` flag. + [#1958](https://github.com/rustwasm/wasm-bindgen/pull/1958) + +* Optional struct fields are now reflected idiomatically in TypeScript. + [#1990](https://github.com/rustwasm/wasm-bindgen/pull/1990) + +* Typed arrays in `js_sys` now have `get_index` and `set_index` methods. + [#2001](https://github.com/rustwasm/wasm-bindgen/pull/2001) + +* The `web_sys::Blob` type has been updated with `arrayBuffer` and `text` + methods. + [#2008](https://github.com/rustwasm/wasm-bindgen/pull/2008) + +* Support for unstable browser interfaces has now been added. By compiling + `web_sys` with `--cfg web_sys_unstable_apis` (typically via `RUSTFLAGS`) + you'll be able to access all bound WebIDL functions, even those like GPU + support on the web, which has now also had its WebIDL updated. + [#1997](https://github.com/rustwasm/wasm-bindgen/pull/1997) + +* The compile time for `web_sys` has been massively reduced by pre-generating + Rust code from WebIDL. It is also readable now since it generates + `#[wasm_bindgen]` annotations instead of expanded code. + [#2012](https://github.com/rustwasm/wasm-bindgen/pull/2012) + +* A new `typescript_type` attribute can be used to specify the TypeScript type + for an `extern` type. [#2012](https://github.com/rustwasm/wasm-bindgen/pull/2012) + +* It is now possible to use string values with `#[wasm_bindgen]` `enum`s. + [#2012](https://github.com/rustwasm/wasm-bindgen/pull/2012) + +* A new `skip_tyepscript` attribute is recognized to skip generating TypeScript + bindings for a function or type. + [#2016](https://github.com/rustwasm/wasm-bindgen/pull/2016) + +### Changed + +* More `uniformMatrix*` bindings now are whitelisted take shared slice instead + of a mutable slice. + [#1957](https://github.com/rustwasm/wasm-bindgen/pull/1957) + +* Non-`dependency` keys in `package.json` are now ignored instead of error'd + about. + [#1969](https://github.com/rustwasm/wasm-bindgen/pull/1969) + +* WebGPU has been removed from `web_sys` since it was outdated and didn't work + anywhere anyway. + [#1972](https://github.com/rustwasm/wasm-bindgen/pull/1972) + +* The JS heap of objects managed by wasm-bindgen has had its definition + tightended up a bit. + [#1987](https://github.com/rustwasm/wasm-bindgen/pull/1987) + +* The `self` identifier is no longe used on the `no-modules` target, making it a + bit more flexible in more environments. + [#1995](https://github.com/rustwasm/wasm-bindgen/pull/1995) + +* The wasm-loading logic is now more flexible and can take promises as well. + [#1996](https://github.com/rustwasm/wasm-bindgen/pull/1996) + +* JS glue for closures is now deduplicated. + [#2002](https://github.com/rustwasm/wasm-bindgen/pull/2002) + +* The `web_sys` crate now emits more accurate TypeScript definitions using named + types instead of `any` everywhere. + [#1998](https://github.com/rustwasm/wasm-bindgen/pull/1998) + +* The `send_with_u8_array` methods in `web_sys` are whitelisted to take shared + slices instead of mutable slices. + [#2015](https://github.com/rustwasm/wasm-bindgen/pull/2015) + +-------------------------------------------------------------------------------- + +## 0.2.58 + +Released 2020-01-07. + +### Added + +* When using the `no-modules` output type the initialization path for the wasm + file is now optional if it can be inferred from the current JS script. + [#1938](https://github.com/rustwasm/wasm-bindgen/pull/1938) + +### Fixed + +* TypeScript for struct methods that have floats has been fixed. + [#1945](https://github.com/rustwasm/wasm-bindgen/pull/1945) + +-------------------------------------------------------------------------------- + +## 0.2.57 + +Released 2020-01-06. + +### Fixed + +* The `js_sys::Promise` type is now marked as `#[must_use]` + [#1927](https://github.com/rustwasm/wasm-bindgen/pull/1927) + +* Duplicate imports of the same name are now handled correctly again. + [#1942](https://github.com/rustwasm/wasm-bindgen/pull/1942) + +-------------------------------------------------------------------------------- + +## 0.2.56 + +Released 2019-12-20. + +### Added + +* Added a `#[wasm_bindgen(inspectable)]` attribute for exported objects to + generate `toJSON` and `toString` implementations. + [#1876](https://github.com/rustwasm/wasm-bindgen/pull/1876) + +* Support for the most recent interface types proposal has been implemented. + [#1882](https://github.com/rustwasm/wasm-bindgen/pull/1882) + +* Initial support for async iterators has been added. + [#1895](https://github.com/rustwasm/wasm-bindgen/pull/1895) + +* Support for an `async` start function was added. + [#1905](https://github.com/rustwasm/wasm-bindgen/pull/1905) + +* `Array::iter` and `Array::to_vec` methods were added to js-sys. + [#1909](https://github.com/rustwasm/wasm-bindgen/pull/1909) + +### Fixed + +* Another webkit-specific WebIDL construct was fixed in web-sys. + [#1865](https://github.com/rustwasm/wasm-bindgen/pull/1865) + +-------------------------------------------------------------------------------- + +## 0.2.55 + +Released 2019-11-19. + +### Fixed + +* Running `wasm-bindgen` over empty anyref modules now works again. + [#1861](https://github.com/rustwasm/wasm-bindgen/pull/1861) + +* Support for multi-value JS engines has been fixed as a wasm interface types + polyfill. + [#1863](https://github.com/rustwasm/wasm-bindgen/pull/1863) + +-------------------------------------------------------------------------------- + +## 0.2.54 + +Released 2019-11-07. + +### Added + +* A safe `to_vec` method has been added for typed arrays. + [#1844](https://github.com/rustwasm/wasm-bindgen/pull/1844) + +* A unsafe method `view_mut_raw` has been added to typed arrays. + [#1850](https://github.com/rustwasm/wasm-bindgen/pull/1850) + +* The `HTMLImageElement` WebIDL has been updated with recent features. + [#1842](https://github.com/rustwasm/wasm-bindgen/pull/1842) + +* Binary crates are now supported and `fn main` will be automatically executed + like the `start` function. + [#1843](https://github.com/rustwasm/wasm-bindgen/pull/1843) + +### Changed + +* Some JS glue generation has been tweaked to avoid TypeScript warnings. + [#1852](https://github.com/rustwasm/wasm-bindgen/pull/1852) + +-------------------------------------------------------------------------------- + +## 0.2.53 + +Released 2019-10-29. + +### Fixed + +* A bug with the experimental support for multi-value interface types has been + fixed. + [#1839](https://github.com/rustwasm/wasm-bindgen/pull/1839) + +-------------------------------------------------------------------------------- + +## 0.2.52 + +Released 2019-10-24. + +### Added + +* The support for wasm-interface-types now uses multi-value by default. + [#1805](https://github.com/rustwasm/wasm-bindgen/pull/1805) + +* The Worklet IDL has been updated. + [#1817](https://github.com/rustwasm/wasm-bindgen/pull/1817) + +* The HTMLInputElement type has selectionStart and selectionEnd properties now. + [#1811](https://github.com/rustwasm/wasm-bindgen/pull/1811) + +* An `unintern` function has been added to remove an interned string from the + cache. + [#1828](https://github.com/rustwasm/wasm-bindgen/pull/1828) + +### Changed + +* Some WebIDL indexing getters have been corrected to reflect that they can + throw and/or return `undefined` + [#1789](https://github.com/rustwasm/wasm-bindgen/pull/1789) + +### Fixed + +* A bug with `TextDecoder` and Safari has been fxied + [#1789](https://github.com/rustwasm/wasm-bindgen/pull/1789) + +-------------------------------------------------------------------------------- + +## 0.2.51 + +Released 2019-09-26. + +### Added + +* The `wasm-bindgen-futures` and `wasm-bindgen-test` crates now require Nightly + Rust and have a new major version published as a result. These crates now + support `async`/`await` by default, and they will be supported in the stable + Rust 1.39.0 release. The previous versions of crates will continue to work on + stable today. + [#1741](https://github.com/rustwasm/wasm-bindgen/pull/1741) + +* Using `#[wasm_bindgen]` on an `async` function will now work and return a + `Promise` on the JS side of things. + [#1754](https://github.com/rustwasm/wasm-bindgen/pull/1754) + +* More helper methods for `js_sys::Array` have been added. + [#1749](https://github.com/rustwasm/wasm-bindgen/pull/1749) + +* Initial support for the WebAssembly multi-value proposal has been added. + [#1764](https://github.com/rustwasm/wasm-bindgen/pull/1764) + +* Constructors for `js_sys::Date` with optional parameters has been added. + [#1759](https://github.com/rustwasm/wasm-bindgen/pull/1759) + +* Headless tests can now be run against a remote webdriver client + [#1744](https://github.com/rustwasm/wasm-bindgen/pull/1744) + +### Changed + +* The `passStringToWasm` function has been optimized for size. + [#1736](https://github.com/rustwasm/wasm-bindgen/pull/1736) + +### Fixed + +* BOM markers will not be preserved when passing strings to/from wasm. + [#1730](https://github.com/rustwasm/wasm-bindgen/pull/1730) + +* Importing a `static` value which isn't a `JsValue` has been fixed. + [#1784](https://github.com/rustwasm/wasm-bindgen/pull/1784) + +* Converting `undefined` to a Rust value via `into_serde` has been fixed. + [#1783](https://github.com/rustwasm/wasm-bindgen/pull/1783) + +* Routine errors are no longer erroneously logged in debug mode. + [#1788](https://github.com/rustwasm/wasm-bindgen/pull/1788) + +-------------------------------------------------------------------------------- + +## 0.2.50 + +Released 2019-08-19. + +### Added + +* Experimental support with a `WASM_INTERFACE_TYPES=1` environment variable has + been added to emit a Wasm Interface Types custom section, making the output of + `wasm-bindgen` a single standalone WebAssembly file. + [#1725](https://github.com/rustwasm/wasm-bindgen/pull/1725) + +### Fixed + +* Unrelated errors are now no longer accidentally swallowed by the + `instantiateStreaming` fallback. + [#1723](https://github.com/rustwasm/wasm-bindgen/pull/1723) + +-------------------------------------------------------------------------------- + +## 0.2.49 + +Released 2019-08-14. + +### Added + +* Add binding for `Element.getElementsByClassName`. + [#1665](https://github.com/rustwasm/wasm-bindgen/pull/1665) + +* `PartialEq` and `Eq` are now implementd for all `web-sys` types. + [#1673](https://github.com/rustwasm/wasm-bindgen/pull/1673) + +* The `wasm-bindgen-futures` crate now has support for futures when the + experimental WebAssembly threading feature is enabled. + [#1514](https://github.com/rustwasm/wasm-bindgen/pull/1514) + +* A new `enable-interning` feature is available to intern strings and reduce the + cost of transferring strings across the JS/Rust boundary. + [#1612](https://github.com/rustwasm/wasm-bindgen/pull/1612) + +* The `wasm-bindgen` CLI has experimental support for reading native + `webidl-bindings` custom sections and generating JS glue. This support is in + addition to Rust's own custom sections and allows using `wasm-bindgen` with + binaries produced by other than rustc possibly. + [#1690](https://github.com/rustwasm/wasm-bindgen/pull/1690) + +* New environment variables have been added to configure webdriver startup + arguments. + [#1703](https://github.com/rustwasm/wasm-bindgen/pull/1703) + +* New `JsValue::{is_truthy,is_falsy}` methods are now available. + [#1638](https://github.com/rustwasm/wasm-bindgen/pull/1638) + +### Changed + +* JS import shims are now skipped again when they are unnecessary. + [#1654](https://github.com/rustwasm/wasm-bindgen/pull/1654) + +* WebAssembly output files now directly embed the module/name for imports if + supported for the target and the import, reducing JS shims even further. + [#1689](https://github.com/rustwasm/wasm-bindgen/pull/1689) + +### Fixed + +* Support for threads have been updated for LLVM 9 and nightly Rust. + [#1675](https://github.com/rustwasm/wasm-bindgen/pull/1675) + [#1688](https://github.com/rustwasm/wasm-bindgen/pull/1688) + +* The `anyref` passes in `wasm-bindgen` have seen a number of fixes to improve + their correctness and get the full test suite running. + [#1692](https://github.com/rustwasm/wasm-bindgen/pull/1692) + [#1704](https://github.com/rustwasm/wasm-bindgen/pull/1704) + +* Support for `futures-preview 0.3.0-alpha.18` has been added to + `wasm-bindgen-futures`. + [#1716](https://github.com/rustwasm/wasm-bindgen/pull/1716) + +-------------------------------------------------------------------------------- + +## 0.2.48 + +Released 2019-07-11. + +### Added + +* All typed arrays now implement `From` for the corresponding Rust slice type, + providing a safe way to create an instance which copies the data. + [#1620](https://github.com/rustwasm/wasm-bindgen/pull/1620) + +* `Function::bind{2,3,4}` are now available in `js-sys`. + [#1633](https://github.com/rustwasm/wasm-bindgen/pull/1633) + +### Changed + +* More WebGL methods have been updated to use shared slices instead of mutable + slices. + [#1639](https://github.com/rustwasm/wasm-bindgen/pull/1639) + +* When using the `bundler` target the import of the wasm file now uses the + `.wasm` extension to ensure a wasm file is loaded. + [#1646](https://github.com/rustwasm/wasm-bindgen/pull/1646) + +* The old internal `Stack` trait has been removed since it is no longer used. + [#1624](https://github.com/rustwasm/wasm-bindgen/pull/1624) + +### Fixed + +* The `js_sys::global()` accessor now attempts other strategies before falling + back to a `Function` constructor which can violate some strict CSP settings. + [#1650](https://github.com/rustwasm/wasm-bindgen/pull/1649) + +* Dropping a `JsFuture` no longer logs a benign error to the console. + [#1649](https://github.com/rustwasm/wasm-bindgen/pull/1649) + +* Fixed an assertion which could happen in some modules when generating + bindings. + [#1617](https://github.com/rustwasm/wasm-bindgen/pull/1617) + +-------------------------------------------------------------------------------- + +## 0.2.47 + +Released 2019-06-19. + +### Changed + +* The `HtmlHyperlinkElement` should now include more native methods after a + small edit to the WebIDL. + [#1604](https://github.com/rustwasm/wasm-bindgen/pull/1604) + +* Duplicate names for getters/setters now have a first-class `wasm-bindgen` + error. + [#1605](https://github.com/rustwasm/wasm-bindgen/pull/1605) + +### Fixed + +* TypeScript definition of `init` with `--target web` now reflects that the + first argument is optional. + [#1599](https://github.com/rustwasm/wasm-bindgen/pull/1599) + +* A panic with the futures 0.3 support has been fixed. + [#1598](https://github.com/rustwasm/wasm-bindgen/pull/1598) + +* More slice types are recognized as becoming immutable in some WebIDL methods. + [#1602](https://github.com/rustwasm/wasm-bindgen/pull/1602) + +* The function table is now no longer too aggressively removed. + [#1606](https://github.com/rustwasm/wasm-bindgen/pull/1606) + +-------------------------------------------------------------------------------- + +## 0.2.46 + +Released 2019-06-14. + +### Added + +* Bindings for `Array#flat` and `Array#flatMap` have been added. + [#1573](https://github.com/rustwasm/wasm-bindgen/pull/1573) + +* All `#[wasm_bindgen]` types now `AsRef` to themslves. + [#1583](https://github.com/rustwasm/wasm-bindgen/pull/1583) + +* When using `--target web` the path passed to `init` is no longer required. + [#1579](https://github.com/rustwasm/wasm-bindgen/pull/1579) + +### Fixed + +* Some diagnostics related to compiler errors in `#[wasm_bindgen]` have been + improved. + [#1550](https://github.com/rustwasm/wasm-bindgen/pull/1550) + +* The support for weak references has been updated to the current JS proposal. + [#1557](https://github.com/rustwasm/wasm-bindgen/pull/1557) + +* Documentation and feature gating for web-sys dictionaries has improved. + [#1572](https://github.com/rustwasm/wasm-bindgen/pull/1572) + +* Getter and setter TypeScript has been fixed. + [#1577](https://github.com/rustwasm/wasm-bindgen/pull/1577) + +* The `env_logger` crate and its tree of dependencies is no longer required to + build `web-sys`. + [#1586](https://github.com/rustwasm/wasm-bindgen/pull/1586) + +-------------------------------------------------------------------------------- + +## 0.2.45 + +Released 2019-05-20. + +### Fixed + +* Using `__wbindgen_cb_forget` on `--target web` has been fixed. + [#1544](https://github.com/rustwasm/wasm-bindgen/pull/1544) + +### Changed + +* More whitelists have been added for `web-sys` to use shared slices instead of + mutable slices. + [#1539](https://github.com/rustwasm/wasm-bindgen/pull/1539) + +-------------------------------------------------------------------------------- + +## 0.2.44 + +Released 2019-05-16. + +### Added + +* Support for exporting "fields" on JS objects wrapping Rust structs which are + hooked up to getters/setters has been added. This is in addition to `pub` + struct fields and allows performing more complicated computations in + getters/setters. + [#1440](https://github.com/rustwasm/wasm-bindgen/pull/1440) + +* Support for futures 0.3 (and `async` / `await` syntax) has been added to the + `wasm-bindgen-futures` crate. + [#1507](https://github.com/rustwasm/wasm-bindgen/pull/1507) + +* Stacks of imported JS functions that throw and aren't marked `catch` are now + logged in debug mode. + [#1466](https://github.com/rustwasm/wasm-bindgen/pull/1466) + +* A utility for counting the size of the `anyref` heap has been added. + [#1521](https://github.com/rustwasm/wasm-bindgen/pull/1521) + +* Passing ASCII-only strings to WASM should now be significantly faster. + [#1470](https://github.com/rustwasm/wasm-bindgen/pull/1470) + +* The `selectionStart` and `selectionEnd` APIs of text areas have been enabled. + [#1533](https://github.com/rustwasm/wasm-bindgen/pull/1533) + +### Changed + +* Some more methods in `web-sys` now take immutable slices instead of mutable + ones. + [#1508](https://github.com/rustwasm/wasm-bindgen/pull/1508) + +* TypeScript bindings for `Option` arguments now use `foo?` where possible. + [#1483](https://github.com/rustwasm/wasm-bindgen/pull/1483) + +### Fixed + +* Unnecessary bindings to `__wbindgen_object_drop_ref` have been fixed. + [#1504](https://github.com/rustwasm/wasm-bindgen/pull/1504) + +* Some direct imports have been fixed for `--target web`. + [#1503](https://github.com/rustwasm/wasm-bindgen/pull/1503) + +* Both importing and exporting the same name has been fixed. + [#1506](https://github.com/rustwasm/wasm-bindgen/pull/1506) + +* TypeScript typings for `init` in `--target web` have been fixed. + [#1520](https://github.com/rustwasm/wasm-bindgen/pull/1520) + +* Calling a dropped `Closure` should no longer "segfault" but produce a clear + error. + [#1530](https://github.com/rustwasm/wasm-bindgen/pull/1530) + +-------------------------------------------------------------------------------- + +## 0.2.43 + +Released 2019-04-29. + +### Added + +* Support for `isize` and `usize` arrays has been added. + [#1448](https://github.com/rustwasm/wasm-bindgen/pull/1448) + +* Support customizing `dyn_ref` and friends via a new `is_type_of` attribute and + apply it to some `js_sys` bindings. + [#1405](https://github.com/rustwasm/wasm-bindgen/pull/1405) + [#1450](https://github.com/rustwasm/wasm-bindgen/pull/1450) + [#1490](https://github.com/rustwasm/wasm-bindgen/pull/1490) + +* A new `skip` attribute to `#[wasm_bindgen]` has been added to skip fields and + methods when generating bindings. + [#1410](https://github.com/rustwasm/wasm-bindgen/pull/1410) + +* More bindings have been added to `web-sys` for interfaces tagged with + `[NoInterfaceObject]` in WebIDL. These types always fail `dyn_ref` and friends + and must be manually casted into. + [#1449](https://github.com/rustwasm/wasm-bindgen/pull/1449) + +* Added `Debug for JsFuture`. + [#1477](https://github.com/rustwasm/wasm-bindgen/pull/1477) + +* Initial bindings for `Atomics` and `SharedArrayBuffer` have been added to + `js_sys`. + [#1463](https://github.com/rustwasm/wasm-bindgen/pull/1463) + +* Bindings for `Object.fromEntries` has been added to `js_sys`. + [#1456](https://github.com/rustwasm/wasm-bindgen/pull/1456) + +* Tuple structs exported to JS now have indexed struct properties. + [#1467](https://github.com/rustwasm/wasm-bindgen/pull/1467) + +* Binding for `new Function(args, body)` has been added to `js_sys`. + [#1492](https://github.com/rustwasm/wasm-bindgen/pull/1492) + +* Bindings for some variadic functions have been added to `js_sys`. + [#1491](https://github.com/rustwasm/wasm-bindgen/pull/1491) + +### Changed + +* Many `js-sys` types have received various tweaks and improvements to ensure + they're consistent and work similarly to native Rust types. + [#1447](https://github.com/rustwasm/wasm-bindgen/pull/1447) + [#1444](https://github.com/rustwasm/wasm-bindgen/pull/1444) + [#1473](https://github.com/rustwasm/wasm-bindgen/pull/1473) + +* Dummy types in `js-sys` only used to namespace methods were removed and now + modules are used for namespacing instead. + [#1451](https://github.com/rustwasm/wasm-bindgen/pull/1451) + +* Bindings in `web-sys` are formatted by default for ease of usage in IDEs. + [#1461](https://github.com/rustwasm/wasm-bindgen/pull/1461) + +### Fixed + +* Documentation for Rust methods now show up in TypeScript as well. + [#1472](https://github.com/rustwasm/wasm-bindgen/pull/1472) + +-------------------------------------------------------------------------------- + +## 0.2.42 + +Released 2019-04-11. + +### Fixed + +* Fixed an issue in Firefox where using `encodeInto` accidentally caused empty + strings to keep getting passed to Rust. + [#1434](https://github.com/rustwasm/wasm-bindgen/pull/1434) + +-------------------------------------------------------------------------------- + +## 0.2.41 + +Released 2019-04-10. + +### Added + +* Initial support for transitive NPM dependencies has been added. + [#1305](https://github.com/rustwasm/wasm-bindgen/pull/1305) + +* The `constructor` property of `Object` is now bound in `js-sys`. + [#1403](https://github.com/rustwasm/wasm-bindgen/pull/1403) + +* The `Closure` type now always implements `Debug`. + [#1408](https://github.com/rustwasm/wasm-bindgen/pull/1408) + +* Closures which take one `&T` argument are now supported. More implementations + may be added in the future, but for now it's just one argument closures. + [#1417](https://github.com/rustwasm/wasm-bindgen/pull/1417) + +* The TypeScript bindings for `--web` now expose the `init` function. + [#1412](https://github.com/rustwasm/wasm-bindgen/pull/1412) + +* A `js_sys::JsString::is_valid_utf16` method has been added to handle unpaired + surrogates in JS strings. Surrounding documentation has also been updated to + document this potential pitfall. + [#1416](https://github.com/rustwasm/wasm-bindgen/pull/1416) + +* A `wasm_bindgen::function_table()` function has been added to expose the + `WebAssembly.Table` and get access to it in wasm code. + [#1431](https://github.com/rustwasm/wasm-bindgen/pull/1431) + +### Fixed + +* Reexporting the `wasm_bindgen` macro in crates has been fixed. + [#1359](https://github.com/rustwasm/wasm-bindgen/pull/1359) + +* Returning `u32` to JS has been fixed where large `u32` values would show up in + JS as large negative numbers. + [#1401](https://github.com/rustwasm/wasm-bindgen/pull/1401) + +* Manual instantiation with `WebAssembly.Module` has been fixed. + [#1419](https://github.com/rustwasm/wasm-bindgen/pull/1419) + +* Error message for non-`Copy` public struct fields has been improved. + [#1430](https://github.com/rustwasm/wasm-bindgen/pull/1430) + +### Changed + +* Performance of passing strings to Rust in Node.js has been improved. + [#1391](https://github.com/rustwasm/wasm-bindgen/pull/1391) + +* Performance of `js_sys::try_iter` has been improved. + [#1393](https://github.com/rustwasm/wasm-bindgen/pull/1393) + +* Performance of using `TextEncoder#encodeInto` has been improved. + [#1414](https://github.com/rustwasm/wasm-bindgen/pull/1414) + +-------------------------------------------------------------------------------- + +## 0.2.40 + +Released 2019-03-21. + +### Added + +* TypeScript and JS generation will now attempt to preserve argument names in + the generated JS where possible. + [#1344](https://github.com/rustwasm/wasm-bindgen/pull/1344) + +* Enable `Option` support for enums defined in WebIDL. + [#1350](https://github.com/rustwasm/wasm-bindgen/pull/1350) + +* Add a `raw_module` attribute to `#[wasm_bindgen]` which is the same as + `module` except doesn't attempt to recognize `./`, `../`, `or `/` prefixed + paths. + [#1353](https://github.com/rustwasm/wasm-bindgen/pull/1353) + +* The `wasm-bindgen` CLI flags have now all been renamed under a `--target` + flag. Instead of `--web` you'll now pass `--target web`, for example. This + increases consistency between the `wasm-bindgen` and `wasm-pack` CLI. + [#1369](https://github.com/rustwasm/wasm-bindgen/pull/1369) + +### Fixed + +* Definitions for `TypedArray` imports of `js-sys` have been unified with a + macro to improve consistency and fix future bugs. + [#1371](https://github.com/rustwasm/wasm-bindgen/pull/1371) + +* Usage of `--no-modules` in CloudFlare workers should now work by default. + [#1384](https://github.com/rustwasm/wasm-bindgen/pull/1384) + +* A use-after-free when a closure is reinvoked after being destroyed on the Rust + die has been fixed. + [#1385](https://github.com/rustwasm/wasm-bindgen/pull/1385) + +* A bug causing nondeterministic generation of JS bindings has been fixed. + [#1383](https://github.com/rustwasm/wasm-bindgen/pull/1383) + +-------------------------------------------------------------------------------- + +## 0.2.39 + +Released 2018-03-13. + +### Added + +* Crates can now import locally written JS snippets to get bundled into the + final output. See [RFC 6] for more details as well as the PR. + [#1295](https://github.com/rustwasm/wasm-bindgen/pull/1295) + +[RFC 6]: https://github.com/rustwasm/rfcs/pull/6 + +### Changed + +* A typo in the return value of `slice` methods on typed arrays in `js-sys` was + corrected. + [#1321](https://github.com/rustwasm/wasm-bindgen/pull/1321) + +* The directory specified by `--out-dir` is now created if it doesn't exist + already. + [#1330](https://github.com/rustwasm/wasm-bindgen/pull/1330) + +### Fixed + +* A bug where if `nom` was in a crate graph and was compiled with the + `verbose-errors` feature has been fixed. Previously the `wasm-bindgen-webidl` + crate wouldn't compile, and now it will. + [#1338](https://github.com/rustwasm/wasm-bindgen/pull/1338) + +-------------------------------------------------------------------------------- + +## 0.2.38 + +Released 2019-03-04. + +### Added + +* Support for `Option` in `#[wasm_bindgen]` functions has now been + added. + [#1275](https://github.com/rustwasm/wasm-bindgen/pull/1275) + +* Experimental support for the `anyref` type proposal in WebAssembly has now + landed and is enabled with `WASM_BINDGEN_ANYREF=1`. + [#1002](https://github.com/rustwasm/wasm-bindgen/pull/1002) + +* Support fot the new browser `TextEncode#encodeInto` API has been added. + [#1279](https://github.com/rustwasm/wasm-bindgen/pull/1279) + +* JS doc comments are now added to TypeScript bindings in addition to the JS + bindings generated. + [#1302](https://github.com/rustwasm/wasm-bindgen/pull/1302) + +* Initial support for `FnOnce` closures has been added to the `Closure` type. + [#1281](https://github.com/rustwasm/wasm-bindgen/pull/1281) + +### Fixed + +* Fixed an internal assert tripping when some modules were compiled with LTO. + [#1274](https://github.com/rustwasm/wasm-bindgen/pull/1274) + +* The `Context` type in the `wasm-bindgen-test` crate had its JS name changed to + avoid conflicts with other crates that have a `Context` type being exported. + [#1280](https://github.com/rustwasm/wasm-bindgen/pull/1280) + +* The headless test runner for Safari on macOS High Sierra has been fixed. + [#1298](https://github.com/rustwasm/wasm-bindgen/pull/1298) + +### Changed + +* The `wasm-bindgen` CLI tool now emits the `producers` section again with + relevant bugs having been fixed in the meantime. The + `--remove-producers-section` flag can continue to be used to omit emission of + this section. + [#1263](https://github.com/rustwasm/wasm-bindgen/pull/1263) + +-------------------------------------------------------------------------------- + +## 0.2.37 + +Released 2019-02-15. + +### Added + +* The `HtmlMediaElement` type now exposes a `src_object` getter. + [#1248](https://github.com/rustwasm/wasm-bindgen/pull/1248). + +* The `js_sys::Reflect` type now has specializes getter/setters for `u32` and + `f64` indices. + [#1225](https://github.com/rustwasm/wasm-bindgen/pull/1225). + +* A `--remove-producers-section` flag has been added to the CLI tool to, well, + remove the `producers` section from the final wasm file. + [#1256](https://github.com/rustwasm/wasm-bindgen/pull/1256). + +### Fixed + +* The `wasm-bindgen` CLI tool will correctly strip DWARF debug information + unless `--keep-debug` is passed. + [#1255](https://github.com/rustwasm/wasm-bindgen/pull/1255). + +### Changed + +* The `wasm-bindgen` CLI tool no longer emits the `producers` custom section by + default to work around a [webpack bug]. See + [#1260](https://github.com/rustwasm/wasm-bindgen/pull/1260). + +[webpack bug]: https://github.com/webpack/webpack/pull/8786 + +-------------------------------------------------------------------------------- + +## 0.2.36 + +Released 2019-02-12. + +### Fixed + +* Fixed a bug where using closures and LTO together caused a panic inside the + `wasm-bindgen` CLI tool. See + [#1244](https://github.com/rustwasm/wasm-bindgen/issues/1244). + +-------------------------------------------------------------------------------- + +## 0.2.35 + +Released 2019-02-12. + +### Changed + +* `wasm-bindgen` now internally uses the `walrus` crate to perform its + transformations of the wasm that rustc/LLVM emits. See + [#1237](https://github.com/rustwasm/wasm-bindgen/pull/1237). + +### Fixed + +* When `WebAssembly.instantiateStreaming` fails due to incorrect MIME type, + *actually* properly recover. See + [#1243](https://github.com/rustwasm/wasm-bindgen/pull/1243). + +-------------------------------------------------------------------------------- + +## 0.2.34 + +Released 2019-02-11. + +### Added + +* Added support for optional `enum`s. See + [#1214](https://github.com/rustwasm/wasm-bindgen/pull/1214). +* Added the `UnwrapThrowExt` trait, which can enable smaller code sizes for + panics. See [#1219](https://github.com/rustwasm/wasm-bindgen/pull/1219). + +### Fixed + +* Some `WebGlRenderingContext` methods are now whitelisted to use shared slices + instead of exclusive slices. See + [#1199](https://github.com/rustwasm/wasm-bindgen/pull/1199). +* Fixed TypeScript definitions for optional types. See + [#1201](https://github.com/rustwasm/wasm-bindgen/pull/1201). +* Quiet clippy warnings inside generated code. See + [1207](https://github.com/rustwasm/wasm-bindgen/pull/1207). +* Fixed using `cfg_attr` and `wasm_bindgen` together like `#[cfg_attr(..., + wasm_bindgen)]`. See + [1208](https://github.com/rustwasm/wasm-bindgen/pull/1208). +* The WebAudio example program was fixed. See + [#1215](https://github.com/rustwasm/wasm-bindgen/pull/1215). +* Fixed logging HTML in `wasm-bindgen-test`. See + [#1233](https://github.com/rustwasm/wasm-bindgen/pull/1233). +* When `WebAssembly.instantiateStreaming` fails due to incorrect MIME type, + properly recover. See + [#1235](https://github.com/rustwasm/wasm-bindgen/pull/1235). + +-------------------------------------------------------------------------------- + +## 0.2.33 + +Released 2019-01-18. + +### Added + +* Improved the `Debug` output of `JsValue` + [#1161](https://github.com/rustwasm/wasm-bindgen/pull/1161) + +* Bindings for `JSON.stringify` and its optional arguments have been added + [#1190](https://github.com/rustwasm/wasm-bindgen/pull/1190) + +### Fixed + +* A bug with windows binaries being released has ben resolved. + +-------------------------------------------------------------------------------- + +## 0.2.32 + +Released 2019-01-16. + +### Added + +* Added support for Web IDL sequences. This enabled bindings generation for a + couple more Web APIs. We generate functions for Web APIs that take sequences + to accept any iterable, and for Web APIs that return sequences, a + `js_sys::Array` is returned. See + [#1152](https://github.com/rustwasm/wasm-bindgen/pull/1152) and + [#1038](https://github.com/rustwasm/wasm-bindgen/issues/1038). +* The `wasm-bindgen-test` test runner will capture `console.debug`, + `console.info`, and `console.warn` log messages and print them to `stdout` + now. It already supported `console.log` and `console.error` and continues to + support them. See + [#1183](https://github.com/rustwasm/wasm-bindgen/issues/1183) and + [#1184](https://github.com/rustwasm/wasm-bindgen/pull/1184). +* Added additional `--debug`-only assertions in the emitted JS glue for cases + where an imported JS function that is not annotated with + `#[wasm_bindgen(catch)]` throws an exception. This should help catch some bugs + earlier! See [#1179](https://github.com/rustwasm/wasm-bindgen/pull/1179). + +### Fixed + +* Fixed a bug where `#[wasm_bindgen_test]` tests would fail in non-headless Web + browsers if they used `console.log`. See + [#1167](https://github.com/rustwasm/wasm-bindgen/pull/1167). +* Fixed a bug where returning closures from exported functions sometimes + resulted in a faulty error. See + [#1174](https://github.com/rustwasm/wasm-bindgen/issues/1174) and + [#1175](https://github.com/rustwasm/wasm-bindgen/pull/1175). +* Sometimes our generated TypeScript interface files had syntax errors in them + (missing semicolons). This has been fixed. See + [#1181](https://github.com/rustwasm/wasm-bindgen/pull/1181). + +-------------------------------------------------------------------------------- + +## 0.2.31 + +Released 2019-01-09. + +### Added + +* A new `spawn_local` function has been added to the `wasm-bindgen-futures` + crate. + [#1148](https://github.com/rustwasm/wasm-bindgen/pull/1148) + +* Built-in conversions are now available from typed arrays and Rust arrays. + [#1147](https://github.com/rustwasm/wasm-bindgen/pull/1147) + +### Fixed + +* Some casing of dictionary properties in WebIDL has been fixed. + [#1155](https://github.com/rustwasm/wasm-bindgen/pull/1155) + +-------------------------------------------------------------------------------- + +## 0.2.30 + +Released 2019-01-07. + +### Added + +* The `wasm-bindgen` CLI now has an `--out-name` argument to name the output + module. + [#1084](https://github.com/rustwasm/wasm-bindgen/pull/1084) + +* Support for importing the `default` export has been added. + [#1106](https://github.com/rustwasm/wasm-bindgen/pull/1106) + +### Changed + +* All `web-sys` methods are now flagged as `structural`, fixing a few bindings. + [#1117](https://github.com/rustwasm/wasm-bindgen/pull/1117) + +### Fixed + +* A small bug with LTO and closures has been fixed. + [#1145](https://github.com/rustwasm/wasm-bindgen/pull/1145) + +-------------------------------------------------------------------------------- + +## 0.2.29 + +Released 2018-12-04. + +### Added + +* Add a `#[wasm_bindgen(start)]` attribute to customize the `start` section of + the wasm module. + [#1057](https://github.com/rustwasm/wasm-bindgen/pull/1057) + +* Add support for producing the new "producers" section of wasm binaries + [#1041](https://github.com/rustwasm/wasm-bindgen/pull/1041) + +* Add support a `typescript_custom_section` attribute for producing custom + typescript abstractions + [#1048](https://github.com/rustwasm/wasm-bindgen/pull/1048) + +* Generate `*.d.ts` files for wasm files in addition to the JS bindings + [#1053](https://github.com/rustwasm/wasm-bindgen/pull/1053) + +* Add a feature to assert that all attributes in `#[wasm_bindgen]` are used to + help catch typos and mistakes + [#1055](https://github.com/rustwasm/wasm-bindgen/pull/1055) + +### Changed + +* JS glue generation has received a few small optimizations such as removing + shims and removing object allocations + [#1033](https://github.com/rustwasm/wasm-bindgen/pull/1033) + [#1030](https://github.com/rustwasm/wasm-bindgen/pull/1030) + +* JS glue now just uses one array of JS objects instead of two + [#1069](https://github.com/rustwasm/wasm-bindgen/pull/1069) + +### Fixed + +* Fix a typo in the `--no-modules` generated JS + [#1045](https://github.com/rustwasm/wasm-bindgen/pull/1045) + +-------------------------------------------------------------------------------- + +## 0.2.28 + +Released 2018-11-12. + +### Added + +* The `js_class` support is now supported on exported types to define a + different class in JS than is named in Rust + [#1012](https://github.com/rustwasm/wasm-bindgen/pull/1012) + +* More WebIDL bindings are exposed with some internal restructuring to ignore + unimplemented types at a different location + [#1014](https://github.com/rustwasm/wasm-bindgen/pull/1014) + +* All imported types now implement `Deref` to their first `extends` attribute + (or `JsValue` if one isn't listed). This is intended to greatly improve the + ergonomics of `web-sys` bindings by allowing easy access to parent class + methods + [#1019](https://github.com/rustwasm/wasm-bindgen/pull/1019) + +* A new attribute, `final`, can be applied to JS imports. This attribute is + relatively nuanced and [best explained in documentation][final-dox], but is + added since `structural` is now the default + [#1019](https://github.com/rustwasm/wasm-bindgen/pull/1019) + +[final-dox]: https://rustwasm.github.io/wasm-bindgen/reference/attributes/on-js-imports/final.html + +* A new CLI flag, `--remove-name-section`, can be passed to remove the wasm + `name` section which contains the names of functions for debugging (typically + not needed in release mode) + [#1024](https://github.com/rustwasm/wasm-bindgen/pull/1024) + +### Changed + +* All imported functions are now `structural` by default. This shouldn't change + the semantics of imported functions, only how they're invoked in the JS + function shims that are generated by `wasm-bindgen`. More discussion can be + founed on [RFC 5] and the PR + [#1019](https://github.com/rustwasm/wasm-bindgen/pull/1019) + +[RFC 5]: https://rustwasm.github.io/rfcs/005-structural-and-deref.html + +* JS glue assertions for moved arguments are now only emitted in debug mode, + which is still off by default + [#1020](https://github.com/rustwasm/wasm-bindgen/pull/1020) + +### Fixed + +* Typescript generated bindings now correctly reflect `Option` for more types + [#1008](https://github.com/rustwasm/wasm-bindgen/pull/1008) + +* The JS shim code generation has been optimized for `structural` bindings (now + the default) to include fewer JS shims and more easily optimizable for JS + engines + [#1019](https://github.com/rustwasm/wasm-bindgen/pull/1019) + +* Passing a `WebAssembly.Module` to the `--no-modules` constructor has been + fixed + [#1025](https://github.com/rustwasm/wasm-bindgen/pull/1025) + +-------------------------------------------------------------------------------- + +## 0.2.27 + +Released 2018-10-29. + +### Fixed + +* Fixed an internal panic where the gc passes were being too aggressive + [#995](https://github.com/rustwasm/wasm-bindgen/pull/995) + +-------------------------------------------------------------------------------- + +## 0.2.26 + +Released 2018-10-29. + +### Added + +* The `TypedArray.slice` methods have now been bound in `js-sys`. + [#956](https://github.com/rustwasm/wasm-bindgen/pull/956) + +* The `Debug` and `Clone` traits are now implemented for `js_sys::Promise`. + [#957](https://github.com/rustwasm/wasm-bindgen/pull/957) + +* The `js_sys::DataView` type now exposes overloads to specify endianness. + [#966](https://github.com/rustwasm/wasm-bindgen/pull/966) + +* When using `--no-modules` a `WebAssembly.Module` can now be directly passed + into the instantiation glue. + [#969](https://github.com/rustwasm/wasm-bindgen/pull/969) + +### Fixed + +* The `JsValue` type is no longer considered `Send`. + [#955](https://github.com/rustwasm/wasm-bindgen/pull/955) + +* The generated JS glue is now more robust in the face of missing APIs. + [#959](https://github.com/rustwasm/wasm-bindgen/pull/959) + +* An issue with the latest version of `safaridriver` used to run headless tests + has been resolved. + [#991](https://github.com/rustwasm/wasm-bindgen/pull/991) + +-------------------------------------------------------------------------------- + +## 0.2.25 + +Released 2018-10-10. + +### Fixed + +* Using `wasm-bindgen` will no longer unconditionally pull in Rust's default + allocator for Wasm (dlmalloc) regardless if you configured a custom global + allocator (eg wee_alloc). + [#947](https://github.com/rustwasm/wasm-bindgen/pull/947) + +* Fixed web-sys build on some Windows machines. + [#943](https://github.com/rustwasm/wasm-bindgen/issues/943) + +* Fixed generated ES class bindings to Rust structs that were only referenced + through struct fields. + [#948](https://github.com/rustwasm/wasm-bindgen/issues/948) + +-------------------------------------------------------------------------------- + +## 0.2.24 + +Released 2018-10-05. + +### Added + +* Constructors for types in `web-sys` should now have better documentation. + +* A new `vendor_prefix` attribute in `#[wasm_bindgen]` is supported to bind APIs + on the web which may have a vendor prefix (like `webkitAudioContext`). This is + then subsequently used to fix `AudioContext` usage in Safari. + +* The `#[wasm_bindgen(extends = Foo)]` attribute now supports full paths, so you + can also say `#[wasm_bindgen(extends = foo::Bar)]` and such. + +### Changed + +* The `Closure` type is now optimized when the underlying closure is a ZST. + The type now no longer allocates memory in this situation. + +* The documentation now has a list of caveats for browser support, including how + `TextEncoder` and `TextDecoder` are not implemented in Edge. If you're using + webpack there's a listed strategy available, and improvements to the polyfill + strategy are always welcome! + +* The `BaseAudioContext` and `AudioScheduledSourceNode` types in `web-sys` have + been deprecated as they don't exist in Safari or Edge. + +### Fixed + +* Fixed the `#[wasm_bindgen_test]`'s error messages in a browser to correctly + escape HTML-looking output. + +* WebIDL Attributes on `Window` are now correctly bound to not go through + `Window.prototype` which doesn't exist but instead use a `structural` + definition. + +* Fixed a codegen error when the `BorrowMut` trait was in scope. + +* Fixed TypeScript generation for constructors of classes, it was accidentally + producing a syntactially invalid file! + +-------------------------------------------------------------------------------- + +## 0.2.23 + +Released 2018-09-26. + +### Added + +* [This is the first release of the `web-sys` + crate!](https://rustwasm.github.io/2018/09/26/announcing-web-sys.html) + +* Added support for unions of interfaces and non-interfaces in the WebIDL + frontend. + +* Added a policy for inclusion of new ECMAScript features in `js-sys`: the + feature must be in stage 4 or greater for us to support it. + +* Added some documentation about size profiling and optimization with + `wasm-bindgen` to the guide. + +* Added the `Clamped` type for generating JavaScript `Uint8ClampedArray`s. + +* CI is now running on beta! Can't wait for the `rustc` release trains to roll + over, so we can run CI on stable too! + +* Added the `js_sys::try_iter` function, which checks arbitrary JS values for + compliance with the JS iteration protocol, and if they are iterable, converts + them into an iterator over the JS values that they yield. + +### Changed + +* We now only generate null checks on methods on the JS side when in debug + mode. For safety we will always null check on the Rust side, however. + +* Improved error messages when defining setters that don't start with `set_` and + don't use `js_name = ...`. + +* Improved generated code for classes in a way that avoids an unnecessary + allocation with static methods that return `Self` but are not the "main" + constructor. + +* **BREAKING:** `js_sys::Reflect` APIs are all fallible now. This is because + reflecting on `Proxy`s whose trap handlers throw an exception can cause any of + the reflection APIs to throw. Accordingly, `js_sys` has been bumped from + `0.2.X` to `0.3.X`. + +### Fixed + +* The method of ensuring that `__wbindgen_malloc` and `__wbindgen_free` are + always emitted in the `.wasm` binary, regardless of seeming reachability is + now zero-overhead. + +-------------------------------------------------------------------------------- + +## 0.2.22 + +Released 2018-09-21 + +### Added + +* The `IntoIterator` trait is now implemented for JS `Iterator` types +* A number of variadic methods in `js-sys` have had explicit arities added. +* The guide has been improved quite a bit as well as enhanced with more examples +* The `js-sys` crate is now complete! Thanks so much to everyone involved to + help fill out all the APIs. +* Exported Rust functions with `#[wasm_bindgen]` can now return a `Result` where + the `Err` payload is raised as an exception in JS. + +### Fixed + +* An issue with running `wasm-bindgen` on crates that have been compiled with + LTO has been resolved. + +-------------------------------------------------------------------------------- + +## 0.2.21 + +Released 2018-09-07 + +### Added + +* Added many more bindings for `WebAssembly` in the `js-sys` crate. + +### Fixed + +* The "names" section of the wasm binary is now correctly preserved by + wasm-bindgen. + +-------------------------------------------------------------------------------- + +## 0.2.20 + +Released 2018-09-06 + +### Added + +* All of `wasm-bindgen` is configured to compile on stable Rust as of the + upcoming 1.30.0 release, scheduled for October 25, 2018. +* The underlying `JsValue` of a `Closure` type can now be extracted at any + time. +* Initial and experimental support was added for modules that have shared memory + (use atomic instructions). + +### Removed + +* The `--wasm2asm` flag of `wasm2es6js` was removed because the `wasm2asm` tool + has been removed from upstream Binaryen. This is replaced with the new + `wasm2js` tool from Binaryen. + +### Fixed + +* The "schema" version for wasm-bindgen now changes on all publishes, meaning we + can't forget to update it. This means that the crate version and CLI version + must exactly match. +* The `wasm-bindgen` crate now has a `links` key which forbids multiple versions + of `wasm-bindgen` from being linked into a dependency graph, fixing obscure + linking errors with a more first-class error message. +* Binary releases for Windows has been fixed. + +-------------------------------------------------------------------------------- + +## 0.2.19 (and 0.2.18) + +Released 2018-08-27. + +### Added + +* Added bindings to `js-sys` for some `WebAssembly` types. +* Added bindings to `js-sys` for some `Intl` types. +* Added bindings to `js-sys` for some `String` methods. +* Added an example of using the WebAudio APIs. +* Added an example of using the `fetch` API. +* Added more `extends` annotations for types in `js-sys`. +* Experimental support for `WeakRef` was added to automatically deallocate Rust + objects when gc'd. +* Added support for executing `wasm-bindgen` over modules that import their + memory. +* Added a global `memory()` function in the `wasm-bindgen` crate for accessing + the JS object that represent wasm's own memory. + +### Removed + +* Removed `AsMut` implementations for imported objects. + +### Fixed + +* Fixed the `constructor` and `catch` attributes combined on imported types. +* Fixed importing the same-named static in two modules. + +-------------------------------------------------------------------------------- + +## 0.2.17 + +Released 2018-08-16. + +### Added + +* Greatly expanded documentation in the wasm-bindgen guide. +* Added bindings to `js-sys` for `Intl.DateTimeFormat` +* Added a number of `extends` attributes for types in `js-sys` + +### Fixed + +* Fixed compile on latest nightly with latest `proc-macro2` +* Fixed compilation in some scenarios on Windows with paths in `module` paths + +-------------------------------------------------------------------------------- + +## 0.2.16 + +Released 2018-08-13. + +### Added + +* Added the `wasm_bindgen::JsCast` trait, as described in [RFC #2][rfc-2]. +* Added [the `#[wasm_bindgen(extends = ...)]` attribute][extends-attr] to + describe inheritance relationships, as described in [RFC #2][rfc-2]. +* Added support for receiving `Option<&T>` parameters from JavaScript in + exported Rust functions and methods. +* Added support for receiving `Option` and other option-wrapped scalars. +* Added reference documentation to the guide for every `#[wasm_bindgen]` + attribute and how it affects the generated bindings. +* Published the `wasm-bindgen-futures` crate for converting between JS + `Promise`s and Rust `Future`s. + +### Changed + +* Overhauled the guide's documentation on passing JS closures to Rust, and Rust + closures to JS. +* Overhauled the guide's documentation on using serde to serialize complex data + to `JsValue` and deserialize `JsValue`s back into complex data. +* Static methods are now always bound to their JS class, as is required for + `Promise`'s static methods. + +### Removed + +* Removed internal usage of `syn`'s `visit-mut` cargo feature, which should + result in faster build times. + +### Fixed + +* Various usage errors for the `#[wasm_bindgen]` proc-macro are now properly + reported with source span information, rather than `panic!()`s inside the + proc-macro. +* Fixed a bug where taking a struct by reference and returning a slice resulted + in lexical variable redeclaration errors in the generated JS glue. [#662][] +* The `#[wasm_bindgen(js_class = "....")]` attribute for binding methods to + renamed imported JS classes now properly works with constructors. + +[rfc-2]: https://rustwasm.github.io/rfcs/002-wasm-bindgen-inheritance-casting.html +[extends-attr]: https://rustwasm.github.io/wasm-bindgen/reference/attributes/on-js-imports/extends.html +[#662]: https://github.com/rustwasm/wasm-bindgen/pull/662 + +-------------------------------------------------------------------------------- + +## 0.2.15 + +Released 2018-07-26. + +### Fixed + +* Fixed `wasm-bindgen` CLI version mismatch checks that got broken in the last + point release. + +-------------------------------------------------------------------------------- + +## 0.2.14 + +Released 2018-07-25. + +### Fixed + +* Fixed compilation errors on targets that use + Mach-O. [#545](https://github.com/rustwasm/wasm-bindgen/issues/545) + +-------------------------------------------------------------------------------- + +## 0.2.13 + +Released 2018-07-22. + +### Added + +* Support the `#[wasm_bindgen(js_name = foo)]` attribute on exported functions + and methods to allow renaming an export to JS. This allows JS to call it by + one name and Rust to call it by another, for example using `camelCase` in JS + and `snake_case` in Rust + +### Fixed + +* Compilation with the latest nightly compiler has been fixed (nightlies on and + after 2018-07-21) + +-------------------------------------------------------------------------------- + +## 0.2.12 + +Released 2018-07-19. + +This release is mostly internal refactorings and minor improvements to the +existing crates and functionality, but the bigs news is an upcoming `js-sys` and +`web-sys` set of crates. The `js-sys` crate will expose [all global JS +bindings][js-all] and the `web-sys` crate will be generated from WebIDL to +expose all APIs browsers have. More info on this soon! + +[js-all]: https://github.com/rustwasm/wasm-bindgen/issues/275 + +### Added + +* Support for `Option` was added where `T` can be a number of slices or + imported types. +* Comments in Rust are now preserved in generated JS bindings, as well as + comments being generated to indicate the types of arguments/return values. +* The online documentation has been reorganized [into a book][book]. +* The generated JS is now formatted better by default for readability. +* A `--keep-debug` flag has been added to the CLI to retain debug sections by + default. This happens by default when `--debug` is passed. + +[book]: https://rustwasm.github.io/wasm-bindgen/ + +### Fixed + +* Compilation with the latest nightly compiler has been fixed (nightlies on and + after 2018-07-19) +* Declarations of an imported function in multiple crates have been fixed to not + conflict. +* Compilation with `#![deny(missing_docs)]` has been fixed. + +-------------------------------------------------------------------------------- + +## 0.2.11 + +Released 2018-05-24. + +-------------------------------------------------------------------------------- + +## 0.2.10 + +Released 2018-05-17. + +-------------------------------------------------------------------------------- + +## 0.2.9 + +Released 2018-05-11. diff --git a/vendor/wasm-bindgen/CONTRIBUTING.md b/vendor/wasm-bindgen/CONTRIBUTING.md new file mode 100644 index 000000000..c98631720 --- /dev/null +++ b/vendor/wasm-bindgen/CONTRIBUTING.md @@ -0,0 +1,4 @@ +# Contributing + +See the ["Contributing" section of the `wasm-bindgen` +guide](https://rustwasm.github.io/docs/wasm-bindgen/contributing/index.html). diff --git a/vendor/wasm-bindgen/Cargo.toml b/vendor/wasm-bindgen/Cargo.toml new file mode 100644 index 000000000..87709d49f --- /dev/null +++ b/vendor/wasm-bindgen/Cargo.toml @@ -0,0 +1,79 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "wasm-bindgen" +version = "0.2.83" +authors = ["The wasm-bindgen Developers"] +description = """ +Easy support for interacting between JS and Rust. +""" +homepage = "https://rustwasm.github.io/" +documentation = "https://docs.rs/wasm-bindgen" +readme = "README.md" +categories = ["wasm"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rustwasm/wasm-bindgen" + +[package.metadata.docs.rs] +features = ["serde-serialize"] + +[lib] +test = false + +[dependencies.cfg-if] +version = "1.0.0" + +[dependencies.serde] +version = "1.0" +optional = true + +[dependencies.serde_json] +version = "1.0" +optional = true + +[dependencies.wasm-bindgen-macro] +version = "=0.2.83" + +[features] +default = [ + "spans", + "std", +] +enable-interning = ["std"] +serde-serialize = [ + "serde", + "serde_json", + "std", +] +spans = ["wasm-bindgen-macro/spans"] +std = [] +strict-macro = ["wasm-bindgen-macro/strict-macro"] +xxx_debug_only_print_generated_code = ["wasm-bindgen-macro/xxx_debug_only_print_generated_code"] + +[target."cfg(target_arch = \"wasm32\")".dev-dependencies.js-sys] +version = "0.3.60" + +[target."cfg(target_arch = \"wasm32\")".dev-dependencies.serde_derive] +version = "1.0" + +[target."cfg(target_arch = \"wasm32\")".dev-dependencies.wasm-bindgen-futures] +version = "=0.4.33" + +[target."cfg(target_arch = \"wasm32\")".dev-dependencies.wasm-bindgen-test] +version = "=0.3.33" + +[target."cfg(target_arch = \"wasm32\")".dev-dependencies.wasm-bindgen-test-crate-a] +version = "0.1" + +[target."cfg(target_arch = \"wasm32\")".dev-dependencies.wasm-bindgen-test-crate-b] +version = "0.1" diff --git a/vendor/wasm-bindgen/LICENSE-APACHE b/vendor/wasm-bindgen/LICENSE-APACHE new file mode 100644 index 000000000..16fe87b06 --- /dev/null +++ b/vendor/wasm-bindgen/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vendor/wasm-bindgen/LICENSE-MIT b/vendor/wasm-bindgen/LICENSE-MIT new file mode 100644 index 000000000..39e0ed660 --- /dev/null +++ b/vendor/wasm-bindgen/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/vendor/wasm-bindgen/README.md b/vendor/wasm-bindgen/README.md new file mode 100644 index 000000000..cf5dafcfd --- /dev/null +++ b/vendor/wasm-bindgen/README.md @@ -0,0 +1,113 @@ +
+ +

wasm-bindgen

+ +

+ Facilitating high-level interactions between Wasm modules and JavaScript. +

+ +

+ Build Status + Crates.io version + Download + docs.rs docs +

+ +

+ Guide + | + API Docs + | + Contributing + | + Chat +

+ + Built with 🦀🕸 by The Rust and WebAssembly Working Group +
+ +## Example + +Import JavaScript things into Rust and export Rust things to JavaScript. + +```rust +use wasm_bindgen::prelude::*; + +// Import the `window.alert` function from the Web. +#[wasm_bindgen] +extern "C" { + fn alert(s: &str); +} + +// Export a `greet` function from Rust to JavaScript, that alerts a +// hello message. +#[wasm_bindgen] +pub fn greet(name: &str) { + alert(&format!("Hello, {}!", name)); +} +``` + +Use exported Rust things from JavaScript with ECMAScript modules! + +```js +import { greet } from "./hello_world"; + +greet("World!"); +``` + +## Features + +* **Lightweight.** Only pay for what you use. `wasm-bindgen` only generates + bindings and glue for the JavaScript imports you actually use and Rust + functionality that you export. For example, importing and using the + `document.querySelector` method doesn't cause `Node.prototype.appendChild` or + `window.alert` to be included in the bindings as well. + +* **ECMAScript modules.** Just import WebAssembly modules the same way you would + import JavaScript modules. Future compatible with [WebAssembly modules and + ECMAScript modules integration][wasm-es-modules]. + +* **Designed with the ["Web IDL bindings" proposal][webidl-bindings] in mind.** + Eventually, there won't be any JavaScript shims between Rust-generated wasm + functions and native DOM methods. Because the wasm functions are statically + type checked, some of those native methods' dynamic type checks should become + unnecessary, promising to unlock even-faster-than-JavaScript DOM access. + +[wasm-es-modules]: https://github.com/WebAssembly/esm-integration +[webidl-bindings]: https://github.com/WebAssembly/proposals/issues/8 + +## Guide + +[**📚 Read the `wasm-bindgen` guide here! 📚**](https://rustwasm.github.io/docs/wasm-bindgen/) + +You can find general documentation about using Rust and WebAssembly together +[here](https://rustwasm.github.io/docs). + +## API Docs + +- [wasm-bindgen](https://docs.rs/wasm-bindgen) +- [js-sys](https://docs.rs/js-sys) +- [web-sys](https://docs.rs/web-sys) +- [wasm-bindgen-futures](https://docs.rs/wasm-bindgen-futures) + +## License + +This project is licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or + http://opensource.org/licenses/MIT) + +at your option. + +## Contribution + +**[See the "Contributing" section of the guide for information on +hacking on `wasm-bindgen`!][contributing]** + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this project by you, as defined in the Apache-2.0 license, +shall be dual licensed as above, without any additional terms or conditions. + +[contributing]: https://rustwasm.github.io/docs/wasm-bindgen/contributing/index.html \ No newline at end of file diff --git a/vendor/wasm-bindgen/_package.json b/vendor/wasm-bindgen/_package.json new file mode 100644 index 000000000..95632f893 --- /dev/null +++ b/vendor/wasm-bindgen/_package.json @@ -0,0 +1,14 @@ +{ + "scripts": { + "build": "webpack", + "serve": "webpack serve" + }, + "devDependencies": { + "@wasm-tool/wasm-pack-plugin": "1.5.0", + "html-webpack-plugin": "^5.3.2", + "text-encoding": "^0.7.0", + "webpack": "^5.49.0", + "webpack-cli": "^4.7.2", + "webpack-dev-server": "^3.11.2" + } +} diff --git a/vendor/wasm-bindgen/build.rs b/vendor/wasm-bindgen/build.rs new file mode 100644 index 000000000..d4038035f --- /dev/null +++ b/vendor/wasm-bindgen/build.rs @@ -0,0 +1,4 @@ +// Empty `build.rs` so that `[package] links = ...` works in `Cargo.toml`. +fn main() { + println!("cargo:rerun-if-changed=build.rs"); +} diff --git a/vendor/wasm-bindgen/examples/README.md b/vendor/wasm-bindgen/examples/README.md new file mode 100644 index 000000000..8b53901c1 --- /dev/null +++ b/vendor/wasm-bindgen/examples/README.md @@ -0,0 +1,7 @@ +# Examples + +This directory contains a number of Cargo projects that are all examples of how +to use `wasm-bindgen` in various contexts. More documentation can be [found +online][dox] + +[dox]: https://rustwasm.github.io/docs/wasm-bindgen/examples/index.html diff --git a/vendor/wasm-bindgen/examples/import_js/README.md b/vendor/wasm-bindgen/examples/import_js/README.md new file mode 100644 index 000000000..58972ee79 --- /dev/null +++ b/vendor/wasm-bindgen/examples/import_js/README.md @@ -0,0 +1,15 @@ +# Importing non-browser JS + +[View documentation for this example online][dox] or [View compiled example +online][compiled] + +[compiled]: https://rustwasm.github.io/wasm-bindgen/exbuild/import_js/ +[dox]: https://rustwasm.github.io/docs/wasm-bindgen/examples/import-js.html + +You can build the example locally with: + +``` +$ npm run serve +``` + +and then visiting http://localhost:8080 in a browser should run the example! diff --git a/vendor/wasm-bindgen/examples/import_js/index.html b/vendor/wasm-bindgen/examples/import_js/index.html new file mode 100644 index 000000000..e83a75f92 --- /dev/null +++ b/vendor/wasm-bindgen/examples/import_js/index.html @@ -0,0 +1,8 @@ + + + + + +

Open up the developer console and you should see "Hello from Rust!"

+ + diff --git a/vendor/wasm-bindgen/examples/import_js/package.json b/vendor/wasm-bindgen/examples/import_js/package.json new file mode 100644 index 000000000..8b08e4870 --- /dev/null +++ b/vendor/wasm-bindgen/examples/import_js/package.json @@ -0,0 +1,14 @@ +{ + "scripts": { + "build": "webpack", + "serve" : "webpack serve" + }, + "devDependencies": { + "@wasm-tool/wasm-pack-plugin": "1.5.0", + "text-encoding": "^0.7.0", + "html-webpack-plugin": "^5.3.2", + "webpack": "^5.49.0", + "webpack-cli": "^4.7.2", + "webpack-dev-server": "^3.11.2" + } +} diff --git a/vendor/wasm-bindgen/publish.rs b/vendor/wasm-bindgen/publish.rs new file mode 100644 index 000000000..d643fc63d --- /dev/null +++ b/vendor/wasm-bindgen/publish.rs @@ -0,0 +1,221 @@ +//! Helper script to publish the wasm-bindgen suite of crates +//! +//! Usage: +//! +//! * First, compile this script +//! * Next, set cwd to the root of the wasm-bindgen repository +//! * Execute `./publish bump` to bump versions +//! * Send a PR +//! * Merge when green +//! * Execute `./publish publish` to publish crates + +use std::collections::HashMap; +use std::env; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; +use std::process::Command; + +// note that this list must be topologically sorted by dependencies +const CRATES_TO_PUBLISH: &[&str] = &[ + "wasm-bindgen-shared", + "wasm-bindgen-backend", + "wasm-bindgen-macro-support", + "wasm-bindgen-macro", + "wasm-bindgen-test-macro", + "wasm-bindgen-test", + "wasm-bindgen-wasm-interpreter", + "wasm-bindgen-wasm-conventions", + "wasm-bindgen-threads-xform", + "wasm-bindgen-multi-value-xform", + "wasm-bindgen-externref-xform", + "wasm-bindgen-cli-support", + "wasm-bindgen-cli", + "wasm-bindgen", + "wasm-bindgen-futures", + "js-sys", + "web-sys", +]; + +const CRATES_TO_AVOID_PUBLISH: &[&str] = &[ + // We'll publish these when they're ready one day + "wasm-bindgen-typescript", + // These are internal crates, unlikely to ever be published + "ui-tests", + "sample", + "webidl-tests", + "typescript-tests", + "wasm-bindgen-webidl", + "example-tests", +]; + +struct Crate { + manifest: PathBuf, + name: String, + version: String, + next_version: String, +} + +fn main() { + let mut crates = Vec::new(); + crates.push(read_crate("./Cargo.toml".as_ref())); + find_crates("crates".as_ref(), &mut crates); + find_crates("examples".as_ref(), &mut crates); + + let pos = CRATES_TO_PUBLISH + .iter() + .chain(CRATES_TO_AVOID_PUBLISH) + .enumerate() + .map(|(i, c)| (*c, i)) + .collect::>(); + crates.sort_by_key(|krate| pos.get(&krate.name[..])); + + match &env::args().nth(1).expect("must have one argument")[..] { + "bump" => { + for krate in crates.iter() { + bump_version(&krate, &crates); + } + } + + "publish" => { + for krate in crates.iter() { + publish(&krate); + } + } + + s => panic!("unknown command: {}", s), + } +} + +fn find_crates(dir: &Path, dst: &mut Vec) { + if dir.join("Cargo.toml").exists() { + let krate = read_crate(&dir.join("Cargo.toml")); + if CRATES_TO_PUBLISH + .iter() + .chain(CRATES_TO_AVOID_PUBLISH) + .any(|c| krate.name == *c) + { + dst.push(krate); + } else if dir.iter().any(|s| s == "examples") { + dst.push(krate); + } else { + panic!("failed to find {:?} in whitelist or blacklist", krate.name); + } + } + + for entry in dir.read_dir().unwrap() { + let entry = entry.unwrap(); + if entry.file_type().unwrap().is_dir() { + find_crates(&entry.path(), dst); + } + } +} + +fn read_crate(manifest: &Path) -> Crate { + let mut name = None; + let mut version = None; + for line in fs::read_to_string(manifest).unwrap().lines() { + if name.is_none() && line.starts_with("name = \"") { + name = Some( + line.replace("name = \"", "") + .replace("\"", "") + .trim() + .to_string(), + ); + } + if version.is_none() && line.starts_with("version = \"") { + version = Some( + line.replace("version = \"", "") + .replace("\"", "") + .trim() + .to_string(), + ); + } + } + let name = name.unwrap(); + let version = version.unwrap(); + let next_version = if CRATES_TO_PUBLISH.contains(&&name[..]) { + bump(&version) + } else { + version.clone() + }; + Crate { + manifest: manifest.to_path_buf(), + name, + version, + next_version, + } +} + +fn bump_version(krate: &Crate, crates: &[Crate]) { + let contents = fs::read_to_string(&krate.manifest).unwrap(); + + let mut new_manifest = String::new(); + let mut is_deps = false; + for line in contents.lines() { + let mut rewritten = false; + if line.starts_with("version =") { + if CRATES_TO_PUBLISH.contains(&&krate.name[..]) { + println!( + "bump `{}` {} => {}", + krate.name, krate.version, krate.next_version + ); + new_manifest.push_str(&line.replace(&krate.version, &krate.next_version)); + rewritten = true; + } + } + + is_deps = if line.starts_with("[") { + line.contains("dependencies") + } else { + is_deps + }; + + for other in crates { + if !is_deps || !line.starts_with(&format!("{} ", other.name)) { + continue; + } + if !line.contains(&other.version) { + if !line.contains("version =") { + continue; + } + panic!( + "{:?} has a dep on {} but doesn't list version {}", + krate.manifest, other.name, other.version + ); + } + rewritten = true; + new_manifest.push_str(&line.replace(&other.version, &other.next_version)); + break; + } + if !rewritten { + new_manifest.push_str(line); + } + new_manifest.push_str("\n"); + } + fs::write(&krate.manifest, new_manifest).unwrap(); +} + +fn bump(version: &str) -> String { + let mut iter = version.split('.').map(|s| s.parse::().unwrap()); + let major = iter.next().expect("major version"); + let minor = iter.next().expect("minor version"); + let patch = iter.next().expect("patch version"); + format!("{}.{}.{}", major, minor, patch + 1) +} + +fn publish(krate: &Crate) { + if !CRATES_TO_PUBLISH.iter().any(|s| *s == krate.name) { + return; + } + let status = Command::new("cargo") + .arg("publish") + .current_dir(krate.manifest.parent().unwrap()) + .arg("--no-verify") + .arg("--allow-dirty") + .status() + .expect("failed to run cargo"); + if !status.success() { + println!("FAIL: failed to publish `{}`: {}", krate.name, status); + } +} diff --git a/vendor/wasm-bindgen/releases/friends.sh b/vendor/wasm-bindgen/releases/friends.sh new file mode 100755 index 000000000..4486b4229 --- /dev/null +++ b/vendor/wasm-bindgen/releases/friends.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash + +set -eu +set -o pipefail + +cd $(dirname $0) + +if [[ -z "${1+x}" ]]; then + read -p "List friends since which commit/tag? " since + echo +else + since=$1 +fi + +git shortlog -s -n "$since.." \ + | cut -f 2- \ + | sort -u \ + | grep -v bors\-servo \ + | xargs -d '\n' -I{} echo "- {}" diff --git a/vendor/wasm-bindgen/releases/release-announcement-template.md b/vendor/wasm-bindgen/releases/release-announcement-template.md new file mode 100644 index 000000000..a1feaf4b6 --- /dev/null +++ b/vendor/wasm-bindgen/releases/release-announcement-template.md @@ -0,0 +1,39 @@ +# Announcing `wasm-bindgen` $TODO_VERSION + +`wasm-bindgen` facilitates high-level interactions between wasm modules and +JavaScript. + +* [GitHub][] +* [crates.io][] +* [The `wasm-bindgen` Guide][guide] + +Upgrade to this release by updating your `Cargo.toml`: + +```toml +wasm-bindgen = "$TODO_VERSION" +``` + +## Changelog + + + +## Friends + +Thanks to everyone who contributed to this release! + + + +## Contributing + +Want to join us? Check out our [The "Contributing" section of the +guide][contributing] and take a look at some of these issues: + +* [Issues labeled "good first issue"][good-first-issue] +* [Issues labeled "help wanted"][help-wanted] + +[GitHub]: https://github.com/rustwasm/wasm-bindgen +[crates.io]: https://crates.io/crates/wasm-bindgen +[guide]: https://rustwasm.github.io/wasm-bindgen +[contributing]: https://rustwasm.github.io/wasm-bindgen/contributing.md +[good-first-issue]: https://github.com/rustwasm/wasm-bindgen/labels/good%20first%20issue +[help-wanted]: https://github.com/rustwasm/wasm-bindgen/labels/help%20wanted diff --git a/vendor/wasm-bindgen/src/cache/intern.rs b/vendor/wasm-bindgen/src/cache/intern.rs new file mode 100644 index 000000000..c8aa51b2c --- /dev/null +++ b/vendor/wasm-bindgen/src/cache/intern.rs @@ -0,0 +1,103 @@ +use cfg_if::cfg_if; + + +cfg_if! { + if #[cfg(feature = "enable-interning")] { + use std::thread_local; + use std::string::String; + use std::borrow::ToOwned; + use std::cell::RefCell; + use std::collections::HashMap; + use crate::JsValue; + + struct Cache { + entries: RefCell>, + } + + thread_local! { + static CACHE: Cache = Cache { + entries: RefCell::new(HashMap::new()), + }; + } + + /// This returns the raw index of the cached JsValue, so you must take care + /// so that you don't use it after it is freed. + pub(crate) fn unsafe_get_str(s: &str) -> Option { + CACHE.with(|cache| { + let cache = cache.entries.borrow(); + + cache.get(s).map(|x| x.idx) + }) + } + + fn intern_str(key: &str) { + CACHE.with(|cache| { + let mut cache = cache.entries.borrow_mut(); + + // Can't use `entry` because `entry` requires a `String` + if !cache.contains_key(key) { + cache.insert(key.to_owned(), JsValue::from(key)); + } + }) + } + + fn unintern_str(key: &str) { + CACHE.with(|cache| { + let mut cache = cache.entries.borrow_mut(); + + cache.remove(key); + }) + } + } +} + + +/// Interns Rust strings so that it's much faster to send them to JS. +/// +/// Sending strings from Rust to JS is slow, because it has to do a full `O(n)` +/// copy and *also* encode from UTF-8 to UTF-16. This must be done every single +/// time a string is sent to JS. +/// +/// If you are sending the same string multiple times, you can call this `intern` +/// function, which simply returns its argument unchanged: +/// +/// ```rust +/// # use wasm_bindgen::intern; +/// intern("foo") // returns "foo" +/// # ; +/// ``` +/// +/// However, if you enable the `"enable-interning"` feature for wasm-bindgen, +/// then it will add the string into an internal cache. +/// +/// When you send that cached string to JS, it will look it up in the cache, +/// which completely avoids the `O(n)` copy and encoding. This has a significant +/// speed boost (as high as 783%)! +/// +/// However, there is a small cost to this caching, so you shouldn't cache every +/// string. Only cache strings which have a high likelihood of being sent +/// to JS multiple times. +/// +/// Also, keep in mind that this function is a *performance hint*: it's not +/// *guaranteed* that the string will be cached, and the caching strategy +/// might change at any time, so don't rely upon it. +#[inline] +pub fn intern(s: &str) -> &str { + #[cfg(feature = "enable-interning")] + intern_str(s); + + s +} + + +/// Removes a Rust string from the intern cache. +/// +/// This does the opposite of the [`intern`](fn.intern.html) function. +/// +/// If the [`intern`](fn.intern.html) function is called again then it will re-intern the string. +#[allow(unused_variables)] +#[inline] +pub fn unintern(s: &str) { + #[cfg(feature = "enable-interning")] + unintern_str(s); +} diff --git a/vendor/wasm-bindgen/src/cache/mod.rs b/vendor/wasm-bindgen/src/cache/mod.rs new file mode 100644 index 000000000..96d1a4920 --- /dev/null +++ b/vendor/wasm-bindgen/src/cache/mod.rs @@ -0,0 +1 @@ +pub mod intern; diff --git a/vendor/wasm-bindgen/src/cast.rs b/vendor/wasm-bindgen/src/cast.rs new file mode 100644 index 000000000..6be56a2d7 --- /dev/null +++ b/vendor/wasm-bindgen/src/cast.rs @@ -0,0 +1,160 @@ +use crate::{describe::WasmDescribe, JsValue}; + +/// A trait for checked and unchecked casting between JS types. +/// +/// Specified [in an RFC][rfc] this trait is intended to provide support for +/// casting JS values between differnet types of one another. In JS there aren't +/// many static types but we've ascribed JS values with static types in Rust, +/// yet they often need to be switched to other types temporarily! This trait +/// provides both checked and unchecked casting into various kinds of values. +/// +/// This trait is automatically implemented for any type imported in a +/// `#[wasm_bindgen]` `extern` block. +/// +/// [rfc]: https://github.com/rustwasm/rfcs/blob/master/text/002-wasm-bindgen-inheritance-casting.md +pub trait JsCast +where + Self: AsRef + Into, +{ + /// Test whether this JS value has a type `T`. + /// + /// This method will dynamically check to see if this JS object can be + /// casted to the JS object of type `T`. Usually this uses the `instanceof` + /// operator. This also works with primitive types like + /// booleans/strings/numbers as well as cross-realm object like `Array` + /// which can originate from other iframes. + /// + /// In general this is intended to be a more robust version of + /// `is_instance_of`, but if you want strictly the `instanceof` operator + /// it's recommended to use that instead. + fn has_type(&self) -> bool + where + T: JsCast, + { + T::is_type_of(self.as_ref()) + } + + /// Performs a dynamic cast (checked at runtime) of this value into the + /// target type `T`. + /// + /// This method will return `Err(self)` if `self.has_type::()` + /// returns `false`, and otherwise it will return `Ok(T)` manufactured with + /// an unchecked cast (verified correct via the `has_type` operation). + fn dyn_into(self) -> Result + where + T: JsCast, + { + if self.has_type::() { + Ok(self.unchecked_into()) + } else { + Err(self) + } + } + + /// Performs a dynamic cast (checked at runtime) of this value into the + /// target type `T`. + /// + /// This method will return `None` if `self.has_type::()` + /// returns `false`, and otherwise it will return `Some(&T)` manufactured + /// with an unchecked cast (verified correct via the `has_type` operation). + fn dyn_ref(&self) -> Option<&T> + where + T: JsCast, + { + if self.has_type::() { + Some(self.unchecked_ref()) + } else { + None + } + } + + /// Performs a zero-cost unchecked cast into the specified type. + /// + /// This method will convert the `self` value to the type `T`, where both + /// `self` and `T` are simple wrappers around `JsValue`. This method **does + /// not check whether `self` is an instance of `T`**. If used incorrectly + /// then this method may cause runtime exceptions in both Rust and JS, this + /// should be used with caution. + fn unchecked_into(self) -> T + where + T: JsCast, + { + T::unchecked_from_js(self.into()) + } + + /// Performs a zero-cost unchecked cast into a reference to the specified + /// type. + /// + /// This method will convert the `self` value to the type `T`, where both + /// `self` and `T` are simple wrappers around `JsValue`. This method **does + /// not check whether `self` is an instance of `T`**. If used incorrectly + /// then this method may cause runtime exceptions in both Rust and JS, this + /// should be used with caution. + /// + /// This method, unlike `unchecked_into`, does not consume ownership of + /// `self` and instead works over a shared reference. + fn unchecked_ref(&self) -> &T + where + T: JsCast, + { + T::unchecked_from_js_ref(self.as_ref()) + } + + /// Test whether this JS value is an instance of the type `T`. + /// + /// This method performs a dynamic check (at runtime) using the JS + /// `instanceof` operator. This method returns `self instanceof T`. + /// + /// Note that `instanceof` does not always work with primitive values or + /// across different realms (e.g. iframes). If you're not sure whether you + /// specifically need only `instanceof` it's recommended to use `has_type` + /// instead. + fn is_instance_of(&self) -> bool + where + T: JsCast, + { + T::instanceof(self.as_ref()) + } + + /// Performs a dynamic `instanceof` check to see whether the `JsValue` + /// provided is an instance of this type. + /// + /// This is intended to be an internal implementation detail, you likely + /// won't need to call this. It's generally called through the + /// `is_instance_of` method instead. + fn instanceof(val: &JsValue) -> bool; + + /// Performs a dynamic check to see whether the `JsValue` provided + /// is a value of this type. + /// + /// Unlike `instanceof`, this can be specialised to use a custom check by + /// adding a `#[wasm_bindgen(is_type_of = callback)]` attribute to the + /// type import declaration. + /// + /// Other than that, this is intended to be an internal implementation + /// detail of `has_type` and you likely won't need to call this. + fn is_type_of(val: &JsValue) -> bool { + Self::instanceof(val) + } + + /// Performs a zero-cost unchecked conversion from a `JsValue` into an + /// instance of `Self` + /// + /// This is intended to be an internal implementation detail, you likely + /// won't need to call this. + fn unchecked_from_js(val: JsValue) -> Self; + + /// Performs a zero-cost unchecked conversion from a `&JsValue` into an + /// instance of `&Self`. + /// + /// Note the safety of this method, which basically means that `Self` must + /// be a newtype wrapper around `JsValue`. + /// + /// This is intended to be an internal implementation detail, you likely + /// won't need to call this. + fn unchecked_from_js_ref(val: &JsValue) -> &Self; +} + +/// Trait implemented for wrappers around `JsValue`s generated by `#[wasm_bindgen]`. +#[doc(hidden)] +pub trait JsObject: JsCast + WasmDescribe {} diff --git a/vendor/wasm-bindgen/src/closure.rs b/vendor/wasm-bindgen/src/closure.rs new file mode 100644 index 000000000..37cef06dc --- /dev/null +++ b/vendor/wasm-bindgen/src/closure.rs @@ -0,0 +1,885 @@ +//! Support for long-lived closures in `wasm-bindgen` +//! +//! This module defines the `Closure` type which is used to pass "owned +//! closures" from Rust to JS. Some more details can be found on the `Closure` +//! type itself. + +use std::fmt; +use std::mem::{self, ManuallyDrop}; +use std::prelude::v1::*; + +use crate::convert::*; +use crate::describe::*; +use crate::throw_str; +use crate::JsValue; +use crate::UnwrapThrowExt; + +/// A handle to both a closure in Rust as well as JS closure which will invoke +/// the Rust closure. +/// +/// A `Closure` is the primary way that a `'static` lifetime closure is +/// transferred from Rust to JS. `Closure` currently requires that the closures +/// it's created with have the `'static` lifetime in Rust for soundness reasons. +/// +/// This type is a "handle" in the sense that whenever it is dropped it will +/// invalidate the JS closure that it refers to. Any usage of the closure in JS +/// after the `Closure` has been dropped will raise an exception. It's then up +/// to you to arrange for `Closure` to be properly deallocate at an appropriate +/// location in your program. +/// +/// The type parameter on `Closure` is the type of closure that this represents. +/// Currently this can only be the `Fn` and `FnMut` traits with up to 7 +/// arguments (and an optional return value). +/// +/// # Examples +/// +/// Here are a number of examples of using `Closure`. +/// +/// ## Using the `setInterval` API +/// +/// Sample usage of `Closure` to invoke the `setInterval` API. +/// +/// ```rust,no_run +/// use wasm_bindgen::prelude::*; +/// +/// #[wasm_bindgen] +/// extern "C" { +/// fn setInterval(closure: &Closure, time: u32) -> i32; +/// fn clearInterval(id: i32); +/// +/// #[wasm_bindgen(js_namespace = console)] +/// fn log(s: &str); +/// } +/// +/// #[wasm_bindgen] +/// pub struct IntervalHandle { +/// interval_id: i32, +/// _closure: Closure, +/// } +/// +/// impl Drop for IntervalHandle { +/// fn drop(&mut self) { +/// clearInterval(self.interval_id); +/// } +/// } +/// +/// #[wasm_bindgen] +/// pub fn run() -> IntervalHandle { +/// // First up we use `Closure::new` to wrap up a Rust closure and create +/// // a JS closure. +/// let cb = Closure::new(|| { +/// log("interval elapsed!"); +/// }); +/// +/// // Next we pass this via reference to the `setInterval` function, and +/// // `setInterval` gets a handle to the corresponding JS closure. +/// let interval_id = setInterval(&cb, 1_000); +/// +/// // If we were to drop `cb` here it would cause an exception to be raised +/// // whenever the interval elapses. Instead we *return* our handle back to JS +/// // so JS can decide when to cancel the interval and deallocate the closure. +/// IntervalHandle { +/// interval_id, +/// _closure: cb, +/// } +/// } +/// ``` +/// +/// ## Casting a `Closure` to a `js_sys::Function` +/// +/// This is the same `setInterval` example as above, except it is using +/// `web_sys` (which uses `js_sys::Function` for callbacks) instead of manually +/// writing bindings to `setInterval` and other Web APIs. +/// +/// ```rust,ignore +/// use wasm_bindgen::JsCast; +/// +/// #[wasm_bindgen] +/// pub struct IntervalHandle { +/// interval_id: i32, +/// _closure: Closure, +/// } +/// +/// impl Drop for IntervalHandle { +/// fn drop(&mut self) { +/// let window = web_sys::window().unwrap(); +/// window.clear_interval_with_handle(self.interval_id); +/// } +/// } +/// +/// #[wasm_bindgen] +/// pub fn run() -> Result { +/// let cb = Closure::new(|| { +/// web_sys::console::log_1(&"interval elapsed!".into()); +/// }); +/// +/// let window = web_sys::window().unwrap(); +/// let interval_id = window.set_interval_with_callback_and_timeout_and_arguments_0( +/// // Note this method call, which uses `as_ref()` to get a `JsValue` +/// // from our `Closure` which is then converted to a `&Function` +/// // using the `JsCast::unchecked_ref` function. +/// cb.as_ref().unchecked_ref(), +/// 1_000, +/// )?; +/// +/// // Same as above. +/// Ok(IntervalHandle { +/// interval_id, +/// _closure: cb, +/// }) +/// } +/// ``` +/// +/// ## Using `FnOnce` and `Closure::once` with `requestAnimationFrame` +/// +/// Because `requestAnimationFrame` only calls its callback once, we can use +/// `FnOnce` and `Closure::once` with it. +/// +/// ```rust,no_run +/// use wasm_bindgen::prelude::*; +/// +/// #[wasm_bindgen] +/// extern "C" { +/// fn requestAnimationFrame(closure: &Closure) -> u32; +/// fn cancelAnimationFrame(id: u32); +/// +/// #[wasm_bindgen(js_namespace = console)] +/// fn log(s: &str); +/// } +/// +/// #[wasm_bindgen] +/// pub struct AnimationFrameHandle { +/// animation_id: u32, +/// _closure: Closure, +/// } +/// +/// impl Drop for AnimationFrameHandle { +/// fn drop(&mut self) { +/// cancelAnimationFrame(self.animation_id); +/// } +/// } +/// +/// // A type that will log a message when it is dropped. +/// struct LogOnDrop(&'static str); +/// impl Drop for LogOnDrop { +/// fn drop(&mut self) { +/// log(self.0); +/// } +/// } +/// +/// #[wasm_bindgen] +/// pub fn run() -> AnimationFrameHandle { +/// // We are using `Closure::once` which takes a `FnOnce`, so the function +/// // can drop and/or move things that it closes over. +/// let fired = LogOnDrop("animation frame fired or canceled"); +/// let cb = Closure::once(move || drop(fired)); +/// +/// // Schedule the animation frame! +/// let animation_id = requestAnimationFrame(&cb); +/// +/// // Again, return a handle to JS, so that the closure is not dropped +/// // immediately and JS can decide whether to cancel the animation frame. +/// AnimationFrameHandle { +/// animation_id, +/// _closure: cb, +/// } +/// } +/// ``` +/// +/// ## Converting `FnOnce`s directly into JavaScript Functions with `Closure::once_into_js` +/// +/// If we don't want to allow a `FnOnce` to be eagerly dropped (maybe because we +/// just want it to drop after it is called and don't care about cancellation) +/// then we can use the `Closure::once_into_js` function. +/// +/// This is the same `requestAnimationFrame` example as above, but without +/// supporting early cancellation. +/// +/// ``` +/// use wasm_bindgen::prelude::*; +/// +/// #[wasm_bindgen] +/// extern "C" { +/// // We modify the binding to take an untyped `JsValue` since that is what +/// // is returned by `Closure::once_into_js`. +/// // +/// // If we were using the `web_sys` binding for `requestAnimationFrame`, +/// // then the call sites would cast the `JsValue` into a `&js_sys::Function` +/// // using `f.unchecked_ref::()`. See the `web_sys` +/// // example above for details. +/// fn requestAnimationFrame(callback: JsValue); +/// +/// #[wasm_bindgen(js_namespace = console)] +/// fn log(s: &str); +/// } +/// +/// // A type that will log a message when it is dropped. +/// struct LogOnDrop(&'static str); +/// impl Drop for LogOnDrop { +/// fn drop(&mut self) { +/// log(self.0); +/// } +/// } +/// +/// #[wasm_bindgen] +/// pub fn run() { +/// // We are using `Closure::once_into_js` which takes a `FnOnce` and +/// // converts it into a JavaScript function, which is returned as a +/// // `JsValue`. +/// let fired = LogOnDrop("animation frame fired"); +/// let cb = Closure::once_into_js(move || drop(fired)); +/// +/// // Schedule the animation frame! +/// requestAnimationFrame(cb); +/// +/// // No need to worry about whether or not we drop a `Closure` +/// // here or return some sort of handle to JS! +/// } +/// ``` +pub struct Closure { + js: ManuallyDrop, + data: ManuallyDrop>, +} + +union FatPtr { + ptr: *mut T, + fields: (usize, usize), +} + +impl Closure +where + T: ?Sized + WasmClosure, +{ + /// Creates a new instance of `Closure` from the provided Rust function. + /// + /// Note that the closure provided here, `F`, has a few requirements + /// associated with it: + /// + /// * It must implement `Fn` or `FnMut` (for `FnOnce` functions see + /// `Closure::once` and `Closure::once_into_js`). + /// + /// * It must be `'static`, aka no stack references (use the `move` + /// keyword). + /// + /// * It can have at most 7 arguments. + /// + /// * Its arguments and return values are all types that can be shared with + /// JS (i.e. have `#[wasm_bindgen]` annotations or are simple numbers, + /// etc.) + pub fn new(t: F) -> Closure + where + F: IntoWasmClosure + 'static, + { + Closure::wrap(Box::new(t).unsize()) + } + + /// A more direct version of `Closure::new` which creates a `Closure` from + /// a `Box`/`Box`, which is how it's kept internally. + pub fn wrap(mut data: Box) -> Closure { + assert_eq!(mem::size_of::<*const T>(), mem::size_of::>()); + let (a, b) = unsafe { + FatPtr { + ptr: &mut *data as *mut T, + } + .fields + }; + + // Here we need to create a `JsValue` with the data and `T::invoke()` + // function pointer. To do that we... take a few unconventional turns. + // In essence what happens here is this: + // + // 1. First up, below we call a function, `breaks_if_inlined`. This + // function, as the name implies, does not work if it's inlined. + // More on that in a moment. + // 2. This function internally calls a special import recognized by the + // `wasm-bindgen` CLI tool, `__wbindgen_describe_closure`. This + // imported symbol is similar to `__wbindgen_describe` in that it's + // not intended to show up in the final binary but it's an + // intermediate state for a `wasm-bindgen` binary. + // 3. The `__wbindgen_describe_closure` import is namely passed a + // descriptor function, monomorphized for each invocation. + // + // Most of this doesn't actually make sense to happen at runtime! The + // real magic happens when `wasm-bindgen` comes along and updates our + // generated code. When `wasm-bindgen` runs it performs a few tasks: + // + // * First, it finds all functions that call + // `__wbindgen_describe_closure`. These are all `breaks_if_inlined` + // defined below as the symbol isn't called anywhere else. + // * Next, `wasm-bindgen` executes the `breaks_if_inlined` + // monomorphized functions, passing it dummy arguments. This will + // execute the function just enough to invoke the special import, + // namely telling us about the function pointer that is the describe + // shim. + // * This knowledge is then used to actually find the descriptor in the + // function table which is then executed to figure out the signature + // of the closure. + // * Finally, and probably most heinously, the call to + // `breaks_if_inlined` is rewritten to call an otherwise globally + // imported function. This globally imported function will generate + // the `JsValue` for this closure specialized for the signature in + // question. + // + // Later on `wasm-gc` will clean up all the dead code and ensure that + // we don't actually call `__wbindgen_describe_closure` at runtime. This + // means we will end up not actually calling `breaks_if_inlined` in the + // final binary, all calls to that function should be pruned. + // + // See crates/cli-support/src/js/closures.rs for a more information + // about what's going on here. + + extern "C" fn describe() { + inform(CLOSURE); + T::describe() + } + + #[inline(never)] + unsafe fn breaks_if_inlined(a: usize, b: usize) -> u32 { + super::__wbindgen_describe_closure(a as u32, b as u32, describe:: as u32) + } + + let idx = unsafe { breaks_if_inlined::(a, b) }; + + Closure { + js: ManuallyDrop::new(JsValue::_new(idx)), + data: ManuallyDrop::new(data), + } + } + + /// Release memory management of this closure from Rust to the JS GC. + /// + /// When a `Closure` is dropped it will release the Rust memory and + /// invalidate the associated JS closure, but this isn't always desired. + /// Some callbacks are alive for the entire duration of the program or for a + /// lifetime dynamically managed by the JS GC. This function can be used + /// to drop this `Closure` while keeping the associated JS function still + /// valid. + /// + /// By default this function will leak memory. This can be dangerous if this + /// function is called many times in an application because the memory leak + /// will overwhelm the page quickly and crash the wasm. + /// + /// If the browser, however, supports weak references, then this function + /// will not leak memory. Instead the Rust memory will be reclaimed when the + /// JS closure is GC'd. Weak references are not enabled by default since + /// they're still a proposal for the JS standard. They can be enabled with + /// `WASM_BINDGEN_WEAKREF=1` when running `wasm-bindgen`, however. + pub fn into_js_value(self) -> JsValue { + let idx = self.js.idx; + mem::forget(self); + JsValue::_new(idx) + } + + /// Same as `into_js_value`, but doesn't return a value. + pub fn forget(self) { + drop(self.into_js_value()); + } +} + +// NB: we use a specific `T` for this `Closure` impl block to avoid every +// call site having to provide an explicit, turbo-fished type like +// `Closure::::once(...)`. +impl Closure { + /// Create a `Closure` from a function that can only be called once. + /// + /// Since we have no way of enforcing that JS cannot attempt to call this + /// `FnOne(A...) -> R` more than once, this produces a `Closure R>` that will dynamically throw a JavaScript error if called more + /// than once. + /// + /// # Example + /// + /// ```rust,no_run + /// use wasm_bindgen::prelude::*; + /// + /// // Create an non-`Copy`, owned `String`. + /// let mut s = String::from("Hello"); + /// + /// // Close over `s`. Since `f` returns `s`, it is `FnOnce` and can only be + /// // called once. If it was called a second time, it wouldn't have any `s` + /// // to work with anymore! + /// let f = move || { + /// s += ", World!"; + /// s + /// }; + /// + /// // Create a `Closure` from `f`. Note that the `Closure`'s type parameter + /// // is `FnMut`, even though `f` is `FnOnce`. + /// let closure: Closure String> = Closure::once(f); + /// ``` + pub fn once(fn_once: F) -> Closure + where + F: 'static + WasmClosureFnOnce, + { + Closure::wrap(fn_once.into_fn_mut()) + } + + /// Convert a `FnOnce(A...) -> R` into a JavaScript `Function` object. + /// + /// If the JavaScript function is invoked more than once, it will throw an + /// exception. + /// + /// Unlike `Closure::once`, this does *not* return a `Closure` that can be + /// dropped before the function is invoked to deallocate the closure. The + /// only way the `FnOnce` is deallocated is by calling the JavaScript + /// function. If the JavaScript function is never called then the `FnOnce` + /// and everything it closes over will leak. + /// + /// ```rust,ignore + /// use wasm_bindgen::{prelude::*, JsCast}; + /// + /// let f = Closure::once_into_js(move || { + /// // ... + /// }); + /// + /// assert!(f.is_instance_of::()); + /// ``` + pub fn once_into_js(fn_once: F) -> JsValue + where + F: 'static + WasmClosureFnOnce, + { + fn_once.into_js_function() + } +} + +/// A trait for converting an `FnOnce(A...) -> R` into a `FnMut(A...) -> R` that +/// will throw if ever called more than once. +#[doc(hidden)] +pub trait WasmClosureFnOnce: 'static { + type FnMut: ?Sized + 'static + WasmClosure; + + fn into_fn_mut(self) -> Box; + + fn into_js_function(self) -> JsValue; +} + +impl AsRef for Closure { + fn as_ref(&self) -> &JsValue { + &self.js + } +} + +impl WasmDescribe for Closure +where + T: WasmClosure + ?Sized, +{ + fn describe() { + inform(EXTERNREF); + } +} + +// `Closure` can only be passed by reference to imports. +impl<'a, T> IntoWasmAbi for &'a Closure +where + T: WasmClosure + ?Sized, +{ + type Abi = u32; + + fn into_abi(self) -> u32 { + (&*self.js).into_abi() + } +} + +impl<'a, T> OptionIntoWasmAbi for &'a Closure +where + T: WasmClosure + ?Sized, +{ + fn none() -> Self::Abi { + 0 + } +} + +fn _check() { + fn _assert() {} + _assert::<&Closure>(); + _assert::<&Closure>(); + _assert::<&Closure String>>(); + _assert::<&Closure>(); + _assert::<&Closure>(); + _assert::<&Closure String>>(); +} + +impl fmt::Debug for Closure +where + T: ?Sized, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Closure {{ ... }}") + } +} + +impl Drop for Closure +where + T: ?Sized, +{ + fn drop(&mut self) { + unsafe { + // this will implicitly drop our strong reference in addition to + // invalidating all future invocations of the closure + if super::__wbindgen_cb_drop(self.js.idx) != 0 { + ManuallyDrop::drop(&mut self.data); + } + } + } +} + +/// An internal trait for the `Closure` type. +/// +/// This trait is not stable and it's not recommended to use this in bounds or +/// implement yourself. +#[doc(hidden)] +pub unsafe trait WasmClosure { + fn describe(); +} + +/// An internal trait for the `Closure` type. +/// +/// This trait is not stable and it's not recommended to use this in bounds or +/// implement yourself. +#[doc(hidden)] +pub trait IntoWasmClosure { + fn unsize(self: Box) -> Box; +} + +// The memory safety here in these implementations below is a bit tricky. We +// want to be able to drop the `Closure` object from within the invocation of a +// `Closure` for cases like promises. That means that while it's running we +// might drop the `Closure`, but that shouldn't invalidate the environment yet. +// +// Instead what we do is to wrap closures in `Rc` variables. The main `Closure` +// has a strong reference count which keeps the trait object alive. Each +// invocation of a closure then *also* clones this and gets a new reference +// count. When the closure returns it will release the reference count. +// +// This means that if the main `Closure` is dropped while it's being invoked +// then destruction is deferred until execution returns. Otherwise it'll +// deallocate data immediately. + +macro_rules! doit { + ($( + ($($var:ident)*) + )*) => ($( + unsafe impl<$($var,)* R> WasmClosure for dyn Fn($($var),*) -> R + 'static + where $($var: FromWasmAbi + 'static,)* + R: ReturnWasmAbi + 'static, + { + fn describe() { + #[allow(non_snake_case)] + unsafe extern "C" fn invoke<$($var: FromWasmAbi,)* R: ReturnWasmAbi>( + a: usize, + b: usize, + $($var: <$var as FromWasmAbi>::Abi),* + ) -> ::Abi { + if a == 0 { + throw_str("closure invoked recursively or destroyed already"); + } + // Make sure all stack variables are converted before we + // convert `ret` as it may throw (for `Result`, for + // example) + let ret = { + let f: *const dyn Fn($($var),*) -> R = + FatPtr { fields: (a, b) }.ptr; + $( + let $var = <$var as FromWasmAbi>::from_abi($var); + )* + (*f)($($var),*) + }; + ret.return_abi() + } + + inform(invoke::<$($var,)* R> as u32); + + unsafe extern fn destroy<$($var: FromWasmAbi,)* R: ReturnWasmAbi>( + a: usize, + b: usize, + ) { + // This can be called by the JS glue in erroneous situations + // such as when the closure has already been destroyed. If + // that's the case let's not make things worse by + // segfaulting and/or asserting, so just ignore null + // pointers. + if a == 0 { + return; + } + drop(Box::from_raw(FatPtr:: R> { + fields: (a, b) + }.ptr)); + } + inform(destroy::<$($var,)* R> as u32); + + <&Self>::describe(); + } + } + + unsafe impl<$($var,)* R> WasmClosure for dyn FnMut($($var),*) -> R + 'static + where $($var: FromWasmAbi + 'static,)* + R: ReturnWasmAbi + 'static, + { + fn describe() { + #[allow(non_snake_case)] + unsafe extern "C" fn invoke<$($var: FromWasmAbi,)* R: ReturnWasmAbi>( + a: usize, + b: usize, + $($var: <$var as FromWasmAbi>::Abi),* + ) -> ::Abi { + if a == 0 { + throw_str("closure invoked recursively or destroyed already"); + } + // Make sure all stack variables are converted before we + // convert `ret` as it may throw (for `Result`, for + // example) + let ret = { + let f: *const dyn FnMut($($var),*) -> R = + FatPtr { fields: (a, b) }.ptr; + let f = f as *mut dyn FnMut($($var),*) -> R; + $( + let $var = <$var as FromWasmAbi>::from_abi($var); + )* + (*f)($($var),*) + }; + ret.return_abi() + } + + inform(invoke::<$($var,)* R> as u32); + + unsafe extern fn destroy<$($var: FromWasmAbi,)* R: ReturnWasmAbi>( + a: usize, + b: usize, + ) { + // See `Fn()` above for why we simply return + if a == 0 { + return; + } + drop(Box::from_raw(FatPtr:: R> { + fields: (a, b) + }.ptr)); + } + inform(destroy::<$($var,)* R> as u32); + + <&mut Self>::describe(); + } + } + + #[allow(non_snake_case, unused_parens)] + impl WasmClosureFnOnce<($($var),*), R> for T + where T: 'static + FnOnce($($var),*) -> R, + $($var: FromWasmAbi + 'static,)* + R: ReturnWasmAbi + 'static + { + type FnMut = dyn FnMut($($var),*) -> R; + + fn into_fn_mut(self) -> Box { + let mut me = Some(self); + Box::new(move |$($var),*| { + let me = me.take().expect_throw("FnOnce called more than once"); + me($($var),*) + }) + } + + fn into_js_function(self) -> JsValue { + use std::rc::Rc; + use crate::__rt::WasmRefCell; + + let mut me = Some(self); + + let rc1 = Rc::new(WasmRefCell::new(None)); + let rc2 = rc1.clone(); + + let closure = Closure::wrap(Box::new(move |$($var),*| { + // Invoke ourself and get the result. + let me = me.take().expect_throw("FnOnce called more than once"); + let result = me($($var),*); + + // And then drop the `Rc` holding this function's `Closure` + // alive. + debug_assert_eq!(Rc::strong_count(&rc2), 1); + let option_closure = rc2.borrow_mut().take(); + debug_assert!(option_closure.is_some()); + drop(option_closure); + + result + }) as Box R>); + + let js_val = closure.as_ref().clone(); + + *rc1.borrow_mut() = Some(closure); + debug_assert_eq!(Rc::strong_count(&rc1), 2); + drop(rc1); + + js_val + } + } + + impl IntoWasmClosure R> for T + where T: 'static + FnMut($($var),*) -> R, + $($var: FromWasmAbi + 'static,)* + R: ReturnWasmAbi + 'static, + { + fn unsize(self: Box) -> Box R> { self } + } + + impl IntoWasmClosure R> for T + where T: 'static + Fn($($var),*) -> R, + $($var: FromWasmAbi + 'static,)* + R: ReturnWasmAbi + 'static, + { + fn unsize(self: Box) -> Box R> { self } + } + )*) +} + +doit! { + () + (A) + (A B) + (A B C) + (A B C D) + (A B C D E) + (A B C D E F) + (A B C D E F G) + (A B C D E F G H) +} + +// Copy the above impls down here for where there's only one argument and it's a +// reference. We could add more impls for more kinds of references, but it +// becomes a combinatorial explosion quickly. Let's see how far we can get with +// just this one! Maybe someone else can figure out voodoo so we don't have to +// duplicate. + +unsafe impl WasmClosure for dyn Fn(&A) -> R +where + A: RefFromWasmAbi, + R: ReturnWasmAbi + 'static, +{ + fn describe() { + #[allow(non_snake_case)] + unsafe extern "C" fn invoke( + a: usize, + b: usize, + arg: ::Abi, + ) -> ::Abi { + if a == 0 { + throw_str("closure invoked recursively or destroyed already"); + } + // Make sure all stack variables are converted before we + // convert `ret` as it may throw (for `Result`, for + // example) + let ret = { + let f: *const dyn Fn(&A) -> R = FatPtr { fields: (a, b) }.ptr; + let arg = ::ref_from_abi(arg); + (*f)(&*arg) + }; + ret.return_abi() + } + + inform(invoke:: as u32); + + unsafe extern "C" fn destroy(a: usize, b: usize) { + // See `Fn()` above for why we simply return + if a == 0 { + return; + } + drop(Box::from_raw( + FatPtr:: R> { fields: (a, b) }.ptr, + )); + } + inform(destroy:: as u32); + + <&Self>::describe(); + } +} + +unsafe impl WasmClosure for dyn FnMut(&A) -> R +where + A: RefFromWasmAbi, + R: ReturnWasmAbi + 'static, +{ + fn describe() { + #[allow(non_snake_case)] + unsafe extern "C" fn invoke( + a: usize, + b: usize, + arg: ::Abi, + ) -> ::Abi { + if a == 0 { + throw_str("closure invoked recursively or destroyed already"); + } + // Make sure all stack variables are converted before we + // convert `ret` as it may throw (for `Result`, for + // example) + let ret = { + let f: *const dyn FnMut(&A) -> R = FatPtr { fields: (a, b) }.ptr; + let f = f as *mut dyn FnMut(&A) -> R; + let arg = ::ref_from_abi(arg); + (*f)(&*arg) + }; + ret.return_abi() + } + + inform(invoke:: as u32); + + unsafe extern "C" fn destroy(a: usize, b: usize) { + // See `Fn()` above for why we simply return + if a == 0 { + return; + } + drop(Box::from_raw( + FatPtr:: R> { fields: (a, b) }.ptr, + )); + } + inform(destroy:: as u32); + + <&mut Self>::describe(); + } +} + +#[allow(non_snake_case)] +impl WasmClosureFnOnce<(&A,), R> for T +where + T: 'static + FnOnce(&A) -> R, + A: RefFromWasmAbi + 'static, + R: ReturnWasmAbi + 'static, +{ + type FnMut = dyn FnMut(&A) -> R; + + fn into_fn_mut(self) -> Box { + let mut me = Some(self); + Box::new(move |arg| { + let me = me.take().expect_throw("FnOnce called more than once"); + me(arg) + }) + } + + fn into_js_function(self) -> JsValue { + use crate::__rt::WasmRefCell; + use std::rc::Rc; + + let mut me = Some(self); + + let rc1 = Rc::new(WasmRefCell::new(None)); + let rc2 = rc1.clone(); + + let closure = Closure::wrap(Box::new(move |arg: &A| { + // Invoke ourself and get the result. + let me = me.take().expect_throw("FnOnce called more than once"); + let result = me(arg); + + // And then drop the `Rc` holding this function's `Closure` + // alive. + debug_assert_eq!(Rc::strong_count(&rc2), 1); + let option_closure = rc2.borrow_mut().take(); + debug_assert!(option_closure.is_some()); + drop(option_closure); + + result + }) as Box R>); + + let js_val = closure.as_ref().clone(); + + *rc1.borrow_mut() = Some(closure); + debug_assert_eq!(Rc::strong_count(&rc1), 2); + drop(rc1); + + js_val + } +} diff --git a/vendor/wasm-bindgen/src/convert/closures.rs b/vendor/wasm-bindgen/src/convert/closures.rs new file mode 100644 index 000000000..97755b8ee --- /dev/null +++ b/vendor/wasm-bindgen/src/convert/closures.rs @@ -0,0 +1,225 @@ +use core::mem; + +use crate::convert::slices::WasmSlice; +use crate::convert::RefFromWasmAbi; +use crate::convert::{FromWasmAbi, IntoWasmAbi, ReturnWasmAbi}; +use crate::describe::{inform, WasmDescribe, FUNCTION}; +use crate::throw_str; + +macro_rules! stack_closures { + ($( ($cnt:tt $invoke:ident $invoke_mut:ident $($var:ident)*) )*) => ($( + impl<'a, 'b, $($var,)* R> IntoWasmAbi for &'a (dyn Fn($($var),*) -> R + 'b) + where $($var: FromWasmAbi,)* + R: ReturnWasmAbi + { + type Abi = WasmSlice; + + fn into_abi(self) -> WasmSlice { + unsafe { + let (a, b): (usize, usize) = mem::transmute(self); + WasmSlice { ptr: a as u32, len: b as u32 } + } + } + } + + #[allow(non_snake_case)] + unsafe extern "C" fn $invoke<$($var: FromWasmAbi,)* R: ReturnWasmAbi>( + a: usize, + b: usize, + $($var: <$var as FromWasmAbi>::Abi),* + ) -> ::Abi { + if a == 0 { + throw_str("closure invoked recursively or destroyed already"); + } + // Scope all local variables before we call `return_abi` to + // ensure they're all destroyed as `return_abi` may throw + let ret = { + let f: &dyn Fn($($var),*) -> R = mem::transmute((a, b)); + $( + let $var = <$var as FromWasmAbi>::from_abi($var); + )* + f($($var),*) + }; + ret.return_abi() + } + + impl<'a, $($var,)* R> WasmDescribe for dyn Fn($($var),*) -> R + 'a + where $($var: FromWasmAbi,)* + R: ReturnWasmAbi + { + fn describe() { + inform(FUNCTION); + inform($invoke::<$($var,)* R> as u32); + inform($cnt); + $(<$var as WasmDescribe>::describe();)* + ::describe(); + ::describe(); + } + } + + impl<'a, 'b, $($var,)* R> IntoWasmAbi for &'a mut (dyn FnMut($($var),*) -> R + 'b) + where $($var: FromWasmAbi,)* + R: ReturnWasmAbi + { + type Abi = WasmSlice; + + fn into_abi(self) -> WasmSlice { + unsafe { + let (a, b): (usize, usize) = mem::transmute(self); + WasmSlice { ptr: a as u32, len: b as u32 } + } + } + } + + #[allow(non_snake_case)] + unsafe extern "C" fn $invoke_mut<$($var: FromWasmAbi,)* R: ReturnWasmAbi>( + a: usize, + b: usize, + $($var: <$var as FromWasmAbi>::Abi),* + ) -> ::Abi { + if a == 0 { + throw_str("closure invoked recursively or destroyed already"); + } + // Scope all local variables before we call `return_abi` to + // ensure they're all destroyed as `return_abi` may throw + let ret = { + let f: &mut dyn FnMut($($var),*) -> R = mem::transmute((a, b)); + $( + let $var = <$var as FromWasmAbi>::from_abi($var); + )* + f($($var),*) + }; + ret.return_abi() + } + + impl<'a, $($var,)* R> WasmDescribe for dyn FnMut($($var),*) -> R + 'a + where $($var: FromWasmAbi,)* + R: ReturnWasmAbi + { + fn describe() { + inform(FUNCTION); + inform($invoke_mut::<$($var,)* R> as u32); + inform($cnt); + $(<$var as WasmDescribe>::describe();)* + ::describe(); + ::describe(); + } + } + )*) +} + +stack_closures! { + (0 invoke0 invoke0_mut) + (1 invoke1 invoke1_mut A) + (2 invoke2 invoke2_mut A B) + (3 invoke3 invoke3_mut A B C) + (4 invoke4 invoke4_mut A B C D) + (5 invoke5 invoke5_mut A B C D E) + (6 invoke6 invoke6_mut A B C D E F) + (7 invoke7 invoke7_mut A B C D E F G) + (8 invoke8 invoke8_mut A B C D E F G H) +} + +impl<'a, 'b, A, R> IntoWasmAbi for &'a (dyn Fn(&A) -> R + 'b) +where + A: RefFromWasmAbi, + R: ReturnWasmAbi, +{ + type Abi = WasmSlice; + + fn into_abi(self) -> WasmSlice { + unsafe { + let (a, b): (usize, usize) = mem::transmute(self); + WasmSlice { + ptr: a as u32, + len: b as u32, + } + } + } +} + +#[allow(non_snake_case)] +unsafe extern "C" fn invoke1_ref( + a: usize, + b: usize, + arg: ::Abi, +) -> ::Abi { + if a == 0 { + throw_str("closure invoked recursively or destroyed already"); + } + // Scope all local variables before we call `return_abi` to + // ensure they're all destroyed as `return_abi` may throw + let ret = { + let f: &dyn Fn(&A) -> R = mem::transmute((a, b)); + let arg = ::ref_from_abi(arg); + f(&*arg) + }; + ret.return_abi() +} + +impl<'a, A, R> WasmDescribe for dyn Fn(&A) -> R + 'a +where + A: RefFromWasmAbi, + R: ReturnWasmAbi, +{ + fn describe() { + inform(FUNCTION); + inform(invoke1_ref:: as u32); + inform(1); + <&A as WasmDescribe>::describe(); + ::describe(); + ::describe(); + } +} + +impl<'a, 'b, A, R> IntoWasmAbi for &'a mut (dyn FnMut(&A) -> R + 'b) +where + A: RefFromWasmAbi, + R: ReturnWasmAbi, +{ + type Abi = WasmSlice; + + fn into_abi(self) -> WasmSlice { + unsafe { + let (a, b): (usize, usize) = mem::transmute(self); + WasmSlice { + ptr: a as u32, + len: b as u32, + } + } + } +} + +#[allow(non_snake_case)] +unsafe extern "C" fn invoke1_mut_ref( + a: usize, + b: usize, + arg: ::Abi, +) -> ::Abi { + if a == 0 { + throw_str("closure invoked recursively or destroyed already"); + } + // Scope all local variables before we call `return_abi` to + // ensure they're all destroyed as `return_abi` may throw + let ret = { + let f: &mut dyn FnMut(&A) -> R = mem::transmute((a, b)); + let arg = ::ref_from_abi(arg); + f(&*arg) + }; + ret.return_abi() +} + +impl<'a, A, R> WasmDescribe for dyn FnMut(&A) -> R + 'a +where + A: RefFromWasmAbi, + R: ReturnWasmAbi, +{ + fn describe() { + inform(FUNCTION); + inform(invoke1_mut_ref:: as u32); + inform(1); + <&A as WasmDescribe>::describe(); + ::describe(); + ::describe(); + } +} diff --git a/vendor/wasm-bindgen/src/convert/impls.rs b/vendor/wasm-bindgen/src/convert/impls.rs new file mode 100644 index 000000000..79ccd67af --- /dev/null +++ b/vendor/wasm-bindgen/src/convert/impls.rs @@ -0,0 +1,378 @@ +use core::char; +use core::mem::{self, ManuallyDrop}; + +use crate::convert::traits::WasmAbi; +use crate::convert::{FromWasmAbi, IntoWasmAbi, RefFromWasmAbi}; +use crate::convert::{OptionFromWasmAbi, OptionIntoWasmAbi, ReturnWasmAbi}; +use crate::{Clamped, JsError, JsValue}; + +unsafe impl WasmAbi for () {} + +#[repr(C, u32)] +pub enum WasmOption { + None, + Some(T), +} + +unsafe impl WasmAbi for WasmOption {} + +impl WasmOption { + pub fn from_option>(option: Option) -> Self { + match option { + Some(v) => WasmOption::Some(v.into_abi()), + None => WasmOption::None, + } + } + + pub unsafe fn into_option>(v: Self) -> Option { + match v { + WasmOption::Some(v) => Some(T::from_abi(v)), + WasmOption::None => None, + } + } +} + +macro_rules! type_wasm_native { + ($($t:tt as $c:tt)*) => ($( + impl IntoWasmAbi for $t { + type Abi = $c; + + #[inline] + fn into_abi(self) -> $c { self as $c } + } + + impl FromWasmAbi for $t { + type Abi = $c; + + #[inline] + unsafe fn from_abi(js: $c) -> Self { js as $t } + } + + impl IntoWasmAbi for Option<$t> { + type Abi = WasmOption<$c>; + + #[inline] + fn into_abi(self) -> Self::Abi { + WasmOption::from_option(self.map(|v| v as $c)) + } + } + + impl FromWasmAbi for Option<$t> { + type Abi = WasmOption<$c>; + + #[inline] + unsafe fn from_abi(js: Self::Abi) -> Self { + WasmOption::into_option(js).map(|v: $c| v as $t) + } + } + )*) +} + +type_wasm_native!( + i32 as i32 + isize as i32 + u32 as u32 + usize as u32 + i64 as i64 + u64 as u64 + f32 as f32 + f64 as f64 +); + +macro_rules! type_abi_as_u32 { + ($($t:tt)*) => ($( + impl IntoWasmAbi for $t { + type Abi = u32; + + #[inline] + fn into_abi(self) -> u32 { self as u32 } + } + + impl FromWasmAbi for $t { + type Abi = u32; + + #[inline] + unsafe fn from_abi(js: u32) -> Self { js as $t } + } + + impl OptionIntoWasmAbi for $t { + #[inline] + fn none() -> u32 { 0x00FF_FFFFu32 } + } + + impl OptionFromWasmAbi for $t { + #[inline] + fn is_none(js: &u32) -> bool { *js == 0x00FF_FFFFu32 } + } + )*) +} + +type_abi_as_u32!(i8 u8 i16 u16); + +impl IntoWasmAbi for bool { + type Abi = u32; + + #[inline] + fn into_abi(self) -> u32 { + self as u32 + } +} + +impl FromWasmAbi for bool { + type Abi = u32; + + #[inline] + unsafe fn from_abi(js: u32) -> bool { + js != 0 + } +} + +impl OptionIntoWasmAbi for bool { + #[inline] + fn none() -> u32 { + 0x00FF_FFFFu32 + } +} + +impl OptionFromWasmAbi for bool { + #[inline] + fn is_none(js: &u32) -> bool { + *js == 0x00FF_FFFFu32 + } +} + +impl IntoWasmAbi for char { + type Abi = u32; + + #[inline] + fn into_abi(self) -> u32 { + self as u32 + } +} + +impl FromWasmAbi for char { + type Abi = u32; + + #[inline] + unsafe fn from_abi(js: u32) -> char { + char::from_u32_unchecked(js) + } +} + +impl OptionIntoWasmAbi for char { + #[inline] + fn none() -> u32 { + 0x00FF_FFFFu32 + } +} + +impl OptionFromWasmAbi for char { + #[inline] + fn is_none(js: &u32) -> bool { + *js == 0x00FF_FFFFu32 + } +} + +impl IntoWasmAbi for *const T { + type Abi = u32; + + #[inline] + fn into_abi(self) -> u32 { + self as u32 + } +} + +impl FromWasmAbi for *const T { + type Abi = u32; + + #[inline] + unsafe fn from_abi(js: u32) -> *const T { + js as *const T + } +} + +impl IntoWasmAbi for *mut T { + type Abi = u32; + + #[inline] + fn into_abi(self) -> u32 { + self as u32 + } +} + +impl FromWasmAbi for *mut T { + type Abi = u32; + + #[inline] + unsafe fn from_abi(js: u32) -> *mut T { + js as *mut T + } +} + +impl IntoWasmAbi for JsValue { + type Abi = u32; + + #[inline] + fn into_abi(self) -> u32 { + let ret = self.idx; + mem::forget(self); + ret + } +} + +impl FromWasmAbi for JsValue { + type Abi = u32; + + #[inline] + unsafe fn from_abi(js: u32) -> JsValue { + JsValue::_new(js) + } +} + +impl<'a> IntoWasmAbi for &'a JsValue { + type Abi = u32; + + #[inline] + fn into_abi(self) -> u32 { + self.idx + } +} + +impl RefFromWasmAbi for JsValue { + type Abi = u32; + type Anchor = ManuallyDrop; + + #[inline] + unsafe fn ref_from_abi(js: u32) -> Self::Anchor { + ManuallyDrop::new(JsValue::_new(js)) + } +} + +impl IntoWasmAbi for Option { + type Abi = T::Abi; + + #[inline] + fn into_abi(self) -> T::Abi { + match self { + None => T::none(), + Some(me) => me.into_abi(), + } + } +} + +impl FromWasmAbi for Option { + type Abi = T::Abi; + + #[inline] + unsafe fn from_abi(js: T::Abi) -> Self { + if T::is_none(&js) { + None + } else { + Some(T::from_abi(js)) + } + } +} + +impl IntoWasmAbi for Clamped { + type Abi = T::Abi; + + #[inline] + fn into_abi(self) -> Self::Abi { + self.0.into_abi() + } +} + +impl FromWasmAbi for Clamped { + type Abi = T::Abi; + + #[inline] + unsafe fn from_abi(js: T::Abi) -> Self { + Clamped(T::from_abi(js)) + } +} + +impl IntoWasmAbi for () { + type Abi = (); + + #[inline] + fn into_abi(self) { + self + } +} + +/// This is an encoding of a Result. It can only store things that can be decoded by the JS +/// bindings. +/// +/// At the moment, we do not write the exact struct packing layout of everything into the +/// glue/descriptions of datatypes, so T cannot be arbitrary. The current requirements of the +/// struct unpacker (StructUnpacker), which apply to ResultAbi as a whole, are as follows: +/// +/// - repr(C), of course +/// - u32/i32/f32/f64 fields at the "leaf fields" of the "field tree" +/// - layout equivalent to a completely flattened repr(C) struct, constructed by an in order +/// traversal of all the leaf fields in it. +/// +/// This means that you can't embed struct A(u32, f64) as struct B(u32, A); because the "completely +/// flattened" struct AB(u32, u32, f64) would miss the 4 byte padding that is actually present +/// within B and then as a consequence also miss the 4 byte padding within A that repr(C) inserts. +/// +/// The enemy is padding. Padding is only required when there is an `f64` field. So the enemy is +/// `f64` after anything else, particularly anything arbitrary. There is no smaller sized type, so +/// we don't need to worry about 1-byte integers, etc. It's best, therefore, to place your f64s +/// first in your structs, that's why we have `abi` first, although here it doesn't matter as the +/// other two fields total 8 bytes anyway. +/// +#[repr(C)] +pub struct ResultAbi { + /// This field is the same size/align as `T`. + abi: ResultAbiUnion, + /// Order of args here is such that we can pop() the possible error first, deal with it and + /// move on. Later fields are popped off the stack first. + err: u32, + is_err: u32, +} + +#[repr(C)] +pub union ResultAbiUnion { + // ManuallyDrop is #[repr(transparent)] + ok: std::mem::ManuallyDrop, + err: (), +} + +unsafe impl WasmAbi for ResultAbi {} +unsafe impl WasmAbi for ResultAbiUnion {} + +impl> ReturnWasmAbi for Result { + type Abi = ResultAbi; + #[inline] + fn return_abi(self) -> Self::Abi { + match self { + Ok(v) => { + let abi = ResultAbiUnion { + ok: std::mem::ManuallyDrop::new(v.into_abi()), + }; + ResultAbi { + abi, + is_err: 0, + err: 0, + } + } + Err(e) => { + let jsval = e.into(); + ResultAbi { + abi: ResultAbiUnion { err: () }, + is_err: 1, + err: jsval.into_abi(), + } + } + } + } +} + +impl IntoWasmAbi for JsError { + type Abi = ::Abi; + + fn into_abi(self) -> Self::Abi { + self.value.into_abi() + } +} diff --git a/vendor/wasm-bindgen/src/convert/mod.rs b/vendor/wasm-bindgen/src/convert/mod.rs new file mode 100644 index 000000000..ce2c0b2c8 --- /dev/null +++ b/vendor/wasm-bindgen/src/convert/mod.rs @@ -0,0 +1,11 @@ +//! This is mostly an internal module, no stability guarantees are provided. Use +//! at your own risk. + +mod closures; +mod impls; +mod slices; +mod traits; + +pub use self::impls::*; +pub use self::slices::WasmSlice; +pub use self::traits::*; diff --git a/vendor/wasm-bindgen/src/convert/slices.rs b/vendor/wasm-bindgen/src/convert/slices.rs new file mode 100644 index 000000000..9d0970f4e --- /dev/null +++ b/vendor/wasm-bindgen/src/convert/slices.rs @@ -0,0 +1,311 @@ +#[cfg(feature = "std")] +use std::prelude::v1::*; + +use core::slice; +use core::str; + +use crate::cast::JsObject; +use crate::convert::OptionIntoWasmAbi; +use crate::convert::{FromWasmAbi, IntoWasmAbi, RefFromWasmAbi, RefMutFromWasmAbi, WasmAbi}; +use cfg_if::cfg_if; + +if_std! { + use core::mem; + use crate::convert::OptionFromWasmAbi; +} + +#[repr(C)] +pub struct WasmSlice { + pub ptr: u32, + pub len: u32, +} + +unsafe impl WasmAbi for WasmSlice {} + +#[inline] +fn null_slice() -> WasmSlice { + WasmSlice { ptr: 0, len: 0 } +} + +macro_rules! vectors { + ($($t:ident)*) => ($( + if_std! { + impl IntoWasmAbi for Box<[$t]> { + type Abi = WasmSlice; + + #[inline] + fn into_abi(self) -> WasmSlice { + let ptr = self.as_ptr(); + let len = self.len(); + mem::forget(self); + WasmSlice { + ptr: ptr.into_abi(), + len: len as u32, + } + } + } + + impl OptionIntoWasmAbi for Box<[$t]> { + #[inline] + fn none() -> WasmSlice { null_slice() } + } + + impl FromWasmAbi for Box<[$t]> { + type Abi = WasmSlice; + + #[inline] + unsafe fn from_abi(js: WasmSlice) -> Self { + let ptr = <*mut $t>::from_abi(js.ptr); + let len = js.len as usize; + Vec::from_raw_parts(ptr, len, len).into_boxed_slice() + } + } + + impl OptionFromWasmAbi for Box<[$t]> { + #[inline] + fn is_none(slice: &WasmSlice) -> bool { slice.ptr == 0 } + } + } + + impl<'a> IntoWasmAbi for &'a [$t] { + type Abi = WasmSlice; + + #[inline] + fn into_abi(self) -> WasmSlice { + WasmSlice { + ptr: self.as_ptr().into_abi(), + len: self.len() as u32, + } + } + } + + impl<'a> OptionIntoWasmAbi for &'a [$t] { + #[inline] + fn none() -> WasmSlice { null_slice() } + } + + impl<'a> IntoWasmAbi for &'a mut [$t] { + type Abi = WasmSlice; + + #[inline] + fn into_abi(self) -> WasmSlice { + (&*self).into_abi() + } + } + + impl<'a> OptionIntoWasmAbi for &'a mut [$t] { + #[inline] + fn none() -> WasmSlice { null_slice() } + } + + impl RefFromWasmAbi for [$t] { + type Abi = WasmSlice; + type Anchor = Box<[$t]>; + + #[inline] + unsafe fn ref_from_abi(js: WasmSlice) -> Box<[$t]> { + >::from_abi(js) + } + } + + impl RefMutFromWasmAbi for [$t] { + type Abi = WasmSlice; + type Anchor = &'static mut [$t]; + + #[inline] + unsafe fn ref_mut_from_abi(js: WasmSlice) + -> &'static mut [$t] + { + slice::from_raw_parts_mut( + <*mut $t>::from_abi(js.ptr), + js.len as usize, + ) + } + } + )*) +} + +vectors! { + u8 i8 u16 i16 u32 i32 u64 i64 usize isize f32 f64 +} + +cfg_if! { + if #[cfg(feature = "enable-interning")] { + #[inline] + fn unsafe_get_cached_str(x: &str) -> Option { + // This uses 0 for the ptr as an indication that it is a JsValue and not a str. + crate::cache::intern::unsafe_get_str(x).map(|x| WasmSlice { ptr: 0, len: x }) + } + + } else { + #[inline] + fn unsafe_get_cached_str(_x: &str) -> Option { + None + } + } +} + +if_std! { + impl IntoWasmAbi for Vec where Box<[T]>: IntoWasmAbi { + type Abi = as IntoWasmAbi>::Abi; + + #[inline] + fn into_abi(self) -> Self::Abi { + self.into_boxed_slice().into_abi() + } + } + + impl OptionIntoWasmAbi for Vec where Box<[T]>: IntoWasmAbi { + #[inline] + fn none() -> WasmSlice { null_slice() } + } + + impl FromWasmAbi for Vec where Box<[T]>: FromWasmAbi { + type Abi = as FromWasmAbi>::Abi; + + #[inline] + unsafe fn from_abi(js: Self::Abi) -> Self { + >::from_abi(js).into() + } + } + + impl OptionFromWasmAbi for Vec where Box<[T]>: FromWasmAbi { + #[inline] + fn is_none(abi: &WasmSlice) -> bool { abi.ptr == 0 } + } + + impl IntoWasmAbi for String { + type Abi = as IntoWasmAbi>::Abi; + + #[inline] + fn into_abi(self) -> Self::Abi { + // This is safe because the JsValue is immediately looked up in the heap and + // then returned, so use-after-free cannot occur. + unsafe_get_cached_str(&self).unwrap_or_else(|| self.into_bytes().into_abi()) + } + } + + impl OptionIntoWasmAbi for String { + #[inline] + fn none() -> Self::Abi { null_slice() } + } + + impl FromWasmAbi for String { + type Abi = as FromWasmAbi>::Abi; + + #[inline] + unsafe fn from_abi(js: Self::Abi) -> Self { + String::from_utf8_unchecked(>::from_abi(js)) + } + } + + impl OptionFromWasmAbi for String { + #[inline] + fn is_none(slice: &WasmSlice) -> bool { slice.ptr == 0 } + } +} + +impl<'a> IntoWasmAbi for &'a str { + type Abi = <&'a [u8] as IntoWasmAbi>::Abi; + + #[inline] + fn into_abi(self) -> Self::Abi { + // This is safe because the JsValue is immediately looked up in the heap and + // then returned, so use-after-free cannot occur. + unsafe_get_cached_str(self).unwrap_or_else(|| self.as_bytes().into_abi()) + } +} + +impl<'a> OptionIntoWasmAbi for &'a str { + #[inline] + fn none() -> Self::Abi { + null_slice() + } +} + +impl RefFromWasmAbi for str { + type Abi = <[u8] as RefFromWasmAbi>::Abi; + type Anchor = Box; + + #[inline] + unsafe fn ref_from_abi(js: Self::Abi) -> Self::Anchor { + mem::transmute::, Box>(>::from_abi(js)) + } +} + +if_std! { + use crate::JsValue; + + impl IntoWasmAbi for Box<[JsValue]> { + type Abi = WasmSlice; + + #[inline] + fn into_abi(self) -> WasmSlice { + let ptr = self.as_ptr(); + let len = self.len(); + mem::forget(self); + WasmSlice { + ptr: ptr.into_abi(), + len: len as u32, + } + } + } + + impl OptionIntoWasmAbi for Box<[JsValue]> { + #[inline] + fn none() -> WasmSlice { null_slice() } + } + + impl FromWasmAbi for Box<[JsValue]> { + type Abi = WasmSlice; + + #[inline] + unsafe fn from_abi(js: WasmSlice) -> Self { + let ptr = <*mut JsValue>::from_abi(js.ptr); + let len = js.len as usize; + Vec::from_raw_parts(ptr, len, len).into_boxed_slice() + } + } + + impl OptionFromWasmAbi for Box<[JsValue]> { + #[inline] + fn is_none(slice: &WasmSlice) -> bool { slice.ptr == 0 } + } + + impl IntoWasmAbi for Box<[T]> where T: JsObject { + type Abi = WasmSlice; + + #[inline] + fn into_abi(self) -> WasmSlice { + let ptr = self.as_ptr(); + let len = self.len(); + mem::forget(self); + WasmSlice { + ptr: ptr.into_abi(), + len: len as u32, + } + } + } + + impl OptionIntoWasmAbi for Box<[T]> where T: JsObject { + #[inline] + fn none() -> WasmSlice { null_slice() } + } + + impl FromWasmAbi for Box<[T]> where T: JsObject { + type Abi = WasmSlice; + + #[inline] + unsafe fn from_abi(js: WasmSlice) -> Self { + let ptr = <*mut JsValue>::from_abi(js.ptr); + let len = js.len as usize; + let vec: Vec = Vec::from_raw_parts(ptr, len, len).drain(..).map(|js_value| T::unchecked_from_js(js_value)).collect(); + return vec.into_boxed_slice(); + } + } + + impl OptionFromWasmAbi for Box<[T]> where T: JsObject { + #[inline] + fn is_none(slice: &WasmSlice) -> bool { slice.ptr == 0 } + } +} diff --git a/vendor/wasm-bindgen/src/convert/traits.rs b/vendor/wasm-bindgen/src/convert/traits.rs new file mode 100644 index 000000000..b9d12b4c8 --- /dev/null +++ b/vendor/wasm-bindgen/src/convert/traits.rs @@ -0,0 +1,131 @@ +use core::ops::{Deref, DerefMut}; + +use crate::describe::*; + +/// A trait for anything that can be converted into a type that can cross the +/// wasm ABI directly, eg `u32` or `f64`. +/// +/// This is the opposite operation as `FromWasmAbi` and `Ref[Mut]FromWasmAbi`. +pub trait IntoWasmAbi: WasmDescribe { + /// The wasm ABI type that this converts into when crossing the ABI + /// boundary. + type Abi: WasmAbi; + + /// Convert `self` into `Self::Abi` so that it can be sent across the wasm + /// ABI boundary. + fn into_abi(self) -> Self::Abi; +} + +/// A trait for anything that can be recovered by-value from the wasm ABI +/// boundary, eg a Rust `u8` can be recovered from the wasm ABI `u32` type. +/// +/// This is the by-value variant of the opposite operation as `IntoWasmAbi`. +pub trait FromWasmAbi: WasmDescribe { + /// The wasm ABI type that this converts from when coming back out from the + /// ABI boundary. + type Abi: WasmAbi; + + /// Recover a `Self` from `Self::Abi`. + /// + /// # Safety + /// + /// This is only safe to call when -- and implementations may assume that -- + /// the supplied `Self::Abi` was previously generated by a call to `::into_abi()` or the moral equivalent in JS. + unsafe fn from_abi(js: Self::Abi) -> Self; +} + +/// A trait for anything that can be recovered as some sort of shared reference +/// from the wasm ABI boundary. +/// +/// This is the shared reference variant of the opposite operation as +/// `IntoWasmAbi`. +pub trait RefFromWasmAbi: WasmDescribe { + /// The wasm ABI type references to `Self` are recovered from. + type Abi: WasmAbi; + + /// The type that holds the reference to `Self` for the duration of the + /// invocation of the function that has an `&Self` parameter. This is + /// required to ensure that the lifetimes don't persist beyond one function + /// call, and so that they remain anonymous. + type Anchor: Deref; + + /// Recover a `Self::Anchor` from `Self::Abi`. + /// + /// # Safety + /// + /// Same as `FromWasmAbi::from_abi`. + unsafe fn ref_from_abi(js: Self::Abi) -> Self::Anchor; +} + +/// Dual of the `RefFromWasmAbi` trait, except for mutable references. +pub trait RefMutFromWasmAbi: WasmDescribe { + /// Same as `RefFromWasmAbi::Abi` + type Abi: WasmAbi; + /// Same as `RefFromWasmAbi::Anchor` + type Anchor: DerefMut; + /// Same as `RefFromWasmAbi::ref_from_abi` + unsafe fn ref_mut_from_abi(js: Self::Abi) -> Self::Anchor; +} + +/// Indicates that this type can be passed to JS as `Option`. +/// +/// This trait is used when implementing `IntoWasmAbi for Option`. +pub trait OptionIntoWasmAbi: IntoWasmAbi { + /// Returns an ABI instance indicating "none", which JS will interpret as + /// the `None` branch of this option. + /// + /// It should be guaranteed that the `IntoWasmAbi` can never produce the ABI + /// value returned here. + fn none() -> Self::Abi; +} + +/// Indicates that this type can be received from JS as `Option`. +/// +/// This trait is used when implementing `FromWasmAbi for Option`. +pub trait OptionFromWasmAbi: FromWasmAbi { + /// Tests whether the argument is a "none" instance. If so it will be + /// deserialized as `None`, and otherwise it will be passed to + /// `FromWasmAbi`. + fn is_none(abi: &Self::Abi) -> bool; +} + +/// An unsafe trait which represents types that are ABI-safe to pass via wasm +/// arguments. +/// +/// This is an unsafe trait to implement as there's no guarantee the type is +/// actually safe to transfer across the was boundary, it's up to you to +/// guarantee this so codegen works correctly. +pub unsafe trait WasmAbi {} + +unsafe impl WasmAbi for u32 {} +unsafe impl WasmAbi for i32 {} +unsafe impl WasmAbi for u64 {} +unsafe impl WasmAbi for i64 {} +unsafe impl WasmAbi for f32 {} +unsafe impl WasmAbi for f64 {} + +/// A trait representing how to interepret the return value of a function for +/// the wasm ABI. +/// +/// This is very similar to the `IntoWasmAbi` trait and in fact has a blanket +/// implementation for all implementors of the `IntoWasmAbi`. The primary use +/// case of this trait is to enable functions to return `Result`, interpreting +/// an error as "rethrow this to JS" +pub trait ReturnWasmAbi: WasmDescribe { + /// Same as `IntoWasmAbi::Abi` + type Abi: WasmAbi; + + /// Same as `IntoWasmAbi::into_abi`, except that it may throw and never + /// return in the case of `Err`. + fn return_abi(self) -> Self::Abi; +} + +impl ReturnWasmAbi for T { + type Abi = T::Abi; + + #[inline] + fn return_abi(self) -> Self::Abi { + self.into_abi() + } +} diff --git a/vendor/wasm-bindgen/src/describe.rs b/vendor/wasm-bindgen/src/describe.rs new file mode 100644 index 000000000..2b7c4b628 --- /dev/null +++ b/vendor/wasm-bindgen/src/describe.rs @@ -0,0 +1,192 @@ +//! This is an internal module, no stability guarantees are provided. Use at +//! your own risk. + +#![doc(hidden)] + +use crate::{Clamped, JsError, JsValue}; +use cfg_if::cfg_if; + +macro_rules! tys { + ($($a:ident)*) => (tys! { @ ($($a)*) 0 }); + (@ () $v:expr) => {}; + (@ ($a:ident $($b:ident)*) $v:expr) => { + pub const $a: u32 = $v; + tys!(@ ($($b)*) $v+1); + } +} + +// NB: this list must be kept in sync with `crates/cli-support/src/descriptor.rs` +tys! { + I8 + U8 + I16 + U16 + I32 + U32 + I64 + U64 + F32 + F64 + BOOLEAN + FUNCTION + CLOSURE + CACHED_STRING + STRING + REF + REFMUT + SLICE + VECTOR + EXTERNREF + NAMED_EXTERNREF + ENUM + RUST_STRUCT + CHAR + OPTIONAL + RESULT + UNIT + CLAMPED +} + +#[inline(always)] // see the wasm-interpreter crate +pub fn inform(a: u32) { + unsafe { super::__wbindgen_describe(a) } +} + +pub trait WasmDescribe { + fn describe(); +} + +macro_rules! simple { + ($($t:ident => $d:ident)*) => ($( + impl WasmDescribe for $t { + fn describe() { inform($d) } + } + )*) +} + +simple! { + i8 => I8 + u8 => U8 + i16 => I16 + u16 => U16 + i32 => I32 + u32 => U32 + i64 => I64 + u64 => U64 + isize => I32 + usize => U32 + f32 => F32 + f64 => F64 + bool => BOOLEAN + char => CHAR + JsValue => EXTERNREF +} + +cfg_if! { + if #[cfg(feature = "enable-interning")] { + simple! { + str => CACHED_STRING + } + + } else { + simple! { + str => STRING + } + } +} + +impl WasmDescribe for *const T { + fn describe() { + inform(I32) + } +} + +impl WasmDescribe for *mut T { + fn describe() { + inform(I32) + } +} + +impl WasmDescribe for [T] { + fn describe() { + inform(SLICE); + T::describe(); + } +} + +impl<'a, T: WasmDescribe + ?Sized> WasmDescribe for &'a T { + fn describe() { + inform(REF); + T::describe(); + } +} + +impl<'a, T: WasmDescribe + ?Sized> WasmDescribe for &'a mut T { + fn describe() { + inform(REFMUT); + T::describe(); + } +} + +if_std! { + use std::prelude::v1::*; + + cfg_if! { + if #[cfg(feature = "enable-interning")] { + simple! { + String => CACHED_STRING + } + + } else { + simple! { + String => STRING + } + } + } + + impl WasmDescribe for Box<[T]> { + fn describe() { + inform(VECTOR); + T::describe(); + } + } + + impl WasmDescribe for Vec where Box<[T]>: WasmDescribe { + fn describe() { + >::describe(); + } + } +} + +impl WasmDescribe for Option { + fn describe() { + inform(OPTIONAL); + T::describe(); + } +} + +impl WasmDescribe for () { + fn describe() { + inform(UNIT) + } +} + +impl> WasmDescribe for Result { + fn describe() { + inform(RESULT); + T::describe(); + } +} + +impl WasmDescribe for Clamped { + fn describe() { + inform(CLAMPED); + T::describe(); + } +} + +impl WasmDescribe for JsError { + fn describe() { + JsValue::describe(); + } +} diff --git a/vendor/wasm-bindgen/src/externref.rs b/vendor/wasm-bindgen/src/externref.rs new file mode 100644 index 000000000..a7e5f3ebc --- /dev/null +++ b/vendor/wasm-bindgen/src/externref.rs @@ -0,0 +1,184 @@ +use crate::JsValue; +use std::alloc::{self, Layout}; +use std::cell::Cell; +use std::mem; +use std::ptr; +use std::slice; +use std::vec::Vec; +use std::cmp::max; + +externs! { + #[link(wasm_import_module = "__wbindgen_externref_xform__")] + extern "C" { + fn __wbindgen_externref_table_grow(delta: usize) -> i32; + fn __wbindgen_externref_table_set_null(idx: usize) -> (); + } +} + +pub struct Slab { + data: Vec, + head: usize, + base: usize, +} + +impl Slab { + fn new() -> Slab { + Slab { + data: Vec::new(), + head: 0, + base: 0, + } + } + + fn alloc(&mut self) -> usize { + let ret = self.head; + if ret == self.data.len() { + let curr_len = self.data.len(); + if curr_len == self.data.capacity() { + let extra = max(128, curr_len); + let r = unsafe { __wbindgen_externref_table_grow(extra) }; + if r == -1 { + internal_error("table grow failure") + } + if self.base == 0 { + self.base = r as usize; + } else if self.base + self.data.len() != r as usize { + internal_error("someone else allocated table entires?") + } + + // poor man's `try_reserve_exact` until that's stable + unsafe { + let new_cap = self.data.capacity() + extra; + let size = mem::size_of::() * new_cap; + let align = mem::align_of::(); + let layout = match Layout::from_size_align(size, align) { + Ok(l) => l, + Err(_) => internal_error("size/align layout failure"), + }; + let ptr = alloc::alloc(layout) as *mut usize; + if ptr.is_null() { + internal_error("allocation failure"); + } + ptr::copy_nonoverlapping(self.data.as_ptr(), ptr, self.data.len()); + let new_vec = Vec::from_raw_parts(ptr, self.data.len(), new_cap); + let mut old = mem::replace(&mut self.data, new_vec); + old.set_len(0); + } + } + + // custom condition to ensure `push` below doesn't call `reserve` in + // optimized builds which pulls in lots of panic infrastructure + if self.data.len() >= self.data.capacity() { + internal_error("push should be infallible now") + } + self.data.push(ret + 1); + } + + // usage of `get_mut` thwarts panicking infrastructure in optimized + // builds + match self.data.get_mut(ret) { + Some(slot) => self.head = *slot, + None => internal_error("ret out of bounds"), + } + ret + self.base + } + + fn dealloc(&mut self, slot: usize) { + if slot < self.base { + internal_error("free reserved slot"); + } + let slot = slot - self.base; + + // usage of `get_mut` thwarts panicking infrastructure in optimized + // builds + match self.data.get_mut(slot) { + Some(ptr) => { + *ptr = self.head; + self.head = slot; + } + None => internal_error("slot out of bounds"), + } + } + + fn live_count(&self) -> u32 { + let mut free_count = 0; + let mut next = self.head; + while next < self.data.len() { + debug_assert!((free_count as usize) < self.data.len()); + free_count += 1; + match self.data.get(next) { + Some(n) => next = *n, + None => internal_error("slot out of bounds"), + }; + } + self.data.len() as u32 - free_count + } +} + +fn internal_error(msg: &str) -> ! { + if cfg!(debug_assertions) { + super::throw_str(msg) + } else { + std::process::abort() + } +} + +// Management of `externref` is always thread local since an `externref` value +// can't cross threads in wasm. Indices as a result are always thread-local. +std::thread_local!(pub static HEAP_SLAB: Cell = Cell::new(Slab::new())); + +#[no_mangle] +pub extern "C" fn __externref_table_alloc() -> usize { + HEAP_SLAB + .try_with(|slot| { + let mut slab = slot.replace(Slab::new()); + let ret = slab.alloc(); + slot.replace(slab); + ret + }) + .unwrap_or_else(|_| internal_error("tls access failure")) +} + +#[no_mangle] +pub extern "C" fn __externref_table_dealloc(idx: usize) { + if idx < super::JSIDX_RESERVED as usize { + return; + } + // clear this value from the table so while the table slot is un-allocated + // we don't keep around a strong reference to a potentially large object + unsafe { + __wbindgen_externref_table_set_null(idx); + } + HEAP_SLAB + .try_with(|slot| { + let mut slab = slot.replace(Slab::new()); + slab.dealloc(idx); + slot.replace(slab); + }) + .unwrap_or_else(|_| internal_error("tls access failure")) +} + +#[no_mangle] +pub unsafe extern "C" fn __externref_drop_slice(ptr: *mut JsValue, len: usize) { + for slot in slice::from_raw_parts_mut(ptr, len) { + __externref_table_dealloc(slot.idx as usize); + } +} + +// Implementation of `__wbindgen_externref_heap_live_count` for when we are using +// `externref` instead of the JS `heap`. +#[no_mangle] +pub unsafe extern "C" fn __externref_heap_live_count() -> u32 { + HEAP_SLAB + .try_with(|slot| { + let slab = slot.replace(Slab::new()); + let count = slab.live_count(); + slot.replace(slab); + count + }) + .unwrap_or_else(|_| internal_error("tls access failure")) +} + +// see comment in module above this in `link_mem_intrinsics` +#[inline(never)] +pub fn link_intrinsics() {} diff --git a/vendor/wasm-bindgen/src/lib.rs b/vendor/wasm-bindgen/src/lib.rs new file mode 100644 index 000000000..2ccb284b9 --- /dev/null +++ b/vendor/wasm-bindgen/src/lib.rs @@ -0,0 +1,1800 @@ +//! Runtime support for the `wasm-bindgen` tool +//! +//! This crate contains the runtime support necessary for `wasm-bindgen` the +//! attribute and tool. Crates pull in the `#[wasm_bindgen]` attribute through +//! this crate and this crate also provides JS bindings through the `JsValue` +//! interface. + +#![no_std] +#![allow(coherence_leak_check)] +#![doc(html_root_url = "https://docs.rs/wasm-bindgen/0.2")] + +use core::convert::TryFrom; +use core::fmt; +use core::marker; +use core::mem; +use core::ops::{ + Add, BitAnd, BitOr, BitXor, Deref, DerefMut, Div, Mul, Neg, Not, Rem, Shl, Shr, Sub, +}; +use core::u32; + +use crate::convert::{FromWasmAbi, WasmSlice}; + +macro_rules! if_std { + ($($i:item)*) => ($( + #[cfg(feature = "std")] $i + )*) +} + +macro_rules! externs { + ($(#[$attr:meta])* extern "C" { $(fn $name:ident($($args:tt)*) -> $ret:ty;)* }) => ( + #[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))] + $(#[$attr])* + extern "C" { + $(fn $name($($args)*) -> $ret;)* + } + + $( + #[cfg(not(all(target_arch = "wasm32", not(target_os = "emscripten"))))] + #[allow(unused_variables)] + unsafe extern fn $name($($args)*) -> $ret { + panic!("function not implemented on non-wasm32 targets") + } + )* + ) +} + +/// A module which is typically glob imported from: +/// +/// ``` +/// use wasm_bindgen::prelude::*; +/// ``` +pub mod prelude { + pub use crate::JsValue; + pub use crate::UnwrapThrowExt; + #[doc(hidden)] + pub use wasm_bindgen_macro::__wasm_bindgen_class_marker; + pub use wasm_bindgen_macro::wasm_bindgen; + + if_std! { + pub use crate::closure::Closure; + } + + pub use crate::JsError; +} + +pub mod convert; +pub mod describe; + +mod cast; +pub use crate::cast::{JsCast, JsObject}; +use convert::WasmOption; + +if_std! { + extern crate std; + use std::prelude::v1::*; + pub mod closure; + mod externref; + + mod cache; + pub use cache::intern::{intern, unintern}; +} + +/// Representation of an object owned by JS. +/// +/// A `JsValue` doesn't actually live in Rust right now but actually in a table +/// owned by the `wasm-bindgen` generated JS glue code. Eventually the ownership +/// will transfer into wasm directly and this will likely become more efficient, +/// but for now it may be slightly slow. +pub struct JsValue { + idx: u32, + _marker: marker::PhantomData<*mut u8>, // not at all threadsafe +} + +const JSIDX_OFFSET: u32 = 32; // keep in sync with js/mod.rs +const JSIDX_UNDEFINED: u32 = JSIDX_OFFSET + 0; +const JSIDX_NULL: u32 = JSIDX_OFFSET + 1; +const JSIDX_TRUE: u32 = JSIDX_OFFSET + 2; +const JSIDX_FALSE: u32 = JSIDX_OFFSET + 3; +const JSIDX_RESERVED: u32 = JSIDX_OFFSET + 4; + +impl JsValue { + /// The `null` JS value constant. + pub const NULL: JsValue = JsValue { + idx: JSIDX_NULL, + _marker: marker::PhantomData, + }; + + /// The `undefined` JS value constant. + pub const UNDEFINED: JsValue = JsValue { + idx: JSIDX_UNDEFINED, + _marker: marker::PhantomData, + }; + + /// The `true` JS value constant. + pub const TRUE: JsValue = JsValue { + idx: JSIDX_TRUE, + _marker: marker::PhantomData, + }; + + /// The `false` JS value constant. + pub const FALSE: JsValue = JsValue { + idx: JSIDX_FALSE, + _marker: marker::PhantomData, + }; + + #[inline] + fn _new(idx: u32) -> JsValue { + JsValue { + idx, + _marker: marker::PhantomData, + } + } + + /// Creates a new JS value which is a string. + /// + /// The utf-8 string provided is copied to the JS heap and the string will + /// be owned by the JS garbage collector. + #[inline] + pub fn from_str(s: &str) -> JsValue { + unsafe { JsValue::_new(__wbindgen_string_new(s.as_ptr(), s.len())) } + } + + /// Creates a new JS value which is a number. + /// + /// This function creates a JS value representing a number (a heap + /// allocated number) and returns a handle to the JS version of it. + #[inline] + pub fn from_f64(n: f64) -> JsValue { + unsafe { JsValue::_new(__wbindgen_number_new(n)) } + } + + /// Creates a new JS value which is a bigint from a string representing a number. + /// + /// This function creates a JS value representing a bigint (a heap + /// allocated large integer) and returns a handle to the JS version of it. + #[inline] + pub fn bigint_from_str(s: &str) -> JsValue { + unsafe { JsValue::_new(__wbindgen_bigint_from_str(s.as_ptr(), s.len())) } + } + + /// Creates a new JS value which is a boolean. + /// + /// This function creates a JS object representing a boolean (a heap + /// allocated boolean) and returns a handle to the JS version of it. + #[inline] + pub fn from_bool(b: bool) -> JsValue { + if b { + JsValue::TRUE + } else { + JsValue::FALSE + } + } + + /// Creates a new JS value representing `undefined`. + #[inline] + pub fn undefined() -> JsValue { + JsValue::UNDEFINED + } + + /// Creates a new JS value representing `null`. + #[inline] + pub fn null() -> JsValue { + JsValue::NULL + } + + /// Creates a new JS symbol with the optional description specified. + /// + /// This function will invoke the `Symbol` constructor in JS and return the + /// JS object corresponding to the symbol created. + pub fn symbol(description: Option<&str>) -> JsValue { + unsafe { + match description { + Some(description) => JsValue::_new(__wbindgen_symbol_named_new( + description.as_ptr(), + description.len(), + )), + None => JsValue::_new(__wbindgen_symbol_anonymous_new()), + } + } + } + + /// Creates a new `JsValue` from the JSON serialization of the object `t` + /// provided. + /// + /// **This function is deprecated**, due to [creating a dependency cycle in + /// some circumstances][dep-cycle-issue]. Use [`serde-wasm-bindgen`] or + /// [`gloo_utils::format::JsValueSerdeExt`] instead. + /// + /// [dep-cycle-issue]: https://github.com/rustwasm/wasm-bindgen/issues/2770 + /// [`serde-wasm-bindgen`]: https://docs.rs/serde-wasm-bindgen + /// [`gloo_utils::format::JsValueSerdeExt`]: https://docs.rs/gloo-utils/latest/gloo_utils/format/trait.JsValueSerdeExt.html + /// + /// This function will serialize the provided value `t` to a JSON string, + /// send the JSON string to JS, parse it into a JS object, and then return + /// a handle to the JS object. This is unlikely to be super speedy so it's + /// not recommended for large payloads, but it's a nice to have in some + /// situations! + /// + /// Usage of this API requires activating the `serde-serialize` feature of + /// the `wasm-bindgen` crate. + /// + /// # Errors + /// + /// Returns any error encountered when serializing `T` into JSON. + #[cfg(feature = "serde-serialize")] + #[deprecated = "causes dependency cycles, use `serde-wasm-bindgen` or `gloo_utils::format::JsValueSerdeExt` instead"] + pub fn from_serde(t: &T) -> serde_json::Result + where + T: serde::ser::Serialize + ?Sized, + { + let s = serde_json::to_string(t)?; + unsafe { Ok(JsValue::_new(__wbindgen_json_parse(s.as_ptr(), s.len()))) } + } + + /// Invokes `JSON.stringify` on this value and then parses the resulting + /// JSON into an arbitrary Rust value. + /// + /// **This function is deprecated**, due to [creating a dependency cycle in + /// some circumstances][dep-cycle-issue]. Use [`serde-wasm-bindgen`] or + /// [`gloo_utils::format::JsValueSerdeExt`] instead. + /// + /// [dep-cycle-issue]: https://github.com/rustwasm/wasm-bindgen/issues/2770 + /// [`serde-wasm-bindgen`]: https://docs.rs/serde-wasm-bindgen + /// [`gloo_utils::format::JsValueSerdeExt`]: https://docs.rs/gloo-utils/latest/gloo_utils/format/trait.JsValueSerdeExt.html + /// + /// This function will first call `JSON.stringify` on the `JsValue` itself. + /// The resulting string is then passed into Rust which then parses it as + /// JSON into the resulting value. + /// + /// Usage of this API requires activating the `serde-serialize` feature of + /// the `wasm-bindgen` crate. + /// + /// # Errors + /// + /// Returns any error encountered when parsing the JSON into a `T`. + #[cfg(feature = "serde-serialize")] + #[deprecated = "causes dependency cycles, use `serde-wasm-bindgen` or `gloo_utils::format::JsValueSerdeExt` instead"] + pub fn into_serde(&self) -> serde_json::Result + where + T: for<'a> serde::de::Deserialize<'a>, + { + unsafe { + let ret = __wbindgen_json_serialize(self.idx); + let s = String::from_abi(ret); + serde_json::from_str(&s) + } + } + + /// Returns the `f64` value of this JS value if it's an instance of a + /// number. + /// + /// If this JS value is not an instance of a number then this returns + /// `None`. + #[inline] + pub fn as_f64(&self) -> Option { + unsafe { FromWasmAbi::from_abi(__wbindgen_number_get(self.idx)) } + } + + /// Tests whether this JS value is a JS string. + #[inline] + pub fn is_string(&self) -> bool { + unsafe { __wbindgen_is_string(self.idx) == 1 } + } + + /// If this JS value is a string value, this function copies the JS string + /// value into wasm linear memory, encoded as UTF-8, and returns it as a + /// Rust `String`. + /// + /// To avoid the copying and re-encoding, consider the + /// `JsString::try_from()` function from [js-sys](https://docs.rs/js-sys) + /// instead. + /// + /// If this JS value is not an instance of a string or if it's not valid + /// utf-8 then this returns `None`. + /// + /// # UTF-16 vs UTF-8 + /// + /// JavaScript strings in general are encoded as UTF-16, but Rust strings + /// are encoded as UTF-8. This can cause the Rust string to look a bit + /// different than the JS string sometimes. For more details see the + /// [documentation about the `str` type][caveats] which contains a few + /// caveats about the encodings. + /// + /// [caveats]: https://rustwasm.github.io/docs/wasm-bindgen/reference/types/str.html + #[cfg(feature = "std")] + #[inline] + pub fn as_string(&self) -> Option { + unsafe { FromWasmAbi::from_abi(__wbindgen_string_get(self.idx)) } + } + + /// Returns the `bool` value of this JS value if it's an instance of a + /// boolean. + /// + /// If this JS value is not an instance of a boolean then this returns + /// `None`. + #[inline] + pub fn as_bool(&self) -> Option { + unsafe { + match __wbindgen_boolean_get(self.idx) { + 0 => Some(false), + 1 => Some(true), + _ => None, + } + } + } + + /// Tests whether this JS value is `null` + #[inline] + pub fn is_null(&self) -> bool { + unsafe { __wbindgen_is_null(self.idx) == 1 } + } + + /// Tests whether this JS value is `undefined` + #[inline] + pub fn is_undefined(&self) -> bool { + unsafe { __wbindgen_is_undefined(self.idx) == 1 } + } + + /// Tests whether the type of this JS value is `symbol` + #[inline] + pub fn is_symbol(&self) -> bool { + unsafe { __wbindgen_is_symbol(self.idx) == 1 } + } + + /// Tests whether `typeof self == "object" && self !== null`. + #[inline] + pub fn is_object(&self) -> bool { + unsafe { __wbindgen_is_object(self.idx) == 1 } + } + + /// Tests whether the type of this JS value is `function`. + #[inline] + pub fn is_function(&self) -> bool { + unsafe { __wbindgen_is_function(self.idx) == 1 } + } + + /// Tests whether the type of this JS value is `bigint`. + #[inline] + pub fn is_bigint(&self) -> bool { + unsafe { __wbindgen_is_bigint(self.idx) == 1 } + } + + /// Applies the unary `typeof` JS operator on a `JsValue`. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) + #[inline] + pub fn js_typeof(&self) -> JsValue { + unsafe { JsValue::_new(__wbindgen_typeof(self.idx)) } + } + + /// Applies the binary `in` JS operator on the two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in) + #[inline] + pub fn js_in(&self, obj: &JsValue) -> bool { + unsafe { __wbindgen_in(self.idx, obj.idx) == 1 } + } + + /// Tests whether the value is ["truthy"]. + /// + /// ["truthy"]: https://developer.mozilla.org/en-US/docs/Glossary/Truthy + #[inline] + pub fn is_truthy(&self) -> bool { + !self.is_falsy() + } + + /// Tests whether the value is ["falsy"]. + /// + /// ["falsy"]: https://developer.mozilla.org/en-US/docs/Glossary/Falsy + #[inline] + pub fn is_falsy(&self) -> bool { + unsafe { __wbindgen_is_falsy(self.idx) == 1 } + } + + /// Get a string representation of the JavaScript object for debugging. + #[cfg(feature = "std")] + fn as_debug_string(&self) -> String { + unsafe { + let mut ret = [0; 2]; + __wbindgen_debug_string(&mut ret, self.idx); + let data = Vec::from_raw_parts(ret[0] as *mut u8, ret[1], ret[1]); + String::from_utf8_unchecked(data) + } + } + + /// Compare two `JsValue`s for equality, using the `==` operator in JS. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality) + #[inline] + pub fn loose_eq(&self, other: &Self) -> bool { + unsafe { __wbindgen_jsval_loose_eq(self.idx, other.idx) != 0 } + } + + /// Applies the unary `~` JS operator on a `JsValue`. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_NOT) + #[inline] + pub fn bit_not(&self) -> JsValue { + unsafe { JsValue::_new(__wbindgen_bit_not(self.idx)) } + } + + /// Applies the binary `>>>` JS operator on the two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift) + #[inline] + pub fn unsigned_shr(&self, rhs: &Self) -> u32 { + unsafe { __wbindgen_unsigned_shr(self.idx, rhs.idx) } + } + + /// Applies the binary `/` JS operator on two `JsValue`s, catching and returning any `RangeError` thrown. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Division) + #[inline] + pub fn checked_div(&self, rhs: &Self) -> Self { + unsafe { JsValue::_new(__wbindgen_checked_div(self.idx, rhs.idx)) } + } + + /// Applies the binary `**` JS operator on the two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation) + #[inline] + pub fn pow(&self, rhs: &Self) -> Self { + unsafe { JsValue::_new(__wbindgen_pow(self.idx, rhs.idx)) } + } + + /// Applies the binary `<` JS operator on the two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Less_than) + #[inline] + pub fn lt(&self, other: &Self) -> bool { + unsafe { __wbindgen_lt(self.idx, other.idx) == 1 } + } + + /// Applies the binary `<=` JS operator on the two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Less_than_or_equal) + #[inline] + pub fn le(&self, other: &Self) -> bool { + unsafe { __wbindgen_le(self.idx, other.idx) == 1 } + } + + /// Applies the binary `>=` JS operator on the two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than_or_equal) + #[inline] + pub fn ge(&self, other: &Self) -> bool { + unsafe { __wbindgen_ge(self.idx, other.idx) == 1 } + } + + /// Applies the binary `>` JS operator on the two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than) + #[inline] + pub fn gt(&self, other: &Self) -> bool { + unsafe { __wbindgen_gt(self.idx, other.idx) == 1 } + } + + /// Applies the unary `+` JS operator on a `JsValue`. Can throw. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus) + #[inline] + pub fn unchecked_into_f64(&self) -> f64 { + unsafe { __wbindgen_as_number(self.idx) } + } +} + +impl PartialEq for JsValue { + /// Compares two `JsValue`s for equality, using the `===` operator in JS. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) + #[inline] + fn eq(&self, other: &Self) -> bool { + unsafe { __wbindgen_jsval_eq(self.idx, other.idx) != 0 } + } +} + +impl PartialEq for JsValue { + #[inline] + fn eq(&self, other: &bool) -> bool { + self.as_bool() == Some(*other) + } +} + +impl PartialEq for JsValue { + #[inline] + fn eq(&self, other: &str) -> bool { + *self == JsValue::from_str(other) + } +} + +impl<'a> PartialEq<&'a str> for JsValue { + #[inline] + fn eq(&self, other: &&'a str) -> bool { + >::eq(self, other) + } +} + +if_std! { + impl PartialEq for JsValue { + #[inline] + fn eq(&self, other: &String) -> bool { + >::eq(self, other) + } + } + impl<'a> PartialEq<&'a String> for JsValue { + #[inline] + fn eq(&self, other: &&'a String) -> bool { + >::eq(self, other) + } + } +} + +macro_rules! forward_deref_unop { + (impl $imp:ident, $method:ident for $t:ty) => { + impl $imp for $t { + type Output = <&'static $t as $imp>::Output; + + #[inline] + fn $method(self) -> <&'static $t as $imp>::Output { + $imp::$method(&self) + } + } + }; +} + +macro_rules! forward_deref_binop { + (impl $imp:ident, $method:ident for $t:ty) => { + impl<'a> $imp<$t> for &'a $t { + type Output = <&'static $t as $imp<&'static $t>>::Output; + + #[inline] + fn $method(self, other: $t) -> <&'static $t as $imp<&'static $t>>::Output { + $imp::$method(self, &other) + } + } + + impl $imp<&$t> for $t { + type Output = <&'static $t as $imp<&'static $t>>::Output; + + #[inline] + fn $method(self, other: &$t) -> <&'static $t as $imp<&'static $t>>::Output { + $imp::$method(&self, other) + } + } + + impl $imp<$t> for $t { + type Output = <&'static $t as $imp<&'static $t>>::Output; + + #[inline] + fn $method(self, other: $t) -> <&'static $t as $imp<&'static $t>>::Output { + $imp::$method(&self, &other) + } + } + }; +} + +impl Not for &JsValue { + type Output = bool; + + /// Applies the `!` JS operator on a `JsValue`. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT) + #[inline] + fn not(self) -> Self::Output { + JsValue::is_falsy(self) + } +} + +forward_deref_unop!(impl Not, not for JsValue); + +impl TryFrom for f64 { + type Error = JsValue; + + /// Applies the unary `+` JS operator on a `JsValue`. + /// Returns the numeric result on success, or the JS error value on error. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus) + #[inline] + fn try_from(val: JsValue) -> Result { + f64::try_from(&val) + } +} + +impl TryFrom<&JsValue> for f64 { + type Error = JsValue; + + /// Applies the unary `+` JS operator on a `JsValue`. + /// Returns the numeric result on success, or the JS error value on error. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus) + #[inline] + fn try_from(val: &JsValue) -> Result { + let jsval = unsafe { JsValue::_new(__wbindgen_try_into_number(val.idx)) }; + return match jsval.as_f64() { + Some(num) => Ok(num), + None => Err(jsval), + }; + } +} + +impl Neg for &JsValue { + type Output = JsValue; + + /// Applies the unary `-` JS operator on a `JsValue`. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_negation) + #[inline] + fn neg(self) -> Self::Output { + unsafe { JsValue::_new(__wbindgen_neg(self.idx)) } + } +} + +forward_deref_unop!(impl Neg, neg for JsValue); + +impl BitAnd for &JsValue { + type Output = JsValue; + + /// Applies the binary `&` JS operator on two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND) + #[inline] + fn bitand(self, rhs: Self) -> Self::Output { + unsafe { JsValue::_new(__wbindgen_bit_and(self.idx, rhs.idx)) } + } +} + +forward_deref_binop!(impl BitAnd, bitand for JsValue); + +impl BitOr for &JsValue { + type Output = JsValue; + + /// Applies the binary `|` JS operator on two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR) + #[inline] + fn bitor(self, rhs: Self) -> Self::Output { + unsafe { JsValue::_new(__wbindgen_bit_or(self.idx, rhs.idx)) } + } +} + +forward_deref_binop!(impl BitOr, bitor for JsValue); + +impl BitXor for &JsValue { + type Output = JsValue; + + /// Applies the binary `^` JS operator on two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR) + #[inline] + fn bitxor(self, rhs: Self) -> Self::Output { + unsafe { JsValue::_new(__wbindgen_bit_xor(self.idx, rhs.idx)) } + } +} + +forward_deref_binop!(impl BitXor, bitxor for JsValue); + +impl Shl for &JsValue { + type Output = JsValue; + + /// Applies the binary `<<` JS operator on two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift) + #[inline] + fn shl(self, rhs: Self) -> Self::Output { + unsafe { JsValue::_new(__wbindgen_shl(self.idx, rhs.idx)) } + } +} + +forward_deref_binop!(impl Shl, shl for JsValue); + +impl Shr for &JsValue { + type Output = JsValue; + + /// Applies the binary `>>` JS operator on two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift) + #[inline] + fn shr(self, rhs: Self) -> Self::Output { + unsafe { JsValue::_new(__wbindgen_shr(self.idx, rhs.idx)) } + } +} + +forward_deref_binop!(impl Shr, shr for JsValue); + +impl Add for &JsValue { + type Output = JsValue; + + /// Applies the binary `+` JS operator on two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition) + #[inline] + fn add(self, rhs: Self) -> Self::Output { + unsafe { JsValue::_new(__wbindgen_add(self.idx, rhs.idx)) } + } +} + +forward_deref_binop!(impl Add, add for JsValue); + +impl Sub for &JsValue { + type Output = JsValue; + + /// Applies the binary `-` JS operator on two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction) + #[inline] + fn sub(self, rhs: Self) -> Self::Output { + unsafe { JsValue::_new(__wbindgen_sub(self.idx, rhs.idx)) } + } +} + +forward_deref_binop!(impl Sub, sub for JsValue); + +impl Div for &JsValue { + type Output = JsValue; + + /// Applies the binary `/` JS operator on two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Division) + #[inline] + fn div(self, rhs: Self) -> Self::Output { + unsafe { JsValue::_new(__wbindgen_div(self.idx, rhs.idx)) } + } +} + +forward_deref_binop!(impl Div, div for JsValue); + +impl Mul for &JsValue { + type Output = JsValue; + + /// Applies the binary `*` JS operator on two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Multiplication) + #[inline] + fn mul(self, rhs: Self) -> Self::Output { + unsafe { JsValue::_new(__wbindgen_mul(self.idx, rhs.idx)) } + } +} + +forward_deref_binop!(impl Mul, mul for JsValue); + +impl Rem for &JsValue { + type Output = JsValue; + + /// Applies the binary `%` JS operator on two `JsValue`s. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder) + #[inline] + fn rem(self, rhs: Self) -> Self::Output { + unsafe { JsValue::_new(__wbindgen_rem(self.idx, rhs.idx)) } + } +} + +forward_deref_binop!(impl Rem, rem for JsValue); + +impl<'a> From<&'a str> for JsValue { + #[inline] + fn from(s: &'a str) -> JsValue { + JsValue::from_str(s) + } +} + +if_std! { + impl<'a> From<&'a String> for JsValue { + #[inline] + fn from(s: &'a String) -> JsValue { + JsValue::from_str(s) + } + } + + impl From for JsValue { + #[inline] + fn from(s: String) -> JsValue { + JsValue::from_str(&s) + } + } +} + +impl From for JsValue { + #[inline] + fn from(s: bool) -> JsValue { + JsValue::from_bool(s) + } +} + +impl<'a, T> From<&'a T> for JsValue +where + T: JsCast, +{ + #[inline] + fn from(s: &'a T) -> JsValue { + s.as_ref().clone() + } +} + +impl From> for JsValue +where + JsValue: From, +{ + #[inline] + fn from(s: Option) -> JsValue { + match s { + Some(s) => s.into(), + None => JsValue::undefined(), + } + } +} + +impl JsCast for JsValue { + // everything is a `JsValue`! + #[inline] + fn instanceof(_val: &JsValue) -> bool { + true + } + #[inline] + fn unchecked_from_js(val: JsValue) -> Self { + val + } + #[inline] + fn unchecked_from_js_ref(val: &JsValue) -> &Self { + val + } +} + +impl AsRef for JsValue { + #[inline] + fn as_ref(&self) -> &JsValue { + self + } +} + +macro_rules! numbers { + ($($n:ident)*) => ($( + impl PartialEq<$n> for JsValue { + #[inline] + fn eq(&self, other: &$n) -> bool { + self.as_f64() == Some(f64::from(*other)) + } + } + + impl From<$n> for JsValue { + #[inline] + fn from(n: $n) -> JsValue { + JsValue::from_f64(n.into()) + } + } + )*) +} + +numbers! { i8 u8 i16 u16 i32 u32 f32 f64 } + +macro_rules! big_numbers { + (|$arg:ident|, $($n:ident = $handle:expr,)*) => ($( + impl PartialEq<$n> for JsValue { + #[inline] + fn eq(&self, other: &$n) -> bool { + self == &JsValue::from(*other) + } + } + + impl From<$n> for JsValue { + #[inline] + fn from($arg: $n) -> JsValue { + unsafe { JsValue::_new($handle) } + } + } + )*) +} + +fn bigint_get_as_i64(v: &JsValue) -> Option { + unsafe { Option::from_abi(__wbindgen_bigint_get_as_i64(v.idx)) } +} + +macro_rules! try_from_for_num64 { + ($ty:ty) => { + impl TryFrom for $ty { + type Error = JsValue; + + #[inline] + fn try_from(v: JsValue) -> Result { + bigint_get_as_i64(&v) + // Reinterpret bits; ABI-wise this is safe to do and allows us to avoid + // having separate intrinsics per signed/unsigned types. + .map(|as_i64| as_i64 as Self) + // Double-check that we didn't truncate the bigint to 64 bits. + .filter(|as_self| v == *as_self) + // Not a bigint or not in range. + .ok_or(v) + } + } + }; +} + +try_from_for_num64!(i64); +try_from_for_num64!(u64); + +macro_rules! try_from_for_num128 { + ($ty:ty, $hi_ty:ty) => { + impl TryFrom for $ty { + type Error = JsValue; + + #[inline] + fn try_from(v: JsValue) -> Result { + // Truncate the bigint to 64 bits, this will give us the lower part. + let lo = match bigint_get_as_i64(&v) { + // The lower part must be interpreted as unsigned in both i128 and u128. + Some(lo) => lo as u64, + // Not a bigint. + None => return Err(v), + }; + // Now we know it's a bigint, so we can safely use `>> 64n` without + // worrying about a JS exception on type mismatch. + let hi = v >> JsValue::from(64_u64); + // The high part is the one we want checked against a 64-bit range. + // If it fits, then our original number is in the 128-bit range. + let hi = <$hi_ty>::try_from(hi)?; + Ok(Self::from(hi) << 64 | Self::from(lo)) + } + } + }; +} + +try_from_for_num128!(i128, i64); +try_from_for_num128!(u128, u64); + +big_numbers! { + |n|, + i64 = __wbindgen_bigint_from_i64(n), + u64 = __wbindgen_bigint_from_u64(n), + i128 = __wbindgen_bigint_from_i128((n >> 64) as i64, n as u64), + u128 = __wbindgen_bigint_from_u128((n >> 64) as u64, n as u64), +} + +// `usize` and `isize` have to be treated a bit specially, because we know that +// they're 32-bit but the compiler conservatively assumes they might be bigger. +// So, we have to manually forward to the `u32`/`i32` versions. +impl PartialEq for JsValue { + #[inline] + fn eq(&self, other: &usize) -> bool { + *self == (*other as u32) + } +} + +impl From for JsValue { + #[inline] + fn from(n: usize) -> Self { + Self::from(n as u32) + } +} + +impl PartialEq for JsValue { + #[inline] + fn eq(&self, other: &isize) -> bool { + *self == (*other as i32) + } +} + +impl From for JsValue { + #[inline] + fn from(n: isize) -> Self { + Self::from(n as i32) + } +} + +externs! { + #[link(wasm_import_module = "__wbindgen_placeholder__")] + extern "C" { + fn __wbindgen_object_clone_ref(idx: u32) -> u32; + fn __wbindgen_object_drop_ref(idx: u32) -> (); + + fn __wbindgen_string_new(ptr: *const u8, len: usize) -> u32; + fn __wbindgen_number_new(f: f64) -> u32; + fn __wbindgen_bigint_from_str(ptr: *const u8, len: usize) -> u32; + fn __wbindgen_bigint_from_i64(n: i64) -> u32; + fn __wbindgen_bigint_from_u64(n: u64) -> u32; + fn __wbindgen_bigint_from_i128(hi: i64, lo: u64) -> u32; + fn __wbindgen_bigint_from_u128(hi: u64, lo: u64) -> u32; + fn __wbindgen_symbol_named_new(ptr: *const u8, len: usize) -> u32; + fn __wbindgen_symbol_anonymous_new() -> u32; + + fn __wbindgen_externref_heap_live_count() -> u32; + + fn __wbindgen_is_null(idx: u32) -> u32; + fn __wbindgen_is_undefined(idx: u32) -> u32; + fn __wbindgen_is_symbol(idx: u32) -> u32; + fn __wbindgen_is_object(idx: u32) -> u32; + fn __wbindgen_is_function(idx: u32) -> u32; + fn __wbindgen_is_string(idx: u32) -> u32; + fn __wbindgen_is_bigint(idx: u32) -> u32; + fn __wbindgen_typeof(idx: u32) -> u32; + + fn __wbindgen_in(prop: u32, obj: u32) -> u32; + + fn __wbindgen_is_falsy(idx: u32) -> u32; + fn __wbindgen_as_number(idx: u32) -> f64; + fn __wbindgen_try_into_number(idx: u32) -> u32; + fn __wbindgen_neg(idx: u32) -> u32; + fn __wbindgen_bit_and(a: u32, b: u32) -> u32; + fn __wbindgen_bit_or(a: u32, b: u32) -> u32; + fn __wbindgen_bit_xor(a: u32, b: u32) -> u32; + fn __wbindgen_bit_not(idx: u32) -> u32; + fn __wbindgen_shl(a: u32, b: u32) -> u32; + fn __wbindgen_shr(a: u32, b: u32) -> u32; + fn __wbindgen_unsigned_shr(a: u32, b: u32) -> u32; + fn __wbindgen_add(a: u32, b: u32) -> u32; + fn __wbindgen_sub(a: u32, b: u32) -> u32; + fn __wbindgen_div(a: u32, b: u32) -> u32; + fn __wbindgen_checked_div(a: u32, b: u32) -> u32; + fn __wbindgen_mul(a: u32, b: u32) -> u32; + fn __wbindgen_rem(a: u32, b: u32) -> u32; + fn __wbindgen_pow(a: u32, b: u32) -> u32; + fn __wbindgen_lt(a: u32, b: u32) -> u32; + fn __wbindgen_le(a: u32, b: u32) -> u32; + fn __wbindgen_ge(a: u32, b: u32) -> u32; + fn __wbindgen_gt(a: u32, b: u32) -> u32; + + fn __wbindgen_number_get(idx: u32) -> WasmOption; + fn __wbindgen_boolean_get(idx: u32) -> u32; + fn __wbindgen_string_get(idx: u32) -> WasmSlice; + fn __wbindgen_bigint_get_as_i64(idx: u32) -> WasmOption; + + fn __wbindgen_debug_string(ret: *mut [usize; 2], idx: u32) -> (); + + fn __wbindgen_throw(a: *const u8, b: usize) -> !; + fn __wbindgen_rethrow(a: u32) -> !; + fn __wbindgen_error_new(a: *const u8, b: usize) -> u32; + + fn __wbindgen_cb_drop(idx: u32) -> u32; + + fn __wbindgen_describe(v: u32) -> (); + fn __wbindgen_describe_closure(a: u32, b: u32, c: u32) -> u32; + + fn __wbindgen_json_parse(ptr: *const u8, len: usize) -> u32; + fn __wbindgen_json_serialize(idx: u32) -> WasmSlice; + fn __wbindgen_jsval_eq(a: u32, b: u32) -> u32; + fn __wbindgen_jsval_loose_eq(a: u32, b: u32) -> u32; + + fn __wbindgen_not(idx: u32) -> u32; + + fn __wbindgen_memory() -> u32; + fn __wbindgen_module() -> u32; + fn __wbindgen_function_table() -> u32; + } +} + +impl Clone for JsValue { + #[inline] + fn clone(&self) -> JsValue { + unsafe { + let idx = __wbindgen_object_clone_ref(self.idx); + JsValue::_new(idx) + } + } +} + +#[cfg(feature = "std")] +impl fmt::Debug for JsValue { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "JsValue({})", self.as_debug_string()) + } +} + +#[cfg(not(feature = "std"))] +impl fmt::Debug for JsValue { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("JsValue") + } +} + +impl Drop for JsValue { + #[inline] + fn drop(&mut self) { + unsafe { + // We definitely should never drop anything in the stack area + debug_assert!(self.idx >= JSIDX_OFFSET, "free of stack slot {}", self.idx); + + // Otherwise if we're not dropping one of our reserved values, + // actually call the intrinsic. See #1054 for eventually removing + // this branch. + if self.idx >= JSIDX_RESERVED { + __wbindgen_object_drop_ref(self.idx); + } + } + } +} + +impl Default for JsValue { + fn default() -> Self { + Self::UNDEFINED + } +} + +/// Wrapper type for imported statics. +/// +/// This type is used whenever a `static` is imported from a JS module, for +/// example this import: +/// +/// ```ignore +/// #[wasm_bindgen] +/// extern "C" { +/// static console: JsValue; +/// } +/// ``` +/// +/// will generate in Rust a value that looks like: +/// +/// ```ignore +/// static console: JsStatic = ...; +/// ``` +/// +/// This type implements `Deref` to the inner type so it's typically used as if +/// it were `&T`. +#[cfg(feature = "std")] +pub struct JsStatic { + #[doc(hidden)] + pub __inner: &'static std::thread::LocalKey, +} + +#[cfg(feature = "std")] +impl Deref for JsStatic { + type Target = T; + fn deref(&self) -> &T { + // We know that our tls key is never overwritten after initialization, + // so it should be safe (on that axis at least) to hand out a reference + // that lives longer than the closure below. + // + // FIXME: this is not sound if we ever implement thread exit hooks on + // wasm, as the pointer will eventually be invalidated but you can get + // `&'static T` from this interface. We... probably need to deprecate + // and/or remove this interface nowadays. + unsafe { self.__inner.with(|ptr| &*(ptr as *const T)) } + } +} + +#[cold] +#[inline(never)] +#[deprecated(note = "renamed to `throw_str`")] +#[doc(hidden)] +pub fn throw(s: &str) -> ! { + throw_str(s) +} + +/// Throws a JS exception. +/// +/// This function will throw a JS exception with the message provided. The +/// function will not return as the wasm stack will be popped when the exception +/// is thrown. +/// +/// Note that it is very easy to leak memory with this function because this +/// function, unlike `panic!` on other platforms, **will not run destructors**. +/// It's recommended to return a `Result` where possible to avoid the worry of +/// leaks. +#[cold] +#[inline(never)] +pub fn throw_str(s: &str) -> ! { + unsafe { + __wbindgen_throw(s.as_ptr(), s.len()); + } +} + +/// Rethrow a JS exception +/// +/// This function will throw a JS exception with the JS value provided. This +/// function will not return and the wasm stack will be popped until the point +/// of entry of wasm itself. +/// +/// Note that it is very easy to leak memory with this function because this +/// function, unlike `panic!` on other platforms, **will not run destructors**. +/// It's recommended to return a `Result` where possible to avoid the worry of +/// leaks. +#[cold] +#[inline(never)] +pub fn throw_val(s: JsValue) -> ! { + unsafe { + let idx = s.idx; + mem::forget(s); + __wbindgen_rethrow(idx); + } +} + +/// Get the count of live `externref`s / `JsValue`s in `wasm-bindgen`'s heap. +/// +/// ## Usage +/// +/// This is intended for debugging and writing tests. +/// +/// To write a test that asserts against unnecessarily keeping `anref`s / +/// `JsValue`s alive: +/// +/// * get an initial live count, +/// +/// * perform some series of operations or function calls that should clean up +/// after themselves, and should not keep holding onto `externref`s / `JsValue`s +/// after completion, +/// +/// * get the final live count, +/// +/// * and assert that the initial and final counts are the same. +/// +/// ## What is Counted +/// +/// Note that this only counts the *owned* `externref`s / `JsValue`s that end up in +/// `wasm-bindgen`'s heap. It does not count borrowed `externref`s / `JsValue`s +/// that are on its stack. +/// +/// For example, these `JsValue`s are accounted for: +/// +/// ```ignore +/// #[wasm_bindgen] +/// pub fn my_function(this_is_counted: JsValue) { +/// let also_counted = JsValue::from_str("hi"); +/// assert!(wasm_bindgen::externref_heap_live_count() >= 2); +/// } +/// ``` +/// +/// While this borrowed `JsValue` ends up on the stack, not the heap, and +/// therefore is not accounted for: +/// +/// ```ignore +/// #[wasm_bindgen] +/// pub fn my_other_function(this_is_not_counted: &JsValue) { +/// // ... +/// } +/// ``` +pub fn externref_heap_live_count() -> u32 { + unsafe { __wbindgen_externref_heap_live_count() } +} + +#[doc(hidden)] +pub fn anyref_heap_live_count() -> u32 { + externref_heap_live_count() +} + +/// An extension trait for `Option` and `Result` for unwrapping 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. +/// +/// # Example +/// +/// ``` +/// use wasm_bindgen::prelude::*; +/// +/// // If the value is `Option::Some` or `Result::Ok`, then we just get the +/// // contained `T` value. +/// let x = Some(42); +/// assert_eq!(x.unwrap_throw(), 42); +/// +/// let y: Option = None; +/// +/// // This call would throw an error to JS! +/// // +/// // y.unwrap_throw() +/// // +/// // And this call would throw an error to JS with a custom error message! +/// // +/// // y.expect_throw("woopsie daisy!") +/// ``` +pub trait UnwrapThrowExt: Sized { + /// Unwrap this `Option` or `Result`, but instead of panicking on failure, + /// throw an exception to JavaScript. + fn unwrap_throw(self) -> T { + self.expect_throw("`unwrap_throw` failed") + } + + /// Unwrap this container's `T` value, or throw an error to JS with the + /// given message if the `T` value is unavailable (e.g. an `Option` is + /// `None`). + fn expect_throw(self, message: &str) -> T; +} + +impl UnwrapThrowExt for Option { + fn expect_throw(self, message: &str) -> T { + if cfg!(all(target_arch = "wasm32", not(target_os = "emscripten"))) { + match self { + Some(val) => val, + None => throw_str(message), + } + } else { + self.expect(message) + } + } +} + +impl UnwrapThrowExt for Result +where + E: core::fmt::Debug, +{ + fn expect_throw(self, message: &str) -> T { + if cfg!(all(target_arch = "wasm32", not(target_os = "emscripten"))) { + match self { + Ok(val) => val, + Err(_) => throw_str(message), + } + } else { + self.expect(message) + } + } +} + +/// Returns a handle to this wasm instance's `WebAssembly.Module` +/// +/// Note that this is only available when the final wasm app is built with +/// `--target no-modules`, it's not recommended to rely on this API yet! This is +/// largely just an experimental addition to enable threading demos. Using this +/// may prevent your wasm module from building down the road. +#[doc(hidden)] +pub fn module() -> JsValue { + unsafe { JsValue::_new(__wbindgen_module()) } +} + +/// Returns a handle to this wasm instance's `WebAssembly.Memory` +pub fn memory() -> JsValue { + unsafe { JsValue::_new(__wbindgen_memory()) } +} + +/// Returns a handle to this wasm instance's `WebAssembly.Table` which is the +/// indirect function table used by Rust +pub fn function_table() -> JsValue { + unsafe { JsValue::_new(__wbindgen_function_table()) } +} + +#[doc(hidden)] +pub mod __rt { + use crate::JsValue; + use core::cell::{Cell, UnsafeCell}; + use core::ops::{Deref, DerefMut}; + + pub extern crate core; + #[cfg(feature = "std")] + pub extern crate std; + + #[macro_export] + #[doc(hidden)] + #[cfg(feature = "std")] + macro_rules! __wbindgen_if_not_std { + ($($i:item)*) => {}; + } + + #[macro_export] + #[doc(hidden)] + #[cfg(not(feature = "std"))] + macro_rules! __wbindgen_if_not_std { + ($($i:item)*) => ($($i)*) + } + + #[inline] + pub fn assert_not_null(s: *mut T) { + if s.is_null() { + throw_null(); + } + } + + #[cold] + #[inline(never)] + fn throw_null() -> ! { + super::throw_str("null pointer passed to rust"); + } + + /// A vendored version of `RefCell` from the standard library. + /// + /// Now why, you may ask, would we do that? Surely `RefCell` in libstd is + /// quite good. And you're right, it is indeed quite good! Functionally + /// nothing more is needed from `RefCell` in the standard library but for + /// now this crate is also sort of optimizing for compiled code size. + /// + /// One major factor to larger binaries in Rust is when a panic happens. + /// Panicking in the standard library involves a fair bit of machinery + /// (formatting, panic hooks, synchronization, etc). It's all worthwhile if + /// you need it but for something like `WasmRefCell` here we don't actually + /// need all that! + /// + /// This is just a wrapper around all Rust objects passed to JS intended to + /// guard accidental reentrancy, so this vendored version is intended solely + /// to not panic in libstd. Instead when it "panics" it calls our `throw` + /// function in this crate which raises an error in JS. + pub struct WasmRefCell { + borrow: Cell, + value: UnsafeCell, + } + + impl WasmRefCell { + pub fn new(value: T) -> WasmRefCell + where + T: Sized, + { + WasmRefCell { + value: UnsafeCell::new(value), + borrow: Cell::new(0), + } + } + + pub fn get_mut(&mut self) -> &mut T { + unsafe { &mut *self.value.get() } + } + + pub fn borrow(&self) -> Ref { + unsafe { + if self.borrow.get() == usize::max_value() { + borrow_fail(); + } + self.borrow.set(self.borrow.get() + 1); + Ref { + value: &*self.value.get(), + borrow: &self.borrow, + } + } + } + + pub fn borrow_mut(&self) -> RefMut { + unsafe { + if self.borrow.get() != 0 { + borrow_fail(); + } + self.borrow.set(usize::max_value()); + RefMut { + value: &mut *self.value.get(), + borrow: &self.borrow, + } + } + } + + pub fn into_inner(self) -> T + where + T: Sized, + { + self.value.into_inner() + } + } + + pub struct Ref<'b, T: ?Sized + 'b> { + value: &'b T, + borrow: &'b Cell, + } + + impl<'b, T: ?Sized> Deref for Ref<'b, T> { + type Target = T; + + #[inline] + fn deref(&self) -> &T { + self.value + } + } + + impl<'b, T: ?Sized> Drop for Ref<'b, T> { + fn drop(&mut self) { + self.borrow.set(self.borrow.get() - 1); + } + } + + pub struct RefMut<'b, T: ?Sized + 'b> { + value: &'b mut T, + borrow: &'b Cell, + } + + impl<'b, T: ?Sized> Deref for RefMut<'b, T> { + type Target = T; + + #[inline] + fn deref(&self) -> &T { + self.value + } + } + + impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> { + #[inline] + fn deref_mut(&mut self) -> &mut T { + self.value + } + } + + impl<'b, T: ?Sized> Drop for RefMut<'b, T> { + fn drop(&mut self) { + self.borrow.set(0); + } + } + + fn borrow_fail() -> ! { + super::throw_str( + "recursive use of an object detected which would lead to \ + unsafe aliasing in rust", + ); + } + + if_std! { + use std::alloc::{alloc, dealloc, realloc, Layout}; + use std::mem; + + #[no_mangle] + pub extern "C" fn __wbindgen_malloc(size: usize) -> *mut u8 { + let align = mem::align_of::(); + if let Ok(layout) = Layout::from_size_align(size, align) { + unsafe { + if layout.size() > 0 { + let ptr = alloc(layout); + if !ptr.is_null() { + return ptr + } + } else { + return align as *mut u8 + } + } + } + + malloc_failure(); + } + + #[no_mangle] + pub unsafe extern "C" fn __wbindgen_realloc(ptr: *mut u8, old_size: usize, new_size: usize) -> *mut u8 { + let align = mem::align_of::(); + debug_assert!(old_size > 0); + debug_assert!(new_size > 0); + if let Ok(layout) = Layout::from_size_align(old_size, align) { + let ptr = realloc(ptr, layout, new_size); + if !ptr.is_null() { + return ptr + } + } + malloc_failure(); + } + + #[cold] + fn malloc_failure() -> ! { + if cfg!(debug_assertions) { + super::throw_str("invalid malloc request") + } else { + std::process::abort(); + } + } + + #[no_mangle] + pub unsafe extern "C" fn __wbindgen_free(ptr: *mut u8, size: usize) { + // This happens for zero-length slices, and in that case `ptr` is + // likely bogus so don't actually send this to the system allocator + if size == 0 { + return + } + let align = mem::align_of::(); + let layout = Layout::from_size_align_unchecked(size, align); + dealloc(ptr, layout); + } + } + + /// This is a curious function necessary to get wasm-bindgen working today, + /// and it's a bit of an unfortunate hack. + /// + /// The general problem is that somehow we need the above two symbols to + /// exist in the final output binary (__wbindgen_malloc and + /// __wbindgen_free). These symbols may be called by JS for various + /// bindings, so we for sure need to make sure they're exported. + /// + /// The problem arises, though, when what if no Rust code uses the symbols? + /// For all intents and purposes it looks to LLVM and the linker like the + /// above two symbols are dead code, so they're completely discarded! + /// + /// Specifically what happens is this: + /// + /// * The above two symbols are generated into some object file inside of + /// libwasm_bindgen.rlib + /// * The linker, LLD, will not load this object file unless *some* symbol + /// is loaded from the object. In this case, if the Rust code never calls + /// __wbindgen_malloc or __wbindgen_free then the symbols never get linked + /// in. + /// * Later when `wasm-bindgen` attempts to use the symbols they don't + /// exist, causing an error. + /// + /// This function is a weird hack for this problem. We inject a call to this + /// function in all generated code. Usage of this function should then + /// ensure that the above two intrinsics are translated. + /// + /// Due to how rustc creates object files this function (and anything inside + /// it) will be placed into the same object file as the two intrinsics + /// above. That means if this function is called and referenced we'll pull + /// in the object file and link the intrinsics. + /// + /// Ideas for how to improve this are most welcome! + pub fn link_mem_intrinsics() { + crate::externref::link_intrinsics(); + } + + static mut GLOBAL_EXNDATA: [u32; 2] = [0; 2]; + + #[no_mangle] + pub unsafe extern "C" fn __wbindgen_exn_store(idx: u32) { + debug_assert_eq!(GLOBAL_EXNDATA[0], 0); + GLOBAL_EXNDATA[0] = 1; + GLOBAL_EXNDATA[1] = idx; + } + + pub fn take_last_exception() -> Result<(), super::JsValue> { + unsafe { + let ret = if GLOBAL_EXNDATA[0] == 1 { + Err(super::JsValue::_new(GLOBAL_EXNDATA[1])) + } else { + Ok(()) + }; + GLOBAL_EXNDATA[0] = 0; + GLOBAL_EXNDATA[1] = 0; + return ret; + } + } + + /// An internal helper trait for usage in `#[wasm_bindgen]` on `async` + /// functions to convert the return value of the function to + /// `Result` which is what we'll return to JS (where an + /// error is a failed future). + pub trait IntoJsResult { + fn into_js_result(self) -> Result; + } + + impl IntoJsResult for () { + fn into_js_result(self) -> Result { + Ok(JsValue::undefined()) + } + } + + impl> IntoJsResult for T { + fn into_js_result(self) -> Result { + Ok(self.into()) + } + } + + impl, E: Into> IntoJsResult for Result { + fn into_js_result(self) -> Result { + match self { + Ok(e) => Ok(e.into()), + Err(e) => Err(e.into()), + } + } + } + + impl> IntoJsResult for Result<(), E> { + fn into_js_result(self) -> Result { + match self { + Ok(()) => Ok(JsValue::undefined()), + Err(e) => Err(e.into()), + } + } + } + + /// An internal helper trait for usage in `#[wasm_bindgen(start)]` + /// functions to throw the error (if it is `Err`). + pub trait Start { + fn start(self); + } + + impl Start for () { + #[inline] + fn start(self) {} + } + + impl> Start for Result<(), E> { + #[inline] + fn start(self) { + if let Err(e) = self { + crate::throw_val(e.into()); + } + } + } +} + +/// A wrapper type around slices and vectors for binding the `Uint8ClampedArray` +/// array in JS. +/// +/// If you need to invoke a JS API which must take `Uint8ClampedArray` array, +/// then you can define it as taking one of these types: +/// +/// * `Clamped<&[u8]>` +/// * `Clamped<&mut [u8]>` +/// * `Clamped>` +/// +/// All of these types will show up as `Uint8ClampedArray` in JS and will have +/// different forms of ownership in Rust. +#[derive(Copy, Clone, PartialEq, Debug, Eq)] +pub struct Clamped(pub T); + +impl Deref for Clamped { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +impl DerefMut for Clamped { + fn deref_mut(&mut self) -> &mut T { + &mut self.0 + } +} + +/// Convenience type for use on exported `fn() -> Result` functions, where you wish to +/// throw a JavaScript `Error` object. +/// +/// You can get wasm_bindgen to throw basic errors by simply returning +/// `Err(JsError::new("message"))` from such a function. +/// +/// For more complex error handling, `JsError` implements `From where T: std::error::Error` by +/// converting it to a string, so you can use it with `?`. Many Rust error types already do this, +/// and you can use [`thiserror`](https://crates.io/crates/thiserror) to derive Display +/// implementations easily or use any number of boxed error types that implement it already. +/// +/// +/// To allow JavaScript code to catch only your errors, you may wish to add a subclass of `Error` +/// in a JS module, and then implement `Into` directly on a type and instantiate that +/// subclass. In that case, you would not need `JsError` at all. +/// +/// ### Basic example +/// +/// ```rust,no_run +/// use wasm_bindgen::prelude::*; +/// +/// #[wasm_bindgen] +/// pub fn throwing_function() -> Result<(), JsError> { +/// Err(JsError::new("message")) +/// } +/// ``` +/// +/// ### Complex Example +/// +/// ```rust,no_run +/// use wasm_bindgen::prelude::*; +/// +/// #[derive(Debug, Clone)] +/// enum MyErrorType { +/// SomeError, +/// } +/// +/// use core::fmt; +/// impl std::error::Error for MyErrorType {} +/// impl fmt::Display for MyErrorType { +/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +/// write!(f, "display implementation becomes the error message") +/// } +/// } +/// +/// fn internal_api() -> Result<(), MyErrorType> { +/// Err(MyErrorType::SomeError) +/// } +/// +/// #[wasm_bindgen] +/// pub fn throwing_function() -> Result<(), JsError> { +/// internal_api()?; +/// Ok(()) +/// } +/// +/// ``` +#[derive(Clone)] +pub struct JsError { + value: JsValue, +} + +impl JsError { + /// Construct a JavaScript `Error` object with a string message + #[inline] + pub fn new(s: &str) -> JsError { + Self { + value: unsafe { JsValue::_new(crate::__wbindgen_error_new(s.as_ptr(), s.len())) }, + } + } +} + +if_std! { + impl From for JsError + where + E: std::error::Error, + { + fn from(error: E) -> Self { + JsError::new(&error.to_string()) + } + } +} + +impl From for JsValue { + fn from(error: JsError) -> Self { + error.value + } +} diff --git a/vendor/wasm-bindgen/tests/headless/externref_heap_live_count.rs b/vendor/wasm-bindgen/tests/headless/externref_heap_live_count.rs new file mode 100644 index 000000000..c344febbf --- /dev/null +++ b/vendor/wasm-bindgen/tests/headless/externref_heap_live_count.rs @@ -0,0 +1,20 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +// This test is in the headless suite so that we can test the `externref` table +// implementation of `externref_heap_live_count` (as opposed to the JS `heap` +// implementation) in Firefox. +#[wasm_bindgen_test] +fn test_externref_heap_live_count() { + let initial = wasm_bindgen::externref_heap_live_count(); + + let after_alloc = { + let _vals: Vec<_> = (0..10).map(JsValue::from).collect(); + wasm_bindgen::externref_heap_live_count() + }; + + let after_dealloc = wasm_bindgen::externref_heap_live_count(); + + assert_eq!(initial, after_dealloc); + assert_eq!(initial + 10, after_alloc); +} diff --git a/vendor/wasm-bindgen/tests/headless/main.js b/vendor/wasm-bindgen/tests/headless/main.js new file mode 100644 index 000000000..cfedddf93 --- /dev/null +++ b/vendor/wasm-bindgen/tests/headless/main.js @@ -0,0 +1,2 @@ +export function import_export_same_name() { +} diff --git a/vendor/wasm-bindgen/tests/headless/main.rs b/vendor/wasm-bindgen/tests/headless/main.rs new file mode 100644 index 000000000..b5f6f12a0 --- /dev/null +++ b/vendor/wasm-bindgen/tests/headless/main.rs @@ -0,0 +1,61 @@ +#![cfg(target_arch = "wasm32")] + +extern crate wasm_bindgen; +extern crate wasm_bindgen_test; + +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +wasm_bindgen_test_configure!(run_in_browser); + +#[wasm_bindgen] +pub struct ConsumeRetString; + +#[wasm_bindgen] +impl ConsumeRetString { + // https://github.com/rustwasm/wasm-bindgen/issues/329#issuecomment-411082013 + // + // This used to cause two `const ptr = ...` declarations, which is invalid + // JS. + pub fn consume(self) -> String { + String::new() + } +} + +#[wasm_bindgen_test] +fn works() { + ConsumeRetString.consume(); +} + +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(js_namespace = console)] + pub fn log(s: &str); +} + +#[wasm_bindgen_test] +fn can_log_html_strings() { + log(""); +} + +#[wasm_bindgen] +pub fn import_export_same_name() { + #[wasm_bindgen(module = "/tests/headless/main.js")] + extern "C" { + fn import_export_same_name(); + } + import_export_same_name(); +} + +pub mod externref_heap_live_count; +pub mod modules; +pub mod snippets; +pub mod strings; + +#[wasm_bindgen_test] +fn closures_work() { + let x = Closure::wrap(Box::new(|| {}) as Box); + drop(x); + let x = Closure::wrap(Box::new(|| {}) as Box); + x.forget(); +} diff --git a/vendor/wasm-bindgen/tests/headless/modules.js b/vendor/wasm-bindgen/tests/headless/modules.js new file mode 100644 index 000000000..c6ce3f0eb --- /dev/null +++ b/vendor/wasm-bindgen/tests/headless/modules.js @@ -0,0 +1,3 @@ +export function get_five() { + return 5; +} diff --git a/vendor/wasm-bindgen/tests/headless/modules.rs b/vendor/wasm-bindgen/tests/headless/modules.rs new file mode 100644 index 000000000..9e894f340 --- /dev/null +++ b/vendor/wasm-bindgen/tests/headless/modules.rs @@ -0,0 +1,12 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(raw_module = "./tests/headless/modules.js")] +extern "C" { + fn get_five() -> u32; +} + +#[wasm_bindgen_test] +fn test_get_five() { + assert_eq!(get_five(), 5); +} diff --git a/vendor/wasm-bindgen/tests/headless/snippets.rs b/vendor/wasm-bindgen/tests/headless/snippets.rs new file mode 100644 index 000000000..6e637fe7e --- /dev/null +++ b/vendor/wasm-bindgen/tests/headless/snippets.rs @@ -0,0 +1,58 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "/tests/headless/snippets1.js")] +extern "C" { + fn get_two() -> u32; + #[wasm_bindgen(js_name = get_stateful)] + fn get_stateful1() -> u32; +} + +#[wasm_bindgen(module = "/tests/headless/snippets1.js")] +extern "C" { + #[wasm_bindgen(js_name = get_stateful)] + fn get_stateful2() -> u32; +} + +#[wasm_bindgen_test] +fn test_get_two() { + assert_eq!(get_two(), 2); +} + +#[wasm_bindgen_test] +fn stateful_deduplicated() { + assert_eq!(get_stateful1(), 1); + assert_eq!(get_stateful2(), 2); + assert_eq!(get_stateful1(), 3); + assert_eq!(get_stateful2(), 4); +} + +#[wasm_bindgen(inline_js = "export function get_three() { return 3; }")] +extern "C" { + fn get_three() -> u32; +} + +#[wasm_bindgen_test] +fn test_get_three() { + assert_eq!(get_three(), 3); +} + +#[wasm_bindgen(inline_js = "let a = 0; export function get() { a += 1; return a; }")] +extern "C" { + #[wasm_bindgen(js_name = get)] + fn duplicate1() -> u32; +} + +#[wasm_bindgen(inline_js = "let a = 0; export function get() { a += 1; return a; }")] +extern "C" { + #[wasm_bindgen(js_name = get)] + fn duplicate2() -> u32; +} + +#[wasm_bindgen_test] +fn duplicate_inline_not_unified() { + assert_eq!(duplicate1(), 1); + assert_eq!(duplicate2(), 1); + assert_eq!(duplicate1(), 2); + assert_eq!(duplicate2(), 2); +} diff --git a/vendor/wasm-bindgen/tests/headless/snippets1.js b/vendor/wasm-bindgen/tests/headless/snippets1.js new file mode 100644 index 000000000..12e5a6bff --- /dev/null +++ b/vendor/wasm-bindgen/tests/headless/snippets1.js @@ -0,0 +1,9 @@ +export function get_two() { + return 2; +} + +let a = 0; +export function get_stateful() { + a += 1; + return a; +} diff --git a/vendor/wasm-bindgen/tests/headless/strings.js b/vendor/wasm-bindgen/tests/headless/strings.js new file mode 100644 index 000000000..866bad653 --- /dev/null +++ b/vendor/wasm-bindgen/tests/headless/strings.js @@ -0,0 +1,21 @@ +export function test_string_roundtrip(f) { + const test = expected => { + const actual = f(expected); + if (actual === expected) + return; + throw new Error(`string roundtrip "${actual}" != "${expected}"`); + }; + + test(''); + test('a'); + test('💖'); + + test('a longer string'); + test('a longer 💖 string'); + + test('\uFEFFbar'); +} + +export function identity(s) { + return s; +} diff --git a/vendor/wasm-bindgen/tests/headless/strings.rs b/vendor/wasm-bindgen/tests/headless/strings.rs new file mode 100644 index 000000000..300187b2c --- /dev/null +++ b/vendor/wasm-bindgen/tests/headless/strings.rs @@ -0,0 +1,16 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "/tests/headless/strings.js")] +extern "C" { + fn test_string_roundtrip(c: &Closure String>); + + fn identity(s: &str) -> String; +} + +#[wasm_bindgen_test] +fn string_roundtrip() { + test_string_roundtrip(&Closure::wrap(Box::new(|s| s))); + + assert_eq!("\u{feff}bar", &identity("\u{feff}bar")); +} diff --git a/vendor/wasm-bindgen/tests/must_use.rs b/vendor/wasm-bindgen/tests/must_use.rs new file mode 100644 index 000000000..912e92e4b --- /dev/null +++ b/vendor/wasm-bindgen/tests/must_use.rs @@ -0,0 +1,10 @@ +//! This test validates that the generated bindings don't cause linting warnings +//! when used with structs annotated with `#[must_use]`. + +#![deny(unused)] + +use wasm_bindgen::prelude::*; + +#[wasm_bindgen] +#[must_use] +pub struct MustUse {} diff --git a/vendor/wasm-bindgen/tests/non_wasm.rs b/vendor/wasm-bindgen/tests/non_wasm.rs new file mode 100644 index 000000000..00c2a3961 --- /dev/null +++ b/vendor/wasm-bindgen/tests/non_wasm.rs @@ -0,0 +1,50 @@ +extern crate wasm_bindgen; + +use wasm_bindgen::prelude::*; + +#[wasm_bindgen] +pub struct A { + x: u32, +} + +#[wasm_bindgen] +impl A { + pub fn new() -> A { + A { x: 3 } + } + + pub fn foo(&self) { + drop(self.x); + } +} + +#[wasm_bindgen] +pub fn foo(x: bool) { + A::new().foo(); + + if x { + bar("test"); + baz(JsValue::from(3)); + } +} + +#[wasm_bindgen] +extern "C" { + fn some_import(); + static A: JsValue; +} + +#[wasm_bindgen] +pub fn bar(_: &str) -> JsValue { + some_import(); + A.clone() +} + +#[wasm_bindgen] +pub fn baz(_: JsValue) {} + +#[test] +fn test_foo() { + foo(false); + A::new().foo(); +} diff --git a/vendor/wasm-bindgen/tests/std-crate-no-std-dep.rs b/vendor/wasm-bindgen/tests/std-crate-no-std-dep.rs new file mode 100644 index 000000000..bc09e4a63 --- /dev/null +++ b/vendor/wasm-bindgen/tests/std-crate-no-std-dep.rs @@ -0,0 +1,29 @@ +//! This is a test that we can define items in a `#![no_std]` crate when +//! `wasm-bindgen` is compiled itself with the `std` feature and everything +//! works out just fine. + +#![no_std] + +extern crate wasm_bindgen; + +use wasm_bindgen::prelude::*; + +#[wasm_bindgen] +extern "C" { + fn test(a: &str); + + type Js; + #[wasm_bindgen(constructor)] + fn new() -> Js; + #[wasm_bindgen(method, structural)] + fn init(this: &Js); +} + +#[wasm_bindgen] +pub struct A {} + +#[wasm_bindgen] +impl A { + pub fn foo(&self) {} + pub fn bar(&mut self) {} +} diff --git a/vendor/wasm-bindgen/tests/unwrap_throw.rs b/vendor/wasm-bindgen/tests/unwrap_throw.rs new file mode 100644 index 000000000..8a45004ed --- /dev/null +++ b/vendor/wasm-bindgen/tests/unwrap_throw.rs @@ -0,0 +1,23 @@ +extern crate wasm_bindgen; +use wasm_bindgen::prelude::*; + +#[test] +fn unwrap_throw_ok() { + assert_eq!(Some(42).unwrap_throw(), 42); + let x: Result = Ok(42); + assert_eq!(x.unwrap_throw(), 42); +} + +#[test] +#[should_panic] +fn unwrap_throw_none() { + let x: Option = None; + x.unwrap_throw(); +} + +#[test] +#[should_panic] +fn unwrap_throw_err() { + let x: Result = Err(()); + x.unwrap_throw(); +} diff --git a/vendor/wasm-bindgen/tests/wasm/api.js b/vendor/wasm-bindgen/tests/wasm/api.js new file mode 100644 index 000000000..ebbce0431 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/api.js @@ -0,0 +1,75 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +exports.assert_null = x => { + assert.strictEqual(x, null); +}; + +exports.js_works = () => { + assert.strictEqual(wasm.api_foo(), 'foo'); + assert.strictEqual(wasm.api_bar('a'), 'a'); + assert.strictEqual(wasm.api_baz(), 1); + wasm.api_baz2(2, 'a'); + + assert.strictEqual(wasm.api_js_null(), null); + assert.strictEqual(wasm.api_js_undefined(), undefined); + + wasm.api_test_is_null_undefined(null, undefined, 1.0); + + assert.strictEqual(wasm.api_get_true(), true); + assert.strictEqual(wasm.api_get_false(), false); + wasm.api_test_bool(true, false, 1.0); + + assert.strictEqual(typeof (wasm.api_mk_symbol()), 'symbol'); + assert.strictEqual(typeof (wasm.api_mk_symbol2('a')), 'symbol'); + assert.strictEqual(Symbol.keyFor(wasm.api_mk_symbol()), undefined); + assert.strictEqual(Symbol.keyFor(wasm.api_mk_symbol2('b')), undefined); + + wasm.api_assert_symbols(Symbol(), 'a'); + wasm.api_acquire_string('foo', null); + assert.strictEqual(wasm.api_acquire_string2(''), ''); + assert.strictEqual(wasm.api_acquire_string2('a'), 'a'); + + let arr = [1, 2, 3, 4, {}, ['a', 'b', 'c']] + wasm.api_completely_variadic(...arr).forEach((element, index) => { + assert.strictEqual(element, arr[index]); + }); + assert.strictEqual( + wasm.api_completely_variadic().length, + 0 + ); + wasm.api_variadic_with_prefixed_params([], {}, ...arr).forEach((element, index) => { + assert.strictEqual(element, arr[index]); + }); +}; + +exports.js_eq_works = () => { + assert.strictEqual(wasm.eq_test('a', 'a'), true); + assert.strictEqual(wasm.eq_test('a', 'b'), false); + assert.strictEqual(wasm.eq_test(NaN, NaN), false); + assert.strictEqual(wasm.eq_test({ a: 'a' }, { a: 'a' }), false); + assert.strictEqual(wasm.eq_test1(NaN), false); + let x = { a: 'a' }; + assert.strictEqual(wasm.eq_test(x, x), true); + assert.strictEqual(wasm.eq_test1(x), true); +}; + +exports.debug_values = () => ([ + null, + undefined, + 0, + 1.0, + true, + [1, 2, 3], + "string", + { test: "object" }, + [1.0, [2.0, 3.0]], + () => (null), + new Set(), +]); + +exports.assert_function_table = (x, i) => { + const rawWasm = require('wasm-bindgen-test.js').__wasm; + assert.ok(x instanceof WebAssembly.Table); + assert.strictEqual(x.get(i), rawWasm.function_table_lookup); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/api.rs b/vendor/wasm-bindgen/tests/wasm/api.rs new file mode 100644 index 000000000..c1c542d67 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/api.rs @@ -0,0 +1,199 @@ +use js_sys::{Uint8Array, WebAssembly}; +use wasm_bindgen::prelude::*; +use wasm_bindgen::{self, JsCast}; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/api.js")] +extern "C" { + fn js_works(); + fn js_eq_works(); + fn assert_null(v: JsValue); + fn debug_values() -> JsValue; + fn assert_function_table(a: JsValue, b: usize); +} + +#[wasm_bindgen_test] +fn works() { + js_works(); +} + +#[wasm_bindgen] +pub fn api_foo() -> JsValue { + JsValue::from("foo") +} + +#[wasm_bindgen] +pub fn api_bar(s: &str) -> JsValue { + JsValue::from(s) +} + +#[wasm_bindgen] +pub fn api_baz() -> JsValue { + JsValue::from(1.0) +} + +#[wasm_bindgen] +pub fn api_baz2(a: &JsValue, b: &JsValue) { + assert_eq!(a.as_f64(), Some(2.0)); + assert_eq!(b.as_f64(), None); +} + +#[wasm_bindgen] +pub fn api_js_null() -> JsValue { + JsValue::null() +} + +#[wasm_bindgen] +pub fn api_js_undefined() -> JsValue { + JsValue::undefined() +} + +#[wasm_bindgen] +pub fn api_test_is_null_undefined(a: &JsValue, b: &JsValue, c: &JsValue) { + assert!(a.is_null()); + assert!(!a.is_undefined()); + + assert!(!b.is_null()); + assert!(b.is_undefined()); + + assert!(!c.is_null()); + assert!(!c.is_undefined()); +} + +#[wasm_bindgen] +pub fn api_get_true() -> JsValue { + JsValue::from(true) +} + +#[wasm_bindgen] +pub fn api_get_false() -> JsValue { + JsValue::from(false) +} + +#[wasm_bindgen] +pub fn api_test_bool(a: &JsValue, b: &JsValue, c: &JsValue) { + assert_eq!(a.as_bool(), Some(true)); + assert_eq!(format!("{:?}", a), "JsValue(true)"); + assert_eq!(b.as_bool(), Some(false)); + assert_eq!(c.as_bool(), None); +} + +#[wasm_bindgen] +pub fn api_mk_symbol() -> JsValue { + let a = JsValue::symbol(None); + assert!(a.is_symbol()); + assert_eq!(format!("{:?}", a), "JsValue(Symbol)"); + return a; +} + +#[wasm_bindgen] +pub fn api_mk_symbol2(s: &str) -> JsValue { + let a = JsValue::symbol(Some(s)); + assert!(a.is_symbol()); + return a; +} + +#[wasm_bindgen] +pub fn api_assert_symbols(a: &JsValue, b: &JsValue) { + assert!(a.is_symbol()); + assert!(!b.is_symbol()); +} + +#[wasm_bindgen] +pub fn api_acquire_string(a: &JsValue, b: &JsValue) { + assert_eq!(a.as_string().unwrap(), "foo"); + assert_eq!(format!("{:?}", a), "JsValue(\"foo\")"); + assert_eq!(b.as_string(), None); +} + +#[wasm_bindgen] +pub fn api_acquire_string2(a: &JsValue) -> String { + a.as_string().unwrap_or("wrong".to_string()) +} + +#[wasm_bindgen_test] +fn eq_works() { + js_eq_works(); +} + +#[wasm_bindgen] +pub fn eq_test(a: &JsValue, b: &JsValue) -> bool { + a == b +} + +#[wasm_bindgen] +pub fn eq_test1(a: &JsValue) -> bool { + a == a +} + +#[wasm_bindgen(variadic)] +pub fn api_completely_variadic(args: &JsValue) -> JsValue { + args.into() +} + +#[wasm_bindgen(variadic)] +pub fn api_variadic_with_prefixed_params( + first: &JsValue, + second: &JsValue, + args: &JsValue, +) -> JsValue { + args.into() +} + +#[wasm_bindgen_test] +fn null_keeps_working() { + assert_null(JsValue::null()); + assert_null(JsValue::null()); +} + +#[wasm_bindgen_test] +fn memory_accessor_appears_to_work() { + let data = 3u32; + let ptr = &data as *const u32 as u32; + + let my_mem = wasm_bindgen::memory(); + let mem = my_mem.dyn_into::().unwrap(); + let buf = mem.buffer(); + let slice = Uint8Array::new(&buf); + let mut v = Vec::new(); + slice + .subarray(ptr, ptr + 4) + .for_each(&mut |val, _, _| v.push(val)); + assert_eq!(v, [3, 0, 0, 0]); +} + +#[wasm_bindgen_test] +fn debug_output() { + let test_iter = debug_values() + .dyn_into::() + .unwrap() + .values() + .into_iter(); + let expecteds = vec![ + "JsValue(null)", + "JsValue(undefined)", + "JsValue(0)", + "JsValue(1)", + "JsValue(true)", + "JsValue([1, 2, 3])", + "JsValue(\"string\")", + "JsValue(Object({\"test\":\"object\"}))", + "JsValue([1, [2, 3]])", + "JsValue(Function)", + "JsValue(Set)", + ]; + for (test, expected) in test_iter.zip(expecteds) { + assert_eq!(format!("{:?}", test.unwrap()), expected); + } +} + +#[wasm_bindgen_test] +fn function_table_is() { + assert_function_table( + wasm_bindgen::function_table(), + function_table_lookup as usize, + ); +} + +#[no_mangle] +pub extern "C" fn function_table_lookup() {} diff --git a/vendor/wasm-bindgen/tests/wasm/arg_names.js b/vendor/wasm-bindgen/tests/wasm/arg_names.js new file mode 100644 index 000000000..255604b3e --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/arg_names.js @@ -0,0 +1,16 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +const ARGUMENT_NAMES = /([^\s,]+)/g; +const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; + +// https://stackoverflow.com/q/1007981/210304 +function getArgNames(func) { + let fnStr = func.toString().replace(STRIP_COMMENTS, ''); + let result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES); + return result === null ? [] : result; +} + +exports.js_arg_names = () => { + assert.deepEqual(getArgNames(wasm.fn_with_many_args), ['_a', '_b', '_c', '_d']); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/arg_names.rs b/vendor/wasm-bindgen/tests/wasm/arg_names.rs new file mode 100644 index 000000000..e6f044ee1 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/arg_names.rs @@ -0,0 +1,15 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/arg_names.js")] +extern "C" { + fn js_arg_names(); +} + +#[wasm_bindgen] +pub fn fn_with_many_args(_a: i32, _b: i32, _c: i32, _d: i32) {} + +#[wasm_bindgen_test] +fn rust_arg_names() { + js_arg_names(); +} diff --git a/vendor/wasm-bindgen/tests/wasm/bigint.js b/vendor/wasm-bindgen/tests/wasm/bigint.js new file mode 100644 index 000000000..3971d2279 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/bigint.js @@ -0,0 +1,53 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +exports.i64_js_identity = a => a; +exports.u64_js_identity = a => a; + +exports.js_works = () => { + assert.strictEqual(wasm.zero(), BigInt('0')); + assert.strictEqual(wasm.one(), BigInt('1')); + assert.strictEqual(wasm.neg_one(), BigInt('-1')); + assert.strictEqual(wasm.i32_min(), BigInt('-2147483648')); + assert.strictEqual(wasm.u32_max(), BigInt('4294967295')); + assert.strictEqual(wasm.i64_min(), BigInt('-9223372036854775808')); + assert.strictEqual(wasm.u64_max(), BigInt('18446744073709551615')); + + const i64_min = BigInt('-9223372036854775808'); + const u64_max = BigInt('18446744073709551615'); + + const identityTestI64Values = [ + BigInt('0'), + BigInt('1'), + BigInt('-1'), + i64_min, + ]; + for (const value of identityTestI64Values) { + assert.strictEqual(wasm.i64_rust_identity(value), value); + assert.strictEqual(wasm.i64_jsvalue_identity(value), value); + } + + const identityTestU64Values = [ + BigInt('0'), + BigInt('1'), + u64_max, + ]; + for (const value of identityTestU64Values) { + assert.strictEqual(wasm.u64_rust_identity(value), value); + assert.strictEqual(wasm.u64_jsvalue_identity(value), value); + } + + assert.strictEqual(wasm.u64_rust_identity(BigInt('1') << BigInt('64')), BigInt('0')); + assert.strictEqual(wasm.i128_min_jsvalue(), BigInt('-170141183460469231731687303715884105728')); + assert.strictEqual(wasm.u128_max_jsvalue(), BigInt('340282366920938463463374607431768211455')); + + assert.deepStrictEqual(wasm.u64_slice([]), new BigUint64Array()); + assert.deepStrictEqual(wasm.i64_slice([]), new BigInt64Array()); + const arr1 = new BigUint64Array([BigInt('1'), BigInt('2')]); + assert.deepStrictEqual(wasm.u64_slice([BigInt('1'), BigInt('2')]), arr1); + const arr2 = new BigInt64Array([BigInt('1'), BigInt('2')]); + assert.deepStrictEqual(wasm.i64_slice([BigInt('1'), BigInt('2')]), arr2); + + assert.deepStrictEqual(wasm.i64_slice([i64_min]), new BigInt64Array([i64_min])); + assert.deepStrictEqual(wasm.u64_slice([u64_max]), new BigUint64Array([u64_max])); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/bigint.rs b/vendor/wasm-bindgen/tests/wasm/bigint.rs new file mode 100644 index 000000000..30eb5c5cf --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/bigint.rs @@ -0,0 +1,118 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/bigint.js")] +extern "C" { + fn i64_js_identity(a: i64) -> i64; + fn u64_js_identity(a: u64) -> u64; + fn js_works(); +} + +#[wasm_bindgen] +pub fn zero() -> u64 { + 0 +} + +#[wasm_bindgen] +pub fn one() -> u64 { + 1 +} + +#[wasm_bindgen] +pub fn neg_one() -> i64 { + -1 +} + +#[wasm_bindgen] +pub fn i32_min() -> i64 { + i32::min_value() as i64 +} + +#[wasm_bindgen] +pub fn u32_max() -> u64 { + u32::max_value() as u64 +} + +#[wasm_bindgen] +pub fn i64_min() -> i64 { + i64::min_value() +} + +#[wasm_bindgen] +pub fn u64_max() -> u64 { + u64::max_value() +} + +#[wasm_bindgen] +pub fn i64_rust_identity(a: i64) -> i64 { + i64_js_identity(a) +} + +#[wasm_bindgen] +pub fn u64_rust_identity(a: u64) -> u64 { + u64_js_identity(a) +} + +#[wasm_bindgen] +pub fn i64_jsvalue_identity(a: i64) -> JsValue { + JsValue::from(a) +} + +#[wasm_bindgen] +pub fn u64_jsvalue_identity(a: u64) -> JsValue { + JsValue::from(a) +} + +#[wasm_bindgen] +pub fn i128_min_jsvalue() -> JsValue { + JsValue::from(i128::min_value()) +} + +#[wasm_bindgen] +pub fn u128_max_jsvalue() -> JsValue { + JsValue::from(u128::max_value()) +} + +#[wasm_bindgen] +pub fn i64_slice(a: &[i64]) -> Vec { + a.to_vec() +} + +#[wasm_bindgen] +pub fn u64_slice(a: &[u64]) -> Vec { + a.to_vec() +} + +#[wasm_bindgen_test] +fn works() { + js_works(); +} + +mod try_from_works { + use super::*; + use crate::JsValue; + use core::convert::TryFrom; + + macro_rules! test_type_boundaries { + ($($ty:ident)*) => { + $( + #[wasm_bindgen_test] + fn $ty() { + // Not a bigint. + assert!($ty::try_from(JsValue::NULL).is_err()); + assert!($ty::try_from(JsValue::from_f64(0.0)).is_err()); + // Within range. + assert_eq!($ty::try_from(JsValue::from($ty::MIN)), Ok($ty::MIN)); + // Too small. + assert!($ty::try_from(JsValue::from($ty::MIN) - JsValue::from(1_i64)).is_err()); + // Within range. + assert_eq!($ty::try_from(JsValue::from($ty::MAX)), Ok($ty::MAX)); + // Too large. + assert!($ty::try_from(JsValue::from($ty::MAX) + JsValue::from(1_i64)).is_err()); + } + )* + }; + } + + test_type_boundaries!(i64 u64 i128 u128); +} diff --git a/vendor/wasm-bindgen/tests/wasm/char.js b/vendor/wasm-bindgen/tests/wasm/char.js new file mode 100644 index 000000000..d145333e3 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/char.js @@ -0,0 +1,17 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +exports.js_identity = a => a; + +exports.js_works = () => { + assert.strictEqual(wasm.letter(), 'a'); + assert.strictEqual(wasm.face(), '😀'); + assert.strictEqual(wasm.rust_identity('Ղ'), 'Ղ'); + assert.strictEqual(wasm.rust_identity('ҝ'), 'ҝ'); + assert.strictEqual(wasm.rust_identity('Δ'), 'Δ'); + assert.strictEqual(wasm.rust_identity('䉨'), '䉨'); + assert.strictEqual(wasm.rust_js_identity('a'), 'a'); + assert.strictEqual(wasm.rust_js_identity('㊻'), '㊻'); + wasm.rust_letter('a'); + wasm.rust_face('😀'); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/char.rs b/vendor/wasm-bindgen/tests/wasm/char.rs new file mode 100644 index 000000000..f852b8d81 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/char.rs @@ -0,0 +1,43 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/char.js")] +extern "C" { + fn js_identity(c: char) -> char; + fn js_works(); +} + +#[wasm_bindgen] +pub fn rust_identity(c: char) -> char { + c +} + +#[wasm_bindgen] +pub fn rust_js_identity(c: char) -> char { + js_identity(c) +} + +#[wasm_bindgen] +pub fn letter() -> char { + 'a' +} + +#[wasm_bindgen] +pub fn face() -> char { + '😀' +} + +#[wasm_bindgen] +pub fn rust_letter(a: char) { + assert_eq!(a, 'a'); +} + +#[wasm_bindgen] +pub fn rust_face(p: char) { + assert_eq!(p, '😀'); +} + +#[wasm_bindgen_test] +fn works() { + js_works(); +} diff --git a/vendor/wasm-bindgen/tests/wasm/classes.js b/vendor/wasm-bindgen/tests/wasm/classes.js new file mode 100644 index 000000000..93a76107a --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/classes.js @@ -0,0 +1,239 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +exports.js_simple = () => { + const r = new wasm.ClassesSimple(); + assert.strictEqual(r.add(0), 0); + assert.strictEqual(r.add(1), 1); + assert.strictEqual(r.add(1), 2); + r.add(2); + assert.strictEqual(r.consume(), 4); + assert.throws(() => r.free(), /null pointer passed to rust/); + + const r2 = wasm.ClassesSimple.with_contents(10); + assert.strictEqual(r2.add(1), 11); + assert.strictEqual(r2.add(2), 13); + assert.strictEqual(r2.add(3), 16); + r2.free(); + + const r3 = new wasm.ClassesSimple(); + assert.strictEqual(r3.add(42), 42); + r3.free(); +}; + +exports.js_strings = () => { + const r = wasm.ClassesStrings1.new(); + r.set(3); + let bar = r.bar('baz'); + r.free(); + assert.strictEqual(bar.name(), 'foo-baz-3'); + bar.free(); +}; + +exports.js_exceptions = () => { + // this test only works when `--debug` is passed to `wasm-bindgen` (or the + // equivalent thereof) + if (require('process').env.WASM_BINDGEN_NO_DEBUG) + return; + assert.throws(() => new wasm.ClassesExceptions1(), /cannot invoke `new` directly/); + let a = wasm.ClassesExceptions1.new(); + a.free(); + assert.throws(() => a.free(), /null pointer passed to rust/); + + let b = wasm.ClassesExceptions1.new(); + b.foo(b); + assert.throws(() => b.bar(b), /recursive use of an object/); + + let c = wasm.ClassesExceptions1.new(); + let d = wasm.ClassesExceptions2.new(); + assert.throws(() => c.foo(d), /expected instance of ClassesExceptions1/); + d.free(); + c.free(); +}; + +exports.js_pass_one_to_another = () => { + let a = wasm.ClassesPassA.new(); + let b = wasm.ClassesPassB.new(); + a.foo(b); + a.bar(b); + a.free(); +}; + +exports.take_class = foo => { + assert.strictEqual(foo.inner(), 13); + foo.free(); + assert.throws(() => foo.free(), /null pointer passed to rust/); +}; + +exports.js_constructors = () => { + const foo = new wasm.ConstructorsFoo(1); + assert.strictEqual(foo.get_number(), 1); + foo.free(); + + assert.strictEqual(wasm.ConstructorsBar.new, undefined); + const foo2 = new wasm.ConstructorsFoo(2); + assert.strictEqual(foo2.get_number(), 2); + foo2.free(); + + const bar = new wasm.ConstructorsBar(3, 4); + assert.strictEqual(bar.get_sum(), 7); + bar.free(); + + assert.strictEqual(wasm.ConstructorsBar.other_name, undefined); + const bar2 = new wasm.ConstructorsBar(5, 6); + assert.strictEqual(bar2.get_sum(), 11); + bar2.free(); + + assert.strictEqual(wasm.cross_item_construction().get_sum(), 15); +}; + +exports.js_empty_structs = () => { + wasm.OtherEmpty.return_a_value(); +}; + +exports.js_public_fields = () => { + const a = wasm.PublicFields.new(); + assert.strictEqual(a.a, 0); + a.a = 3; + assert.strictEqual(a.a, 3); + + assert.strictEqual(a.b, 0); + a.b = 7; + assert.strictEqual(a.b, 7); + + assert.strictEqual(a.c, 0); + a.c = 8; + assert.strictEqual(a.c, 8); + + assert.strictEqual(a.d, 0); + a.d = 3.3; + assert.strictEqual(a.d, 3); + + assert.strictEqual(a.skipped, undefined); +}; + +exports.js_getter_with_clone = () => { + const a = wasm.GetterWithCloneStruct.new(); + assert.strictEqual(a.a, ''); + a.a = 'foo'; + assert.strictEqual(a.a, 'foo'); + + const b = wasm.GetterWithCloneStructField.new(); + assert.strictEqual(b.a, ''); + b.a = 'foo'; + assert.strictEqual(b.a, 'foo'); +}; + +exports.js_using_self = () => { + wasm.UseSelf.new().free(); +}; + +exports.js_readonly_fields = () => { + const a = wasm.Readonly.new(); + assert.strictEqual(a.a, 0); + a.a = 3; + assert.strictEqual(a.a, 0); + a.free(); +}; + +exports.js_double_consume = () => { + const r = new wasm.DoubleConsume(); + assert.throws(() => r.consume(r)); +}; + + +exports.js_js_rename = () => { + (new wasm.JsRename()).bar(); + wasm.classes_foo(); +}; + +exports.js_access_fields = () => { + assert.ok((new wasm.AccessFieldFoo()).bar instanceof wasm.AccessFieldBar); + assert.ok((new wasm.AccessField0())[0] instanceof wasm.AccessFieldBar); +}; + +exports.js_renamed_export = () => { + const x = new wasm.JsRenamedExport(); + assert.ok(x.x === 3); + x.foo(); + x.bar(x); +}; + +exports.js_renamed_field = () => { + const x = new wasm.RenamedField(); + assert.ok(x.bar === 3); + + x.foo(); +} + +exports.js_conditional_bindings = () => { + const x = new wasm.ConditionalBindings(); + x.free(); +}; + +exports.js_assert_none = x => { + assert.strictEqual(x, undefined); +}; +exports.js_assert_some = x => { + assert.ok(x instanceof wasm.OptionClass); +}; +exports.js_return_none1 = () => null; +exports.js_return_none2 = () => undefined; +exports.js_return_some = x => x; + +exports.js_test_option_classes = () => { + assert.strictEqual(wasm.option_class_none(), undefined); + wasm.option_class_assert_none(undefined); + wasm.option_class_assert_none(null); + const c = wasm.option_class_some(); + assert.ok(c instanceof wasm.OptionClass); + wasm.option_class_assert_some(c); +}; + +/** + * Invokes `console.log`, but logs to a string rather than stdout + * @param {any} data Data to pass to `console.log` + * @returns {string} Output from `console.log`, without color or trailing newlines + */ +const console_log_to_string = data => { + // Store the original stdout.write and create a console that logs without color + const original_write = process.stdout.write; + const colorless_console = new console.Console({ + stdout: process.stdout, + colorMode: false + }); + let output = ''; + + // Change stdout.write to append to our string, then restore the original function + process.stdout.write = chunk => output += chunk.trim(); + colorless_console.log(data); + process.stdout.write = original_write; + + return output; +}; + +exports.js_test_inspectable_classes = () => { + const inspectable = wasm.Inspectable.new(); + const not_inspectable = wasm.NotInspectable.new(); + // Inspectable classes have a toJSON and toString implementation generated + assert.deepStrictEqual(inspectable.toJSON(), { a: inspectable.a }); + assert.strictEqual(inspectable.toString(), `{"a":${inspectable.a}}`); + // Inspectable classes in Node.js have improved console.log formatting as well + assert(console_log_to_string(inspectable).endsWith(`{ a: ${inspectable.a} }`)); + // Non-inspectable classes do not have a toJSON or toString generated + assert.strictEqual(not_inspectable.toJSON, undefined); + assert.strictEqual(not_inspectable.toString(), '[object Object]'); + // Non-inspectable classes in Node.js have no special console.log formatting + assert.strictEqual(console_log_to_string(not_inspectable), `NotInspectable { ptr: ${not_inspectable.ptr} }`); + inspectable.free(); + not_inspectable.free(); +}; + +exports.js_test_inspectable_classes_can_override_generated_methods = () => { + const overridden_inspectable = wasm.OverriddenInspectable.new(); + // Inspectable classes can have the generated toJSON and toString overwritten + assert.strictEqual(overridden_inspectable.a, 0); + assert.deepStrictEqual(overridden_inspectable.toJSON(), 'JSON was overwritten'); + assert.strictEqual(overridden_inspectable.toString(), 'string was overwritten'); + overridden_inspectable.free(); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/classes.rs b/vendor/wasm-bindgen/tests/wasm/classes.rs new file mode 100644 index 000000000..3588bb74c --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/classes.rs @@ -0,0 +1,610 @@ +#[allow(unused_imports)] // test for #919 +use std::borrow::BorrowMut; + +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/classes.js")] +extern "C" { + fn js_simple(); + fn js_strings(); + fn js_exceptions(); + fn js_pass_one_to_another(); + fn take_class(foo: ClassesIntoJs); + #[wasm_bindgen(js_name = take_class)] + fn take_class_as_jsvalue(foo: JsValue); + fn js_constructors(); + fn js_empty_structs(); + fn js_public_fields(); + fn js_getter_with_clone(); + fn js_using_self(); + fn js_readonly_fields(); + fn js_double_consume(); + fn js_js_rename(); + fn js_access_fields(); + fn js_renamed_export(); + fn js_renamed_field(); + fn js_conditional_bindings(); + + fn js_assert_none(a: Option); + fn js_assert_some(a: Option); + fn js_return_none1() -> Option; + fn js_return_none2() -> Option; + fn js_return_some(a: OptionClass) -> Option; + fn js_test_option_classes(); + fn js_test_inspectable_classes(); + fn js_test_inspectable_classes_can_override_generated_methods(); +} + +#[wasm_bindgen_test] +fn simple() { + js_simple(); +} + +#[wasm_bindgen] +pub struct ClassesSimple { + contents: u32, +} + +#[wasm_bindgen] +impl ClassesSimple { + #[wasm_bindgen(constructor)] + pub fn new() -> ClassesSimple { + ClassesSimple::with_contents(0) + } + + pub fn with_contents(a: u32) -> ClassesSimple { + ClassesSimple { contents: a } + } + + pub fn add(&mut self, amt: u32) -> u32 { + self.contents += amt; + self.contents + } + + pub fn consume(self) -> u32 { + self.contents + } +} + +#[wasm_bindgen_test] +fn strings() { + js_strings() +} + +#[wasm_bindgen] +pub struct ClassesStrings1 { + name: u32, +} + +#[wasm_bindgen] +pub struct ClassesStrings2 { + contents: String, +} + +#[wasm_bindgen] +impl ClassesStrings1 { + pub fn new() -> ClassesStrings1 { + ClassesStrings1 { name: 0 } + } + + pub fn set(&mut self, amt: u32) { + self.name = amt; + } + + pub fn bar(&self, mix: &str) -> ClassesStrings2 { + ClassesStrings2 { + contents: format!("foo-{}-{}", mix, self.name), + } + } +} + +#[wasm_bindgen] +impl ClassesStrings2 { + pub fn name(&self) -> String { + self.contents.clone() + } +} + +#[wasm_bindgen_test] +fn exceptions() { + js_exceptions(); +} + +#[wasm_bindgen] +pub struct ClassesExceptions1 {} + +#[wasm_bindgen] +impl ClassesExceptions1 { + pub fn new() -> ClassesExceptions1 { + ClassesExceptions1 {} + } + + pub fn foo(&self, _: &ClassesExceptions1) {} + + pub fn bar(&mut self, _: &mut ClassesExceptions1) {} +} + +#[wasm_bindgen] +pub struct ClassesExceptions2 {} + +#[wasm_bindgen] +impl ClassesExceptions2 { + pub fn new() -> ClassesExceptions2 { + ClassesExceptions2 {} + } +} + +#[wasm_bindgen_test] +fn pass_one_to_another() { + js_pass_one_to_another(); +} + +#[wasm_bindgen] +pub struct ClassesPassA {} + +#[wasm_bindgen] +impl ClassesPassA { + pub fn new() -> ClassesPassA { + ClassesPassA {} + } + + pub fn foo(&self, _other: &ClassesPassB) {} + + pub fn bar(&self, _other: ClassesPassB) {} +} + +#[wasm_bindgen] +pub struct ClassesPassB {} + +#[wasm_bindgen] +impl ClassesPassB { + pub fn new() -> ClassesPassB { + ClassesPassB {} + } +} + +#[wasm_bindgen_test] +fn pass_into_js() { + take_class(ClassesIntoJs(13)); +} + +#[wasm_bindgen] +pub struct ClassesIntoJs(i32); + +#[wasm_bindgen] +impl ClassesIntoJs { + pub fn inner(&self) -> i32 { + self.0 + } +} + +#[wasm_bindgen] +pub struct Issue27Context {} + +#[wasm_bindgen] +impl Issue27Context { + pub fn parse(&self, _expr: &str) -> Issue27Expr { + panic!() + } + pub fn eval(&self, _expr: &Issue27Expr) -> f64 { + panic!() + } + pub fn set(&mut self, _var: &str, _val: f64) { + panic!() + } +} + +#[wasm_bindgen] +pub struct Issue27Expr {} + +#[wasm_bindgen_test] +fn pass_into_js_as_js_class() { + take_class_as_jsvalue(ClassesIntoJs(13).into()); +} + +#[wasm_bindgen_test] +fn constructors() { + js_constructors(); +} + +#[wasm_bindgen] +pub fn cross_item_construction() -> ConstructorsBar { + ConstructorsBar::other_name(7, 8) +} + +#[wasm_bindgen] +pub struct ConstructorsFoo { + number: u32, +} + +#[wasm_bindgen] +impl ConstructorsFoo { + #[wasm_bindgen(constructor)] + pub fn new(number: u32) -> ConstructorsFoo { + ConstructorsFoo { number } + } + + pub fn get_number(&self) -> u32 { + self.number + } +} + +#[wasm_bindgen] +pub struct ConstructorsBar { + number: u32, + number2: u32, +} + +#[wasm_bindgen] +impl ConstructorsBar { + #[wasm_bindgen(constructor)] + pub fn other_name(number: u32, number2: u32) -> ConstructorsBar { + ConstructorsBar { number, number2 } + } + + pub fn get_sum(&self) -> u32 { + self.number + self.number2 + } +} + +#[wasm_bindgen_test] +fn empty_structs() { + js_empty_structs(); +} + +#[wasm_bindgen] +pub struct MissingClass {} + +#[wasm_bindgen] +pub struct OtherEmpty {} + +#[wasm_bindgen] +impl OtherEmpty { + pub fn return_a_value() -> MissingClass { + MissingClass {} + } +} + +#[wasm_bindgen_test] +fn public_fields() { + js_public_fields(); +} + +#[wasm_bindgen] +#[derive(Default)] +pub struct PublicFields { + pub a: u32, + pub b: f32, + pub c: f64, + pub d: i32, + #[wasm_bindgen(skip)] + pub skipped: u32, +} + +#[wasm_bindgen] +impl PublicFields { + pub fn new() -> PublicFields { + PublicFields::default() + } +} + +#[wasm_bindgen_test] +fn getter_with_clone() { + js_getter_with_clone(); +} + +#[wasm_bindgen(getter_with_clone)] +#[derive(Default)] +pub struct GetterWithCloneStruct { + pub a: String, +} + +#[wasm_bindgen] +impl GetterWithCloneStruct { + pub fn new() -> GetterWithCloneStruct { + GetterWithCloneStruct::default() + } +} + +#[wasm_bindgen] +#[derive(Default)] +pub struct GetterWithCloneStructField { + #[wasm_bindgen(getter_with_clone)] + pub a: String, +} + +#[wasm_bindgen] +impl GetterWithCloneStructField { + pub fn new() -> GetterWithCloneStructField { + GetterWithCloneStructField::default() + } +} + +#[wasm_bindgen_test] +fn using_self() { + js_using_self(); +} + +#[wasm_bindgen] +pub struct UseSelf {} + +#[wasm_bindgen] +impl UseSelf { + pub fn new() -> Self { + UseSelf {} + } +} + +#[wasm_bindgen_test] +fn readonly_fields() { + js_readonly_fields(); +} + +#[wasm_bindgen] +#[derive(Default)] +pub struct Readonly { + #[wasm_bindgen(readonly)] + pub a: u32, +} + +#[wasm_bindgen] +impl Readonly { + pub fn new() -> Readonly { + Readonly::default() + } +} + +#[wasm_bindgen_test] +fn double_consume() { + js_double_consume(); +} + +#[wasm_bindgen] +pub struct DoubleConsume {} + +#[wasm_bindgen] +impl DoubleConsume { + #[wasm_bindgen(constructor)] + pub fn new() -> DoubleConsume { + DoubleConsume {} + } + + pub fn consume(self, other: DoubleConsume) { + drop(other); + } +} + +#[wasm_bindgen_test] +fn rename_function_for_js() { + js_js_rename(); + foo(); +} + +#[wasm_bindgen] +pub struct JsRename {} + +#[wasm_bindgen] +impl JsRename { + #[wasm_bindgen(constructor)] + pub fn new() -> JsRename { + let f = JsRename {}; + f.foo(); + f + } + + #[wasm_bindgen(js_name = bar)] + pub fn foo(&self) {} +} + +#[wasm_bindgen(js_name = classes_foo)] +pub fn foo() {} + +#[wasm_bindgen] +pub struct AccessFieldFoo { + pub bar: AccessFieldBar, +} + +#[wasm_bindgen] +pub struct AccessField0(pub AccessFieldBar); + +#[wasm_bindgen] +#[derive(Copy, Clone)] +pub struct AccessFieldBar { + _value: u32, +} + +#[wasm_bindgen] +impl AccessFieldFoo { + #[wasm_bindgen(constructor)] + pub fn new() -> AccessFieldFoo { + AccessFieldFoo { + bar: AccessFieldBar { _value: 2 }, + } + } +} + +#[wasm_bindgen] +impl AccessField0 { + #[wasm_bindgen(constructor)] + pub fn new() -> AccessField0 { + AccessField0(AccessFieldBar { _value: 2 }) + } +} + +#[wasm_bindgen_test] +fn access_fields() { + js_access_fields(); +} + +#[wasm_bindgen(js_name = JsRenamedExport)] +pub struct RenamedExport { + pub x: u32, +} + +#[wasm_bindgen(js_class = JsRenamedExport)] +impl RenamedExport { + #[wasm_bindgen(constructor)] + pub fn new() -> RenamedExport { + RenamedExport { x: 3 } + } + pub fn foo(&self) {} + + pub fn bar(&self, other: &RenamedExport) { + drop(other); + } +} + +#[wasm_bindgen_test] +fn renamed_export() { + js_renamed_export(); +} + +#[wasm_bindgen] +pub struct RenamedField { + #[wasm_bindgen(js_name = bar)] + pub foo: u32, +} + +#[wasm_bindgen(js_class = RenamedField)] +impl RenamedField { + #[wasm_bindgen(constructor)] + pub fn new() -> RenamedField { + RenamedField { foo: 3 } + } + + pub fn foo(&self) {} +} + +#[wasm_bindgen_test] +fn renamed_field() { + js_renamed_field(); +} + +#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] +pub struct ConditionalBindings {} + +#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] +impl ConditionalBindings { + #[cfg_attr(target_arch = "wasm32", wasm_bindgen(constructor))] + pub fn new() -> ConditionalBindings { + ConditionalBindings {} + } +} + +#[wasm_bindgen_test] +fn conditional_bindings() { + js_conditional_bindings(); +} + +#[wasm_bindgen] +pub struct OptionClass(u32); + +#[wasm_bindgen_test] +fn option_class() { + js_assert_none(None); + js_assert_some(Some(OptionClass(1))); + assert!(js_return_none1().is_none()); + assert!(js_return_none2().is_none()); + assert_eq!(js_return_some(OptionClass(2)).unwrap().0, 2); + js_test_option_classes(); +} + +#[wasm_bindgen] +pub fn option_class_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn option_class_some() -> Option { + Some(OptionClass(3)) +} + +#[wasm_bindgen] +pub fn option_class_assert_none(x: Option) { + assert!(x.is_none()); +} + +#[wasm_bindgen] +pub fn option_class_assert_some(x: Option) { + assert_eq!(x.unwrap().0, 3); +} + +mod works_in_module { + use wasm_bindgen::prelude::wasm_bindgen; + + #[wasm_bindgen] + pub struct WorksInModule(u32); + + #[wasm_bindgen] + impl WorksInModule { + #[wasm_bindgen(constructor)] + pub fn new() -> WorksInModule { + WorksInModule(1) + } + + pub fn foo(&self) {} + } +} + +#[wasm_bindgen_test] +fn inspectable_classes() { + js_test_inspectable_classes(); +} + +#[wasm_bindgen(inspectable)] +#[derive(Default)] +pub struct Inspectable { + pub a: u32, + // This private field will not be exposed unless a getter is provided for it + #[allow(dead_code)] + private: u32, +} + +#[wasm_bindgen] +impl Inspectable { + pub fn new() -> Self { + Self::default() + } +} + +#[wasm_bindgen] +#[derive(Default)] +pub struct NotInspectable { + pub a: u32, +} + +#[wasm_bindgen] +impl NotInspectable { + pub fn new() -> Self { + Self::default() + } +} + +#[wasm_bindgen_test] +fn inspectable_classes_can_override_generated_methods() { + js_test_inspectable_classes_can_override_generated_methods(); +} + +#[wasm_bindgen(inspectable)] +#[derive(Default)] +pub struct OverriddenInspectable { + pub a: u32, +} + +#[wasm_bindgen] +impl OverriddenInspectable { + pub fn new() -> Self { + Self::default() + } + + #[wasm_bindgen(js_name = toJSON)] + pub fn to_json(&self) -> String { + String::from("JSON was overwritten") + } + + #[wasm_bindgen(js_name = toString)] + pub fn to_string(&self) -> String { + String::from("string was overwritten") + } +} diff --git a/vendor/wasm-bindgen/tests/wasm/closures.js b/vendor/wasm-bindgen/tests/wasm/closures.js new file mode 100644 index 000000000..dfc3d871e --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/closures.js @@ -0,0 +1,164 @@ +const assert = require('assert'); +const wasm = require('wasm-bindgen-test'); + +exports.works_call = a => { + a(); +}; + +exports.works_thread = a => a(2); + +let CANNOT_REUSE_CACHE = null; + +exports.cannot_reuse_call = a => { + CANNOT_REUSE_CACHE = a; +}; + +exports.cannot_reuse_call_again = () => { + CANNOT_REUSE_CACHE(); +}; + +exports.long_lived_call1 = a => { + a(); +}; + +exports.long_lived_call2 = a => a(2); + +exports.many_arity_call1 = a => { + a(); +}; +exports.many_arity_call2 = a => { + a(1); +}; +exports.many_arity_call3 = a => { + a(1, 2); +}; +exports.many_arity_call4 = a => { + a(1, 2, 3); +}; +exports.many_arity_call5 = a => { + a(1, 2, 3, 4); +}; +exports.many_arity_call6 = a => { + a(1, 2, 3, 4, 5); +}; +exports.many_arity_call7 = a => { + a(1, 2, 3, 4, 5, 6); +}; +exports.many_arity_call8 = a => { + a(1, 2, 3, 4, 5, 6, 7); +}; +exports.many_arity_call9 = a => { + a(1, 2, 3, 4, 5, 6, 7, 8); +}; + +exports.option_call1 = a => { + if (a) { + a(); + } +}; +exports.option_call2 = a => { + if (a) { + return a(2); + } +}; +exports.option_call3 = a => a == undefined; + +let LONG_LIVED_DROPPING_CACHE = null; + +exports.long_lived_dropping_cache = a => { + LONG_LIVED_DROPPING_CACHE = a; +}; +exports.long_lived_dropping_call = () => { + LONG_LIVED_DROPPING_CACHE(); +}; + +let LONG_LIVED_OPTION_DROPPING_CACHE = null; + +exports.long_lived_option_dropping_cache = a => { + if (a) { + LONG_LIVED_OPTION_DROPPING_CACHE = a; + return true; + } else { + return false; + } +} +exports.long_lived_option_dropping_call = () => { + LONG_LIVED_OPTION_DROPPING_CACHE(); +} + +let LONG_FNMUT_RECURSIVE_CACHE = null; + +exports.long_fnmut_recursive_cache = a => { + LONG_FNMUT_RECURSIVE_CACHE = a; +}; +exports.long_fnmut_recursive_call = () => { + LONG_FNMUT_RECURSIVE_CACHE(); +}; + +exports.fnmut_call = a => { + a(); +}; + +exports.fnmut_thread = a => a(2); + +let FNMUT_BAD_F = null; + +exports.fnmut_bad_call = a => { + FNMUT_BAD_F = a; + a(); +}; + +exports.fnmut_bad_again = x => { + if (x) { + FNMUT_BAD_F(); + } +}; + +exports.string_arguments_call = a => { + a('foo'); +}; + +exports.string_ret_call = a => { + assert.strictEqual(a('foo'), 'foobar'); +}; + +let DROP_DURING_CALL = null; +exports.drop_during_call_save = f => { + DROP_DURING_CALL = f; +}; +exports.drop_during_call_call = () => DROP_DURING_CALL(); + +exports.js_test_closure_returner = () => { + wasm.closure_returner().someKey(); +}; + +exports.calling_it_throws = a => { + try { + a(); + return false; + } catch(_) { + return true; + } +}; + +exports.call_val = f => f(); + +exports.pass_reference_first_arg_twice = (a, b, c) => { + b(a); + c(a); + a.free(); +}; + +exports.call_destroyed = f => { + assert.throws(f, /invoked recursively or destroyed/); +}; + +let FORGOTTEN_CLOSURE = null; + +exports.js_store_forgotten_closure = f => { + FORGOTTEN_CLOSURE = f; +}; + +exports.js_call_forgotten_closure = () => { + FORGOTTEN_CLOSURE(); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/closures.rs b/vendor/wasm-bindgen/tests/wasm/closures.rs new file mode 100644 index 000000000..dc88b43ad --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/closures.rs @@ -0,0 +1,645 @@ +use js_sys::Number; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/closures.js")] +extern "C" { + fn works_call(a: &dyn Fn()); + fn works_thread(a: &dyn Fn(u32) -> u32) -> u32; + + fn cannot_reuse_call(a: &dyn Fn()); + #[wasm_bindgen(catch)] + fn cannot_reuse_call_again() -> Result<(), JsValue>; + + fn long_lived_call1(a: &Closure); + fn long_lived_call2(a: &Closure u32>) -> u32; + + fn many_arity_call1(a: &Closure); + fn many_arity_call2(a: &Closure); + fn many_arity_call3(a: &Closure); + fn many_arity_call4(a: &Closure); + fn many_arity_call5(a: &Closure); + fn many_arity_call6(a: &Closure); + fn many_arity_call7(a: &Closure); + fn many_arity_call8(a: &Closure); + fn many_arity_call9(a: &Closure); + + #[wasm_bindgen(js_name = many_arity_call1)] + fn many_arity_call_mut1(a: &Closure); + #[wasm_bindgen(js_name = many_arity_call2)] + fn many_arity_call_mut2(a: &Closure); + #[wasm_bindgen(js_name = many_arity_call3)] + fn many_arity_call_mut3(a: &Closure); + #[wasm_bindgen(js_name = many_arity_call4)] + fn many_arity_call_mut4(a: &Closure); + #[wasm_bindgen(js_name = many_arity_call5)] + fn many_arity_call_mut5(a: &Closure); + #[wasm_bindgen(js_name = many_arity_call6)] + fn many_arity_call_mut6(a: &Closure); + #[wasm_bindgen(js_name = many_arity_call7)] + fn many_arity_call_mut7(a: &Closure); + #[wasm_bindgen(js_name = many_arity_call8)] + fn many_arity_call_mut8(a: &Closure); + #[wasm_bindgen(js_name = many_arity_call9)] + fn many_arity_call_mut9(a: &Closure); + + fn option_call1(a: Option<&Closure>); + fn option_call2(a: Option<&Closure u32>>) -> u32; + fn option_call3(a: Option<&Closure>) -> bool; + + #[wasm_bindgen(js_name = many_arity_call1)] + fn many_arity_stack1(a: &dyn Fn()); + #[wasm_bindgen(js_name = many_arity_call2)] + fn many_arity_stack2(a: &dyn Fn(u32)); + #[wasm_bindgen(js_name = many_arity_call3)] + fn many_arity_stack3(a: &dyn Fn(u32, u32)); + #[wasm_bindgen(js_name = many_arity_call4)] + fn many_arity_stack4(a: &dyn Fn(u32, u32, u32)); + #[wasm_bindgen(js_name = many_arity_call5)] + fn many_arity_stack5(a: &dyn Fn(u32, u32, u32, u32)); + #[wasm_bindgen(js_name = many_arity_call6)] + fn many_arity_stack6(a: &dyn Fn(u32, u32, u32, u32, u32)); + #[wasm_bindgen(js_name = many_arity_call7)] + fn many_arity_stack7(a: &dyn Fn(u32, u32, u32, u32, u32, u32)); + #[wasm_bindgen(js_name = many_arity_call8)] + fn many_arity_stack8(a: &dyn Fn(u32, u32, u32, u32, u32, u32, u32)); + #[wasm_bindgen(js_name = many_arity_call9)] + fn many_arity_stack9(a: &dyn Fn(u32, u32, u32, u32, u32, u32, u32, u32)); + + fn long_lived_dropping_cache(a: &Closure); + #[wasm_bindgen(catch)] + fn long_lived_dropping_call() -> Result<(), JsValue>; + + fn long_lived_option_dropping_cache(a: Option<&Closure>) -> bool; + #[wasm_bindgen(catch)] + fn long_lived_option_dropping_call() -> Result<(), JsValue>; + + fn long_fnmut_recursive_cache(a: &Closure); + #[wasm_bindgen(catch)] + fn long_fnmut_recursive_call() -> Result<(), JsValue>; + + fn fnmut_call(a: &mut dyn FnMut()); + fn fnmut_thread(a: &mut dyn FnMut(u32) -> u32) -> u32; + + fn fnmut_bad_call(a: &mut dyn FnMut()); + #[wasm_bindgen(catch)] + fn fnmut_bad_again(a: bool) -> Result<(), JsValue>; + + fn string_arguments_call(a: &mut dyn FnMut(String)); + + fn string_ret_call(a: &mut dyn FnMut(String) -> String); + + fn drop_during_call_save(a: &Closure); + fn drop_during_call_call(); + + fn js_test_closure_returner(); + + fn calling_it_throws(a: &Closure) -> bool; + + fn call_val(f: &JsValue); + + #[wasm_bindgen(js_name = calling_it_throws)] + fn call_val_throws(f: &JsValue) -> bool; + + fn pass_reference_first_arg_twice( + a: RefFirstArgument, + b: &Closure, + c: &Closure, + ); + #[wasm_bindgen(js_name = pass_reference_first_arg_twice)] + fn pass_reference_first_arg_twice2( + a: RefFirstArgument, + b: &mut dyn FnMut(&RefFirstArgument), + c: &mut dyn FnMut(&RefFirstArgument), + ); + fn call_destroyed(a: &JsValue); + + fn js_store_forgotten_closure(closure: &Closure); + fn js_call_forgotten_closure(); + + #[wasm_bindgen(js_name = many_arity_call2)] + fn externref_call(a: &Closure); + #[wasm_bindgen(js_name = many_arity_call2)] + fn named_externref_call(a: &Closure); +} + +#[wasm_bindgen_test] +fn works() { + let a = Cell::new(false); + works_call(&|| a.set(true)); + assert!(a.get()); + + assert_eq!(works_thread(&|a| a + 1), 3); +} + +#[wasm_bindgen_test] +fn cannot_reuse() { + cannot_reuse_call(&|| {}); + assert!(cannot_reuse_call_again().is_err()); +} + +#[wasm_bindgen_test] +fn debug() { + let closure = Closure::wrap(Box::new(|| {}) as Box); + assert_eq!(&format!("{:?}", closure), "Closure { ... }"); +} + +#[wasm_bindgen_test] +fn long_lived() { + let hit = Rc::new(Cell::new(false)); + let hit2 = hit.clone(); + let a = Closure::new(move || hit2.set(true)); + assert!(!hit.get()); + long_lived_call1(&a); + assert!(hit.get()); + + let hit = Rc::new(Cell::new(false)); + { + let hit = hit.clone(); + let a = Closure::new(move |x| { + hit.set(true); + x + 3 + }); + assert_eq!(long_lived_call2(&a), 5); + } + assert!(hit.get()); +} + +#[wasm_bindgen_test] +fn many_arity() { + many_arity_call1(&Closure::new(|| {})); + many_arity_call2(&Closure::new(|a| assert_eq!(a, 1))); + many_arity_call3(&Closure::new(|a, b| assert_eq!((a, b), (1, 2)))); + many_arity_call4(&Closure::new(|a, b, c| assert_eq!((a, b, c), (1, 2, 3)))); + many_arity_call5(&Closure::new(|a, b, c, d| { + assert_eq!((a, b, c, d), (1, 2, 3, 4)) + })); + many_arity_call6(&Closure::new(|a, b, c, d, e| { + assert_eq!((a, b, c, d, e), (1, 2, 3, 4, 5)) + })); + many_arity_call7(&Closure::new(|a, b, c, d, e, f| { + assert_eq!((a, b, c, d, e, f), (1, 2, 3, 4, 5, 6)) + })); + many_arity_call8(&Closure::new(|a, b, c, d, e, f, g| { + assert_eq!((a, b, c, d, e, f, g), (1, 2, 3, 4, 5, 6, 7)) + })); + many_arity_call9(&Closure::new(|a, b, c, d, e, f, g, h| { + assert_eq!((a, b, c, d, e, f, g, h), (1, 2, 3, 4, 5, 6, 7, 8)) + })); + + let s = String::new(); + many_arity_call_mut1(&Closure::once(move || drop(s))); + let s = String::new(); + many_arity_call_mut2(&Closure::once(move |a| { + drop(s); + assert_eq!(a, 1); + })); + let s = String::new(); + many_arity_call_mut3(&Closure::once(move |a, b| { + drop(s); + assert_eq!((a, b), (1, 2)); + })); + let s = String::new(); + many_arity_call_mut4(&Closure::once(move |a, b, c| { + drop(s); + assert_eq!((a, b, c), (1, 2, 3)); + })); + let s = String::new(); + many_arity_call_mut5(&Closure::once(move |a, b, c, d| { + drop(s); + assert_eq!((a, b, c, d), (1, 2, 3, 4)); + })); + let s = String::new(); + many_arity_call_mut6(&Closure::once(move |a, b, c, d, e| { + drop(s); + assert_eq!((a, b, c, d, e), (1, 2, 3, 4, 5)); + })); + let s = String::new(); + many_arity_call_mut7(&Closure::once(move |a, b, c, d, e, f| { + drop(s); + assert_eq!((a, b, c, d, e, f), (1, 2, 3, 4, 5, 6)); + })); + let s = String::new(); + many_arity_call_mut8(&Closure::once(move |a, b, c, d, e, f, g| { + drop(s); + assert_eq!((a, b, c, d, e, f, g), (1, 2, 3, 4, 5, 6, 7)); + })); + let s = String::new(); + many_arity_call_mut9(&Closure::once(move |a, b, c, d, e, f, g, h| { + drop(s); + assert_eq!((a, b, c, d, e, f, g, h), (1, 2, 3, 4, 5, 6, 7, 8)); + })); + + many_arity_stack1(&(|| {})); + many_arity_stack2(&(|a| assert_eq!(a, 1))); + many_arity_stack3(&(|a, b| assert_eq!((a, b), (1, 2)))); + many_arity_stack4(&(|a, b, c| assert_eq!((a, b, c), (1, 2, 3)))); + many_arity_stack5(&(|a, b, c, d| assert_eq!((a, b, c, d), (1, 2, 3, 4)))); + many_arity_stack6(&(|a, b, c, d, e| assert_eq!((a, b, c, d, e), (1, 2, 3, 4, 5)))); + many_arity_stack7(&(|a, b, c, d, e, f| assert_eq!((a, b, c, d, e, f), (1, 2, 3, 4, 5, 6)))); + many_arity_stack8( + &(|a, b, c, d, e, f, g| assert_eq!((a, b, c, d, e, f, g), (1, 2, 3, 4, 5, 6, 7))), + ); + many_arity_stack9( + &(|a, b, c, d, e, f, g, h| assert_eq!((a, b, c, d, e, f, g, h), (1, 2, 3, 4, 5, 6, 7, 8))), + ); +} + +#[wasm_bindgen_test] +fn option() { + let hit = Rc::new(Cell::new(false)); + let hit2 = hit.clone(); + let a = Closure::new(move || hit2.set(true)); + assert!(!hit.get()); + option_call1(Some(&a)); + assert!(hit.get()); + + let hit = Rc::new(Cell::new(false)); + { + let hit = hit.clone(); + let a = Closure::new(move |x| { + hit.set(true); + x + 3 + }); + assert_eq!(option_call2(Some(&a)), 5); + } + assert!(hit.get()); + + assert!(option_call3(None)); +} + +struct Dropper(Rc>); +impl Drop for Dropper { + fn drop(&mut self) { + assert!(!self.0.get()); + self.0.set(true); + } +} + +#[wasm_bindgen_test] +fn call_fn_once_twice() { + let dropped = Rc::new(Cell::new(false)); + let dropper = Dropper(dropped.clone()); + let called = Rc::new(Cell::new(false)); + + let c = Closure::once({ + let called = called.clone(); + move || { + assert!(!called.get()); + called.set(true); + drop(dropper); + } + }); + + many_arity_call_mut1(&c); + assert!(called.get()); + assert!(dropped.get()); + + assert!(calling_it_throws(&c)); +} + +#[wasm_bindgen_test] +fn once_into_js() { + let dropped = Rc::new(Cell::new(false)); + let dropper = Dropper(dropped.clone()); + let called = Rc::new(Cell::new(false)); + + let f = Closure::once_into_js({ + let called = called.clone(); + move || { + assert!(!called.get()); + called.set(true); + drop(dropper); + } + }); + + call_val(&f); + assert!(called.get()); + assert!(dropped.get()); + + assert!(call_val_throws(&f)); +} + +#[wasm_bindgen_test] +fn long_lived_dropping() { + let hit = Rc::new(Cell::new(false)); + let hit2 = hit.clone(); + let a = Closure::new(move || hit2.set(true)); + long_lived_dropping_cache(&a); + assert!(!hit.get()); + assert!(long_lived_dropping_call().is_ok()); + assert!(hit.get()); + drop(a); + assert!(long_lived_dropping_call().is_err()); +} + +#[wasm_bindgen_test] +fn long_lived_option_dropping() { + let hit = Rc::new(Cell::new(false)); + let hit2 = hit.clone(); + + let a = Closure::new(move || hit2.set(true)); + + assert!(!long_lived_option_dropping_cache(None)); + assert!(long_lived_option_dropping_cache(Some(&a))); + + assert!(!hit.get()); + assert!(long_lived_option_dropping_call().is_ok()); + assert!(hit.get()); + + drop(a); + assert!(long_lived_option_dropping_call().is_err()); +} + +#[wasm_bindgen_test] +fn long_fnmut_recursive() { + let a = Closure::new(|| { + assert!(long_fnmut_recursive_call().is_err()); + }); + long_fnmut_recursive_cache(&a); + assert!(long_fnmut_recursive_call().is_ok()); +} + +#[wasm_bindgen_test] +fn fnmut() { + let mut a = false; + fnmut_call(&mut || a = true); + assert!(a); + + let mut x = false; + assert_eq!( + fnmut_thread(&mut |a| { + x = true; + a + 1 + }), + 3 + ); + assert!(x); +} + +#[wasm_bindgen_test] +fn fnmut_bad() { + let mut x = true; + let mut hits = 0; + fnmut_bad_call(&mut || { + hits += 1; + if fnmut_bad_again(hits == 1).is_err() { + return; + } + x = false; + }); + assert_eq!(hits, 1); + assert!(x); + + assert!(fnmut_bad_again(true).is_err()); +} + +#[wasm_bindgen_test] +fn string_arguments() { + let mut x = false; + string_arguments_call(&mut |s| { + assert_eq!(s, "foo"); + x = true; + }); + assert!(x); +} + +#[wasm_bindgen_test] +fn string_ret() { + let mut x = false; + string_ret_call(&mut |mut s| { + assert_eq!(s, "foo"); + s.push_str("bar"); + x = true; + s + }); + assert!(x); +} + +#[wasm_bindgen_test] +fn drop_drops() { + static mut HIT: bool = false; + + struct A; + + impl Drop for A { + fn drop(&mut self) { + unsafe { + HIT = true; + } + } + } + let a = A; + let x: Closure = Closure::new(move || drop(&a)); + drop(x); + unsafe { + assert!(HIT); + } +} + +#[wasm_bindgen_test] +fn drop_during_call_ok() { + static mut HIT: bool = false; + struct A; + impl Drop for A { + fn drop(&mut self) { + unsafe { + HIT = true; + } + } + } + + let rc = Rc::new(RefCell::new(None)); + let rc2 = rc.clone(); + let x = 3; + let a = A; + let x: Closure = Closure::new(move || { + // "drop ourselves" + drop(rc2.borrow_mut().take().unwrap()); + + // `A` should not have been destroyed as a result + unsafe { + assert!(!HIT); + } + + // allocate some heap memory to try to paper over our `3` + drop(String::from("1234567890")); + + // make sure our closure memory is still valid + assert_eq!(x, 3); + + // make sure `A` is bound to our closure environment. + drop(&a); + unsafe { + assert!(!HIT); + } + }); + drop_during_call_save(&x); + *rc.borrow_mut() = Some(x); + drop(rc); + unsafe { + assert!(!HIT); + } + drop_during_call_call(); + unsafe { + assert!(HIT); + } +} + +#[wasm_bindgen_test] +fn test_closure_returner() { + type ClosureType = dyn FnMut() -> BadStruct; + + use js_sys::{Object, Reflect}; + use wasm_bindgen::JsCast; + + js_test_closure_returner(); + + #[wasm_bindgen] + pub struct ClosureHandle(Closure); + + #[wasm_bindgen] + pub struct BadStruct {} + + #[wasm_bindgen] + pub fn closure_returner() -> Result { + let o = Object::new(); + + let some_fn = Closure::wrap(Box::new(move || BadStruct {}) as Box); + Reflect::set( + &o, + &JsValue::from("someKey"), + &some_fn.as_ref().unchecked_ref(), + ) + .unwrap(); + Reflect::set( + &o, + &JsValue::from("handle"), + &JsValue::from(ClosureHandle(some_fn)), + ) + .unwrap(); + + Ok(o) + } +} + +#[wasm_bindgen] +pub struct RefFirstArgument { + contents: u32, +} + +#[wasm_bindgen_test] +fn reference_as_first_argument_builds_at_all() { + #[wasm_bindgen] + extern "C" { + fn ref_first_arg1(a: &dyn Fn(&JsValue)); + fn ref_first_arg2(a: &mut dyn FnMut(&JsValue)); + fn ref_first_arg3(a: &Closure); + fn ref_first_arg4(a: &Closure); + fn ref_first_custom1(a: &dyn Fn(&RefFirstArgument)); + fn ref_first_custom2(a: &mut dyn FnMut(&RefFirstArgument)); + fn ref_first_custom3(a: &Closure); + fn ref_first_custom4(a: &Closure); + } + + Closure::wrap(Box::new(|_: &JsValue| ()) as Box); + Closure::wrap(Box::new(|_: &JsValue| ()) as Box); + Closure::once(|_: &JsValue| ()); + Closure::once_into_js(|_: &JsValue| ()); + Closure::wrap(Box::new(|_: &RefFirstArgument| ()) as Box); + Closure::wrap(Box::new(|_: &RefFirstArgument| ()) as Box); + Closure::once(|_: &RefFirstArgument| ()); + Closure::once_into_js(|_: &RefFirstArgument| ()); +} + +#[wasm_bindgen_test] +fn reference_as_first_argument_works() { + let a = Rc::new(Cell::new(0)); + let b = { + let a = a.clone(); + Closure::once(move |x: &RefFirstArgument| { + assert_eq!(a.get(), 0); + assert_eq!(x.contents, 3); + a.set(a.get() + 1); + }) + }; + let c = { + let a = a.clone(); + Closure::once(move |x: &RefFirstArgument| { + assert_eq!(a.get(), 1); + assert_eq!(x.contents, 3); + a.set(a.get() + 1); + }) + }; + pass_reference_first_arg_twice(RefFirstArgument { contents: 3 }, &b, &c); + assert_eq!(a.get(), 2); +} + +#[wasm_bindgen_test] +fn reference_as_first_argument_works2() { + let a = Cell::new(0); + pass_reference_first_arg_twice2( + RefFirstArgument { contents: 3 }, + &mut |x: &RefFirstArgument| { + assert_eq!(a.get(), 0); + assert_eq!(x.contents, 3); + a.set(a.get() + 1); + }, + &mut |x: &RefFirstArgument| { + assert_eq!(a.get(), 1); + assert_eq!(x.contents, 3); + a.set(a.get() + 1); + }, + ); + assert_eq!(a.get(), 2); +} + +#[wasm_bindgen_test] +fn call_destroyed_doesnt_segfault() { + struct A(i32, i32); + impl Drop for A { + fn drop(&mut self) { + assert_eq!(self.0, self.1); + } + } + + let a = A(1, 1); + let a = Closure::wrap(Box::new(move || drop(&a)) as Box); + let b = a.as_ref().clone(); + drop(a); + call_destroyed(&b); + + let a = A(2, 2); + let a = Closure::wrap(Box::new(move || drop(&a)) as Box); + let b = a.as_ref().clone(); + drop(a); + call_destroyed(&b); + + let a = A(1, 1); + let a = Closure::wrap(Box::new(move |_: &JsValue| drop(&a)) as Box); + let b = a.as_ref().clone(); + drop(a); + call_destroyed(&b); + + let a = A(2, 2); + let a = Closure::wrap(Box::new(move |_: &JsValue| drop(&a)) as Box); + let b = a.as_ref().clone(); + drop(a); + call_destroyed(&b); +} + +#[wasm_bindgen_test] +fn forget_works() { + let a = Closure::wrap(Box::new(|| {}) as Box); + js_store_forgotten_closure(&a); + a.forget(); + js_call_forgotten_closure(); +} + +#[wasm_bindgen_test] +fn named_externref_no_duplicate_adapter() { + externref_call(&Closure::new(|a| assert_eq!(a, 1))); + named_externref_call(&Closure::new(|a| assert_eq!(a, 1))); +} diff --git a/vendor/wasm-bindgen/tests/wasm/comments.js b/vendor/wasm-bindgen/tests/wasm/comments.js new file mode 100644 index 000000000..1443281b5 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/comments.js @@ -0,0 +1,19 @@ +const fs = require('fs'); +const assert = require('assert'); + +exports.assert_comments_exist = function() { + const bindings_file = require.resolve('wasm-bindgen-test'); + const contents = fs.readFileSync(bindings_file); + assert.ok(contents.includes("* annotated function ✔️ \" \\ ' {")); + assert.ok(contents.includes("* annotated struct type")); + assert.ok(contents.includes("* annotated struct field b")); + assert.ok(contents.includes("* annotated struct field c")); + assert.ok(contents.includes("* annotated struct constructor")); + assert.ok(contents.includes("* annotated struct method")); + assert.ok(contents.includes("* annotated struct getter")); + assert.ok(contents.includes("* annotated struct setter")); + assert.ok(contents.includes("* annotated struct static method")); + assert.ok(contents.includes("* annotated enum type")); + assert.ok(contents.includes("* annotated enum variant 1")); + assert.ok(contents.includes("* annotated enum variant 2")); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/comments.rs b/vendor/wasm-bindgen/tests/wasm/comments.rs new file mode 100644 index 000000000..2d44e7b4a --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/comments.rs @@ -0,0 +1,73 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/comments.js")] +extern "C" { + fn assert_comments_exist(); +} + +/// annotated function ✔️ " \ ' { +#[wasm_bindgen] +pub fn annotated() -> String { + String::new() +} + +/// annotated struct type +#[wasm_bindgen] +pub struct Annotated { + a: String, + /// annotated struct field b + pub b: u32, + /// annotated struct field c + #[wasm_bindgen(readonly)] + pub c: u32, + d: u32, +} + +#[wasm_bindgen] +impl Annotated { + /// annotated struct constructor + #[wasm_bindgen(constructor)] + pub fn new() -> Self { + Self { + a: String::new(), + b: 0, + c: 0, + d: 0, + } + } + + /// annotated struct method + pub fn get_a(&self) -> String { + self.a.clone() + } + + /// annotated struct getter + #[wasm_bindgen(getter)] + pub fn d(&self) -> u32 { + self.d + } + + /// annotated struct setter + #[wasm_bindgen(setter)] + pub fn set_d(&mut self, value: u32) { + self.d = value + } + + /// annotated struct static method + pub fn static_method() {} +} + +/// annotated enum type +#[wasm_bindgen] +pub enum AnnotatedEnum { + /// annotated enum variant 1 + Variant1, + /// annotated enum variant 2 + Variant2, +} + +#[wasm_bindgen_test] +fn works() { + assert_comments_exist(); +} diff --git a/vendor/wasm-bindgen/tests/wasm/duplicate_deps.js b/vendor/wasm-bindgen/tests/wasm/duplicate_deps.js new file mode 100644 index 000000000..b69139dfa --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/duplicate_deps.js @@ -0,0 +1,17 @@ +const assert = require('assert'); + +let next = null; + +exports.assert_next_undefined = function() { + next = undefined; +}; + +exports.assert_next_ten = function() { + next = 10; +}; + +exports.foo = function(a) { + console.log(a, next); + assert.strictEqual(a, next); + next = null; +}; diff --git a/vendor/wasm-bindgen/tests/wasm/duplicate_deps.rs b/vendor/wasm-bindgen/tests/wasm/duplicate_deps.rs new file mode 100644 index 000000000..4d3506b90 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/duplicate_deps.rs @@ -0,0 +1,18 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; +use wasm_bindgen_test_crate_a as a; +use wasm_bindgen_test_crate_b as b; + +#[wasm_bindgen(module = "tests/wasm/duplicate_deps.js")] +extern "C" { + fn assert_next_undefined(); + fn assert_next_ten(); +} + +#[wasm_bindgen_test] +fn works() { + assert_next_undefined(); + a::test(); + assert_next_ten(); + b::test(); +} diff --git a/vendor/wasm-bindgen/tests/wasm/duplicates.rs b/vendor/wasm-bindgen/tests/wasm/duplicates.rs new file mode 100644 index 000000000..206fede71 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/duplicates.rs @@ -0,0 +1,57 @@ +use wasm_bindgen_test::*; + +pub mod same_function_different_locations_a { + use wasm_bindgen::prelude::*; + + #[wasm_bindgen(module = "tests/wasm/duplicates_a.js")] + extern "C" { + pub fn foo(); + pub static bar: JsValue; + } +} + +pub mod same_function_different_locations_b { + use wasm_bindgen::prelude::*; + + #[wasm_bindgen(module = "tests/wasm/duplicates_a.js")] + extern "C" { + pub fn foo(); + pub static bar: JsValue; + } +} + +#[wasm_bindgen_test] +fn same_function_different_locations() { + same_function_different_locations_a::foo(); + same_function_different_locations_b::foo(); + assert_eq!(*same_function_different_locations_a::bar, 3); + assert_eq!(*same_function_different_locations_a::bar, 3); +} + +pub mod same_function_different_modules_a { + use wasm_bindgen::prelude::*; + + #[wasm_bindgen(module = "tests/wasm/duplicates_b.js")] + extern "C" { + pub fn foo() -> bool; + pub static bar: JsValue; + } +} + +pub mod same_function_different_modules_b { + use wasm_bindgen::prelude::*; + + #[wasm_bindgen(module = "tests/wasm/duplicates_c.js")] + extern "C" { + pub fn foo() -> bool; + pub static bar: JsValue; + } +} + +#[wasm_bindgen_test] +fn same_function_different_modules() { + assert!(same_function_different_modules_a::foo()); + assert!(!same_function_different_modules_b::foo()); + assert_eq!(*same_function_different_modules_a::bar, 4); + assert_eq!(*same_function_different_modules_b::bar, 5); +} diff --git a/vendor/wasm-bindgen/tests/wasm/duplicates_a.js b/vendor/wasm-bindgen/tests/wasm/duplicates_a.js new file mode 100644 index 000000000..e52f346bc --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/duplicates_a.js @@ -0,0 +1,2 @@ +exports.foo = () => {}; +exports.bar = 3; diff --git a/vendor/wasm-bindgen/tests/wasm/duplicates_b.js b/vendor/wasm-bindgen/tests/wasm/duplicates_b.js new file mode 100644 index 000000000..75263a245 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/duplicates_b.js @@ -0,0 +1,2 @@ +exports.foo = () => true; +exports.bar = 4; diff --git a/vendor/wasm-bindgen/tests/wasm/duplicates_c.js b/vendor/wasm-bindgen/tests/wasm/duplicates_c.js new file mode 100644 index 000000000..601a99a57 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/duplicates_c.js @@ -0,0 +1,2 @@ +exports.foo = () => false; +exports.bar = 5; diff --git a/vendor/wasm-bindgen/tests/wasm/enums.js b/vendor/wasm-bindgen/tests/wasm/enums.js new file mode 100644 index 000000000..640597dac --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/enums.js @@ -0,0 +1,40 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +exports.js_c_style_enum = () => { + assert.strictEqual(wasm.Color.Green, 0); + assert.strictEqual(wasm.Color.Yellow, 1); + assert.strictEqual(wasm.Color.Red, 2); + assert.strictEqual(wasm.Color[0], 'Green'); + assert.strictEqual(wasm.Color[1], 'Yellow'); + assert.strictEqual(wasm.Color[2], 'Red'); + assert.strictEqual(Object.keys(wasm.Color).length, 6); + + assert.strictEqual(wasm.enum_cycle(wasm.Color.Green), wasm.Color.Yellow); +}; + +exports.js_c_style_enum_with_custom_values = () => { + assert.strictEqual(wasm.ColorWithCustomValues.Green, 21); + assert.strictEqual(wasm.ColorWithCustomValues.Yellow, 34); + assert.strictEqual(wasm.ColorWithCustomValues.Red, 2); + assert.strictEqual(wasm.ColorWithCustomValues[21], 'Green'); + assert.strictEqual(wasm.ColorWithCustomValues[34], 'Yellow'); + assert.strictEqual(wasm.ColorWithCustomValues[2], 'Red'); + assert.strictEqual(Object.keys(wasm.ColorWithCustomValues).length, 6); + + assert.strictEqual(wasm.enum_with_custom_values_cycle(wasm.ColorWithCustomValues.Green), wasm.ColorWithCustomValues.Yellow); +}; + +exports.js_handle_optional_enums = x => wasm.handle_optional_enums(x); + +exports.js_expect_enum = (a, b) => { + assert.strictEqual(a, b); +}; + +exports.js_expect_enum_none = a => { + assert.strictEqual(a, undefined); +}; + +exports.js_renamed_enum = b => { + assert.strictEqual(wasm.JsRenamedEnum.B, b); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/enums.rs b/vendor/wasm-bindgen/tests/wasm/enums.rs new file mode 100644 index 000000000..959a3e271 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/enums.rs @@ -0,0 +1,97 @@ +use self::inner::ColorWithCustomValues; +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/enums.js")] +extern "C" { + fn js_c_style_enum(); + fn js_c_style_enum_with_custom_values(); + fn js_handle_optional_enums(x: Option) -> Option; + fn js_expect_enum(x: Color, y: Option); + fn js_expect_enum_none(x: Option); + fn js_renamed_enum(b: RenamedEnum); +} + +#[wasm_bindgen] +#[derive(PartialEq, Debug)] +pub enum Color { + Green, + Yellow, + Red, +} + +pub mod inner { + use wasm_bindgen::prelude::*; + + #[wasm_bindgen] + pub enum ColorWithCustomValues { + Green = 21, + Yellow = 34, + Red = 2, + } +} + +#[wasm_bindgen(js_name = JsRenamedEnum)] +#[derive(Copy, Clone)] +pub enum RenamedEnum { + A = 10, + B = 20, +} + +#[wasm_bindgen] +pub fn enum_cycle(color: Color) -> Color { + match color { + Color::Green => Color::Yellow, + Color::Yellow => Color::Red, + Color::Red => Color::Green, + } +} + +#[wasm_bindgen] +pub fn enum_with_custom_values_cycle(color: ColorWithCustomValues) -> ColorWithCustomValues { + match color { + ColorWithCustomValues::Green => ColorWithCustomValues::Yellow, + ColorWithCustomValues::Yellow => ColorWithCustomValues::Red, + ColorWithCustomValues::Red => ColorWithCustomValues::Green, + } +} + +#[wasm_bindgen_test] +fn c_style_enum() { + js_c_style_enum(); +} + +#[wasm_bindgen_test] +fn c_style_enum_with_custom_values() { + js_c_style_enum_with_custom_values(); +} + +#[wasm_bindgen] +pub fn handle_optional_enums(x: Option) -> Option { + x +} + +#[wasm_bindgen_test] +fn test_optional_enums() { + use self::Color::*; + + assert_eq!(js_handle_optional_enums(None), None); + assert_eq!(js_handle_optional_enums(Some(Green)), Some(Green)); + assert_eq!(js_handle_optional_enums(Some(Yellow)), Some(Yellow)); + assert_eq!(js_handle_optional_enums(Some(Red)), Some(Red)); +} + +#[wasm_bindgen_test] +fn test_optional_enum_values() { + use self::Color::*; + + js_expect_enum(Green, Some(Green)); + js_expect_enum(Yellow, Some(Yellow)); + js_expect_enum(Red, Some(Red)); + js_expect_enum_none(None); +} + +#[wasm_bindgen_test] +fn test_renamed_enum() { + js_renamed_enum(RenamedEnum::B); +} diff --git a/vendor/wasm-bindgen/tests/wasm/final.js b/vendor/wasm-bindgen/tests/wasm/final.js new file mode 100644 index 000000000..15b576d02 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/final.js @@ -0,0 +1,25 @@ +const assert = require('assert'); + +exports.MyType = class { + static foo(y) { + assert.equal(y, 'x'); + return y + 'y'; + } + + constructor(x) { + assert.equal(x, 2); + this._a = 1; + } + + bar(x) { + assert.equal(x, true); + return 3.2; + } + + get a() { + return this._a; + } + set a(v) { + this._a = v; + } +}; diff --git a/vendor/wasm-bindgen/tests/wasm/final.rs b/vendor/wasm-bindgen/tests/wasm/final.rs new file mode 100644 index 000000000..63aa661f5 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/final.rs @@ -0,0 +1,40 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen] +extern "C" { + type Math; + #[wasm_bindgen(static_method_of = Math, final)] + fn log(f: f32) -> f32; +} + +#[wasm_bindgen(module = "tests/wasm/final.js")] +extern "C" { + type MyType; + #[wasm_bindgen(constructor, final)] + fn new(x: u32) -> MyType; + #[wasm_bindgen(static_method_of = MyType, final)] + fn foo(a: &str) -> String; + #[wasm_bindgen(method, final)] + fn bar(this: &MyType, arg: bool) -> f32; + + #[wasm_bindgen(method, getter, final)] + fn a(this: &MyType) -> u32; + #[wasm_bindgen(method, setter, final)] + fn set_a(this: &MyType, a: u32); +} + +#[wasm_bindgen_test] +fn simple() { + assert_eq!(Math::log(1.0), 0.0); +} + +#[wasm_bindgen_test] +fn classes() { + assert_eq!(MyType::foo("x"), "xy"); + let x = MyType::new(2); + assert_eq!(x.bar(true), 3.2); + assert_eq!(x.a(), 1); + x.set_a(3); + assert_eq!(x.a(), 3); +} diff --git a/vendor/wasm-bindgen/tests/wasm/futures.js b/vendor/wasm-bindgen/tests/wasm/futures.js new file mode 100644 index 000000000..5f4564bac --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/futures.js @@ -0,0 +1,44 @@ +const assert = require('assert'); +const wasm = require('wasm-bindgen-test'); + +exports.call_exports = async function() { + await wasm.async_do_nothing(); + assert.strictEqual(1, await wasm.async_return_1()); + assert.strictEqual(2, await wasm.async_return_2()); + await wasm.async_nothing_again(); + assert.strictEqual(3, await wasm.async_return_3()); + assert.strictEqual(4, await wasm.async_return_4()); + assert.strictEqual(5, (await wasm.async_return_5()).val); + assert.strictEqual(6, (await wasm.async_return_6()).val); + await assert.rejects(wasm.async_throw_7(), /7/); + await assert.rejects(wasm.async_throw_custom(), /\[object Object\]/); + await assert.rejects(wasm.async_throw_message(), /async message/); + await assert.rejects(wasm.async_throw_jserror(), /async message/); + await assert.rejects(wasm.async_throw_custom_error(), /custom error/); + assert.strictEqual("Hi, Jim!", await wasm.async_take_reference("Jim")); + const foo = await new wasm.AsyncStruct(); + assert.strictEqual(42, await foo.method()); +}; + +exports.call_promise = async function() { + return "ok"; +} + +exports.call_promise_ok = async function() { + return "ok"; +} + +exports.call_promise_err = async function() { + throw "error"; +} + +exports.call_promise_unit = async function() { + console.log("asdfasdf"); +} + +exports.call_promise_ok_unit = async function() { +} + +exports.call_promise_err_unit = async function() { + throw "error"; +} diff --git a/vendor/wasm-bindgen/tests/wasm/futures.rs b/vendor/wasm-bindgen/tests/wasm/futures.rs new file mode 100644 index 000000000..ad2be0f71 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/futures.rs @@ -0,0 +1,166 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[rustfmt::skip] +#[wasm_bindgen(module = "tests/wasm/futures.js")] +extern "C" { + #[wasm_bindgen(catch)] + async fn call_exports() -> Result; + + async fn call_promise() -> JsValue; + #[wasm_bindgen(catch)] + async fn call_promise_ok() -> Result; + #[wasm_bindgen(catch)] + async fn call_promise_err() -> Result; + + #[wasm_bindgen] + async fn call_promise_unit(); + #[wasm_bindgen(catch)] + async fn call_promise_ok_unit() -> Result<(), JsValue>; + #[wasm_bindgen(catch)] + async fn call_promise_err_unit() -> Result<(), JsValue>; +} + +#[wasm_bindgen_test] +async fn smoke() { + call_exports().await.unwrap(); +} + +#[wasm_bindgen] +pub async fn async_do_nothing() {} + +#[wasm_bindgen] +pub async fn async_return_1() -> JsValue { + 1.into() +} + +#[wasm_bindgen] +pub async fn async_return_2() -> u32 { + 2 +} + +#[wasm_bindgen] +pub async fn async_nothing_again() -> Result<(), JsValue> { + Ok(()) +} + +#[wasm_bindgen] +pub async fn async_return_3() -> Result { + Ok(3) +} + +#[wasm_bindgen] +pub async fn async_return_4() -> Result { + Ok(4.into()) +} + +#[wasm_bindgen] +pub struct AsyncCustomReturn { + pub val: u32, +} + +#[wasm_bindgen] +pub async fn async_return_5() -> AsyncCustomReturn { + AsyncCustomReturn { val: 5 } +} + +#[wasm_bindgen] +pub async fn async_return_6() -> Result { + Ok(AsyncCustomReturn { val: 6 }) +} + +#[wasm_bindgen] +pub async fn async_throw_7() -> Result { + Err(7.into()) +} + +#[wasm_bindgen] +pub async fn async_throw_custom() -> Result { + Err(AsyncCustomReturn { val: 8 }.into()) +} + +#[wasm_bindgen] +pub async fn async_throw_message() -> Result<(), JsValue> { + Err(js_sys::Error::new("async message").into()) +} + +#[wasm_bindgen] +pub async fn async_throw_jserror() -> Result { + Err(JsError::new("async message")) +} + +pub struct AsyncCustomError { + pub val: JsValue, +} + +impl Into for AsyncCustomError { + fn into(self) -> JsValue { + self.val + } +} + +#[wasm_bindgen] +pub async fn async_throw_custom_error() -> Result { + Err(AsyncCustomError { + val: JsValue::from("custom error"), + }) +} + +#[wasm_bindgen] +pub async fn async_take_reference(x: &str) -> String { + format!("Hi, {x}!") +} + +#[wasm_bindgen] +pub struct AsyncStruct; + +#[wasm_bindgen] +impl AsyncStruct { + #[wasm_bindgen(constructor)] + pub async fn new() -> AsyncStruct { + AsyncStruct + } + + pub async fn method(&self) -> u32 { + 42 + } +} + +#[wasm_bindgen_test] +async fn test_promise() { + assert_eq!(call_promise().await.as_string(), Some(String::from("ok"))) +} + +#[wasm_bindgen_test] +async fn test_promise_ok() { + assert_eq!( + call_promise_ok().await.map(|j| j.as_string()), + Ok(Some(String::from("ok"))) + ) +} + +#[wasm_bindgen_test] +async fn test_promise_err() { + assert_eq!( + call_promise_err().await.map_err(|j| j.as_string()), + Err(Some(String::from("error"))) + ) +} + +#[wasm_bindgen_test] +async fn test_promise_unit() { + call_promise_unit().await +} + +#[wasm_bindgen_test] +async fn test_promise_ok_unit() { + call_promise_ok_unit().await.unwrap() +} + +#[wasm_bindgen_test] +async fn test_promise_err_unit() { + assert_eq!( + call_promise_err_unit().await.map_err(|j| j.as_string()), + Err::<(), _>(Some(String::from("error"))) + ) +} diff --git a/vendor/wasm-bindgen/tests/wasm/getters_and_setters.js b/vendor/wasm-bindgen/tests/wasm/getters_and_setters.js new file mode 100644 index 000000000..48379e2e8 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/getters_and_setters.js @@ -0,0 +1,107 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +exports._1_js = (rules) => { + assert.equal(rules.field, 1); + rules.field *= 2; + return rules; +} + +exports._2_js = (rules) => { + let value = rules.no_js_name__no_getter_with_name__no_getter_without_name(); + assert.equal(value, 2); + rules.set_no_js_name__no_setter_with_name__no_setter_without_name(value * 2); + return rules; +} + +exports._3_js = (rules) => { + let value = rules.no_js_name__no_getter_with_name__getter_without_name; + assert.equal(value, 3); + rules.no_js_name__no_setter_with_name__setter_without_name = value * 2; + return rules; +} + +exports._4_js = (rules) => { + let value = rules.new_no_js_name__getter_with_name__getter_without_name; + assert.equal(value, 4); + rules.new_no_js_name__setter_with_name__setter_without_name = value * 2; + return rules; +} + +exports._5_js = (rules) => { + let value = rules.new_js_name__no_getter_with_name__no_getter_without_name(); + assert.equal(value, 5); + rules.new_js_name__no_setter_with_name__no_setter_without_name(value * 2); + return rules; +} + +exports._6_js = (rules) => { + let value = rules.new_js_name__no_getter_with_name__getter_without_name; + assert.equal(value, 6); + rules.new_js_name__no_setter_with_name__setter_without_name = value * 2; + return rules; +} + +exports._7_js = (rules) => { + let value = rules.new_js_name__getter_with_name__no_getter_without_name_for_field; + assert.equal(value, 7); + rules.new_js_name__setter_with_name__no_setter_without_name_for_field = value * 2; + return rules; +} + +exports._8_js = (rules) => { + let value = rules.new_js_name__no_getter_setter_with_name__getter_setter_without_name__same_getter_setter_name; + assert.equal(value, 8); + rules.new_js_name__no_getter_setter_with_name__getter_setter_without_name__same_getter_setter_name = value * 2; + return rules; +} + +exports._9_js = (rules) => { + let value = rules.new_js_name__no_getter_setter_with_name__getter_setter_without_name__same_getter_setter_name__same_getter_setter_origin_name; + assert.equal(value, 9); + rules.new_js_name__no_getter_setter_with_name__getter_setter_without_name__same_getter_setter_name__same_getter_setter_origin_name = value * 2; + return rules; +} + +exports._10_js = (rules) => { + let value = rules.new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_field__same_getter_setter_name; + assert.equal(value, 10); + rules.new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_field__same_getter_setter_name = value * 2; + return rules; +} + +exports._11_js = (rules) => { + let value = rules.new_js_name__getter_with_name__no_getter_without_name_for_field__same_getter_setter_name; + assert.equal(value, 11); + rules.new_js_name__setter_with_name__no_setter_without_name_for_field__same_getter_setter_name = value * 2; + return rules; +} + +exports._12_js = (rules) => { + let value = rules.new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_field__same_getter_setter_name__same_getter_setter_origin_name; + assert.equal(value, 12); + rules.new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_field__same_getter_setter_name__same_getter_setter_origin_name = value * 2; + return rules; +} + +exports._13_js = (rules) => { + let value = rules.new_js_name__getter_with_name__no_getter_without_name_for_field__same_getter_setter_name__same_getter_setter_origin_name; + assert.equal(value, 13); + rules.new_js_name__setter_with_name__no_setter_without_name_for_field__same_getter_setter_name__same_getter_setter_origin_name = value * 2; + return rules; +} + +exports.test_getter_compute = x => { + assert.equal(x.foo, 3) +}; + +exports.test_setter_compute = x => { + x.foo = 97; +}; + +exports.test_statics = x => { + assert.equal(x.field, 3); + assert.equal(wasm.Statics.field, 4); + x.field = 13; + wasm.Statics.field = 14; +} diff --git a/vendor/wasm-bindgen/tests/wasm/getters_and_setters.rs b/vendor/wasm-bindgen/tests/wasm/getters_and_setters.rs new file mode 100644 index 000000000..7425fc23e --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/getters_and_setters.rs @@ -0,0 +1,348 @@ +use std::cell::Cell; +use std::rc::Rc; +use std::sync::atomic::{AtomicU32, Ordering}; +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/getters_and_setters.js")] +extern "C" { + fn _1_js(rules: Rules) -> Rules; + fn _2_js(rules: Rules) -> Rules; + fn _3_js(rules: Rules) -> Rules; + fn _4_js(rules: Rules) -> Rules; + fn _5_js(rules: Rules) -> Rules; + fn _6_js(rules: Rules) -> Rules; + fn _7_js(rules: Rules) -> Rules; + fn _8_js(rules: Rules) -> Rules; + fn _9_js(rules: Rules) -> Rules; + fn _10_js(rules: Rules) -> Rules; + fn _11_js(rules: Rules) -> Rules; + fn _12_js(rules: Rules) -> Rules; + fn _13_js(rules: Rules) -> Rules; + + fn test_getter_compute(x: GetterCompute); + fn test_setter_compute(x: SetterCompute); + fn test_statics(x: Statics); +} + +// Each getter/setter combination is derived +// from https://github.com/rustwasm/wasm-bindgen/pull/1440#issuecomment-487113564 +#[wasm_bindgen] +pub struct Rules { + pub field: i32, +} + +#[wasm_bindgen] +#[allow(non_snake_case)] +impl Rules { + #[wasm_bindgen] + pub fn no_js_name__no_getter_with_name__no_getter_without_name(&self) -> i32 { + self.field + } + #[wasm_bindgen] + pub fn set_no_js_name__no_setter_with_name__no_setter_without_name(&mut self, field: i32) { + self.field = field; + } + + #[wasm_bindgen(getter)] + pub fn no_js_name__no_getter_with_name__getter_without_name(&self) -> i32 { + self.field + } + #[wasm_bindgen(setter)] + pub fn set_no_js_name__no_setter_with_name__setter_without_name(&mut self, field: i32) { + self.field = field; + } + + #[wasm_bindgen(getter = new_no_js_name__getter_with_name__getter_without_name)] + pub fn no_js_name__getter_with_name__getter_without_name(&self) -> i32 { + self.field + } + #[wasm_bindgen(setter = new_no_js_name__setter_with_name__setter_without_name)] + pub fn set_no_js_name__setter_with_name__setter_without_name(&mut self, field: i32) { + self.field = field; + } + + #[wasm_bindgen(js_name = new_js_name__no_getter_with_name__no_getter_without_name)] + pub fn js_name__no_getter_with_name__no_getter_without_name(&self) -> i32 { + self.field + } + #[wasm_bindgen(js_name = new_js_name__no_setter_with_name__no_setter_without_name)] + pub fn set_js_name__no_setter_with_name__no_setter_without_name(&mut self, field: i32) { + self.field = field; + } + + #[wasm_bindgen(getter, js_name = new_js_name__no_getter_with_name__getter_without_name)] + pub fn js_name__no_getter_with_name__getter_without_name(&self) -> i32 { + self.field + } + #[wasm_bindgen(js_name = new_js_name__no_setter_with_name__setter_without_name, setter)] + pub fn set_js_name__no_setter_with_name__setter_without_name(&mut self, field: i32) { + self.field = field; + } + + #[wasm_bindgen( + getter = new_js_name__getter_with_name__no_getter_without_name_for_field, + js_name = new_js_name__getter_with_name__no_getter_without_name_for_method + )] + pub fn js_name__getter_with_name__no_getter_without_name(&self) -> i32 { + self.field + } + #[wasm_bindgen( + js_name = new_js_name__setter_with_name__no_setter_without_name_for_method, + setter = new_js_name__setter_with_name__no_setter_without_name_for_field + )] + pub fn set_js_name__setter_with_name__no_setter_without_name_for_field(&mut self, field: i32) { + self.field = field; + } + + #[wasm_bindgen(getter, js_name = new_js_name__no_getter_setter_with_name__getter_setter_without_name__same_getter_setter_name)] + pub fn js_name__no_getter_with_name__getter_without_name__same_getter_setter_name( + &self, + ) -> i32 { + self.field + } + #[wasm_bindgen(js_name = new_js_name__no_getter_setter_with_name__getter_setter_without_name__same_getter_setter_name, setter)] + pub fn set_js_name__no_setter_with_name__setter_without_name__same_getter_setter_name( + &mut self, + field: i32, + ) { + self.field = field; + } + + #[wasm_bindgen(getter, js_name = new_js_name__no_getter_setter_with_name__getter_setter_without_name__same_getter_setter_name__same_getter_setter_origin_name)] + pub fn js_name__no_getter_setter_with_name__getter_setter_without_name__same_getter_setter_name__same_getter_setter_origin_name( + &self, + ) -> i32 { + self.field + } + #[wasm_bindgen(js_name = new_js_name__no_getter_setter_with_name__getter_setter_without_name__same_getter_setter_name__same_getter_setter_origin_name, setter)] + pub fn set_js_name__no_getter_setter_with_name__getter_setter_without_name__same_getter_setter_name__same_getter_setter_origin_name( + &mut self, + field: i32, + ) { + self.field = field; + } + + #[wasm_bindgen( + getter = new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_field__same_getter_setter_name, + js_name = new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_method__same_getter_setter_name)] + pub fn js_name__getter_with_name__no_getter_without_name__same_getter_setter_name( + &self, + ) -> i32 { + self.field + } + #[wasm_bindgen( + js_name = new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_method__same_getter_setter_name, + setter = new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_field__same_getter_setter_name)] + pub fn set_js_name__setter_with_name__no_setter_without_name__same_getter_setter_name( + &mut self, + field: i32, + ) { + self.field = field; + } + + #[wasm_bindgen( + getter = new_js_name__getter_with_name__no_getter_without_name_for_field__same_getter_setter_name, + js_name = new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_method__same_getter_setter_name__no_same_field_name)] + pub fn js_name__getter_with_name__no_getter_without_name__same_getter_setter_name__no_same_field_name( + &self, + ) -> i32 { + self.field + } + #[wasm_bindgen( + js_name = new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_method__same_getter_setter_name__no_same_field_name, + setter = new_js_name__setter_with_name__no_setter_without_name_for_field__same_getter_setter_name)] + pub fn set_js_name__setter_with_name__no_setter_without_name__same_getter_setter_name__no_same_field_name( + &mut self, + field: i32, + ) { + self.field = field; + } + + #[wasm_bindgen( + getter = new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_field__same_getter_setter_name__same_getter_setter_origin_name, + js_name = new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_method__same_getter_setter_name__same_getter_setter_origin_name)] + pub fn js_name__getter_setter_with_name__no_getter_setter_without_name__same_getter_setter_name__same_getter_setter_origin_name( + &self, + ) -> i32 { + self.field + } + #[wasm_bindgen( + js_name = new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_method__same_getter_setter_name__same_getter_setter_origin_name, + setter = new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_field__same_getter_setter_name__same_getter_setter_origin_name)] + pub fn set_js_name__getter_setter_with_name__no_getter_setter_without_name__same_getter_setter_name__same_getter_setter_origin_name( + &mut self, + field: i32, + ) { + self.field = field; + } + + #[wasm_bindgen( + getter = new_js_name__getter_with_name__no_getter_without_name_for_field__same_getter_setter_name__same_getter_setter_origin_name, + js_name = new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_method__same_getter_setter_name__same_getter_setter_origin_name__no_same_field_name)] + pub fn js_name__getter_setter_with_name__no_getter_setter_without_name__same_getter_setter_name__same_getter_setter_origin_name__no_same_field_name( + &self, + ) -> i32 { + self.field + } + #[wasm_bindgen( + js_name = new_js_name__getter_setter_with_name__no_getter_setter_without_name_for_method__same_getter_setter_name__same_getter_setter_origin_name__no_same_field_name, + setter = new_js_name__setter_with_name__no_setter_without_name_for_field__same_getter_setter_name__same_getter_setter_origin_name)] + pub fn set_js_name__getter_setter_with_name__no_getter_setter_without_name__same_getter_setter_name__same_getter_setter_origin_name__no_same_field_name( + &mut self, + field: i32, + ) { + self.field = field; + } +} + +#[wasm_bindgen_test] +fn _1_rust() { + let rules = _1_js(Rules { field: 1 }); + assert_eq!(rules.field, 2); +} + +#[wasm_bindgen_test] +fn _2_rust() { + let rules = _2_js(Rules { field: 2 }); + assert_eq!(rules.field, 4); +} + +#[wasm_bindgen_test] +fn _3_rust() { + let rules = _3_js(Rules { field: 3 }); + assert_eq!(rules.field, 6); +} + +#[wasm_bindgen_test] +fn _4_rust() { + let rules = _4_js(Rules { field: 4 }); + assert_eq!(rules.field, 8); +} + +#[wasm_bindgen_test] +fn _5_rust() { + let rules = _5_js(Rules { field: 5 }); + assert_eq!(rules.field, 10); +} + +#[wasm_bindgen_test] +fn _6_rust() { + let rules = _6_js(Rules { field: 6 }); + assert_eq!(rules.field, 12); +} + +#[wasm_bindgen_test] +fn _7_rust() { + let rules = _7_js(Rules { field: 7 }); + assert_eq!(rules.field, 14); +} + +#[wasm_bindgen_test] +fn _8_rust() { + let rules = _8_js(Rules { field: 8 }); + assert_eq!(rules.field, 16); +} + +#[wasm_bindgen_test] +fn _9_rust() { + let rules = _9_js(Rules { field: 9 }); + assert_eq!(rules.field, 18); +} + +#[wasm_bindgen_test] +fn _10_rust() { + let rules = _10_js(Rules { field: 10 }); + assert_eq!(rules.field, 20); +} + +#[wasm_bindgen_test] +fn _11_rust() { + let rules = _11_js(Rules { field: 11 }); + assert_eq!(rules.field, 22); +} + +#[wasm_bindgen_test] +fn _12_rust() { + let rules = _12_js(Rules { field: 12 }); + assert_eq!(rules.field, 24); +} + +#[wasm_bindgen_test] +fn _13_rust() { + let rules = _13_js(Rules { field: 13 }); + assert_eq!(rules.field, 26); +} + +#[wasm_bindgen] +struct GetterCompute; + +#[wasm_bindgen] +impl GetterCompute { + #[wasm_bindgen(getter)] + pub fn foo(&self) -> u32 { + 3 + } +} + +#[wasm_bindgen_test] +fn getter_compute() { + test_getter_compute(GetterCompute); +} + +#[wasm_bindgen] +struct SetterCompute(Rc>); + +#[wasm_bindgen] +impl SetterCompute { + #[wasm_bindgen(setter)] + pub fn set_foo(&self, x: u32) { + self.0.set(x + 3); + } +} + +#[wasm_bindgen_test] +fn setter_compute() { + let r = Rc::new(Cell::new(3)); + test_setter_compute(SetterCompute(r.clone())); + assert_eq!(r.get(), 100); +} + +static FIELD: AtomicU32 = AtomicU32::new(3); +static STATIC_FIELD: AtomicU32 = AtomicU32::new(4); + +#[wasm_bindgen] +struct Statics; + +#[wasm_bindgen] +impl Statics { + #[wasm_bindgen(getter = field)] + // Make sure that this still works if we make this mutable for no reason + pub fn getter(&mut self) -> u32 { + FIELD.load(Ordering::Relaxed) + } + + #[wasm_bindgen(setter = field)] + // Make sure that this still works if we make this consume the type for no reason + pub fn setter(self, x: u32) { + FIELD.store(x, Ordering::Relaxed) + } + + // Define a static field with the same name to make sure that works. + #[wasm_bindgen(getter = field)] + pub fn static_getter() -> u32 { + STATIC_FIELD.load(Ordering::Relaxed) + } + + #[wasm_bindgen(setter = field)] + pub fn static_setter(x: u32) { + STATIC_FIELD.store(x, Ordering::Relaxed) + } +} + +#[wasm_bindgen_test] +fn statics() { + test_statics(Statics); + assert_eq!(FIELD.load(Ordering::Relaxed), 13); + assert_eq!(STATIC_FIELD.load(Ordering::Relaxed), 14); +} diff --git a/vendor/wasm-bindgen/tests/wasm/import_class.js b/vendor/wasm-bindgen/tests/wasm/import_class.js new file mode 100644 index 000000000..848be7b14 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/import_class.js @@ -0,0 +1,170 @@ +const assert = require('assert'); +const wasm = require('wasm-bindgen-test'); + +exports.math_log = Math.log; + +exports.StaticFunction = class { + static bar() { return 2; } +}; + +class Construct { + static create() { + const ret = new Construct(); + ret.internal_string = 'this'; + return ret; + } + + get_internal_string() { + return this.internal_string; + } + + append_to_internal_string(s) { + this.internal_string += s; + } + + assert_internal_string(s) { + assert.strictEqual(this.internal_string, s); + } +} + +Construct.internal_string = ''; +exports.Construct = Construct; + +class NewConstructor { + constructor(field) { + this.field = field; + } + + get() { + return this.field + 1; + } +} + +exports.NewConstructors = NewConstructor; +exports.default = NewConstructor; + +let switch_called = false; +class SwitchMethods { + constructor() { + } + + static a() { + switch_called = true; + } + + b() { + switch_called = true; + } +} +exports.SwitchMethods = SwitchMethods; +exports.switch_methods_called = function() { + const tmp = switch_called; + switch_called = false; + return tmp; +}; +exports.switch_methods_a = function() { SwitchMethods.a = function() {}; }; +exports.switch_methods_b = function() { SwitchMethods.prototype.b = function() {}; }; + +exports.Properties = class { + constructor() { + this.num = 1; + } + + get a() { + return this.num; + } + + set a(val) { + this.num = val; + } +}; + +exports.RenameProperties = class { + constructor() { + this.num = 1; + } + + get a() { + return this.num; + } + + set a(val) { + this.num = val; + } +}; + +class Options { +} +exports.Options = Options; + +exports.take_none = function(val) { + assert.strictEqual(val, undefined); +}; + +exports.take_some = function(val) { + assert.strictEqual(val === undefined, false); +}; + +exports.return_null = function() { + return null; +}; + +exports.return_undefined = function() { + return undefined; +}; + +exports.return_some = function() { + return new Options(); +}; + +exports.run_rust_option_tests = function() { + wasm.rust_take_none(); + wasm.rust_take_none(null) + wasm.rust_take_none(undefined); + wasm.rust_take_some(new Options()); + assert.strictEqual(wasm.rust_return_none(), undefined); + assert.strictEqual(wasm.rust_return_none(), undefined); + assert.strictEqual(wasm.rust_return_some() === undefined, false); +}; + +exports.CatchConstructors = class { + constructor(x) { + if (x == 0) { + throw new Error('bad!'); + } + } +}; + +exports.StaticStructural = class { + static static_structural(x) { + return x + 3; + } +}; + +class InnerClass { + static inner_static_function(x) { + return x + 5; + } + + static create_inner_instance() { + const ret = new InnerClass(); + ret.internal_int = 3; + return ret; + } + + get_internal_int() { + return this.internal_int; + } + + append_to_internal_int(i) { + this.internal_int += i; + } + + assert_internal_int(i) { + assert.strictEqual(this.internal_int, i); + } +} + +exports.nestedNamespace = { + InnerClass: InnerClass +} diff --git a/vendor/wasm-bindgen/tests/wasm/import_class.rs b/vendor/wasm-bindgen/tests/wasm/import_class.rs new file mode 100644 index 000000000..7de986147 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/import_class.rs @@ -0,0 +1,263 @@ +//! dox + +#![deny(missing_docs)] // test that documenting public bindings is enough + +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/import_class.js")] +extern "C" { + fn math_log(f: f64) -> f64; + + #[wasm_bindgen(js_namespace = StaticFunction)] + fn bar() -> u32; + + #[derive(Clone)] + type Construct; + #[wasm_bindgen(js_namespace = Construct)] + fn create() -> Construct; + #[wasm_bindgen(method)] + fn get_internal_string(this: &Construct) -> String; + #[wasm_bindgen(method)] + fn append_to_internal_string(this: &Construct, s: &str); + #[wasm_bindgen(method)] + fn assert_internal_string(this: &Construct, s: &str); + + type NewConstructors; + #[wasm_bindgen(constructor)] + fn new(arg: i32) -> NewConstructors; + #[wasm_bindgen(method)] + fn get(this: &NewConstructors) -> i32; + + #[wasm_bindgen(js_name = default)] + type RenamedTypes; + #[wasm_bindgen(constructor, js_class = default)] + fn new(arg: i32) -> RenamedTypes; + #[wasm_bindgen(method, js_class = default)] + fn get(this: &RenamedTypes) -> i32; + + fn switch_methods_a(); + fn switch_methods_b(); + type SwitchMethods; + #[wasm_bindgen(constructor)] + #[wasm_bindgen(final)] + fn new() -> SwitchMethods; + #[wasm_bindgen(js_namespace = SwitchMethods, final)] + fn a(); + fn switch_methods_called() -> bool; + #[wasm_bindgen(method, final)] + fn b(this: &SwitchMethods); + + type Properties; + #[wasm_bindgen(constructor)] + fn new() -> Properties; + #[wasm_bindgen(getter, method)] + fn a(this: &Properties) -> i32; + #[wasm_bindgen(setter, method)] + fn set_a(this: &Properties, a: i32); + + type RenameProperties; + #[wasm_bindgen(constructor)] + fn new() -> RenameProperties; + #[wasm_bindgen(getter = a, method)] + fn test(this: &RenameProperties) -> i32; + #[wasm_bindgen(getter, method, js_name = a)] + fn test2(this: &RenameProperties) -> i32; + #[wasm_bindgen(setter = a, method)] + fn another(this: &RenameProperties, a: i32); + #[wasm_bindgen(setter, method, js_name = a)] + fn another2(this: &RenameProperties, a: i32); + + /// dox + pub type AssertImportDenyDocsWorks; + /// dox + #[wasm_bindgen(constructor)] + pub fn new() -> AssertImportDenyDocsWorks; + /// dox + #[wasm_bindgen(getter = a, method)] + pub fn test(this: &AssertImportDenyDocsWorks) -> i32; + /// dox + pub fn foo(); + + pub type Options; + #[wasm_bindgen(constructor)] + fn new() -> Options; + fn take_none(val: Option); + fn take_some(val: Option); + fn return_null() -> Option; + fn return_undefined() -> Option; + fn return_some() -> Option; + fn run_rust_option_tests(); + + type CatchConstructors; + #[wasm_bindgen(constructor, catch)] + fn new(x: u32) -> Result; + + type StaticStructural; + #[wasm_bindgen(static_method_of = StaticStructural, structural)] + fn static_structural(a: u32) -> u32; + + #[derive(Clone)] + type InnerClass; + #[wasm_bindgen(js_namespace = ["nestedNamespace", "InnerClass"])] + fn inner_static_function(a: u32) -> u32; + #[wasm_bindgen(js_namespace = ["nestedNamespace", "InnerClass"])] + fn create_inner_instance() -> InnerClass; + #[wasm_bindgen(method)] + fn get_internal_int(this: &InnerClass) -> u32; + #[wasm_bindgen(method)] + fn append_to_internal_int(this: &InnerClass, i: u32); + #[wasm_bindgen(method)] + fn assert_internal_int(this: &InnerClass, i: u32); +} + +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(js_namespace = Math)] + fn random() -> f64; + #[wasm_bindgen(js_namespace = Math)] + fn log(a: f64) -> f64; +} + +#[wasm_bindgen_test] +fn simple() { + random(); + assert_eq!(log(1.0), math_log(1.0)); +} + +#[wasm_bindgen_test] +fn import_class() { + assert_eq!(bar(), 2); +} + +#[wasm_bindgen_test] +fn construct() { + let f = Construct::create(); + assert_eq!(f.get_internal_string(), "this"); + assert_eq!(f.clone().get_internal_string(), "this"); + f.append_to_internal_string(" foo"); + f.assert_internal_string("this foo"); +} + +#[wasm_bindgen_test] +fn new_constructors() { + let f = NewConstructors::new(1); + assert_eq!(f.get(), 2); +} + +#[wasm_bindgen_test] +fn rename_type() { + let f = RenamedTypes::new(1); + assert_eq!(f.get(), 2); +} + +#[wasm_bindgen_test] +#[cfg(ignored)] // TODO: fix this before landing +fn switch_methods() { + assert!(!switch_methods_called()); + SwitchMethods::a(); + assert!(switch_methods_called()); + + switch_methods_a(); + + assert!(!switch_methods_called()); + SwitchMethods::a(); + assert!(switch_methods_called()); + + assert!(!switch_methods_called()); + SwitchMethods::new().b(); + assert!(switch_methods_called()); + + switch_methods_b(); + + assert!(!switch_methods_called()); + SwitchMethods::new().b(); + assert!(!switch_methods_called()); +} + +#[wasm_bindgen_test] +fn properties() { + let a = Properties::new(); + assert_eq!(a.a(), 1); + a.set_a(2); + assert_eq!(a.a(), 2); +} + +#[wasm_bindgen_test] +fn rename_setter_getter() { + let x: fn() -> RenameProperties = RenameProperties::new; + let a = x(); + assert_eq!(a.test(), 1); + a.another(2); + assert_eq!(a.test(), 2); + a.another2(3); + assert_eq!(a.test2(), 3); +} + +/// dox +#[wasm_bindgen] +pub struct AssertDenyDocsWorks { + /// dox + pub a: u32, + _b: i64, +} + +/// dox +#[wasm_bindgen] +pub fn assert_deny_docs_works() {} + +#[wasm_bindgen_test] +fn options() { + take_none(None); + take_some(Some(Options::new())); + assert!(return_null().is_none()); + assert!(return_undefined().is_none()); + assert!(return_some().is_some()); + run_rust_option_tests(); +} + +/// doc +#[wasm_bindgen] +pub fn rust_take_none(a: Option) { + assert!(a.is_none()); +} + +/// doc +#[wasm_bindgen] +pub fn rust_take_some(a: Option) { + assert!(a.is_some()); +} + +/// doc +#[wasm_bindgen] +pub fn rust_return_none() -> Option { + None +} + +/// doc +#[wasm_bindgen] +pub fn rust_return_some() -> Option { + Some(Options::new()) +} + +#[wasm_bindgen_test] +fn catch_constructors() { + assert!(CatchConstructors::new(0).is_err()); + assert!(CatchConstructors::new(1).is_ok()); +} + +#[wasm_bindgen_test] +fn static_structural() { + assert_eq!(StaticStructural::static_structural(30), 33); +} + +#[wasm_bindgen_test] +fn nested_namespace() { + assert_eq!(InnerClass::inner_static_function(15), 20); + + let f = InnerClass::create_inner_instance(); + assert_eq!(f.get_internal_int(), 3); + assert_eq!(f.clone().get_internal_int(), 3); + f.append_to_internal_int(5); + f.assert_internal_int(8); +} diff --git a/vendor/wasm-bindgen/tests/wasm/imports.js b/vendor/wasm-bindgen/tests/wasm/imports.js new file mode 100644 index 000000000..70d8a3b08 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/imports.js @@ -0,0 +1,143 @@ +const assert = require('assert'); +const wasm = require('wasm-bindgen-test'); +const fs = require('fs'); + +let ARG = null; +let ANOTHER_ARG = null; +let SYM = Symbol('a'); + +exports.simple_foo = function(s) { + assert.strictEqual(ARG, null); + assert.strictEqual(s, "foo"); + ARG = s; +}; + +exports.simple_another = function(s) { + assert.strictEqual(ANOTHER_ARG, null); + assert.strictEqual(s, 21); + ANOTHER_ARG = s; + return 35; +}; + +exports.simple_take_and_return_bool = function(s) { + return s; +}; +exports.simple_return_object = function() { + return SYM; +}; +exports.test_simple = function() { + assert.strictEqual(ARG, null); + wasm.simple_take_str("foo"); + assert.strictEqual(ARG, "foo"); + + assert.strictEqual(ANOTHER_ARG, null); + assert.strictEqual(wasm.simple_another_thunk(21), 35); + assert.strictEqual(ANOTHER_ARG, 21); + + assert.strictEqual(wasm.simple_bool_thunk(true), true); + assert.strictEqual(wasm.simple_bool_thunk(false), false); + + assert.strictEqual(wasm.simple_get_the_object(), SYM); +}; + +exports.return_string = function() { + return 'bar'; +}; + +exports.take_and_ret_string = function(a) { + return a + 'b'; +}; + +exports.exceptions_throw = function() { + throw new Error('error!'); +}; +exports.exceptions_throw2 = function() { + throw new Error('error2'); +}; +exports.test_exception_propagates = function() { + assert.throws(wasm.exceptions_propagate, /error!/); +}; + +exports.assert_valid_error = function(obj) { + assert.strictEqual(obj instanceof Error, true); + assert.strictEqual(obj.message, 'error2'); +}; + +exports.IMPORT = 1.0; + +exports.return_three = function() { return 3; }; + +exports.underscore = function(x) {}; + +exports.pub = function() { return 2; }; + +exports.bar = { foo: 3 }; + +let CUSTOM_TYPE = null; + +exports.take_custom_type = function(f) { + CUSTOM_TYPE = f; + return f; +}; + +exports.custom_type_return_2 = function() { + return 2; +}; + +exports.touch_custom_type = function() { + assert.throws(() => CUSTOM_TYPE.touch(), + /Attempt to use a moved value|null pointer passed to rust/); +}; + +exports.interpret_2_as_custom_type = function() { + assert.throws(wasm.interpret_2_as_custom_type, /expected instance of CustomType/); +}; + +exports.baz$ = function() {}; +exports.$foo = 1.0; + +exports.assert_dead_import_not_generated = function() { + const filename = require.resolve("wasm-bindgen-test"); + const bindings = fs.readFileSync(filename); + assert.ok(!bindings.includes("unused_import")); +}; + +exports.import_inside_function_works = function() {}; +exports.import_inside_private_module = function() {}; +exports.should_call_undefined_functions = () => false; + +exports.STATIC_STRING = 'x'; + +class StaticMethodCheck { + static static_method_of_right_this() { + assert.ok(this === StaticMethodCheck); + } +} + +exports.StaticMethodCheck = StaticMethodCheck; + +exports.receive_undefined = val => { + assert.strictEqual(val, undefined); +}; + +const VAL = {}; + +exports.receive_some = val => { + assert.strictEqual(val, VAL); +}; + +exports.get_some_val = () => VAL; + +exports.Math = { + func_from_module_math: (a) => a * 2 +} + +exports.Number = { + func_from_module_number: () => 3.0 +} + +exports.same_name_from_import = (a) => a * 3; + +exports.same_js_namespace_from_module = { + func_from_module_1_same_js_namespace: (a) => a * 5 +} \ No newline at end of file diff --git a/vendor/wasm-bindgen/tests/wasm/imports.rs b/vendor/wasm-bindgen/tests/wasm/imports.rs new file mode 100644 index 000000000..88dbf5ed6 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/imports.rs @@ -0,0 +1,323 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/imports.js")] +extern "C" { + fn test_simple(); + + fn simple_foo(s: &str); + fn simple_another(a: u32) -> i32; + fn simple_take_and_return_bool(a: bool) -> bool; + fn simple_return_object() -> JsValue; + #[allow(dead_code)] + fn missing_symbol(s: &str); + fn return_string() -> String; + fn take_and_ret_string(s: String) -> String; + #[wasm_bindgen(js_name = take_and_ret_string)] + fn take_and_ret_string2(s: &str) -> String; + + fn exceptions_throw(); + #[wasm_bindgen(catch)] + fn exceptions_throw2() -> Result<(), JsValue>; + fn test_exception_propagates(); + + fn assert_valid_error(val: JsValue); + + static IMPORT: JsValue; + + #[wasm_bindgen(js_name = return_three)] + fn rust_name_for_return_three() -> u32; + + fn underscore(_: u8); + + #[wasm_bindgen(js_name = pub)] + fn js_function_named_rust_keyword() -> u32; + + type bar; + #[wasm_bindgen(js_namespace = bar, js_name = foo)] + static FOO: JsValue; + + fn take_custom_type(f: CustomType) -> CustomType; + fn touch_custom_type(); + fn custom_type_return_2() -> CustomType; + #[wasm_bindgen(js_name = interpret_2_as_custom_type)] + fn js_interpret_2_as_custom_type(); + + #[wasm_bindgen(js_name = "baz$")] + fn renamed_with_dollar_sign(); + #[wasm_bindgen(js_name = "$foo")] + static RENAMED: JsValue; + + fn unused_import(); + fn assert_dead_import_not_generated(); + fn should_call_undefined_functions() -> bool; + + type StaticMethodCheck; + #[wasm_bindgen(static_method_of = StaticMethodCheck)] + fn static_method_of_right_this(); + + static STATIC_STRING: String; + + #[derive(Clone)] + type PassOutOptionUndefined; + fn get_some_val() -> PassOutOptionUndefined; + #[wasm_bindgen(js_name = "receive_undefined")] + fn receive_undefined_ref(arg: Option<&PassOutOptionUndefined>); + #[wasm_bindgen(js_name = "receive_undefined")] + fn receive_undefined_owned(arg: Option); + #[wasm_bindgen(js_name = "receive_some")] + fn receive_some_ref(arg: Option<&PassOutOptionUndefined>); + #[wasm_bindgen(js_name = "receive_some")] + fn receive_some_owned(arg: Option); + + #[wasm_bindgen(js_namespace = Math)] + fn func_from_module_math(a: i32) -> i32; + + #[wasm_bindgen(js_namespace = Number)] + fn func_from_module_number() -> f64; + + #[wasm_bindgen(js_name = "same_name_from_import")] + fn same_name_from_import_1(s: i32) -> i32; + + #[wasm_bindgen(js_namespace = same_js_namespace_from_module)] + fn func_from_module_1_same_js_namespace(s: i32) -> i32; +} + +#[wasm_bindgen(module = "tests/wasm/imports_2.js")] +extern "C" { + #[wasm_bindgen(js_name = "same_name_from_import")] + fn same_name_from_import_2(s: i32) -> i32; + + #[wasm_bindgen(js_namespace = same_js_namespace_from_module)] + fn func_from_module_2_same_js_namespace(s: i32) -> i32; +} + +#[wasm_bindgen] +extern "C" { + fn parseInt(a: &str) -> u32; + + #[wasm_bindgen(js_namespace = Math, js_name = "sqrt")] + fn func_from_global_math(s: f64) -> f64; + + type Number; + #[wasm_bindgen(getter, static_method_of = Number, js_name = "NAN")] + fn static_getter_from_global_number() -> f64; +} + +#[wasm_bindgen_test] +fn simple() { + test_simple(); +} + +#[wasm_bindgen] +pub fn simple_take_str(s: &str) { + simple_foo(s); +} + +#[wasm_bindgen] +pub fn simple_another_thunk(a: u32) -> i32 { + simple_another(a) +} + +#[wasm_bindgen] +pub fn simple_bool_thunk(a: bool) -> bool { + simple_take_and_return_bool(a) +} + +#[wasm_bindgen] +pub fn simple_get_the_object() -> JsValue { + simple_return_object() +} + +#[wasm_bindgen_test] +fn string_ret() { + assert_eq!(return_string(), "bar"); +} + +#[wasm_bindgen_test] +fn strings() { + assert_eq!(take_and_ret_string(String::from("a")), "ab"); + assert_eq!(take_and_ret_string2("b"), "bb"); +} + +#[wasm_bindgen_test] +fn exceptions() { + test_exception_propagates(); + assert!(exceptions_throw2().is_err()); +} + +#[wasm_bindgen] +pub fn exceptions_propagate() { + exceptions_throw(); +} + +#[wasm_bindgen_test] +fn exn_caught() { + assert_valid_error(exceptions_throw2().unwrap_err()); +} + +#[wasm_bindgen_test] +fn free_imports() { + assert_eq!(parseInt("3"), 3); +} + +#[wasm_bindgen_test] +fn import_a_field() { + assert_eq!(IMPORT.as_f64(), Some(1.0)); +} + +#[wasm_bindgen_test] +fn rename() { + assert_eq!(rust_name_for_return_three(), 3); +} + +#[wasm_bindgen_test] +fn underscore_pattern() { + underscore(2); +} + +#[wasm_bindgen_test] +fn rust_keyword() { + assert_eq!(js_function_named_rust_keyword(), 2); +} + +#[wasm_bindgen_test] +fn rust_keyword2() { + assert_eq!(FOO.as_f64(), Some(3.0)); +} + +#[wasm_bindgen_test] +fn custom_type() { + take_custom_type(CustomType(())); + touch_custom_type(); + js_interpret_2_as_custom_type(); +} + +#[wasm_bindgen] +pub fn interpret_2_as_custom_type() { + custom_type_return_2(); +} + +#[wasm_bindgen] +pub struct CustomType(()); + +#[wasm_bindgen] +impl CustomType { + pub fn touch(&self) { + panic!() + } +} + +#[wasm_bindgen_test] +fn rename_with_string() { + renamed_with_dollar_sign(); +} + +#[wasm_bindgen_test] +fn rename_static_with_string() { + assert_eq!(RENAMED.as_f64(), Some(1.0)); +} + +#[wasm_bindgen_test] +fn dead_imports_not_generated() { + assert_dead_import_not_generated(); +} + +#[wasm_bindgen_test] +fn import_inside_function_works() { + #[wasm_bindgen(module = "tests/wasm/imports.js")] + extern "C" { + fn import_inside_function_works(); + } + import_inside_function_works(); +} + +#[wasm_bindgen_test] +fn private_module_imports_work() { + private::foo(); +} + +mod private { + use wasm_bindgen::prelude::*; + + pub fn foo() { + #[wasm_bindgen(module = "tests/wasm/imports.js")] + extern "C" { + fn import_inside_private_module(); + } + import_inside_private_module(); + } +} + +#[wasm_bindgen] +extern "C" { + fn something_not_defined_in_the_environment(); + + type TypeThatIsNotDefined; + #[wasm_bindgen(constructor)] + fn new() -> TypeThatIsNotDefined; + #[wasm_bindgen(method)] + fn method(this: &TypeThatIsNotDefined); + #[wasm_bindgen(method, getter)] + fn property(this: &TypeThatIsNotDefined) -> u32; + #[wasm_bindgen(method, setter)] + fn set_property(this: &TypeThatIsNotDefined, val: u32); +} + +#[wasm_bindgen_test] +fn undefined_function_is_ok() { + if !should_call_undefined_functions() { + return; + } + something_not_defined_in_the_environment(); + + let x = TypeThatIsNotDefined::new(); + x.method(); + x.set_property(x.property()); +} + +#[wasm_bindgen_test] +fn static_string_ok() { + assert_eq!(*STATIC_STRING, "x"); +} + +#[wasm_bindgen_test] +fn static_method_of_has_right_this() { + StaticMethodCheck::static_method_of_right_this(); +} + +#[wasm_bindgen_test] +fn pass_out_options_as_undefined() { + receive_undefined_ref(None); + receive_undefined_ref(None); + receive_undefined_owned(None); + receive_undefined_owned(None); + + let v = get_some_val(); + receive_some_ref(Some(&v)); + receive_some_ref(Some(&v)); + receive_some_owned(Some(v.clone())); + receive_some_owned(Some(v)); +} + +#[wasm_bindgen_test] +fn func_from_global_and_module_same_js_namespace() { + assert_eq!(func_from_global_math(4.0), 2.0); + assert_eq!(func_from_module_math(2), 4); +} +#[wasm_bindgen_test] +fn getter_from_global_and_module_same_name() { + assert!(Number::static_getter_from_global_number().is_nan()); + assert_eq!(func_from_module_number(), 3.0); +} +#[wasm_bindgen_test] +fn func_from_two_modules_same_js_name() { + assert_eq!(same_name_from_import_1(1), 3); + assert_eq!(same_name_from_import_2(1), 4); +} + +#[wasm_bindgen_test] +fn func_from_two_modules_same_js_namespace() { + assert_eq!(func_from_module_1_same_js_namespace(2), 10); + assert_eq!(func_from_module_2_same_js_namespace(2), 12); +} diff --git a/vendor/wasm-bindgen/tests/wasm/imports_2.js b/vendor/wasm-bindgen/tests/wasm/imports_2.js new file mode 100644 index 000000000..78f55be0f --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/imports_2.js @@ -0,0 +1,5 @@ +exports.same_name_from_import = (a) => a * 4; + +exports.same_js_namespace_from_module = { + func_from_module_2_same_js_namespace: (a) => a * 6 +} \ No newline at end of file diff --git a/vendor/wasm-bindgen/tests/wasm/intrinsics.rs b/vendor/wasm-bindgen/tests/wasm/intrinsics.rs new file mode 100644 index 000000000..15985e812 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/intrinsics.rs @@ -0,0 +1,113 @@ +//! Tests that some of our more obscure intrinsics work properly. + +use std::convert::TryFrom; +use std::fmt::Debug; + +use js_sys::{Object, RangeError, Reflect}; +use wasm_bindgen::{JsCast, JsValue}; +use wasm_bindgen_test::wasm_bindgen_test; + +// Shorter `JsValue::from(i32)`. +fn int(x: i32) -> JsValue { + JsValue::from(x) +} + +#[wasm_bindgen_test] +fn bitwise() { + assert_eq!(int(0b1110) & int(0b0111), 0b0110); + assert_eq!(int(0b1000) | int(0b0010), 0b1010); + assert_eq!(int(0b1110) ^ int(0b0100), 0b1010); + assert_eq!(int(0x00ffffff).bit_not(), 0xff000000u32 as i32); + + assert_eq!(int(0b0001) << int(2), 0b0100); + assert_eq!(int(0b1000) >> int(2), 0b0010); + assert_eq!(int(-0b1000) >> int(2), -0b0010); + // Note that bit-wise, this is the same as the above `-0b1000`. + assert_eq!( + JsValue::from(0xfffffff8u32).unsigned_shr(&int(2)), + 0x3ffffffe + ); +} + +#[wasm_bindgen_test] +fn arithmetic() { + assert_eq!(-int(12), -12); + assert_eq!(int(1) + int(2), 3); + assert_eq!(int(1) - int(2), -1); + assert_eq!(int(10) / int(5), 2); + assert_eq!(int(42).checked_div(&int(6)), 7); + // Note that this doesn't throw for regular numbers, since they just give + // `NaN` for invalid results. + assert!(JsValue::bigint_from_str("0") + .checked_div(&JsValue::bigint_from_str("0")) + .dyn_into::() + .is_ok()); + assert_eq!(int(12) * int(34), 408); + assert_eq!(int(17) % int(10), 7); + assert_eq!(int(2).pow(&int(8)), 256) +} + +#[wasm_bindgen_test] +fn cmp() { + assert!(int(2).lt(&int(3))); + assert!(!int(2).lt(&int(2))); + + assert!(int(2).le(&int(3))); + assert!(int(2).le(&int(2))); + + assert!(int(3).ge(&int(2))); + assert!(int(3).ge(&int(3))); + + assert!(int(3).gt(&int(2))); + assert!(!int(3).gt(&int(3))); + + assert!(int(2) == int(2)); + assert!(int(2) != int(3)); + + assert!(int(2) != JsValue::from_str("2")); + assert!(int(2).loose_eq(&JsValue::from_str("2"))); +} + +#[wasm_bindgen_test] +fn types() { + assert!( + Reflect::get(&js_sys::global(), &JsValue::from_str("Number")) + .unwrap() + .is_function() + ); + assert!(JsValue::UNDEFINED.is_undefined()); + assert!(JsValue::NULL.is_null()); + assert!(Object::new().is_object()); + assert!(JsValue::symbol(None).is_symbol()); + assert!(JsValue::from_str("hi").is_string()); + assert!(JsValue::bigint_from_str("5").is_bigint()); + assert_eq!(int(5).js_typeof(), "number"); + assert_eq!(JsValue::bigint_from_str("5").js_typeof(), "bigint"); + assert_eq!(JsValue::NULL.js_typeof(), "object"); +} + +#[wasm_bindgen_test] +fn misc() { + assert!(JsValue::from_str("Number").js_in(&js_sys::global())); + assert!(!JsValue::from_str("frob").js_in(&js_sys::global())); + + assert_eq!(int(5).unchecked_into_f64(), 5.0); + assert_eq!(JsValue::from_str("5").unchecked_into_f64(), 5.0); + + assert_eq!(f64::try_from(int(5)), Ok(5.0)); + assert_eq!(f64::try_from(JsValue::from_str("5")), Ok(5.0)); + assert!(f64::try_from(JsValue::from_str("hi")).unwrap().is_nan()); + assert!(f64::try_from(JsValue::symbol(None)).is_err()); +} + +fn debug(x: impl Debug) -> String { + format!("{x:?}") +} + +#[wasm_bindgen_test] +fn debug_string() { + assert_eq!(debug(int(5)), "JsValue(5)"); + assert_eq!(debug(JsValue::TRUE), "JsValue(true)"); + assert_eq!(debug(JsValue::symbol(None)), "JsValue(Symbol)"); + assert_eq!(debug(JsValue::from_str("hi")), "JsValue(\"hi\")"); +} diff --git a/vendor/wasm-bindgen/tests/wasm/js_keywords.js b/vendor/wasm-bindgen/tests/wasm/js_keywords.js new file mode 100644 index 000000000..f7fb26dea --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/js_keywords.js @@ -0,0 +1,24 @@ +const wasm = require("wasm-bindgen-test.js"); +const assert = require("assert"); + +exports.js_keywords_compile = () => { + assert.strictEqual(wasm._throw(1), 1); + assert.strictEqual(wasm._class(1, 2), false); + assert.strictEqual(wasm.classy(3), 3); + let obj = new wasm.Class("class"); + assert.strictEqual(wasm.Class.void("string"), "string"); + assert.strictEqual(obj.catch, "class"); + assert.strictEqual(obj.instanceof("Class"), "class is instance of Class"); +}; + +exports.test_keyword_1_as_fn_name = (x) => { + return wasm._throw(x); +}; + +exports.test_keyword_2_as_fn_name = (x, y) => { + return wasm._class(x, y); +}; + +exports.test_keyword_as_fn_arg = (x) => { + return wasm.classy(x); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/js_keywords.rs b/vendor/wasm-bindgen/tests/wasm/js_keywords.rs new file mode 100644 index 000000000..57feed7a7 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/js_keywords.rs @@ -0,0 +1,55 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/js_keywords.js")] +extern "C" { + fn js_keywords_compile(); + fn test_keyword_1_as_fn_name(x: u8) -> u8; + fn test_keyword_2_as_fn_name(x: u8, y: u8) -> bool; + fn test_keyword_as_fn_arg(x: u8) -> u8; +} + +#[wasm_bindgen] +pub fn throw(class: u8) -> u8 { + class +} + +#[wasm_bindgen(js_name = class)] +pub fn fn_parsed_to_keyword(instanceof: u8, catch: u8) -> bool { + instanceof > catch +} + +#[wasm_bindgen(js_name = classy)] +pub fn arg_is_keyword(class: u8) -> u8 { + class +} + +#[wasm_bindgen] +struct Class { + name: String, +} +#[wasm_bindgen] +impl Class { + #[wasm_bindgen(constructor)] + pub fn new(void: String) -> Self { + Class { name: void } + } + pub fn instanceof(&self, class: String) -> String { + format!("{} is instance of {}", self.name.clone(), class) + } + #[wasm_bindgen(getter)] + pub fn catch(&self) -> String { + self.name.clone() + } + pub fn void(void: String) -> String { + void + } +} + +#[wasm_bindgen_test] +fn compile() { + js_keywords_compile(); + assert_eq!(test_keyword_1_as_fn_name(1), 1); + assert_eq!(test_keyword_2_as_fn_name(1, 2), false); + assert_eq!(test_keyword_as_fn_arg(1), 1); +} diff --git a/vendor/wasm-bindgen/tests/wasm/js_objects.js b/vendor/wasm-bindgen/tests/wasm/js_objects.js new file mode 100644 index 000000000..c131527b8 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/js_objects.js @@ -0,0 +1,112 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +let SIMPLE_ARG = null; + +exports.simple_foo = s => { + assert.strictEqual(SIMPLE_ARG, null); + SIMPLE_ARG = s; +}; + +exports.js_simple = () => { + assert.strictEqual(SIMPLE_ARG, null); + let sym = Symbol('test'); + wasm.simple_bar(sym); + assert.strictEqual(SIMPLE_ARG, sym); +}; + +let OWNED_ARG = null; + +exports.owned_foo = s => { + assert.strictEqual(OWNED_ARG, null); + OWNED_ARG = s; +}; + +exports.js_owned = () => { + assert.strictEqual(OWNED_ARG, null); + let sym = Symbol('test'); + wasm.owned_bar(sym); + assert.strictEqual(OWNED_ARG, sym); +}; + +let CLONE_ARG = Symbol('test'); + +exports.clone_foo1 = s => { + assert.strictEqual(s, CLONE_ARG); +}; +exports.clone_foo2 = s => { + assert.strictEqual(s, CLONE_ARG); +}; +exports.clone_foo3 = s => { + assert.strictEqual(s, CLONE_ARG); +}; +exports.clone_foo4 = s => { + assert.strictEqual(s, CLONE_ARG); +}; +exports.clone_foo5 = s => { + assert.strictEqual(s, CLONE_ARG); +}; + +exports.js_clone = () => { + wasm.clone_bar(CLONE_ARG); +}; + + +let PROMOTE_ARG = Symbol('test'); + +exports.promote_foo1 = s => { + assert.strictEqual(s, PROMOTE_ARG); +}; +exports.promote_foo2 = s => { + assert.strictEqual(s, PROMOTE_ARG); +}; +exports.promote_foo3 = s => { + assert.strictEqual(s, PROMOTE_ARG); +}; +exports.promote_foo4 = s => { + assert.strictEqual(s, PROMOTE_ARG); +}; + +exports.js_promote = () => { + wasm.promote_bar(PROMOTE_ARG); +}; + +exports.returning_vector_foo = () => { + return {'foo': 'bar'}; +}; + +exports.js_returning_vector = () => { + assert.strictEqual(wasm.returning_vector_bar().length, 10); +}; + +exports.js_another_vector_return = () => { + assert.deepStrictEqual(wasm.another_vector_return_get_array(), [1, 2, 3, 4, 5, 6]); +}; + +exports.returning_vector_string_foo = () => { + return "This is the mostest awesomest string that can possibly exist."; +}; + +exports.js_returning_vector_string = () => { + assert.strictEqual(wasm.returning_vector_string_bar().length, 10); +}; + +exports.js_another_vector_string_return = () => { + assert.deepStrictEqual(wasm.another_vector_string_return_get_array(), ["1", "2", "3", "4", "5", "6"]); +}; + +exports.verify_serde = function(a) { + assert.deepStrictEqual(a, { + a: 0, + b: 'foo', + c: null, + d: { a: 1 } + }); + + return { + a: 2, + b: 'bar', + c: { a: 3 }, + d: { a: 4 }, + } +}; diff --git a/vendor/wasm-bindgen/tests/wasm/js_objects.rs b/vendor/wasm-bindgen/tests/wasm/js_objects.rs new file mode 100644 index 000000000..445d5329a --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/js_objects.rs @@ -0,0 +1,184 @@ +use js_sys::JsString; +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/js_objects.js")] +extern "C" { + fn simple_foo(s: &JsValue); + fn js_simple(); + + fn owned_foo(s: JsValue); + fn js_owned(); + + fn clone_foo1(s: JsValue); + fn clone_foo2(s: &JsValue); + fn clone_foo3(s: JsValue); + fn clone_foo4(s: &JsValue); + fn clone_foo5(s: JsValue); + fn js_clone(); + + fn promote_foo1(s: &JsValue); + fn promote_foo2(s: JsValue); + fn promote_foo3(s: &JsValue); + fn promote_foo4(s: JsValue); + fn js_promote(); + + fn returning_vector_foo() -> JsValue; + fn js_returning_vector(); + fn js_another_vector_return(); + + fn returning_vector_string_foo() -> JsString; + fn js_returning_vector_string(); + fn js_another_vector_string_return(); + + fn verify_serde(val: JsValue) -> JsValue; +} + +#[wasm_bindgen] +pub fn simple_bar(s: &JsValue) { + simple_foo(s); +} + +#[wasm_bindgen_test] +fn simple() { + js_simple(); +} + +#[wasm_bindgen] +pub fn owned_bar(s: JsValue) { + owned_foo(s); +} + +#[wasm_bindgen_test] +fn owned() { + js_owned(); +} + +#[wasm_bindgen] +pub fn clone_bar(s: JsValue) { + clone_foo1(s.clone()); + clone_foo2(&s); + clone_foo3(s.clone()); + clone_foo4(&s); + clone_foo5(s); +} + +#[wasm_bindgen_test] +fn clone() { + js_clone(); +} + +#[wasm_bindgen] +pub fn promote_bar(s: &JsValue) { + promote_foo1(s); + promote_foo2(s.clone()); + promote_foo3(s); + promote_foo4(s.clone()); +} + +#[wasm_bindgen_test] +fn promote() { + js_promote(); +} + +#[wasm_bindgen] +pub fn returning_vector_bar() -> Vec { + let mut res = Vec::new(); + for _ in 0..10 { + res.push(returning_vector_foo()) + } + res +} + +#[wasm_bindgen_test] +fn returning_vector() { + js_returning_vector(); +} + +#[wasm_bindgen] +pub fn another_vector_return_get_array() -> Vec { + vec![ + JsValue::from(1), + JsValue::from(2), + JsValue::from(3), + JsValue::from(4), + JsValue::from(5), + JsValue::from(6), + ] +} + +#[wasm_bindgen_test] +fn another_vector_return() { + js_another_vector_return(); +} + +#[wasm_bindgen] +pub fn returning_vector_string_bar() -> Vec { + let mut res = Vec::new(); + for _ in 0..10 { + res.push(returning_vector_string_foo()) + } + res +} + +#[wasm_bindgen_test] +fn returning_vector_string() { + js_returning_vector_string(); +} + +#[wasm_bindgen] +pub fn another_vector_string_return_get_array() -> Vec { + vec![ + "1".into(), + "2".into(), + "3".into(), + "4".into(), + "5".into(), + "6".into(), + ] +} + +#[wasm_bindgen_test] +fn another_vector_string_return() { + js_another_vector_string_return(); +} + +#[cfg(feature = "serde-serialize")] +#[wasm_bindgen_test] +fn serde() { + #[derive(Deserialize, Serialize)] + pub struct SerdeFoo { + a: u32, + b: String, + c: Option, + d: SerdeBar, + } + + #[derive(Deserialize, Serialize)] + pub struct SerdeBar { + a: u32, + } + + let js = JsValue::from_serde("foo").unwrap(); + assert_eq!(js.as_string(), Some("foo".to_string())); + + let ret = verify_serde( + JsValue::from_serde(&SerdeFoo { + a: 0, + b: "foo".to_string(), + c: None, + d: SerdeBar { a: 1 }, + }) + .unwrap(), + ); + + let foo = ret.into_serde::().unwrap(); + assert_eq!(foo.a, 2); + assert_eq!(foo.b, "bar"); + assert!(foo.c.is_some()); + assert_eq!(foo.c.as_ref().unwrap().a, 3); + assert_eq!(foo.d.a, 4); + + assert_eq!(JsValue::from("bar").into_serde::().unwrap(), "bar"); + assert_eq!(JsValue::undefined().into_serde::().ok(), None); +} diff --git a/vendor/wasm-bindgen/tests/wasm/jscast.js b/vendor/wasm-bindgen/tests/wasm/jscast.js new file mode 100644 index 000000000..3cecd9915 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/jscast.js @@ -0,0 +1,28 @@ +class JsCast1 { + constructor() { + this.val = 1; + } + myval() { return this.val; } +} + +class JsCast2 { +} + +class JsCast3 extends JsCast1 { + constructor() { + super(); + this.val = 3; + } +} + +class JsCast4 extends JsCast3 { + constructor() { + super(); + this.val = 4; + } +} + +exports.JsCast1 = JsCast1; +exports.JsCast2 = JsCast2; +exports.JsCast3 = JsCast3; +exports.JsCast4 = JsCast4; diff --git a/vendor/wasm-bindgen/tests/wasm/jscast.rs b/vendor/wasm-bindgen/tests/wasm/jscast.rs new file mode 100644 index 000000000..1279634d2 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/jscast.rs @@ -0,0 +1,88 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/jscast.js")] +extern "C" { + type JsCast1; + #[wasm_bindgen(constructor)] + fn new() -> JsCast1; + #[wasm_bindgen(method)] + fn myval(this: &JsCast1) -> u32; + + type JsCast2; + #[wasm_bindgen(constructor)] + fn new() -> JsCast2; + + #[wasm_bindgen(extends = JsCast1)] + type JsCast3; + #[wasm_bindgen(constructor)] + fn new() -> JsCast3; + + #[wasm_bindgen(extends = crate::jscast::JsCast1, extends = JsCast3)] + type JsCast4; + #[wasm_bindgen(constructor)] + fn new() -> JsCast4; +} + +#[wasm_bindgen_test] +fn instanceof_works() { + let a = JsCast1::new(); + let b = JsCast2::new(); + let c = JsCast3::new(); + + assert!(a.is_instance_of::()); + assert!(!a.is_instance_of::()); + assert!(!a.is_instance_of::()); + + assert!(!b.is_instance_of::()); + assert!(b.is_instance_of::()); + assert!(!b.is_instance_of::()); + + assert!(c.is_instance_of::()); + assert!(!c.is_instance_of::()); + assert!(c.is_instance_of::()); +} + +#[wasm_bindgen_test] +fn casting() { + let a = JsCast1::new(); + let b = JsCast2::new(); + let c = JsCast3::new(); + + assert!(a.dyn_ref::().is_some()); + assert!(a.dyn_ref::().is_none()); + assert!(a.dyn_ref::().is_none()); + + assert!(b.dyn_ref::().is_none()); + assert!(b.dyn_ref::().is_some()); + assert!(b.dyn_ref::().is_none()); + + assert!(c.dyn_ref::().is_some()); + assert!(c.dyn_ref::().is_none()); + assert!(c.dyn_ref::().is_some()); +} + +#[wasm_bindgen_test] +fn method_calling() { + let a = JsCast1::new(); + let b = JsCast3::new(); + + assert_eq!(a.myval(), 1); + assert_eq!(b.dyn_ref::().unwrap().myval(), 3); + assert_eq!(b.unchecked_ref::().myval(), 3); + let c: &JsCast1 = b.as_ref(); + assert_eq!(c.myval(), 3); +} + +#[wasm_bindgen_test] +fn multiple_layers_of_inheritance() { + let a = JsCast4::new(); + assert!(a.is_instance_of::()); + assert!(a.is_instance_of::()); + assert!(a.is_instance_of::()); + + let _: &JsCast3 = a.as_ref(); + let b: &JsCast1 = a.as_ref(); + assert_eq!(b.myval(), 4); +} diff --git a/vendor/wasm-bindgen/tests/wasm/main.rs b/vendor/wasm-bindgen/tests/wasm/main.rs new file mode 100644 index 000000000..51e6dcafe --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/main.rs @@ -0,0 +1,56 @@ +#![cfg(target_arch = "wasm32")] + +extern crate js_sys; +extern crate wasm_bindgen; +extern crate wasm_bindgen_test; +extern crate wasm_bindgen_test_crate_a; +extern crate wasm_bindgen_test_crate_b; + +#[cfg(feature = "serde-serialize")] +#[macro_use] +extern crate serde_derive; + +use wasm_bindgen::prelude::*; + +pub mod api; +pub mod arg_names; +pub mod bigint; +pub mod char; +pub mod classes; +pub mod closures; +pub mod comments; +pub mod duplicate_deps; +pub mod duplicates; +pub mod enums; +#[path = "final.rs"] +pub mod final_; +pub mod futures; +pub mod getters_and_setters; +pub mod import_class; +pub mod imports; +pub mod intrinsics; +pub mod js_keywords; +pub mod js_objects; +pub mod jscast; +pub mod math; +pub mod no_shims; +pub mod node; +pub mod option; +pub mod optional_primitives; +pub mod result; +pub mod result_jserror; +pub mod rethrow; +pub mod simple; +pub mod slice; +pub mod structural; +pub mod truthy_falsy; +pub mod usize; +pub mod validate_prt; +pub mod variadic; +pub mod vendor_prefix; + +// should not be executed +#[wasm_bindgen(start)] +pub fn start() { + panic!(); +} diff --git a/vendor/wasm-bindgen/tests/wasm/math.js b/vendor/wasm-bindgen/tests/wasm/math.js new file mode 100644 index 000000000..e3b518305 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/math.js @@ -0,0 +1,37 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +exports.js_auto_bind_math = () => { + wasm.math(1.0, 2.0); +}; + +exports.roundtrip = x => x; + +exports.test_js_roundtrip = () => { + assert.strictEqual(wasm.rust_roundtrip_i8(0), 0); + assert.strictEqual(wasm.rust_roundtrip_i8(0x80), -128); + assert.strictEqual(wasm.rust_roundtrip_i8(0x7f), 127); + + assert.strictEqual(wasm.rust_roundtrip_i16(0), 0); + assert.strictEqual(wasm.rust_roundtrip_i16(0x8000), -32768); + assert.strictEqual(wasm.rust_roundtrip_i16(0x7fff), 32767); + + assert.strictEqual(wasm.rust_roundtrip_i32(0), 0); + assert.strictEqual(wasm.rust_roundtrip_i32(0x80000000), -2147483648); + assert.strictEqual(wasm.rust_roundtrip_i32(0x7fffffff), 2147483647); + + assert.strictEqual(wasm.rust_roundtrip_u8(0), 0); + assert.strictEqual(wasm.rust_roundtrip_u8(0x80), 128); + assert.strictEqual(wasm.rust_roundtrip_u8(0x7f), 127); + assert.strictEqual(wasm.rust_roundtrip_u8(0xff), 255); + + assert.strictEqual(wasm.rust_roundtrip_u16(0), 0); + assert.strictEqual(wasm.rust_roundtrip_u16(0x8000), 32768); + assert.strictEqual(wasm.rust_roundtrip_u16(0x7fff), 32767); + assert.strictEqual(wasm.rust_roundtrip_u16(0xffff), 65535); + + assert.strictEqual(wasm.rust_roundtrip_u32(0), 0); + assert.strictEqual(wasm.rust_roundtrip_u32(0x80000000), 2147483648); + assert.strictEqual(wasm.rust_roundtrip_u32(0x7fffffff), 2147483647); + assert.strictEqual(wasm.rust_roundtrip_u32(0xffffffff), 4294967295); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/math.rs b/vendor/wasm-bindgen/tests/wasm/math.rs new file mode 100644 index 000000000..5462cc2d4 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/math.rs @@ -0,0 +1,142 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/math.js")] +extern "C" { + fn js_auto_bind_math(); + + // There's an identity function called `roundtrip` in the module and we bind + // that one function with multiple different signatures here. Note that the + // return value is always `f64` to faithfully capture what was sent to JS + // (what we're interested in) because all JS numbers fit in `f64` anyway. + // This is testing what happens when we pass numbers to JS and what it sees. + #[wasm_bindgen(assert_no_shim, js_name = roundtrip)] + fn roundtrip_i8(a: i8) -> f64; + #[wasm_bindgen(assert_no_shim, js_name = roundtrip)] + fn roundtrip_i16(a: i16) -> f64; + #[wasm_bindgen(assert_no_shim, js_name = roundtrip)] + fn roundtrip_i32(a: i32) -> f64; + #[wasm_bindgen(assert_no_shim, js_name = roundtrip)] + fn roundtrip_u8(a: u8) -> f64; + #[wasm_bindgen(assert_no_shim, js_name = roundtrip)] + fn roundtrip_u16(a: u16) -> f64; + #[wasm_bindgen(js_name = roundtrip)] + fn roundtrip_u32(a: u32) -> f64; + + fn test_js_roundtrip(); +} + +#[wasm_bindgen] +pub fn math(a: f32, b: f64) -> f64 { + b.acos() + + b.asin() + + b.atan() + + b.atan2(b) + + b.cbrt() + + b.cosh() + + b.exp_m1() + + b.ln_1p() + + b.sinh() + + b.tan() + + b.tanh() + + b.hypot(b) + + b.cos() + + b.exp() + + b.exp2() + + b.mul_add(b, b) + + b.ln() + + b.log(b) + + b.log10() + + b.log2() + + b.powi(8) + + b.powf(b) + + b.round() + + b.sin() + + b.abs() + + b.signum() + + b.floor() + + b.ceil() + + b.trunc() + + b.sqrt() + + (b % (a as f64)) + + ((a.cos() + + a.exp() + + a.exp2() + + a.mul_add(a, a) + + a.ln() + + a.log(a) + + a.log10() + + a.log2() + + a.powi(8) + + a.powf(a) + + a.round() + + a.sin() + + a.abs() + + a.signum() + + a.floor() + + a.ceil() + + a.trunc() + + a.sqrt() + + (a % (b as f32))) as f64) + + (b + 2.0f64.powf(a as f64)) +} + +#[wasm_bindgen_test] +fn auto_bind_math() { + js_auto_bind_math(); +} + +macro_rules! t_roundtrip { + ($f:ident($e:expr)) => { + assert_eq!($f($e), $e as f64) + }; +} + +#[wasm_bindgen_test] +fn limits_correct() { + t_roundtrip!(roundtrip_i8(i8::min_value())); + t_roundtrip!(roundtrip_i8(0)); + t_roundtrip!(roundtrip_i8(i8::max_value())); + t_roundtrip!(roundtrip_i16(i16::min_value())); + t_roundtrip!(roundtrip_i16(0)); + t_roundtrip!(roundtrip_i16(i16::max_value())); + t_roundtrip!(roundtrip_i32(i32::min_value())); + t_roundtrip!(roundtrip_i32(0)); + t_roundtrip!(roundtrip_i32(i32::max_value())); + t_roundtrip!(roundtrip_u8(u8::min_value())); + t_roundtrip!(roundtrip_u8(0)); + t_roundtrip!(roundtrip_u8(u8::max_value())); + t_roundtrip!(roundtrip_u16(u16::min_value())); + t_roundtrip!(roundtrip_u16(0)); + t_roundtrip!(roundtrip_u16(u16::max_value())); + t_roundtrip!(roundtrip_u32(u32::min_value())); + t_roundtrip!(roundtrip_u32(0)); + t_roundtrip!(roundtrip_u32(u32::max_value())); + + test_js_roundtrip(); + + #[wasm_bindgen] + pub fn rust_roundtrip_i8(a: i8) -> i8 { + a + } + #[wasm_bindgen] + pub fn rust_roundtrip_i16(a: i16) -> i16 { + a + } + #[wasm_bindgen] + pub fn rust_roundtrip_i32(a: i32) -> i32 { + a + } + #[wasm_bindgen] + pub fn rust_roundtrip_u8(a: u8) -> u8 { + a + } + #[wasm_bindgen] + pub fn rust_roundtrip_u16(a: u16) -> u16 { + a + } + #[wasm_bindgen] + pub fn rust_roundtrip_u32(a: u32) -> u32 { + a + } +} diff --git a/vendor/wasm-bindgen/tests/wasm/no_shims.rs b/vendor/wasm-bindgen/tests/wasm/no_shims.rs new file mode 100644 index 000000000..2f9455ae2 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/no_shims.rs @@ -0,0 +1,152 @@ +//! A collection of tests to exercise imports where we don't need to generate a +//! JS shim to convert arguments/returns even when Web IDL bindings is not +//! implemented. + +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(inline_js = " + function assert_eq(a, b) { + if (a !== b) { + throw new Error(`assert_eq failed: ${a} != ${b}`); + } + } + + module.exports.trivial = function () {}; + + module.exports.incoming_bool = function () { return true; }; + module.exports.incoming_u8 = function () { return 255; }; + module.exports.incoming_i8 = function () { return -127; }; + module.exports.incoming_u16 = function () { return 65535; }; + module.exports.incoming_i16 = function () { return 32767; }; + module.exports.incoming_u32 = function () { return 4294967295; }; + module.exports.incoming_i32 = function () { return 0; }; + module.exports.incoming_f32 = function () { return 1.5; }; + module.exports.incoming_f64 = function () { return 13.37; }; + + module.exports.outgoing_u8 = function (k) { assert_eq(k, 255); }; + module.exports.outgoing_i8 = function (i) { assert_eq(i, -127); }; + module.exports.outgoing_u16 = function (l) { assert_eq(l, 65535); }; + module.exports.outgoing_i16 = function (j) { assert_eq(j, 32767); }; + module.exports.outgoing_i32 = function (x) { assert_eq(x, 0); }; + module.exports.outgoing_f32 = function (y) { assert_eq(y, 1.5); }; + module.exports.outgoing_f64 = function (z) { assert_eq(z, 13.37); }; + + module.exports.many = function (x, y, z) { + assert_eq(x, 0); + assert_eq(y, 1.5); + assert_eq(z, 13.37); + return 42; + }; + + module.exports.works_when_externref_support_is_enabled = function (v) { + assert_eq(v, 'hello'); + return v; + }; + + module.exports.MyNamespace = {}; + module.exports.MyNamespace.incoming_namespaced = function () { return 3.14; }; + module.exports.MyNamespace.outgoing_namespaced = function (pi) { assert_eq(3.14, pi); }; +")] +extern "C" { + #[wasm_bindgen(assert_no_shim)] + fn trivial(); + + #[wasm_bindgen(assert_no_shim)] + fn incoming_bool() -> bool; + #[wasm_bindgen(assert_no_shim)] + fn incoming_u8() -> u8; + #[wasm_bindgen(assert_no_shim)] + fn incoming_i8() -> i8; + #[wasm_bindgen(assert_no_shim)] + fn incoming_u16() -> u16; + #[wasm_bindgen(assert_no_shim)] + fn incoming_i16() -> i16; + #[wasm_bindgen(assert_no_shim)] + fn incoming_u32() -> u32; + #[wasm_bindgen(assert_no_shim)] + fn incoming_i32() -> i32; + #[wasm_bindgen(assert_no_shim)] + fn incoming_f32() -> f32; + #[wasm_bindgen(assert_no_shim)] + fn incoming_f64() -> f64; + + #[wasm_bindgen(assert_no_shim)] + fn outgoing_u8(k: u8); + #[wasm_bindgen(assert_no_shim)] + fn outgoing_i8(i: i8); + #[wasm_bindgen(assert_no_shim)] + fn outgoing_u16(l: u16); + #[wasm_bindgen(assert_no_shim)] + fn outgoing_i16(j: i16); + #[wasm_bindgen(assert_no_shim)] + fn outgoing_i32(x: i32); + #[wasm_bindgen(assert_no_shim)] + fn outgoing_f32(y: f32); + #[wasm_bindgen(assert_no_shim)] + fn outgoing_f64(z: f64); + + #[wasm_bindgen(assert_no_shim)] + fn many(x: i32, y: f32, z: f64) -> i32; + + #[wasm_bindgen(assert_no_shim, js_namespace = MyNamespace)] + fn incoming_namespaced() -> f64; + #[wasm_bindgen(assert_no_shim, js_namespace = MyNamespace)] + fn outgoing_namespaced(x: f64); + + // Note that this should only skip the JS shim if we have externref support + // enabled. + // + // #[wasm_bindgen(assert_no_shim)] + fn works_when_externref_support_is_enabled(v: JsValue) -> JsValue; +} + +#[wasm_bindgen_test] +fn no_shims() { + trivial(); + + let k = incoming_u8(); + assert_eq!(k, 255); + outgoing_u8(k); + + let l = incoming_u16(); + assert_eq!(l, 65535); + outgoing_u16(l); + + let m = incoming_u32(); + assert_eq!(m, 4294967295); + + let i = incoming_i8(); + assert_eq!(i, -127); + outgoing_i8(i); + + let j = incoming_i16(); + assert_eq!(j, 32767); + outgoing_i16(j); + + let x = incoming_i32(); + assert_eq!(x, 0); + outgoing_i32(x); + + let y = incoming_f32(); + assert_eq!(y, 1.5); + outgoing_f32(y); + + let z = incoming_f64(); + assert_eq!(z, 13.37); + outgoing_f64(z); + + let w = many(x, y, z); + assert_eq!(w, 42); + + let pi = incoming_namespaced(); + assert_eq!(pi, 3.14); + outgoing_namespaced(pi); + + let b = incoming_bool(); + assert!(b); + + let v = JsValue::from("hello"); + let vv = works_when_externref_support_is_enabled(v.clone()); + assert_eq!(v, vv); +} diff --git a/vendor/wasm-bindgen/tests/wasm/node.js b/vendor/wasm-bindgen/tests/wasm/node.js new file mode 100644 index 000000000..41baa8b24 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/node.js @@ -0,0 +1,37 @@ +const assert = require('assert'); +const wasm = require('wasm-bindgen-test'); + +var called = false; + +exports.hit = function() { + called = true; +}; + +exports.FOO = 1.0; + +exports.test_works = function() { + assert.strictEqual(called, true); + + var r = wasm.Foo.new(); + assert.strictEqual(r.add(0), 0); + assert.strictEqual(r.add(1), 1); + assert.strictEqual(r.add(2), 3); + r.free(); + + var r2 = wasm.Foo.with_contents(10); + assert.strictEqual(r2.add(0), 10); + assert.strictEqual(r2.add(1), 11); + assert.strictEqual(r2.add(2), 13); + r2.free(); + + assert.strictEqual(wasm.Color.Green, 0); + assert.strictEqual(wasm.Color.Yellow, 1); + assert.strictEqual(wasm.Color.Red, 2); + assert.strictEqual(wasm.Color[0], 'Green'); + assert.strictEqual(wasm.Color[1], 'Yellow'); + assert.strictEqual(wasm.Color[2], 'Red'); + assert.strictEqual(Object.keys(wasm.Color).length, 6); + assert.strictEqual(wasm.cycle(wasm.Color.Green), wasm.Color.Yellow); + + wasm.node_math(1.0, 2.0); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/node.rs b/vendor/wasm-bindgen/tests/wasm/node.rs new file mode 100644 index 000000000..742dbcfb5 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/node.rs @@ -0,0 +1,105 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/node.js")] +extern "C" { + fn test_works(); + static FOO: JsValue; + fn hit(); +} + +#[wasm_bindgen_test] +fn works() { + hit(); + assert_eq!(FOO.as_f64(), Some(1.0)); + test_works(); +} + +#[wasm_bindgen] +pub struct Foo { + contents: u32, +} + +#[wasm_bindgen] +impl Foo { + pub fn new() -> Foo { + Foo::with_contents(0) + } + pub fn with_contents(a: u32) -> Foo { + Foo { contents: a } + } + pub fn add(&mut self, amt: u32) -> u32 { + self.contents += amt; + self.contents + } +} + +#[wasm_bindgen] +pub enum Color { + Green, + Yellow, + Red, +} +#[wasm_bindgen] +pub fn cycle(color: Color) -> Color { + match color { + Color::Green => Color::Yellow, + Color::Yellow => Color::Red, + Color::Red => Color::Green, + } +} + +#[wasm_bindgen] +pub fn node_math(a: f32, b: f64) -> f64 { + b.acos() + + b.asin() + + b.atan() + + b.atan2(b) + + b.cbrt() + + b.cosh() + + b.exp_m1() + + b.ln_1p() + + b.sinh() + + b.tan() + + b.tanh() + + b.hypot(b) + + b.cos() + + b.exp() + + b.exp2() + + b.mul_add(b, b) + + b.ln() + + b.log(b) + + b.log10() + + b.log2() + + b.powi(8) + + b.powf(b) + + b.round() + + b.sin() + + b.abs() + + b.signum() + + b.floor() + + b.ceil() + + b.trunc() + + b.sqrt() + + (b % (a as f64)) + + ((a.cos() + + a.exp() + + a.exp2() + + a.mul_add(a, a) + + a.ln() + + a.log(a) + + a.log10() + + a.log2() + + a.powi(8) + + a.powf(a) + + a.round() + + a.sin() + + a.abs() + + a.signum() + + a.floor() + + a.ceil() + + a.trunc() + + a.sqrt() + + (a % (b as f32))) as f64) + + (b + 2.0f64.powf(a as f64)) +} diff --git a/vendor/wasm-bindgen/tests/wasm/option.js b/vendor/wasm-bindgen/tests/wasm/option.js new file mode 100644 index 000000000..e9162feb1 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/option.js @@ -0,0 +1,28 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +class MyType { +} + +exports.MyType = MyType; + +exports.take_none_byval = x => { + assert.strictEqual(x, undefined); +}; +exports.take_some_byval = x => { + assert.ok(x !== null && x !== undefined); + assert.ok(x instanceof MyType); +}; +exports.return_undef_byval = () => undefined; +exports.return_null_byval = () => null; +exports.return_some_byval = () => new MyType(); + +exports.test_option_values = () => { + wasm.rust_take_none_byval(null); + wasm.rust_take_none_byval(undefined); + wasm.rust_take_some_byval(new MyType()); + assert.strictEqual(wasm.rust_return_none_byval(), undefined); + const x = wasm.rust_return_some_byval(); + assert.ok(x !== null && x !== undefined); + assert.ok(x instanceof MyType); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/option.rs b/vendor/wasm-bindgen/tests/wasm/option.rs new file mode 100644 index 000000000..4b4cc4379 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/option.rs @@ -0,0 +1,61 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/option.js")] +extern "C" { + pub type MyType; + #[wasm_bindgen(constructor)] + fn new() -> MyType; + + fn take_none_byval(t: Option); + fn take_some_byval(t: Option); + fn return_undef_byval() -> Option; + fn return_null_byval() -> Option; + fn return_some_byval() -> Option; + fn test_option_values(); + + #[wasm_bindgen(js_name = take_none_byval)] + fn take_none_byref(t: Option<&MyType>); + #[wasm_bindgen(js_name = take_some_byval)] + fn take_some_byref(t: Option<&MyType>); +} + +#[wasm_bindgen_test] +fn import_by_value() { + take_none_byval(None); + take_some_byval(Some(MyType::new())); + assert!(return_null_byval().is_none()); + assert!(return_undef_byval().is_none()); + assert!(return_some_byval().is_some()); +} + +#[wasm_bindgen_test] +fn export_by_value() { + test_option_values(); +} + +#[wasm_bindgen] +pub fn rust_take_none_byval(t: Option) { + assert!(t.is_none()); +} + +#[wasm_bindgen] +pub fn rust_take_some_byval(t: Option) { + assert!(t.is_some()); +} + +#[wasm_bindgen] +pub fn rust_return_none_byval() -> Option { + None +} + +#[wasm_bindgen] +pub fn rust_return_some_byval() -> Option { + Some(MyType::new()) +} + +#[wasm_bindgen_test] +fn import_by_ref() { + take_none_byref(None); + take_some_byref(Some(&MyType::new())); +} diff --git a/vendor/wasm-bindgen/tests/wasm/optional_primitives.js b/vendor/wasm-bindgen/tests/wasm/optional_primitives.js new file mode 100644 index 000000000..89bf4df7e --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/optional_primitives.js @@ -0,0 +1,102 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +exports.optional_i32_js_identity = a => a; +exports.optional_u32_js_identity = a => a; +exports.optional_isize_js_identity = a => a; +exports.optional_usize_js_identity = a => a; +exports.optional_f32_js_identity = a => a; +exports.optional_f64_js_identity = a => a; +exports.optional_i8_js_identity = a => a; +exports.optional_u8_js_identity = a => a; +exports.optional_i16_js_identity = a => a; +exports.optional_u16_js_identity = a => a; +exports.optional_i64_js_identity = a => a; +exports.optional_u64_js_identity = a => a; +exports.optional_bool_js_identity = a => a; +exports.optional_char_js_identity = a => a; + +exports.js_works = () => { + assert.strictEqual(wasm.optional_i32_identity(wasm.optional_i32_none()), undefined); + assert.strictEqual(wasm.optional_i32_identity(wasm.optional_i32_zero()), 0); + assert.strictEqual(wasm.optional_i32_identity(wasm.optional_i32_one()), 1); + assert.strictEqual(wasm.optional_i32_identity(wasm.optional_i32_neg_one()), -1); + assert.strictEqual(wasm.optional_i32_identity(wasm.optional_i32_min()), -2147483648); + assert.strictEqual(wasm.optional_i32_identity(wasm.optional_i32_max()), 2147483647); + + assert.strictEqual(wasm.optional_u32_identity(wasm.optional_u32_none()), undefined); + assert.strictEqual(wasm.optional_u32_identity(wasm.optional_u32_zero()), 0); + assert.strictEqual(wasm.optional_u32_identity(wasm.optional_u32_one()), 1); + assert.strictEqual(wasm.optional_u32_identity(wasm.optional_u32_min()), 0); + assert.strictEqual(wasm.optional_u32_identity(wasm.optional_u32_max()), 4294967295); + + assert.strictEqual(wasm.optional_isize_identity(wasm.optional_isize_none()), undefined); + assert.strictEqual(wasm.optional_isize_identity(wasm.optional_isize_zero()), 0); + assert.strictEqual(wasm.optional_isize_identity(wasm.optional_isize_one()), 1); + assert.strictEqual(wasm.optional_isize_identity(wasm.optional_isize_neg_one()), -1); + assert.strictEqual(wasm.optional_isize_identity(wasm.optional_isize_min()), -2147483648); + assert.strictEqual(wasm.optional_isize_identity(wasm.optional_isize_max()), 2147483647); + + assert.strictEqual(wasm.optional_usize_identity(wasm.optional_usize_none()), undefined); + assert.strictEqual(wasm.optional_usize_identity(wasm.optional_usize_zero()), 0); + assert.strictEqual(wasm.optional_usize_identity(wasm.optional_usize_one()), 1); + assert.strictEqual(wasm.optional_usize_identity(wasm.optional_usize_min()), 0); + assert.strictEqual(wasm.optional_usize_identity(wasm.optional_usize_max()), 4294967295); + + assert.strictEqual(wasm.optional_f32_identity(wasm.optional_f32_none()), undefined); + assert.strictEqual(wasm.optional_f32_identity(wasm.optional_f32_zero()), 0); + assert.strictEqual(wasm.optional_f32_identity(wasm.optional_f32_one()), 1); + assert.strictEqual(wasm.optional_f32_identity(wasm.optional_f32_neg_one()), -1); + + assert.strictEqual(wasm.optional_f64_identity(wasm.optional_f64_none()), undefined); + assert.strictEqual(wasm.optional_f64_identity(wasm.optional_f64_zero()), 0); + assert.strictEqual(wasm.optional_f64_identity(wasm.optional_f64_one()), 1); + assert.strictEqual(wasm.optional_f64_identity(wasm.optional_f64_neg_one()), -1); + + assert.strictEqual(wasm.optional_i8_identity(wasm.optional_i8_none()), undefined); + assert.strictEqual(wasm.optional_i8_identity(wasm.optional_i8_zero()), 0); + assert.strictEqual(wasm.optional_i8_identity(wasm.optional_i8_one()), 1); + assert.strictEqual(wasm.optional_i8_identity(wasm.optional_i8_neg_one()), -1); + assert.strictEqual(wasm.optional_i8_identity(wasm.optional_i8_min()), -128); + assert.strictEqual(wasm.optional_i8_identity(wasm.optional_i8_max()), 127); + + assert.strictEqual(wasm.optional_u8_identity(wasm.optional_u8_none()), undefined); + assert.strictEqual(wasm.optional_u8_identity(wasm.optional_u8_zero()), 0); + assert.strictEqual(wasm.optional_u8_identity(wasm.optional_u8_one()), 1); + assert.strictEqual(wasm.optional_u8_identity(wasm.optional_u8_min()), 0); + assert.strictEqual(wasm.optional_u8_identity(wasm.optional_u8_max()), 255); + + assert.strictEqual(wasm.optional_i16_identity(wasm.optional_i16_none()), undefined); + assert.strictEqual(wasm.optional_i16_identity(wasm.optional_i16_zero()), 0); + assert.strictEqual(wasm.optional_i16_identity(wasm.optional_i16_one()), 1); + assert.strictEqual(wasm.optional_i16_identity(wasm.optional_i16_neg_one()), -1); + assert.strictEqual(wasm.optional_i16_identity(wasm.optional_i16_min()), -32768); + assert.strictEqual(wasm.optional_i16_identity(wasm.optional_i16_max()), 32767); + + assert.strictEqual(wasm.optional_u16_identity(wasm.optional_u16_none()), undefined); + assert.strictEqual(wasm.optional_u16_identity(wasm.optional_u16_zero()), 0); + assert.strictEqual(wasm.optional_u16_identity(wasm.optional_u16_one()), 1); + assert.strictEqual(wasm.optional_u16_identity(wasm.optional_u16_min()), 0); + assert.strictEqual(wasm.optional_u16_identity(wasm.optional_u16_max()), 65535); + + assert.strictEqual(wasm.optional_i64_identity(wasm.optional_i64_none()), undefined); + assert.strictEqual(wasm.optional_i64_identity(wasm.optional_i64_zero()), BigInt('0')); + assert.strictEqual(wasm.optional_i64_identity(wasm.optional_i64_one()), BigInt('1')); + assert.strictEqual(wasm.optional_i64_identity(wasm.optional_i64_neg_one()), BigInt('-1')); + assert.strictEqual(wasm.optional_i64_identity(wasm.optional_i64_min()), BigInt('-9223372036854775808')); + assert.strictEqual(wasm.optional_i64_identity(wasm.optional_i64_max()), BigInt('9223372036854775807')); + + assert.strictEqual(wasm.optional_u64_identity(wasm.optional_u64_none()), undefined); + assert.strictEqual(wasm.optional_u64_identity(wasm.optional_u64_zero()), BigInt('0')); + assert.strictEqual(wasm.optional_u64_identity(wasm.optional_u64_one()), BigInt('1')); + assert.strictEqual(wasm.optional_u64_identity(wasm.optional_u64_min()), BigInt('0')); + assert.strictEqual(wasm.optional_u64_identity(wasm.optional_u64_max()), BigInt('18446744073709551615')); + + assert.strictEqual(wasm.optional_bool_identity(wasm.optional_bool_none()), undefined); + assert.strictEqual(wasm.optional_bool_identity(wasm.optional_bool_false()), false); + assert.strictEqual(wasm.optional_bool_identity(wasm.optional_bool_true()), true); + + assert.strictEqual(wasm.optional_char_identity(wasm.optional_char_none()), undefined); + assert.strictEqual(wasm.optional_char_identity(wasm.optional_char_letter()), 'a'); + assert.strictEqual(wasm.optional_char_identity(wasm.optional_char_face()), '😀'); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/optional_primitives.rs b/vendor/wasm-bindgen/tests/wasm/optional_primitives.rs new file mode 100644 index 000000000..b314ae5ce --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/optional_primitives.rs @@ -0,0 +1,442 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/optional_primitives.js")] +extern "C" { + fn optional_i32_js_identity(a: Option) -> Option; + fn optional_u32_js_identity(a: Option) -> Option; + fn optional_isize_js_identity(a: Option) -> Option; + fn optional_usize_js_identity(a: Option) -> Option; + fn optional_f32_js_identity(a: Option) -> Option; + fn optional_f64_js_identity(a: Option) -> Option; + fn optional_i8_js_identity(a: Option) -> Option; + fn optional_u8_js_identity(a: Option) -> Option; + fn optional_i16_js_identity(a: Option) -> Option; + fn optional_u16_js_identity(a: Option) -> Option; + fn optional_i64_js_identity(a: Option) -> Option; + fn optional_u64_js_identity(a: Option) -> Option; + fn optional_bool_js_identity(a: Option) -> Option; + fn optional_char_js_identity(a: Option) -> Option; + + fn js_works(); +} + +#[wasm_bindgen] +pub fn optional_i32_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn optional_i32_zero() -> Option { + Some(0) +} + +#[wasm_bindgen] +pub fn optional_i32_one() -> Option { + Some(1) +} + +#[wasm_bindgen] +pub fn optional_i32_neg_one() -> Option { + Some(-1) +} + +#[wasm_bindgen] +pub fn optional_i32_min() -> Option { + Some(i32::min_value()) +} + +#[wasm_bindgen] +pub fn optional_i32_max() -> Option { + Some(i32::max_value()) +} + +#[wasm_bindgen] +pub fn optional_i32_identity(a: Option) -> Option { + optional_i32_js_identity(a) +} + +#[wasm_bindgen] +pub fn optional_u32_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn optional_u32_zero() -> Option { + Some(0) +} + +#[wasm_bindgen] +pub fn optional_u32_one() -> Option { + Some(1) +} + +#[wasm_bindgen] +pub fn optional_u32_min() -> Option { + Some(u32::min_value()) +} + +#[wasm_bindgen] +pub fn optional_u32_max() -> Option { + Some(u32::max_value()) +} + +#[wasm_bindgen] +pub fn optional_u32_identity(a: Option) -> Option { + optional_u32_js_identity(a) +} + +#[wasm_bindgen] +pub fn optional_isize_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn optional_isize_zero() -> Option { + Some(0) +} + +#[wasm_bindgen] +pub fn optional_isize_one() -> Option { + Some(1) +} + +#[wasm_bindgen] +pub fn optional_isize_neg_one() -> Option { + Some(-1) +} + +#[wasm_bindgen] +pub fn optional_isize_min() -> Option { + Some(isize::min_value()) +} + +#[wasm_bindgen] +pub fn optional_isize_max() -> Option { + Some(isize::max_value()) +} + +#[wasm_bindgen] +pub fn optional_isize_identity(a: Option) -> Option { + optional_isize_js_identity(a) +} + +#[wasm_bindgen] +pub fn optional_usize_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn optional_usize_zero() -> Option { + Some(0) +} + +#[wasm_bindgen] +pub fn optional_usize_one() -> Option { + Some(1) +} + +#[wasm_bindgen] +pub fn optional_usize_min() -> Option { + Some(usize::min_value()) +} + +#[wasm_bindgen] +pub fn optional_usize_max() -> Option { + Some(usize::max_value()) +} + +#[wasm_bindgen] +pub fn optional_usize_identity(a: Option) -> Option { + optional_usize_js_identity(a) +} + +#[wasm_bindgen] +pub fn optional_f32_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn optional_f32_zero() -> Option { + Some(0f32) +} + +#[wasm_bindgen] +pub fn optional_f32_one() -> Option { + Some(1f32) +} + +#[wasm_bindgen] +pub fn optional_f32_neg_one() -> Option { + Some(-1f32) +} + +#[wasm_bindgen] +pub fn optional_f32_identity(a: Option) -> Option { + optional_f32_js_identity(a) +} + +#[wasm_bindgen] +pub fn optional_f64_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn optional_f64_zero() -> Option { + Some(0f64) +} + +#[wasm_bindgen] +pub fn optional_f64_one() -> Option { + Some(1f64) +} + +#[wasm_bindgen] +pub fn optional_f64_neg_one() -> Option { + Some(-1f64) +} + +#[wasm_bindgen] +pub fn optional_f64_identity(a: Option) -> Option { + optional_f64_js_identity(a) +} + +#[wasm_bindgen] +pub fn optional_i8_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn optional_i8_zero() -> Option { + Some(0) +} + +#[wasm_bindgen] +pub fn optional_i8_one() -> Option { + Some(1) +} + +#[wasm_bindgen] +pub fn optional_i8_neg_one() -> Option { + Some(-1) +} + +#[wasm_bindgen] +pub fn optional_i8_min() -> Option { + Some(i8::min_value()) +} + +#[wasm_bindgen] +pub fn optional_i8_max() -> Option { + Some(i8::max_value()) +} + +#[wasm_bindgen] +pub fn optional_i8_identity(a: Option) -> Option { + optional_i8_js_identity(a) +} + +#[wasm_bindgen] +pub fn optional_u8_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn optional_u8_zero() -> Option { + Some(0) +} + +#[wasm_bindgen] +pub fn optional_u8_one() -> Option { + Some(1) +} + +#[wasm_bindgen] +pub fn optional_u8_min() -> Option { + Some(u8::min_value()) +} + +#[wasm_bindgen] +pub fn optional_u8_max() -> Option { + Some(u8::max_value()) +} + +#[wasm_bindgen] +pub fn optional_u8_identity(a: Option) -> Option { + optional_u8_js_identity(a) +} + +#[wasm_bindgen] +pub fn optional_i16_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn optional_i16_zero() -> Option { + Some(0) +} + +#[wasm_bindgen] +pub fn optional_i16_one() -> Option { + Some(1) +} + +#[wasm_bindgen] +pub fn optional_i16_neg_one() -> Option { + Some(-1) +} + +#[wasm_bindgen] +pub fn optional_i16_min() -> Option { + Some(i16::min_value()) +} + +#[wasm_bindgen] +pub fn optional_i16_max() -> Option { + Some(i16::max_value()) +} + +#[wasm_bindgen] +pub fn optional_i16_identity(a: Option) -> Option { + optional_i16_js_identity(a) +} + +#[wasm_bindgen] +pub fn optional_u16_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn optional_u16_zero() -> Option { + Some(0) +} + +#[wasm_bindgen] +pub fn optional_u16_one() -> Option { + Some(1) +} + +#[wasm_bindgen] +pub fn optional_u16_min() -> Option { + Some(u16::min_value()) +} + +#[wasm_bindgen] +pub fn optional_u16_max() -> Option { + Some(u16::max_value()) +} + +#[wasm_bindgen] +pub fn optional_u16_identity(a: Option) -> Option { + optional_u16_js_identity(a) +} + +#[wasm_bindgen] +pub fn optional_i64_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn optional_i64_zero() -> Option { + Some(0) +} + +#[wasm_bindgen] +pub fn optional_i64_one() -> Option { + Some(1) +} + +#[wasm_bindgen] +pub fn optional_i64_neg_one() -> Option { + Some(-1) +} + +#[wasm_bindgen] +pub fn optional_i64_min() -> Option { + Some(i64::min_value()) +} + +#[wasm_bindgen] +pub fn optional_i64_max() -> Option { + Some(i64::max_value()) +} + +#[wasm_bindgen] +pub fn optional_i64_identity(a: Option) -> Option { + optional_i64_js_identity(a) +} + +#[wasm_bindgen] +pub fn optional_u64_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn optional_u64_zero() -> Option { + Some(0) +} + +#[wasm_bindgen] +pub fn optional_u64_one() -> Option { + Some(1) +} + +#[wasm_bindgen] +pub fn optional_u64_min() -> Option { + Some(u64::min_value()) +} + +#[wasm_bindgen] +pub fn optional_u64_max() -> Option { + Some(u64::max_value()) +} + +#[wasm_bindgen] +pub fn optional_u64_identity(a: Option) -> Option { + optional_u64_js_identity(a) +} + +#[wasm_bindgen] +pub fn optional_bool_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn optional_bool_false() -> Option { + Some(false) +} + +#[wasm_bindgen] +pub fn optional_bool_true() -> Option { + Some(true) +} + +#[wasm_bindgen] +pub fn optional_bool_identity(a: Option) -> Option { + optional_bool_js_identity(a) +} + +#[wasm_bindgen] +pub fn optional_char_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn optional_char_letter() -> Option { + Some('a') +} + +#[wasm_bindgen] +pub fn optional_char_face() -> Option { + Some('😀') +} + +#[wasm_bindgen] +pub fn optional_char_identity(a: Option) -> Option { + optional_char_js_identity(a) +} + +#[wasm_bindgen_test] +fn works() { + js_works(); +} diff --git a/vendor/wasm-bindgen/tests/wasm/result.js b/vendor/wasm-bindgen/tests/wasm/result.js new file mode 100644 index 000000000..2bf9f378f --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/result.js @@ -0,0 +1,126 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +exports.error_new = function(message) { + return new Error(message) +} + +exports.call_ok = function() { + assert.doesNotThrow(() => { + let five = wasm.return_my_ok(); + assert.strictEqual(five, 5); + }) +} + +exports.call_err = function() { + assert.throws(() => wasm.return_my_err(), { + message: "MyError::Variant" + }); +} + +function check_inflight(struct) { + assert.strictEqual(struct.is_inflight(), false); +} + +exports.all_struct_methods = function() { + let struct; + assert.throws(() => wasm.Struct.new_err(), { + message: "MyError::Variant" + }); + assert.doesNotThrow(() => { + struct = wasm.Struct.new(); + }); + check_inflight(struct); + assert.doesNotThrow(() => { + let five = struct.return_ok(); + assert.strictEqual(five, 5); + }); + check_inflight(struct); + assert.throws(() => struct.return_err(), { + message: "MyError::Variant" + }); + check_inflight(struct); +} + +exports.call_return_string = function() { + assert.doesNotThrow(() => { + let ok = wasm.return_string(); + assert.strictEqual(ok, "string here"); + }) +} + +exports.call_jsvalue_ok = function() { + assert.doesNotThrow(() => { + let five = wasm.return_jsvalue_ok(); + assert.strictEqual(five, 5); + }) +} + +exports.call_jsvalue_err = function() { + try { + wasm.return_jsvalue_err(); + assert.fail("should have thrown"); + } catch (e) { + assert.strictEqual(e, -1); + } +} + +exports.call_string_ok = function() { + assert.doesNotThrow(() => { + let ok = wasm.return_string_ok(); + assert.strictEqual(ok, "Ok"); + }) +} + +exports.call_string_err = function() { + // the behaviour of Result is so finicky that it's not obvious + // how to to reproduce reliably but also pass the test suite. + assert.throws(() => e = wasm.return_string_err(), e => { + // one thing we can do (uncomment to test) + // is to throw an error in here. + // throw new Error("should not cause a SIGBUS in Node") + return e === "Er"; + }); +} + +exports.call_enum_ok = function() { + assert.doesNotThrow(() => { + let ok = wasm.return_enum_ok(); + assert.strictEqual(ok, 2); + }) +} + +exports.call_enum_err = function() { + assert.throws(() => { + wasm.return_enum_err(); + }, { + message: "MyError::Variant" + }) +} + +exports.call_unit = function() { + assert.doesNotThrow(() => { + wasm.return_unit_ok(); + }); + assert.throws(() => { + wasm.return_unit_err(); + }, { + message: "MyError::Variant" + }); +} + +exports.call_option = function() { + assert.doesNotThrow(() => { + let o = wasm.return_option_ok_some(); + assert.strictEqual(o, 10.0); + }); + assert.doesNotThrow(() => { + let o = wasm.return_option_ok_none(); + assert.strictEqual(o, undefined); + }); + assert.throws(() => { + wasm.return_option_err(); + }, { + message: "MyError::Variant" + }); +} diff --git a/vendor/wasm-bindgen/tests/wasm/result.rs b/vendor/wasm-bindgen/tests/wasm/result.rs new file mode 100644 index 000000000..c2c043ab8 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/result.rs @@ -0,0 +1,190 @@ +use std::fmt; +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[derive(Clone, Debug)] +pub enum MyError { + Variant, + InflightShouldBeFalse, +} +// shouldn't technically need this, surely +impl std::error::Error for MyError {} +impl fmt::Display for MyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "MyError::{:?}", self) + } +} + +#[wasm_bindgen(module = "tests/wasm/result.js")] +extern "C" { + fn error_new(message: &str) -> JsValue; +} + +impl Into for MyError { + fn into(self) -> JsValue { + error_new(&format!("{}", self)) + } +} + +macro_rules! call_test { + ($test_fn:ident, $js_fn:ident) => { + #[wasm_bindgen_test] + fn $test_fn() { + #[wasm_bindgen(module = "tests/wasm/result.js")] + extern "C" { + fn $js_fn(); + } + $js_fn(); + } + }; +} + +#[wasm_bindgen] +pub fn return_my_err() -> Result { + let e = Err(MyError::Variant)?; + Ok(e) +} +call_test!(test_err, call_err); + +#[wasm_bindgen] +pub fn return_my_ok() -> Result { + Ok(5) +} +call_test!(test_ok, call_ok); + +#[wasm_bindgen] +pub struct Struct { + inflight: bool, +} + +call_test!(test_struct, all_struct_methods); + +struct ResetOnDrop<'a> { + flag: &'a mut bool, +} + +impl<'a> Drop for ResetOnDrop<'a> { + fn drop(&mut self) { + *self.flag = false; + } +} + +impl<'a> ResetOnDrop<'a> { + fn new(flag: &'a mut bool) -> Result { + if *flag { + return Err(MyError::InflightShouldBeFalse); + } + Ok(Self { flag }) + } +} + +#[wasm_bindgen] +impl Struct { + #[wasm_bindgen] + pub fn new() -> Result { + Ok(Struct { inflight: false }) + } + + #[wasm_bindgen] + pub fn new_err() -> Result { + Err(MyError::Variant.into()) + } + + #[wasm_bindgen] + pub fn return_ok(&mut self) -> Result { + let _guard = ResetOnDrop::new(&mut self.inflight)?; + Ok(5) + } + + #[wasm_bindgen] + pub fn return_err(&mut self) -> Result { + let guard = ResetOnDrop::new(&mut self.inflight)?; + let err = Err(MyError::Variant); + let nope = err?; + // we are checking both for the flag being reset (from js, via is_inflight) + // and for the running of drop code + drop(guard); + Ok(nope) + } + + #[wasm_bindgen] + pub fn is_inflight(&self) -> bool { + self.inflight + } +} + +// check some more Ok types +#[wasm_bindgen] +pub fn return_string() -> Result { + Ok("string here".into()) +} +call_test!(test_return_string, call_return_string); + +// now we check that jsvalue works, as it did before + +#[wasm_bindgen] +pub fn return_jsvalue_ok() -> Result { + Ok(5) +} +call_test!(test_jsvalue_ok, call_jsvalue_ok); + +#[wasm_bindgen] +pub fn return_jsvalue_err() -> Result { + Err(JsValue::from(-1i32)) +} +call_test!(test_jsvalue_err, call_jsvalue_err); + +// test strings (they have a deferred free, in a finally block: tricky) +#[wasm_bindgen] +pub fn return_string_ok() -> Result { + Ok("Ok".into()) +} +call_test!(test_string_ok, call_string_ok); +#[wasm_bindgen] +pub fn return_string_err() -> Result { + Err("Er".into()) +} +call_test!(test_string_err, call_string_err); + +// test enums +#[wasm_bindgen] +pub enum MyEnum { + One = 1, + Two = 2, +} +#[wasm_bindgen] +pub fn return_enum_ok() -> Result { + Ok(MyEnum::Two) +} +call_test!(test_enum_ok, call_enum_ok); +#[wasm_bindgen] +pub fn return_enum_err() -> Result { + Err(MyError::Variant) +} +call_test!(test_enum_err, call_enum_err); + +// T = Unit +#[wasm_bindgen] +pub fn return_unit_ok() -> Result<(), MyError> { + Ok(()) +} +#[wasm_bindgen] +pub fn return_unit_err() -> Result<(), MyError> { + Err(MyError::Variant) +} +call_test!(test_unit, call_unit); + +// T = Option +#[wasm_bindgen] +pub fn return_option_ok_some() -> Result, MyError> { + Ok(Some(10f64)) +} +#[wasm_bindgen] +pub fn return_option_ok_none() -> Result, MyError> { + Ok(None) +} +#[wasm_bindgen] +pub fn return_option_err() -> Result, MyError> { + Err(MyError::Variant) +} +call_test!(test_option, call_option); diff --git a/vendor/wasm-bindgen/tests/wasm/result_jserror.js b/vendor/wasm-bindgen/tests/wasm/result_jserror.js new file mode 100644 index 000000000..d27736d9c --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/result_jserror.js @@ -0,0 +1,54 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +exports.call_ok = function() { + assert.doesNotThrow(() => { + let five = wasm.return_ok(); + assert.strictEqual(five, 5); + }) +} + +exports.call_err = function() { + assert.throws(() => wasm.return_err(), { + message: "MyError::Variant" + }); +} + +exports.call_make_an_error = function() { + assert.doesNotThrow(() => { + let e = wasm.make_an_error() + assert.strictEqual(e.message, "un-thrown error"); + }); +} + +function check_inflight(struct) { + assert.strictEqual(struct.is_inflight(), false); +} + +exports.all_struct_methods = function() { + let struct; + assert.throws(() => wasm.MyStruct.new_err(), { + message: "MyError::Variant" + }); + assert.doesNotThrow(() => { + struct = wasm.MyStruct.new(); + }); + check_inflight(struct); + assert.doesNotThrow(() => { + let five = struct.return_ok(); + assert.strictEqual(five, 5); + }); + check_inflight(struct); + assert.throws(() => struct.return_err(), { + message: "MyError::Variant" + }); + check_inflight(struct); +} + +exports.call_return_string = function() { + assert.doesNotThrow(() => { + let ok = wasm.jserror_return_string(); + assert.strictEqual(ok, "string here"); + }) +} + diff --git a/vendor/wasm-bindgen/tests/wasm/result_jserror.rs b/vendor/wasm-bindgen/tests/wasm/result_jserror.rs new file mode 100644 index 000000000..f714ac2f1 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/result_jserror.rs @@ -0,0 +1,118 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsError; +use wasm_bindgen_test::*; + +use std::fmt; + +#[derive(Clone, Debug)] +enum MyError { + Variant, + InflightShouldBeFalse, +} +// shouldn't technically need this, surely +impl std::error::Error for MyError {} +impl fmt::Display for MyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "MyError::{:?}", self) + } +} + +macro_rules! call_test { + ($test_fn:ident, $js_fn:ident) => { + #[wasm_bindgen_test] + fn $test_fn() { + #[wasm_bindgen(module = "tests/wasm/result_jserror.js")] + extern "C" { + fn $js_fn(); + } + $js_fn(); + } + }; +} + +#[wasm_bindgen] +pub fn return_err() -> Result { + let e = Err(MyError::Variant)?; + Ok(e) +} +call_test!(test_err, call_err); + +#[wasm_bindgen] +pub fn return_ok() -> Result { + Ok(5) +} +call_test!(test_ok, call_ok); + +#[wasm_bindgen] +pub fn make_an_error() -> JsError { + JsError::new("un-thrown error").into() +} +call_test!(test_make_an_error, call_make_an_error); + +#[wasm_bindgen] +pub struct MyStruct { + inflight: bool, +} + +call_test!(test_struct, all_struct_methods); + +struct ResetOnDrop<'a> { + flag: &'a mut bool, +} + +impl<'a> Drop for ResetOnDrop<'a> { + fn drop(&mut self) { + *self.flag = false; + } +} + +impl<'a> ResetOnDrop<'a> { + fn new(flag: &'a mut bool) -> Result { + if *flag { + return Err(MyError::InflightShouldBeFalse); + } + Ok(Self { flag }) + } +} + +#[wasm_bindgen] +impl MyStruct { + #[wasm_bindgen] + pub fn new() -> Result { + Ok(MyStruct { inflight: false }) + } + + #[wasm_bindgen] + pub fn new_err() -> Result { + Err(MyError::Variant.into()) + } + + #[wasm_bindgen] + pub fn return_ok(&mut self) -> Result { + let _guard = ResetOnDrop::new(&mut self.inflight)?; + Ok(5) + } + + #[wasm_bindgen] + pub fn return_err(&mut self) -> Result { + let guard = ResetOnDrop::new(&mut self.inflight)?; + let err = Err(MyError::Variant); + let nope = err?; + // we are checking both for the flag being reset (from js, via is_inflight) + // and for the running of drop code + drop(guard); + Ok(nope) + } + + #[wasm_bindgen] + pub fn is_inflight(&self) -> bool { + self.inflight + } +} + +// check some more Ok types +#[wasm_bindgen] +pub fn jserror_return_string() -> Result { + Ok("string here".into()) +} +call_test!(test_return_string, call_return_string); diff --git a/vendor/wasm-bindgen/tests/wasm/rethrow.js b/vendor/wasm-bindgen/tests/wasm/rethrow.js new file mode 100644 index 000000000..70e9c3381 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/rethrow.js @@ -0,0 +1,14 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +exports.call_throw_one = function() { + try { + wasm.throw_one(); + } catch (e) { + assert.strictEqual(e, 1); + } +}; + +exports.call_ok = function() { + wasm.nothrow(); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/rethrow.rs b/vendor/wasm-bindgen/tests/wasm/rethrow.rs new file mode 100644 index 000000000..d2a0ffafd --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/rethrow.rs @@ -0,0 +1,28 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/rethrow.js")] +extern "C" { + fn call_throw_one(); + fn call_ok(); +} + +#[wasm_bindgen_test] +fn err_works() { + call_throw_one(); +} + +#[wasm_bindgen] +pub fn throw_one() -> Result { + Err(1.into()) +} + +#[wasm_bindgen_test] +fn ok_works() { + call_ok(); +} + +#[wasm_bindgen] +pub fn nothrow() -> Result { + Ok(1) +} diff --git a/vendor/wasm-bindgen/tests/wasm/simple.js b/vendor/wasm-bindgen/tests/wasm/simple.js new file mode 100644 index 000000000..cf53525e6 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/simple.js @@ -0,0 +1,107 @@ +const assert = require('assert'); +const wasm = require('wasm-bindgen-test'); + +exports.test_add = function() { + assert.strictEqual(wasm.simple_add(1, 2), 3); + assert.strictEqual(wasm.simple_add(2, 3), 5); + assert.strictEqual(wasm.simple_add3(2), 5); + assert.strictEqual(wasm.simple_get2(true), 2); + assert.strictEqual(wasm.simple_return_and_take_bool(true, false), false); +}; + +exports.test_string_arguments = function() { + wasm.simple_assert_foo("foo"); + wasm.simple_assert_foo_and_bar("foo2", "bar"); +}; + +exports.test_return_a_string = function() { + assert.strictEqual(wasm.simple_clone("foo"), "foo"); + assert.strictEqual(wasm.simple_clone("another"), "another"); + assert.strictEqual(wasm.simple_concat("a", "b", 3), "a b 3"); + assert.strictEqual(wasm.simple_concat("c", "d", -2), "c d -2"); +}; + +exports.test_wrong_types = function() { + // this test only works when `--debug` is passed to `wasm-bindgen` (or the + // equivalent thereof) + if (require('process').env.WASM_BINDGEN_NO_DEBUG) + return; + assert.throws(() => wasm.simple_int('a'), /expected a number argument/); + assert.throws(() => wasm.simple_str(3), /expected a string argument/); +}; + +exports.test_other_exports_still_available = function() { + require('wasm-bindgen-test').__wasm.foo(3); +}; + +exports.test_jsvalue_typeof = function() { + assert.ok(wasm.is_object({})); + assert.ok(!wasm.is_object(42)); + assert.ok(wasm.is_function(function() {})); + assert.ok(!wasm.is_function(42)); + assert.ok(wasm.is_string("2b or !2b")); + assert.ok(!wasm.is_string(42)); +}; + +exports.optional_str_none = function(x) { + assert.strictEqual(x, undefined); +}; + +exports.optional_str_some = function(x) { + assert.strictEqual(x, 'x'); +}; + +exports.optional_slice_none = function(x) { + assert.strictEqual(x, undefined); +}; + +exports.optional_slice_some = function(x) { + assert.strictEqual(x.length, 3); + assert.strictEqual(x[0], 1); + assert.strictEqual(x[1], 2); + assert.strictEqual(x[2], 3); +} + +exports.optional_string_none = function(x) { + assert.strictEqual(x, undefined); +}; + +exports.optional_string_some = function(x) { + assert.strictEqual(x, 'abcd'); +}; + +exports.optional_string_some_empty = function(x) { + assert.strictEqual(x, ''); +}; + +exports.return_string_none = function() {}; +exports.return_string_some = function() { + return 'foo'; +}; + +exports.test_rust_optional = function() { + wasm.take_optional_str_none(); + wasm.take_optional_str_none(null); + wasm.take_optional_str_none(undefined); + wasm.take_optional_str_some('hello'); + assert.strictEqual(wasm.return_optional_str_none(), undefined); + assert.strictEqual(wasm.return_optional_str_some(), 'world'); +}; + +exports.RenamedInRust = class {}; +exports.new_renamed = () => new exports.RenamedInRust; + +exports.import_export_same_name = () => {}; + +exports.test_string_roundtrip = () => { + const test = s => { + assert.strictEqual(wasm.do_string_roundtrip(s), s); + }; + + test(''); + test('a'); + test('💖'); + + test('a longer string'); + test('a longer 💖 string'); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/simple.rs b/vendor/wasm-bindgen/tests/wasm/simple.rs new file mode 100644 index 000000000..611b5320a --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/simple.rs @@ -0,0 +1,227 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen::{intern, unintern, JsCast}; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/simple.js")] +extern "C" { + fn test_add(); + fn test_string_arguments(); + fn test_return_a_string(); + fn test_wrong_types(); + fn test_other_exports_still_available(); + fn test_jsvalue_typeof(); + + fn optional_str_none(a: Option<&str>); + fn optional_str_some(a: Option<&str>); + fn optional_slice_none(a: Option<&[u8]>); + fn optional_slice_some(a: Option<&[u8]>); + fn optional_string_none(a: Option); + fn optional_string_some(a: Option); + fn optional_string_some_empty(a: Option); + fn return_string_none() -> Option; + fn return_string_some() -> Option; + fn test_rust_optional(); + #[wasm_bindgen(js_name = import_export_same_name)] + fn js_import_export_same_name(); + + #[wasm_bindgen(js_name = RenamedInRust)] + type Renamed; + fn new_renamed() -> Renamed; + + fn test_string_roundtrip(); +} + +#[wasm_bindgen_test] +fn add() { + test_add(); +} + +#[wasm_bindgen] +pub fn simple_add(a: u32, b: u32) -> u32 { + a + b +} + +#[wasm_bindgen] +pub fn simple_add3(a: u32) -> u32 { + a + 3 +} + +#[wasm_bindgen] +pub fn simple_get2(_b: bool) -> u32 { + 2 +} + +#[wasm_bindgen] +pub fn simple_return_and_take_bool(a: bool, b: bool) -> bool { + a && b +} + +#[wasm_bindgen] +pub fn simple_raw_pointers_work(a: *mut u32, b: *const u8) -> *const u32 { + unsafe { + (*a) = (*b) as u32; + return a; + } +} + +#[wasm_bindgen_test] +fn string_arguments() { + test_string_arguments(); +} + +#[wasm_bindgen] +pub fn simple_assert_foo_and_bar(a: &str, b: &str) { + assert_eq!(a, "foo2"); + assert_eq!(b, "bar"); +} + +#[wasm_bindgen] +pub fn simple_assert_foo(a: &str) { + assert_eq!(a, "foo"); +} + +#[wasm_bindgen_test] +fn return_a_string() { + test_return_a_string(); +} + +#[wasm_bindgen] +pub fn simple_clone(a: &str) -> String { + a.to_string() +} + +#[wasm_bindgen] +pub fn simple_concat(a: &str, b: &str, c: i8) -> String { + format!("{} {} {}", a, b, c) +} + +#[wasm_bindgen_test] +fn wrong_types() { + test_wrong_types(); +} + +#[wasm_bindgen] +pub fn simple_int(_a: u32) {} + +#[wasm_bindgen] +pub fn simple_str(_a: &str) {} + +#[wasm_bindgen_test] +fn other_exports() { + test_other_exports_still_available(); +} + +#[no_mangle] +pub extern "C" fn foo(_a: u32) {} + +#[wasm_bindgen_test] +fn jsvalue_typeof() { + test_jsvalue_typeof(); +} + +#[wasm_bindgen] +pub fn is_object(val: &JsValue) -> bool { + val.is_object() +} + +#[wasm_bindgen] +pub fn is_function(val: &JsValue) -> bool { + val.is_function() +} + +#[wasm_bindgen] +pub fn is_string(val: &JsValue) -> bool { + val.is_string() +} + +#[wasm_bindgen] +extern "C" { + #[derive(Clone)] + type Array; + #[wasm_bindgen(constructor)] + fn new() -> Array; + #[wasm_bindgen(method, catch)] + fn standardized_method_this_js_runtime_doesnt_implement_yet( + this: &Array, + ) -> Result<(), JsValue>; +} + +#[wasm_bindgen_test] +fn binding_to_unimplemented_apis_doesnt_break_everything() { + let array = Array::new(); + let res = array.standardized_method_this_js_runtime_doesnt_implement_yet(); + assert!(res.is_err()); +} + +#[wasm_bindgen_test] +fn optional_slices() { + optional_str_none(None); + optional_str_some(Some("x")); + optional_str_some(Some(intern("x"))); + unintern("x"); + optional_str_some(Some("x")); + optional_slice_none(None); + optional_slice_some(Some(&[1, 2, 3])); + optional_string_none(None); + optional_string_some_empty(Some(String::new())); + optional_string_some(Some("abcd".to_string())); + + assert_eq!(return_string_none(), None); + assert_eq!(return_string_some(), Some("foo".to_string())); + test_rust_optional(); +} + +#[wasm_bindgen] +pub fn take_optional_str_none(x: Option) { + assert!(x.is_none()) +} +#[wasm_bindgen] +pub fn take_optional_str_some(x: Option) { + assert_eq!(x, Some(String::from("hello"))); +} + +#[wasm_bindgen] +pub fn return_optional_str_none() -> Option { + None +} + +#[wasm_bindgen] +pub fn return_optional_str_some() -> Option { + Some("world".to_string()) +} + +#[wasm_bindgen_test] +fn renaming_imports_and_instanceof() { + let null = JsValue::NULL; + assert!(!null.is_instance_of::()); + + let arr: JsValue = Array::new().into(); + assert!(!arr.is_instance_of::()); + + let renamed: JsValue = new_renamed().into(); + assert!(renamed.is_instance_of::()); +} + +#[wasm_bindgen] +pub fn import_export_same_name() { + js_import_export_same_name(); +} + +#[wasm_bindgen_test] +fn string_roundtrip() { + test_string_roundtrip(); +} + +#[wasm_bindgen] +pub fn do_string_roundtrip(s: String) -> String { + s +} + +#[wasm_bindgen_test] +fn externref_heap_live_count() { + let x = wasm_bindgen::externref_heap_live_count(); + let y = JsValue::null().clone(); + assert!(wasm_bindgen::externref_heap_live_count() > x); + drop(y); + assert_eq!(x, wasm_bindgen::externref_heap_live_count()); +} diff --git a/vendor/wasm-bindgen/tests/wasm/slice.js b/vendor/wasm-bindgen/tests/wasm/slice.js new file mode 100644 index 000000000..c23535e9b --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/slice.js @@ -0,0 +1,197 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +exports.js_export = () => { + const i8 = new Int8Array(2); + i8[0] = 1; + i8[1] = 2; + assert.deepStrictEqual(wasm.export_i8(i8), i8); + const u8 = new Uint8Array(2); + u8[0] = 1; + u8[1] = 2; + assert.deepStrictEqual(wasm.export_u8(u8), u8); + + const i16 = new Int16Array(2); + i16[0] = 1; + i16[1] = 2; + assert.deepStrictEqual(wasm.export_i16(i16), i16); + const u16 = new Uint16Array(2); + u16[0] = 1; + u16[1] = 2; + assert.deepStrictEqual(wasm.export_u16(u16), u16); + + const i32 = new Int32Array(2); + i32[0] = 1; + i32[1] = 2; + assert.deepStrictEqual(wasm.export_i32(i32), i32); + assert.deepStrictEqual(wasm.export_isize(i32), i32); + const u32 = new Uint32Array(2); + u32[0] = 1; + u32[1] = 2; + assert.deepStrictEqual(wasm.export_u32(u32), u32); + assert.deepStrictEqual(wasm.export_usize(u32), u32); + + const f32 = new Float32Array(2); + f32[0] = 1; + f32[1] = 2; + assert.deepStrictEqual(wasm.export_f32(f32), f32); + const f64 = new Float64Array(2); + f64[0] = 1; + f64[1] = 2; + assert.deepStrictEqual(wasm.export_f64(f64), f64); +}; + +const test_import = (a, b, c) => { + assert.strictEqual(a.length, 2); + assert.strictEqual(a[0], 1); + assert.strictEqual(a[1], 2); + assert.strictEqual(b.length, 2); + assert.strictEqual(b[0], 1); + assert.strictEqual(b[1], 2); + assert.strictEqual(c, undefined); + return a; +}; + +exports.import_js_i8 = test_import; +exports.import_js_u8 = test_import; +exports.import_js_i16 = test_import; +exports.import_js_u16 = test_import; +exports.import_js_i32 = test_import; +exports.import_js_isize = test_import; +exports.import_js_u32 = test_import; +exports.import_js_usize = test_import; +exports.import_js_f32 = test_import; +exports.import_js_f64 = test_import; + +exports.js_import = () => { + const i8 = new Int8Array(2); + i8[0] = 1; + i8[1] = 2; + assert.deepStrictEqual(wasm.import_rust_i8(i8), i8); + const u8 = new Uint8Array(2); + u8[0] = 1; + u8[1] = 2; + assert.deepStrictEqual(wasm.import_rust_u8(u8), u8); + + const i16 = new Int16Array(2); + i16[0] = 1; + i16[1] = 2; + assert.deepStrictEqual(wasm.import_rust_i16(i16), i16); + const u16 = new Uint16Array(2); + u16[0] = 1; + u16[1] = 2; + assert.deepStrictEqual(wasm.import_rust_u16(u16), u16); + + const i32 = new Int32Array(2); + i32[0] = 1; + i32[1] = 2; + assert.deepStrictEqual(wasm.import_rust_i32(i32), i32); + assert.deepStrictEqual(wasm.import_rust_isize(i32), i32); + const u32 = new Uint32Array(2); + u32[0] = 1; + u32[1] = 2; + assert.deepStrictEqual(wasm.import_rust_u32(u32), u32); + assert.deepStrictEqual(wasm.import_rust_usize(u32), u32); + + const f32 = new Float32Array(2); + f32[0] = 1; + f32[1] = 2; + assert.deepStrictEqual(wasm.import_rust_f32(f32), f32); + const f64 = new Float64Array(2); + f64[0] = 1; + f64[1] = 2; + assert.deepStrictEqual(wasm.import_rust_f64(f64), f64); +}; + +exports.js_pass_array = () => { + wasm.pass_array_rust_i8([1, 2]); + wasm.pass_array_rust_u8([1, 2]); + wasm.pass_array_rust_i16([1, 2]); + wasm.pass_array_rust_u16([1, 2]); + wasm.pass_array_rust_i32([1, 2]); + wasm.pass_array_rust_u32([1, 2]); + wasm.pass_array_rust_isize([1, 2]); + wasm.pass_array_rust_usize([1, 2]); + wasm.pass_array_rust_f32([1, 2]); + wasm.pass_array_rust_f64([1, 2]); +}; + +const import_mut_foo = (a, b, c) => { + assert.strictEqual(a.length, 3); + assert.strictEqual(a[0], 1); + assert.strictEqual(a[1], 2); + a[0] = 4; + a[1] = 5; + assert.strictEqual(b.length, 3); + assert.strictEqual(b[0], 4); + assert.strictEqual(b[1], 5); + assert.strictEqual(b[2], 6); + b[0] = 8; + b[1] = 7; + assert.strictEqual(c, undefined); +}; + +exports.import_mut_js_i8 = import_mut_foo; +exports.import_mut_js_u8 = import_mut_foo; +exports.import_mut_js_i16 = import_mut_foo; +exports.import_mut_js_u16 = import_mut_foo; +exports.import_mut_js_i32 = import_mut_foo; +exports.import_mut_js_u32 = import_mut_foo; +exports.import_mut_js_isize = import_mut_foo; +exports.import_mut_js_usize = import_mut_foo; +exports.import_mut_js_f32 = import_mut_foo; +exports.import_mut_js_f64 = import_mut_foo; + +const export_mut_run = (a, rust) => { + assert.strictEqual(a.length, 3); + a[0] = 1; + a[1] = 2; + a[2] = 3; + console.log(a); + rust(a); + console.log(a); + assert.strictEqual(a.length, 3); + assert.strictEqual(a[0], 4); + assert.strictEqual(a[1], 5); + assert.strictEqual(a[2], 3); +}; + +exports.js_export_mut = () => { + export_mut_run(new Int8Array(3), wasm.export_mut_i8); + export_mut_run(new Uint8Array(3), wasm.export_mut_u8); + export_mut_run(new Int16Array(3), wasm.export_mut_i16); + export_mut_run(new Uint16Array(3), wasm.export_mut_u16); + export_mut_run(new Int32Array(3), wasm.export_mut_i32); + export_mut_run(new Uint32Array(3), wasm.export_mut_u32); + export_mut_run(new Int32Array(3), wasm.export_mut_isize); + export_mut_run(new Uint32Array(3), wasm.export_mut_usize); + export_mut_run(new Float32Array(3), wasm.export_mut_f32); + export_mut_run(new Float64Array(3), wasm.export_mut_f64); +}; + +exports.js_return_vec = () => { + const app = wasm.return_vec_web_main(); + + for (let i = 0; i < 10; i++) { + app.tick(); + const bad = wasm.return_vec_broken_vec(); + console.log('Received from rust:', i, bad); + assert.strictEqual(bad[0], 1); + assert.strictEqual(bad[1], 2); + assert.strictEqual(bad[2], 3); + assert.strictEqual(bad[3], 4); + assert.strictEqual(bad[4], 5); + assert.strictEqual(bad[5], 6); + assert.strictEqual(bad[6], 7); + assert.strictEqual(bad[7], 8); + assert.strictEqual(bad[8], 9); + } +}; + +exports.js_clamped = (a, offset) => { + assert.ok(a instanceof Uint8ClampedArray); + assert.equal(a.length, 3); + assert.equal(a[0], offset + 0); + assert.equal(a[1], offset + 1); + assert.equal(a[2], offset + 2); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/slice.rs b/vendor/wasm-bindgen/tests/wasm/slice.rs new file mode 100644 index 000000000..2f2457bc1 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/slice.rs @@ -0,0 +1,240 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen::Clamped; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/slice.js")] +extern "C" { + fn js_export(); + + fn js_import(); + + fn js_pass_array(); + + fn js_export_mut(); + + fn js_return_vec(); + + fn js_clamped(val: Clamped<&[u8]>, offset: u8); + #[wasm_bindgen(js_name = js_clamped)] + fn js_clamped2(val: Clamped>, offset: u8); + #[wasm_bindgen(js_name = js_clamped)] + fn js_clamped3(val: Clamped<&mut [u8]>, offset: u8); +} + +macro_rules! export_macro { + ($(($i:ident, $n:ident))*) => ($( + #[wasm_bindgen] + pub fn $n(a: &[$i]) -> Vec<$i> { + assert_eq!(a.len(), 2); + assert_eq!(a[0], 1 as $i); + assert_eq!(a[1], 2 as $i); + a.to_vec() + } + )*) +} + +export_macro! { + (i8, export_i8) + (u8, export_u8) + (i16, export_i16) + (u16, export_u16) + (i32, export_i32) + (u32, export_u32) + (isize, export_isize) + (usize, export_usize) + (f32, export_f32) + (f64, export_f64) +} + +#[wasm_bindgen_test] +fn export() { + js_export(); +} + +macro_rules! import_macro { + ($(($rust:ident, $js:ident, $i:ident))*) => ($( + #[wasm_bindgen(module = "tests/wasm/slice.js")] + extern "C" { + fn $js(a: &[$i], b: Option<&[$i]>, c: Option<&[$i]>) -> Vec<$i>; + } + + #[wasm_bindgen] + pub fn $rust(a: &[$i]) -> Vec<$i> { + assert_eq!(a.len(), 2); + assert_eq!(a[0], 1 as $i); + assert_eq!(a[1], 2 as $i); + $js(a, Some(a), None) + } + )*) +} + +import_macro! { + (import_rust_i8, import_js_i8, i8) + (import_rust_u8, import_js_u8, u8) + (import_rust_i16, import_js_i16, i16) + (import_rust_u16, import_js_u16, u16) + (import_rust_i32, import_js_i32, i32) + (import_rust_u32, import_js_u32, u32) + (import_rust_isize, import_js_isize, isize) + (import_rust_usize, import_js_usize, usize) + (import_rust_f32, import_js_f32, f32) + (import_rust_f64, import_js_f64, f64) +} + +#[wasm_bindgen_test] +fn import() { + js_import(); +} + +macro_rules! pass_array_marco { + ($(($rust:ident, $i:ident))*) => ($( + #[wasm_bindgen] + pub fn $rust(a: &[$i]) { + assert_eq!(a.len(), 2); + assert_eq!(a[0], 1 as $i); + assert_eq!(a[1], 2 as $i); + } + )*) +} + +pass_array_marco! { + (pass_array_rust_i8, i8) + (pass_array_rust_u8, u8) + (pass_array_rust_i16, i16) + (pass_array_rust_u16, u16) + (pass_array_rust_i32, i32) + (pass_array_rust_u32, u32) + (pass_array_rust_isize, isize) + (pass_array_rust_usize, usize) + (pass_array_rust_f32, f32) + (pass_array_rust_f64, f64) +} + +#[wasm_bindgen_test] +fn pass_array() { + js_pass_array(); +} + +macro_rules! import_mut_macro { + ($(($rust:ident, $js:ident, $i:ident))*) => ( + $( + #[wasm_bindgen(module = "tests/wasm/slice.js")] + extern "C" { + fn $js(a: &mut [$i], b: Option<&mut [$i]>, c: Option<&mut [$i]>); + } + + fn $rust() { + let mut buf1 = [ + 1 as $i, + 2 as $i, + 3 as $i, + ]; + let mut buf2 = [ + 4 as $i, + 5 as $i, + 6 as $i, + ]; + $js(&mut buf1, Some(&mut buf2), None); + assert_eq!(buf1[0], 4 as $i); + assert_eq!(buf1[1], 5 as $i); + assert_eq!(buf1[2], 3 as $i); + assert_eq!(buf2[0], 8 as $i); + assert_eq!(buf2[1], 7 as $i); + assert_eq!(buf2[2], 6 as $i); + } + )* + + #[wasm_bindgen_test] + fn import_mut() { + $($rust();)* + } + ) +} + +import_mut_macro! { + (import_mut_rust_i8, import_mut_js_i8, i8) + (import_mut_rust_u8, import_mut_js_u8, u8) + (import_mut_rust_i16, import_mut_js_i16, i16) + (import_mut_rust_u16, import_mut_js_u16, u16) + (import_mut_rust_i32, import_mut_js_i32, i32) + (import_mut_rust_u32, import_mut_js_u32, u32) + (import_mut_rust_f32, import_mut_js_f32, f32) + (import_mut_rust_f64, import_mut_js_f64, f64) +} + +macro_rules! export_mut_macro { + ($(($i:ident, $n:ident))*) => ($( + #[wasm_bindgen] + pub fn $n(a: &mut [$i]) { + assert_eq!(a.len(), 3); + assert_eq!(a[0], 1 as $i); + assert_eq!(a[1], 2 as $i); + assert_eq!(a[2], 3 as $i); + a[0] = 4 as $i; + a[1] = 5 as $i; + } + )*) +} + +export_mut_macro! { + (i8, export_mut_i8) + (u8, export_mut_u8) + (i16, export_mut_i16) + (u16, export_mut_u16) + (i32, export_mut_i32) + (u32, export_mut_u32) + (isize, export_mut_isize) + (usize, export_mut_usize) + (f32, export_mut_f32) + (f64, export_mut_f64) +} + +#[wasm_bindgen_test] +fn export_mut() { + js_export_mut(); +} + +#[wasm_bindgen] +pub fn return_vec_broken_vec() -> Vec { + vec![1, 2, 3, 4, 5, 6, 7, 8, 9] +} + +#[wasm_bindgen] +pub fn return_vec_web_main() -> ReturnVecApplication { + ReturnVecApplication::new() +} + +#[wasm_bindgen] +pub struct ReturnVecApplication { + thing: Vec, +} + +#[wasm_bindgen] +impl ReturnVecApplication { + pub fn new() -> ReturnVecApplication { + let mut thing = vec![]; + thing.push(0); + thing.push(0); + thing.push(0); + thing.push(0); + thing.push(0); + + ReturnVecApplication { thing } + } + + pub fn tick(&mut self) { + self.thing = self.thing.clone(); + } +} + +#[wasm_bindgen_test] +fn return_vec() { + js_return_vec(); +} + +#[wasm_bindgen_test] +fn take_clamped() { + js_clamped(Clamped(&[1, 2, 3]), 1); + js_clamped2(Clamped(vec![4, 5, 6]), 4); + js_clamped3(Clamped(&mut [7, 8, 9]), 7); +} diff --git a/vendor/wasm-bindgen/tests/wasm/structural.js b/vendor/wasm-bindgen/tests/wasm/structural.js new file mode 100644 index 000000000..0261c50e1 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/structural.js @@ -0,0 +1,13 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +exports.js_works = () => { + let called = false; + wasm.run({ + bar() { + called = true; + }, + baz: 1, + }); + assert.strictEqual(called, true); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/structural.rs b/vendor/wasm-bindgen/tests/wasm/structural.rs new file mode 100644 index 000000000..5066156c6 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/structural.rs @@ -0,0 +1,32 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/structural.js")] +extern "C" { + fn js_works(); +} + +#[wasm_bindgen] +extern "C" { + pub type StructuralFoo; + + #[wasm_bindgen(method, structural)] + fn bar(this: &StructuralFoo); + #[wasm_bindgen(method, getter, structural)] + fn baz(this: &StructuralFoo) -> u32; + #[wasm_bindgen(method, setter, structural)] + fn set_baz(this: &StructuralFoo, val: u32); +} + +#[wasm_bindgen] +pub fn run(a: &StructuralFoo) { + a.bar(); + assert_eq!(a.baz(), 1); + a.set_baz(2); + assert_eq!(a.baz(), 2); +} + +#[wasm_bindgen_test] +fn works() { + js_works(); +} diff --git a/vendor/wasm-bindgen/tests/wasm/truthy_falsy.rs b/vendor/wasm-bindgen/tests/wasm/truthy_falsy.rs new file mode 100644 index 000000000..d04abb053 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/truthy_falsy.rs @@ -0,0 +1,28 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen_test] +fn test_is_truthy() { + assert_eq!(JsValue::from(0).is_truthy(), false); + assert_eq!(JsValue::from("".to_string()).is_truthy(), false); + assert_eq!(JsValue::from(false).is_truthy(), false); + assert_eq!(JsValue::NULL.is_truthy(), false); + assert_eq!(JsValue::UNDEFINED.is_truthy(), false); + + assert_eq!(JsValue::from(10).is_truthy(), true); + assert_eq!(JsValue::from("null".to_string()).is_truthy(), true); + assert_eq!(JsValue::from(true).is_truthy(), true); +} + +#[wasm_bindgen_test] +fn test_is_falsy() { + assert_eq!(JsValue::from(0).is_falsy(), true); + assert_eq!(JsValue::from("".to_string()).is_falsy(), true); + assert_eq!(JsValue::from(false).is_falsy(), true); + assert_eq!(JsValue::NULL.is_falsy(), true); + assert_eq!(JsValue::UNDEFINED.is_falsy(), true); + + assert_eq!(JsValue::from(10).is_falsy(), false); + assert_eq!(JsValue::from("null".to_string()).is_falsy(), false); + assert_eq!(JsValue::from(true).is_falsy(), false); +} diff --git a/vendor/wasm-bindgen/tests/wasm/usize.js b/vendor/wasm-bindgen/tests/wasm/usize.js new file mode 100644 index 000000000..a1e0723e8 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/usize.js @@ -0,0 +1,39 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +exports.isize_js_identity = a => a; +exports.usize_js_identity = a => a; + +exports.js_works = async () => { + assert.strictEqual(wasm.usize_zero(), 0); + assert.strictEqual(wasm.usize_one(), 1); + assert.strictEqual(wasm.isize_neg_one(), -1); + assert.strictEqual(wasm.isize_i32_min(), -2147483648); + assert.strictEqual(wasm.isize_min(), -2147483648); + assert.strictEqual(wasm.usize_u32_max(), 4294967295); + assert.strictEqual(wasm.usize_max(), 4294967295); + + assert.strictEqual(wasm.isize_rust_identity(0), 0); + assert.strictEqual(wasm.isize_rust_identity(1), 1); + assert.strictEqual(wasm.isize_rust_identity(-1), -1); + assert.strictEqual(wasm.usize_rust_identity(0), 0); + assert.strictEqual(wasm.usize_rust_identity(1), 1); + + const usize_max = 4294967295; + const isize_min = -2147483648; + assert.strictEqual(wasm.isize_rust_identity(isize_min), isize_min); + assert.strictEqual(wasm.usize_rust_identity(usize_max), usize_max); + + assert.deepStrictEqual(wasm.usize_slice([]), new Uint32Array()); + assert.deepStrictEqual(wasm.isize_slice([]), new Int32Array()); + const arr1 = new Uint32Array([1, 2]); + assert.deepStrictEqual(wasm.usize_slice([1, 2]), arr1); + const arr2 = new Int32Array([1, 2]); + assert.deepStrictEqual(wasm.isize_slice([1, 2]), arr2); + + assert.deepStrictEqual(wasm.isize_slice([isize_min]), new Int32Array([isize_min])); + assert.deepStrictEqual(wasm.usize_slice([usize_max]), new Uint32Array([usize_max])); + + assert.deepStrictEqual(await wasm.async_usize_one(), 1); + assert.deepStrictEqual(await wasm.async_isize_neg_one(), -1); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/usize.rs b/vendor/wasm-bindgen/tests/wasm/usize.rs new file mode 100644 index 000000000..80395d21e --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/usize.rs @@ -0,0 +1,79 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/usize.js")] +extern "C" { + fn isize_js_identity(a: isize) -> isize; + fn usize_js_identity(a: usize) -> usize; + fn js_works(); +} + +#[wasm_bindgen] +pub fn usize_zero() -> usize { + 0 +} + +#[wasm_bindgen] +pub fn usize_one() -> usize { + 1 +} + +#[wasm_bindgen] +pub fn isize_neg_one() -> isize { + -1 +} + +#[wasm_bindgen] +pub fn isize_i32_min() -> isize { + i32::min_value() as isize +} + +#[wasm_bindgen] +pub fn usize_u32_max() -> usize { + u32::max_value() as usize +} + +#[wasm_bindgen] +pub fn isize_min() -> isize { + isize::min_value() +} + +#[wasm_bindgen] +pub fn usize_max() -> usize { + usize::max_value() +} + +#[wasm_bindgen] +pub fn isize_rust_identity(a: isize) -> isize { + isize_js_identity(a) +} + +#[wasm_bindgen] +pub fn usize_rust_identity(a: usize) -> usize { + usize_js_identity(a) +} + +#[wasm_bindgen] +pub fn isize_slice(a: &[isize]) -> Vec { + a.to_vec() +} + +#[wasm_bindgen] +pub fn usize_slice(a: &[usize]) -> Vec { + a.to_vec() +} + +#[wasm_bindgen] +pub async fn async_usize_one() -> usize { + 1 +} + +#[wasm_bindgen] +pub async fn async_isize_neg_one() -> isize { + -1 +} + +#[wasm_bindgen_test] +fn works() { + js_works(); +} diff --git a/vendor/wasm-bindgen/tests/wasm/validate_prt.js b/vendor/wasm-bindgen/tests/wasm/validate_prt.js new file mode 100644 index 000000000..070d71dfa --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/validate_prt.js @@ -0,0 +1,43 @@ +const wasm = require('wasm-bindgen-test.js'); +const assert = require('assert'); + +// NB: `wasm-pack` uses the presence of checks for moved values as a way to test +// whether it is correctly enabling `--debug` when configured to do so, so don't +// change this expected debug output without also updating `wasm-pack`'s tests. +const assertMovedPtrThrows = process.env.WASM_BINDGEN_NO_DEBUG == null + ? f => assert.throws(f, /Attempt to use a moved value/) + : f => assert.throws(f, /null pointer passed to rust/); + +const useMoved = () => { + const apple = new wasm.Fruit('apple'); + apple.name(); + wasm.eat(apple); + assertMovedPtrThrows(() => apple.name()); +}; + +const moveMoved = () => { + const pear = new wasm.Fruit('pear'); + pear.name(); + wasm.eat(pear); + assertMovedPtrThrows(() => wasm.eat(pear)); +}; + +const methodMoved = () => { + const quince = new wasm.Fruit('quince'); + quince.name(); + quince.rot(); + assertMovedPtrThrows(() => quince.rot()); +}; + +exports.js_works = () => { + useMoved(); + moveMoved(); + methodMoved(); + + const a = new wasm.Fruit('a'); + a.prop; + assertMovedPtrThrows(() => a.prop); + const b = new wasm.Fruit('a'); + b.prop = 3; + assertMovedPtrThrows(() => { b.prop = 4; }); +}; diff --git a/vendor/wasm-bindgen/tests/wasm/validate_prt.rs b/vendor/wasm-bindgen/tests/wasm/validate_prt.rs new file mode 100644 index 000000000..84cbf1d95 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/validate_prt.rs @@ -0,0 +1,44 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/validate_prt.js")] +extern "C" { + fn js_works(); +} + +#[wasm_bindgen] +pub struct Fruit { + name: String, +} + +#[wasm_bindgen] +impl Fruit { + pub fn name(&self) -> String { + self.name.clone() + } + + #[wasm_bindgen(constructor)] + pub fn new(name: String) -> Self { + Fruit { name } + } + + pub fn rot(self) { + drop(self); + } + + #[wasm_bindgen(getter)] + pub fn prop(self) -> u32 { + 0 + } + + #[wasm_bindgen(setter)] + pub fn set_prop(self, _val: u32) {} +} + +#[wasm_bindgen] +pub fn eat(_: Fruit) {} + +#[wasm_bindgen_test] +fn works() { + js_works(); +} diff --git a/vendor/wasm-bindgen/tests/wasm/variadic.js b/vendor/wasm-bindgen/tests/wasm/variadic.js new file mode 100644 index 000000000..6094bc881 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/variadic.js @@ -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 u8; + #[wasm_bindgen(variadic)] + fn variadic_sum_u16(first: u16, second: u16, rest: &[u16]) -> u16; + #[wasm_bindgen(variadic)] + fn variadic_sum_u32(first: u32, second: u32, rest: &[u32]) -> u32; + #[wasm_bindgen(variadic)] + fn variadic_sum_u64(first: u64, second: u64, rest: &[u64]) -> u64; + //#[wasm_bindgen(variadic)] + //fn variadic_sum_usize(first: usize, second: usize, rest: &[usize]) -> usize; + #[wasm_bindgen(variadic)] + fn variadic_sum_i8(first: i8, second: i8, rest: &[i8]) -> i8; + #[wasm_bindgen(variadic)] + fn variadic_sum_i16(first: i16, second: i16, rest: &[i16]) -> i16; + #[wasm_bindgen(variadic)] + fn variadic_sum_i32(first: i32, second: i32, rest: &[i32]) -> i32; + #[wasm_bindgen(variadic)] + fn variadic_sum_i64(first: i64, second: i64, rest: &[i64]) -> i64; + //#[wasm_bindgen(variadic)] + //fn variadic_sum_isize(first: isize, second: isize, rest: &[isize]) -> isize; + #[wasm_bindgen(variadic)] + fn variadic_sum_f32(first: f32, second: f32, rest: &[f32]) -> f32; + #[wasm_bindgen(variadic)] + fn variadic_sum_f64(first: f64, second: f64, rest: &[f64]) -> f64; + //#[wasm_bindgen(variadic)] + //fn variadic_sum_opt(first: Option, second: Option, rest: &[Option]) -> u32; + //#[wasm_bindgen(variadic)] + //fn variadic_concat_str(first: &str, second: &str, rest: &[&str]) -> String; + //#[wasm_bindgen(variadic)] + //fn variadic_concat_string(first: String, + // second: String, + // rest: Vec) -> String; + #[wasm_bindgen(variadic)] + fn variadic_sum_rest_vec(first: u8, second: u8, rest: Vec) -> u8; + //#[wasm_bindgen(variadic)] + //fn variadic_compare_pairs(first: JsValue, second: JsValue, rest: &[JsValue]); + //TODO imported type +} + +// ints + +macro_rules! variadic_test_int { + ($fn_name:ident, $extern_name:ident) => { + #[wasm_bindgen_test] + fn $fn_name() { + assert_eq!($extern_name(1, 2, &[]), 3); + assert_eq!($extern_name(1, 2, &[3]), 6); + assert_eq!($extern_name(1, 2, &[3, 4]), 10); + } + }; +} + +// The 64 tests throw js `Cannot mix BigInt and other types, use explicit conversions` +variadic_test_int!(u8, variadic_sum_u8); +variadic_test_int!(u16, variadic_sum_u16); +variadic_test_int!(u32, variadic_sum_u32); +//variadic_test_int!(u64, variadic_sum_u64); +//variadic_test_int!(usize, variadic_sum_usize); +variadic_test_int!(i8, variadic_sum_i8); +variadic_test_int!(i16, variadic_sum_i16); +variadic_test_int!(i32, variadic_sum_i32); +//variadic_test_int!(i64, variadic_sum_i64); +//variadic_test_int!(isize, variadic_sum_isize); + +// floats + +macro_rules! variadic_test_float { + ($fn_name:ident, $extern_name:ident) => { + #[wasm_bindgen_test] + fn $fn_name() { + assert_eq!($extern_name(1., 2., &[]), 3.); + assert_eq!($extern_name(1., 2., &[3.]), 6.); + assert_eq!($extern_name(1., 2., &[3., 4.]), 10.); + } + }; +} + +variadic_test_float!(f32, variadic_sum_f32); +variadic_test_float!(f64, variadic_sum_f64); + +// strings + +// `the trait `wasm_bindgen::convert::IntoWasmAbi` is not implemented for `&[&str]` +/* +#[wasm_bindgen_test] +fn str() { + assert_eq!(variadic_concat_str("a ", "test", &[]), "a test"); + assert_eq!(variadic_concat_str("a", "nother ", &["test"]), "another test"); + assert_eq!(variadic_concat_str("yet ", "a", &["nother ", "test"]), "yet another test"); +} + +#[wasm_bindgen_test] +fn string() { + assert_eq!(variadic_concat_string("a ".into(), "test".into(), vec![]), "a test"); + assert_eq!(variadic_concat_string("a".into(), "nother ".into(), vec!["test".into()]), + "another test"); + assert_eq!(variadic_concat_string("yet ".into(), + "a".into(), + vec!["nother ".into(), "test".into()]), + "yet another test"); +} +*/ + +// options + +/* +#[wasm_bindgen_test] +fn opt() { + assert_eq!(variadic_sum_opt(Some(1), None, &[]), 1); + assert_eq!(variadic_sum_opt(Some(1), None, &[Some(2)]), 3); + assert_eq!(variadic_sum_opt(Some(1), None, &[None, Some(2)]), 3); +} +*/ + +// vec not slice + +#[wasm_bindgen_test] +fn rest_vec() { + assert_eq!(variadic_sum_rest_vec(1, 2, vec![]), 3); + assert_eq!(variadic_sum_rest_vec(1, 2, vec![3]), 6); + assert_eq!(variadic_sum_rest_vec(1, 2, vec![3, 4]), 10); +} + +// JsValue +//#[wasm_bindgen_test] +//fn jsvalue() { +// variadic_compare_pairs_jsvalue(true, true, vec![]); +// variadic_compare_pairs_jsvalue(false, false, vec![3, 3]); +//} diff --git a/vendor/wasm-bindgen/tests/wasm/vendor_prefix.js b/vendor/wasm-bindgen/tests/wasm/vendor_prefix.js new file mode 100644 index 000000000..a8cd4db15 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/vendor_prefix.js @@ -0,0 +1,11 @@ +exports.import_me = function() {}; + +global.webkitMySpecialApi = class { + foo() { return 123; } +}; +global.MySpecialApi2 = class { + foo() { return 124; } +}; +global.bMySpecialApi3 = class { + foo() { return 125; } +}; diff --git a/vendor/wasm-bindgen/tests/wasm/vendor_prefix.rs b/vendor/wasm-bindgen/tests/wasm/vendor_prefix.rs new file mode 100644 index 000000000..296271906 --- /dev/null +++ b/vendor/wasm-bindgen/tests/wasm/vendor_prefix.rs @@ -0,0 +1,48 @@ +use wasm_bindgen::prelude::*; +use wasm_bindgen_test::*; + +#[wasm_bindgen(module = "tests/wasm/vendor_prefix.js")] +extern "C" { + fn import_me(x: &str); +} + +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(vendor_prefix = webkit)] + type MySpecialApi; + #[wasm_bindgen(constructor)] + fn new() -> MySpecialApi; + #[wasm_bindgen(method)] + fn foo(this: &MySpecialApi) -> u32; + + #[wasm_bindgen(vendor_prefix = webkit)] + type MySpecialApi2; + #[wasm_bindgen(constructor)] + fn new() -> MySpecialApi2; + #[wasm_bindgen(method)] + fn foo(this: &MySpecialApi2) -> u32; + + #[wasm_bindgen(vendor_prefix = a, vendor_prefix = b)] + type MySpecialApi3; + #[wasm_bindgen(constructor)] + fn new() -> MySpecialApi3; + #[wasm_bindgen(method)] + fn foo(this: &MySpecialApi3) -> u32; + + // This API does not exist at all; + // test that Rust gets a chance to catch the error (#2437) + #[wasm_bindgen(vendor_prefix = a, vendor_prefix = b)] + type MyMissingApi; + #[wasm_bindgen(constructor, catch)] + fn new() -> Result; +} + +#[wasm_bindgen_test] +pub fn polyfill_works() { + import_me("foo"); + + assert_eq!(MySpecialApi::new().foo(), 123); + assert_eq!(MySpecialApi2::new().foo(), 124); + assert_eq!(MySpecialApi3::new().foo(), 125); + assert!(MyMissingApi::new().is_err()); +} -- cgit v1.2.3