fork/rules_rust

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

UebelAndreVarious cleanups (#1828)9adfdca9

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