fork/rules_rust

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

UebelAndreAllow rust_wasm_bindgen rules to re-expose rust-analyzer providers (#3035)13746789

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