fork/rules_rust

git clone https://git.julia.blue/fork/rules_rust

UebelAndreUpdated wasm_bindgen rules to only require core `rules_nodejs` rules (#1311)fb4d5546

0.8.1
6.5 KiB191 linesraw
1# Copyright 2019 The Bazel Authors. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#    http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15# buildifier: disable=module-docstring
16load("//rust:defs.bzl", "rust_common")
17
18# buildifier: disable=bzl-visibility
19load("//rust/private:transitions.bzl", "wasm_bindgen_transition")
20load(
21    "//wasm_bindgen:providers.bzl",
22    "DeclarationInfo",
23    "JSModuleInfo",
24)
25
26_WASM_BINDGEN_DOC = """\
27Generates javascript and typescript bindings for a webassembly module using [wasm-bindgen][ws].
28
29[ws]: https://rustwasm.github.io/docs/wasm-bindgen/
30
31To use the Rust WebAssembly bindgen rules, add the following to your `WORKSPACE` file to add the
32external repositories for the Rust bindgen toolchain (in addition to the Rust rules setup):
33
34```python
35load("@rules_rust//wasm_bindgen:repositories.bzl", "rust_wasm_bindgen_repositories")
36
37rust_wasm_bindgen_repositories()
38```
39
40For more details on `rust_wasm_bindgen_repositories`, see [here](#rust_wasm_bindgen_repositories).
41
42An example of this rule in use can be seen at [@rules_rust//examples/wasm](../examples/wasm)
43"""
44
45_WASM_BINDGEN_TOOLCHAIN_DOC = """\
46The tools required for the `rust_wasm_bindgen` rule.
47
48In cases where users want to control or change the version of `wasm-bindgen` used by [rust_wasm_bindgen](#rust_wasm_bindgen),
49a unique toolchain can be created as in the example below:
50
51```python
52load("@rules_rust//bindgen:bindgen.bzl", "rust_bindgen_toolchain")
53
54rust_bindgen_toolchain(
55    bindgen = "//my/cargo_raze:cargo_bin_wasm_bindgen",
56)
57
58toolchain(
59    name = "wasm_bindgen_toolchain",
60    toolchain = "wasm_bindgen_toolchain_impl",
61    toolchain_type = "@rules_rust//wasm_bindgen:wasm_bindgen_toolchain",
62)
63```
64
65Now that you have your own toolchain, you need to register it by
66inserting the following statement in your `WORKSPACE` file:
67
68```python
69register_toolchains("//my/toolchains:wasm_bindgen_toolchain")
70```
71
72For additional information, see the [Bazel toolchains documentation][toolchains].
73
74[toolchains]: https://docs.bazel.build/versions/master/toolchains.html
75"""
76
77def _rust_wasm_bindgen_impl(ctx):
78    toolchain = ctx.toolchains[Label("//wasm_bindgen:wasm_bindgen_toolchain")]
79    bindgen_bin = toolchain.bindgen
80
81    # Since the `wasm_file` attribute is behind a transition, it will be converted
82    # to a list.
83    if len(ctx.attr.wasm_file) == 1 and rust_common.crate_info in ctx.attr.wasm_file[0]:
84        target = ctx.attr.wasm_file[0]
85        crate_info = target[rust_common.crate_info]
86
87        # Provide a helpful warning informing users how to use the rule
88        if rust_common.crate_info in target:
89            supported_types = ["cdylib", "bin"]
90            if crate_info.type not in supported_types:
91                fail("The target '{}' is not a supported type: {}".format(
92                    ctx.attr.crate.label,
93                    supported_types,
94                ))
95
96        progress_message_label = target.label
97        input_file = crate_info.output
98    else:
99        progress_message_label = ctx.file.wasm_file.path
100        input_file = ctx.file.wasm_file
101
102    bindgen_wasm_module = ctx.actions.declare_file(ctx.attr.name + "_bg.wasm")
103
104    js_out = [ctx.actions.declare_file(ctx.attr.name + ".js")]
105    ts_out = [ctx.actions.declare_file(ctx.attr.name + ".d.ts")]
106
107    if ctx.attr.target == "bundler":
108        js_out.append(ctx.actions.declare_file(ctx.attr.name + "_bg.js"))
109        ts_out.append(ctx.actions.declare_file(ctx.attr.name + "_bg.wasm.d.ts"))
110
111    outputs = [bindgen_wasm_module] + js_out + ts_out
112
113    args = ctx.actions.args()
114    args.add("--target", ctx.attr.target)
115    args.add("--out-dir", bindgen_wasm_module.dirname)
116    args.add("--out-name", ctx.attr.name)
117    args.add_all(ctx.attr.bindgen_flags)
118    args.add(input_file)
119
120    ctx.actions.run(
121        executable = bindgen_bin,
122        inputs = [input_file],
123        outputs = outputs,
124        mnemonic = "RustWasmBindgen",
125        progress_message = "Generating WebAssembly bindings for {}...".format(progress_message_label),
126        arguments = [args],
127    )
128
129    # Return a structure that is compatible with the deps[] of a ts_library.
130    declarations = depset(ts_out)
131    es5_sources = depset(js_out)
132
133    return [
134        DefaultInfo(
135            files = depset(outputs),
136        ),
137        DeclarationInfo(
138            declarations = declarations,
139            transitive_declarations = declarations,
140            type_blocklisted_declarations = depset([]),
141        ),
142        JSModuleInfo(
143            direct_sources = es5_sources,
144            sources = es5_sources,
145        ),
146    ]
147
148rust_wasm_bindgen = rule(
149    implementation = _rust_wasm_bindgen_impl,
150    doc = _WASM_BINDGEN_DOC,
151    attrs = {
152        "bindgen_flags": attr.string_list(
153            doc = "Flags to pass directly to the bindgen executable. See https://github.com/rustwasm/wasm-bindgen/ for details.",
154        ),
155        "target": attr.string(
156            doc = "The type of output to generate. See https://rustwasm.github.io/wasm-bindgen/reference/deployment.html for details.",
157            default = "bundler",
158            values = ["web", "bundler", "nodejs", "no-modules", "deno"],
159        ),
160        "wasm_file": attr.label(
161            doc = "The `.wasm` file or crate to generate bindings for.",
162            allow_single_file = True,
163            cfg = wasm_bindgen_transition,
164            mandatory = True,
165        ),
166        "_allowlist_function_transition": attr.label(
167            default = Label("//tools/allowlists/function_transition_allowlist"),
168        ),
169    },
170    toolchains = [
171        str(Label("//wasm_bindgen:wasm_bindgen_toolchain")),
172    ],
173    incompatible_use_toolchain_transition = True,
174)
175
176def _rust_wasm_bindgen_toolchain_impl(ctx):
177    return platform_common.ToolchainInfo(
178        bindgen = ctx.executable.bindgen,
179    )
180
181rust_wasm_bindgen_toolchain = rule(
182    implementation = _rust_wasm_bindgen_toolchain_impl,
183    doc = _WASM_BINDGEN_TOOLCHAIN_DOC,
184    attrs = {
185        "bindgen": attr.label(
186            doc = "The label of a `wasm-bindgen-cli` executable.",
187            executable = True,
188            cfg = "exec",
189        ),
190    },
191)