fork/rules_rust

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

UebelAndreMoved rust extension rules into a separate `rules_rust_ext` workspace. (#3007)2bad96d9

cleanup
7.4 KiB216 linesraw
1"""Bazel rules for [wasm-bindgen](https://crates.io/crates/wasm-bindgen)"""
2
3load("@rules_rust//rust:defs.bzl", "rust_common")
4load("//:providers.bzl", "RustWasmBindgenInfo")
5load(":transitions.bzl", "wasm_bindgen_transition")
6
7def rust_wasm_bindgen_action(ctx, toolchain, wasm_file, target_output, bindgen_flags = []):
8    """Spawn a `RustWasmBindgen` action.
9
10    Args:
11        ctx (ctx): _description_
12        toolchain (ToolchainInfo): _description_
13        wasm_file (Target): _description_
14        target_output (str): _description_
15        bindgen_flags (list, optional): _description_. Defaults to [].
16
17    Returns:
18        RustWasmBindgenInfo: _description_
19    """
20    bindgen_bin = toolchain.bindgen
21
22    # Since the `wasm_file` attribute is behind a transition, it will be converted
23    # to a list.
24    if len(wasm_file) == 1:
25        if rust_common.crate_info in wasm_file[0]:
26            target = wasm_file[0]
27            crate_info = target[rust_common.crate_info]
28
29            # Provide a helpful warning informing users how to use the rule
30            if rust_common.crate_info in target:
31                supported_types = ["cdylib", "bin"]
32                if crate_info.type not in supported_types:
33                    fail("The target '{}' is not a supported type: {}".format(
34                        ctx.attr.crate.label,
35                        supported_types,
36                    ))
37
38            progress_message_label = target.label
39            input_file = crate_info.output
40        else:
41            wasm_files = wasm_file[0][DefaultInfo].files.to_list()
42            if len(wasm_files) != 1:
43                fail("Unexpected number of wasm files: {}".format(wasm_files))
44
45            progress_message_label = wasm_files[0].path
46            input_file = wasm_files[0]
47    else:
48        fail("wasm_file is expected to be a transitioned label attr on `{}`. Got `{}`".format(
49            ctx.label,
50            wasm_file,
51        ))
52
53    bindgen_wasm_module = ctx.actions.declare_file(ctx.label.name + "_bg.wasm")
54
55    js_out = [ctx.actions.declare_file(ctx.label.name + ".js")]
56    ts_out = []
57    if not "--no-typescript" in bindgen_flags:
58        ts_out.append(ctx.actions.declare_file(ctx.label.name + ".d.ts"))
59
60    if target_output == "bundler":
61        js_out.append(ctx.actions.declare_file(ctx.label.name + "_bg.js"))
62        if not "--no-typescript" in bindgen_flags:
63            ts_out.append(ctx.actions.declare_file(ctx.label.name + "_bg.wasm.d.ts"))
64
65    outputs = [bindgen_wasm_module] + js_out + ts_out
66
67    args = ctx.actions.args()
68    args.add("--target", target_output)
69    args.add("--out-dir", bindgen_wasm_module.dirname)
70    args.add("--out-name", ctx.label.name)
71    args.add_all(bindgen_flags)
72    args.add(input_file)
73
74    ctx.actions.run(
75        executable = bindgen_bin,
76        inputs = [input_file],
77        outputs = outputs,
78        mnemonic = "RustWasmBindgen",
79        progress_message = "Generating WebAssembly bindings for {}...".format(progress_message_label),
80        arguments = [args],
81        toolchain = str(Label("//:toolchain_type")),
82    )
83
84    return RustWasmBindgenInfo(
85        wasm = bindgen_wasm_module,
86        js = depset(js_out),
87        ts = depset(ts_out),
88    )
89
90def _rust_wasm_bindgen_impl(ctx):
91    toolchain = ctx.toolchains[Label("//:toolchain_type")]
92
93    info = rust_wasm_bindgen_action(
94        ctx = ctx,
95        toolchain = toolchain,
96        wasm_file = ctx.attr.wasm_file,
97        target_output = ctx.attr.target,
98        bindgen_flags = ctx.attr.bindgen_flags,
99    )
100
101    return [
102        DefaultInfo(
103            files = depset([info.wasm], transitive = [info.js, info.ts]),
104        ),
105        info,
106    ]
107
108WASM_BINDGEN_ATTR = {
109    "bindgen_flags": attr.string_list(
110        doc = "Flags to pass directly to the bindgen executable. See https://github.com/rustwasm/wasm-bindgen/ for details.",
111    ),
112    "target": attr.string(
113        doc = "The type of output to generate. See https://rustwasm.github.io/wasm-bindgen/reference/deployment.html for details.",
114        default = "bundler",
115        values = ["web", "bundler", "nodejs", "no-modules", "deno"],
116    ),
117    "target_arch": attr.string(
118        doc = "The target architecture to use for the wasm-bindgen command line option.",
119        default = "wasm32",
120        values = ["wasm32", "wasm64"],
121    ),
122    "wasm_file": attr.label(
123        doc = "The `.wasm` file or crate to generate bindings for.",
124        allow_single_file = True,
125        cfg = wasm_bindgen_transition,
126        mandatory = True,
127    ),
128    "_allowlist_function_transition": attr.label(
129        default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
130    ),
131}
132
133rust_wasm_bindgen = rule(
134    implementation = _rust_wasm_bindgen_impl,
135    doc = """\
136Generates javascript and typescript bindings for a webassembly module using [wasm-bindgen][ws].
137
138[ws]: https://rustwasm.github.io/docs/wasm-bindgen/
139
140An example of this rule in use can be seen at [@rules_rust//examples/wasm](../examples/wasm)
141""",
142    attrs = {
143        "bindgen_flags": attr.string_list(
144            doc = "Flags to pass directly to the bindgen executable. See https://github.com/rustwasm/wasm-bindgen/ for details.",
145        ),
146        "target": attr.string(
147            doc = "The type of output to generate. See https://rustwasm.github.io/wasm-bindgen/reference/deployment.html for details.",
148            default = "bundler",
149            values = ["web", "bundler", "nodejs", "no-modules", "deno"],
150        ),
151        "target_arch": attr.string(
152            doc = "The target architecture to use for the wasm-bindgen command line option.",
153            default = "wasm32",
154            values = ["wasm32", "wasm64"],
155        ),
156        "wasm_file": attr.label(
157            doc = "The `.wasm` file or crate to generate bindings for.",
158            allow_single_file = True,
159            cfg = wasm_bindgen_transition,
160            mandatory = True,
161        ),
162        "_allowlist_function_transition": attr.label(
163            default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
164        ),
165    },
166    toolchains = [
167        str(Label("//:toolchain_type")),
168    ],
169)
170
171def _rust_wasm_bindgen_toolchain_impl(ctx):
172    return platform_common.ToolchainInfo(
173        bindgen = ctx.executable.bindgen,
174    )
175
176rust_wasm_bindgen_toolchain = rule(
177    implementation = _rust_wasm_bindgen_toolchain_impl,
178    doc = """\
179The tools required for the `rust_wasm_bindgen` rule.
180
181In cases where users want to control or change the version of `wasm-bindgen` used by [rust_wasm_bindgen](#rust_wasm_bindgen),
182a unique toolchain can be created as in the example below:
183
184```python
185load("@rules_rust_bindgen//:defs.bzl", "rust_bindgen_toolchain")
186
187rust_bindgen_toolchain(
188    bindgen = "//3rdparty/crates:wasm_bindgen_cli__bin",
189)
190
191toolchain(
192    name = "wasm_bindgen_toolchain",
193    toolchain = "wasm_bindgen_toolchain_impl",
194    toolchain_type = "@rules_rust_wasm_bindgen//:toolchain_type",
195)
196```
197
198Now that you have your own toolchain, you need to register it by
199inserting the following statement in your `WORKSPACE` file:
200
201```python
202register_toolchains("//my/toolchains:wasm_bindgen_toolchain")
203```
204
205For additional information, see the [Bazel toolchains documentation][toolchains].
206
207[toolchains]: https://docs.bazel.build/versions/master/toolchains.html
208""",
209    attrs = {
210        "bindgen": attr.label(
211            doc = "The label of a `wasm-bindgen-cli` executable.",
212            executable = True,
213            cfg = "exec",
214        ),
215    },
216)