fork/rules_rust

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

UebelAndreMade `cargo_build_script` `streams` output group optional. (#2976)034f2cc8

cleanup
25.5 KiB678 linesraw
1"""Rules for Cargo build scripts (`build.rs` files)"""
2
3load("@bazel_skylib//lib:paths.bzl", "paths")
4load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo")
5load("@bazel_tools//tools/cpp:toolchain_utils.bzl", "find_cpp_toolchain")
6load("@rules_cc//cc:action_names.bzl", "ACTION_NAMES")
7load("//rust:defs.bzl", "rust_common")
8load("//rust:rust_common.bzl", "BuildInfo")
9
10# buildifier: disable=bzl-visibility
11load(
12    "//rust/private:rustc.bzl",
13    "get_compilation_mode_opts",
14    "get_linker_and_args",
15)
16
17# buildifier: disable=bzl-visibility
18load(
19    "//rust/private:utils.bzl",
20    "dedent",
21    "expand_dict_value_locations",
22    "find_cc_toolchain",
23    "find_toolchain",
24    _name_to_crate_name = "name_to_crate_name",
25)
26
27# Reexport for cargo_build_script_wrapper.bzl
28name_to_crate_name = _name_to_crate_name
29
30CargoBuildScriptRunfilesInfo = provider(
31    doc = "Info about a `cargo_build_script.script` target.",
32    fields = {
33        "data": "List[Target]: The raw `cargo_build_script_runfiles.data` attribute.",
34        "tools": "List[Target]: The raw `cargo_build_script_runfiles.tools` attribute.",
35    },
36)
37
38def _cargo_build_script_runfiles_impl(ctx):
39    script = ctx.executable.script
40
41    is_windows = script.extension == "exe"
42    exe = ctx.actions.declare_file("{}{}".format(ctx.label.name, ".exe" if is_windows else ""))
43
44    # Avoid the following issue on Windows when using builds-without-the-bytes.
45    # https://github.com/bazelbuild/bazel/issues/21747
46    if is_windows:
47        args = ctx.actions.args()
48        args.add(script)
49        args.add(exe)
50
51        ctx.actions.run(
52            executable = ctx.executable._copy_file,
53            arguments = [args],
54            inputs = [script],
55            outputs = [exe],
56        )
57    else:
58        ctx.actions.symlink(
59            output = exe,
60            target_file = script,
61            is_executable = True,
62        )
63
64    # Tools are ommitted here because they should be within the `script`
65    # attribute's runfiles.
66    runfiles = ctx.runfiles(files = ctx.files.data)
67
68    return [
69        DefaultInfo(
70            files = depset([exe]),
71            runfiles = runfiles.merge(ctx.attr.script[DefaultInfo].default_runfiles),
72            executable = exe,
73        ),
74        CargoBuildScriptRunfilesInfo(
75            data = ctx.attr.data,
76            tools = ctx.attr.tools,
77        ),
78    ]
79
80cargo_build_script_runfiles = rule(
81    doc = """\
82A rule for producing `cargo_build_script.script` with proper runfiles.
83
84This rule ensure's the executable for `cargo_build_script` has properly formed runfiles with `cfg=target` and
85`cfg=exec` files. This is a challenge becuase had the script binary been directly consumed, it would have been
86in either configuration which would have been incorrect for either the `tools` (exec) or `data` (target) attributes.
87This is solved here by consuming the script as exec and creating a symlink to consumers of this rule can consume
88with `cfg=target` and still get an exec compatible binary.
89
90This rule may not be necessary if it becomes possible to construct runfiles trees within a rule for an action as
91we'd be able to build the correct runfiles tree and configure the script runner to run the script in the new runfiles
92directory:
93https://github.com/bazelbuild/bazel/issues/15486
94""",
95    implementation = _cargo_build_script_runfiles_impl,
96    attrs = {
97        "data": attr.label_list(
98            doc = "Data required by the build script.",
99            allow_files = True,
100        ),
101        "script": attr.label(
102            doc = "The binary script to run, generally a `rust_binary` target.",
103            executable = True,
104            mandatory = True,
105            providers = [rust_common.crate_info],
106            cfg = "exec",
107        ),
108        "tools": attr.label_list(
109            doc = "Tools required by the build script.",
110            allow_files = True,
111            cfg = "exec",
112        ),
113        "_copy_file": attr.label(
114            cfg = "exec",
115            executable = True,
116            default = Label("//cargo/private:copy_file"),
117        ),
118    },
119    executable = True,
120)
121
122def get_cc_compile_args_and_env(cc_toolchain, feature_configuration):
123    """Gather cc environment variables from the given `cc_toolchain`
124
125    Args:
126        cc_toolchain (cc_toolchain): The current rule's `cc_toolchain`.
127        feature_configuration (FeatureConfiguration): Class used to construct command lines from CROSSTOOL features.
128
129    Returns:
130        tuple: A tuple of the following items:
131            - (sequence): A flattened C command line flags for given action.
132            - (sequence): A flattened CXX command line flags for given action.
133            - (dict): C environment variables to be set for given action.
134    """
135    compile_variables = cc_common.create_compile_variables(
136        feature_configuration = feature_configuration,
137        cc_toolchain = cc_toolchain,
138    )
139    cc_c_args = cc_common.get_memory_inefficient_command_line(
140        feature_configuration = feature_configuration,
141        action_name = ACTION_NAMES.c_compile,
142        variables = compile_variables,
143    )
144    cc_cxx_args = cc_common.get_memory_inefficient_command_line(
145        feature_configuration = feature_configuration,
146        action_name = ACTION_NAMES.cpp_compile,
147        variables = compile_variables,
148    )
149    cc_env = cc_common.get_environment_variables(
150        feature_configuration = feature_configuration,
151        action_name = ACTION_NAMES.c_compile,
152        variables = compile_variables,
153    )
154    return cc_c_args, cc_cxx_args, cc_env
155
156def _pwd_flags_sysroot(args):
157    """Prefix execroot-relative paths of known arguments with ${pwd}.
158
159    Args:
160        args (list): List of tool arguments.
161
162    Returns:
163        list: The modified argument list.
164    """
165    res = []
166    for arg in args:
167        s, opt, path = arg.partition("--sysroot=")
168        if s == "" and not paths.is_absolute(path):
169            res.append("{}${{pwd}}/{}".format(opt, path))
170        else:
171            res.append(arg)
172    return res
173
174def _pwd_flags_isystem(args):
175    """Prefix execroot-relative paths of known arguments with ${pwd}.
176
177    Args:
178        args (list): List of tool arguments.
179
180    Returns:
181        list: The modified argument list.
182    """
183    res = []
184    fix_next_arg = False
185    for arg in args:
186        if fix_next_arg and not paths.is_absolute(arg):
187            res.append("${{pwd}}/{}".format(arg))
188        else:
189            res.append(arg)
190
191        fix_next_arg = arg == "-isystem"
192
193    return res
194
195def _pwd_flags_fsanitize_ignorelist(args):
196    """Prefix execroot-relative paths of known arguments with ${pwd}.
197
198    Args:
199        args (list): List of tool arguments.
200
201    Returns:
202        list: The modified argument list.
203    """
204    res = []
205    for arg in args:
206        s, opt, path = arg.partition("-fsanitize-ignorelist=")
207        if s == "" and not paths.is_absolute(path):
208            res.append("{}${{pwd}}/{}".format(opt, path))
209        else:
210            res.append(arg)
211    return res
212
213def _pwd_flags(args):
214    return _pwd_flags_fsanitize_ignorelist(_pwd_flags_isystem(_pwd_flags_sysroot(args)))
215
216def _feature_enabled(ctx, feature_name, default = False):
217    """Check if a feature is enabled.
218
219    If the feature is explicitly enabled or disabled, return accordingly.
220
221    In the case where the feature is not explicitly enabled or disabled, return the default value.
222
223    Args:
224        ctx: The context object.
225        feature_name: The name of the feature.
226        default: The default value to return if the feature is not explicitly enabled or disabled.
227
228    Returns:
229        Boolean defining whether the feature is enabled.
230    """
231    if feature_name in ctx.disabled_features:
232        return False
233
234    if feature_name in ctx.features:
235        return True
236
237    return default
238
239def _rlocationpath(file, workspace_name):
240    if file.short_path.startswith("../"):
241        return file.short_path[len("../"):]
242
243    return "{}/{}".format(workspace_name, file.short_path)
244
245def _create_runfiles_dir(ctx, script, retain_list):
246    """Create a runfiles directory to represent `CARGO_MANIFEST_DIR`.
247
248    Due to the inability to forcibly generate runfiles directories for use as inputs
249    to actions, this function creates a custom runfiles directory that can more
250    consistently be relied upon as an input. For more details see:
251    https://github.com/bazelbuild/bazel/issues/15486
252
253    If runfiles directories can ever be more directly treated as an input this function
254    can be retired.
255
256    Args:
257        ctx (ctx): The rule's context object
258        script (Target): The `cargo_build_script.script` target.
259        retain_list (list): A list of strings to keep in generated runfiles directories.
260
261    Returns:
262        Tuple[File, Depset[File], Args]:
263            - The output directory to be created.
264            - Runfile inputs needed by the action.
265            - The args required to create the directory.
266    """
267    runfiles_dir = ctx.actions.declare_directory("{}.cargo_runfiles".format(ctx.label.name))
268
269    # External repos always fall into the `../` branch of `_rlocationpath`.
270    workspace_name = ctx.workspace_name
271
272    def _runfiles_map(file):
273        return "{}={}".format(file.path, _rlocationpath(file, workspace_name))
274
275    runfiles = script[DefaultInfo].default_runfiles
276
277    args = ctx.actions.args()
278    args.use_param_file("--cargo_manifest_args=@%s", use_always = True)
279    args.add(runfiles_dir.path)
280    args.add(",".join(retain_list))
281    args.add_all(runfiles.files, map_each = _runfiles_map, allow_closure = True)
282
283    return runfiles_dir, runfiles.files, args
284
285def _cargo_build_script_impl(ctx):
286    """The implementation for the `cargo_build_script` rule.
287
288    Args:
289        ctx (ctx): The rules context object
290
291    Returns:
292        list: A list containing a BuildInfo provider
293    """
294    script = ctx.executable.script
295    script_info = ctx.attr.script[CargoBuildScriptRunfilesInfo]
296    toolchain = find_toolchain(ctx)
297    out_dir = ctx.actions.declare_directory(ctx.label.name + ".out_dir")
298    env_out = ctx.actions.declare_file(ctx.label.name + ".env")
299    dep_env_out = ctx.actions.declare_file(ctx.label.name + ".depenv")
300    flags_out = ctx.actions.declare_file(ctx.label.name + ".flags")
301    link_flags = ctx.actions.declare_file(ctx.label.name + ".linkflags")
302    link_search_paths = ctx.actions.declare_file(ctx.label.name + ".linksearchpaths")  # rustc-link-search, propagated from transitive dependencies
303    compilation_mode_opt_level = get_compilation_mode_opts(ctx, toolchain).opt_level
304
305    script_tools = []
306    script_data = []
307    for target in script_info.data:
308        script_data.append(target[DefaultInfo].files)
309        script_data.append(target[DefaultInfo].default_runfiles.files)
310    for target in script_info.tools:
311        script_tools.append(target[DefaultInfo].files)
312        script_tools.append(target[DefaultInfo].default_runfiles.files)
313
314    workspace_name = ctx.label.workspace_name
315    if not workspace_name:
316        workspace_name = ctx.workspace_name
317
318    extra_args = []
319    extra_inputs = []
320    extra_output = []
321
322    # Relying on runfiles directories is unreliable when passing data to
323    # dependent actions. Instead, an explicit directory should be created
324    # until more reliable functionality is implemented in Bazel:
325    # https://github.com/bazelbuild/bazel/issues/15486
326    incompatible_runfiles_cargo_manifest_dir = ctx.attr._incompatible_runfiles_cargo_manifest_dir[BuildSettingInfo].value
327    if not incompatible_runfiles_cargo_manifest_dir:
328        script_data.append(ctx.attr.script[DefaultInfo].default_runfiles.files)
329        manifest_dir = "{}.runfiles/{}/{}".format(script.path, workspace_name, ctx.label.package)
330    else:
331        runfiles_dir, runfiles_inputs, runfiles_args = _create_runfiles_dir(
332            ctx = ctx,
333            script = ctx.attr.script,
334            retain_list = ctx.attr._cargo_manifest_dir_filename_suffixes_to_retain[BuildSettingInfo].value,
335        )
336        manifest_dir = "{}/{}/{}".format(runfiles_dir.path, workspace_name, ctx.label.package)
337        extra_args.append(runfiles_args)
338        extra_inputs.append(runfiles_inputs)
339        extra_output = [runfiles_dir]
340
341    pkg_name = ctx.attr.pkg_name
342    if pkg_name == "":
343        pkg_name = name_to_pkg_name(ctx.label.name)
344
345    toolchain_tools = [toolchain.all_files]
346
347    cc_toolchain = find_cpp_toolchain(ctx)
348
349    # Start with the default shell env, which contains any --action_env
350    # settings passed in on the command line.
351    env = dict(ctx.configuration.default_shell_env)
352
353    env.update({
354        "CARGO_CRATE_NAME": name_to_crate_name(pkg_name),
355        "CARGO_MANIFEST_DIR": manifest_dir,
356        "CARGO_PKG_NAME": pkg_name,
357        "HOST": toolchain.exec_triple.str,
358        "NUM_JOBS": "1",
359        "OPT_LEVEL": compilation_mode_opt_level,
360        "RUSTC": toolchain.rustc.path,
361        "TARGET": toolchain.target_flag_value,
362        # OUT_DIR is set by the runner itself, rather than on the action.
363    })
364
365    # This isn't exactly right, but Bazel doesn't have exact views of "debug" and "release", so...
366    env.update({
367        "DEBUG": {"dbg": "true", "fastbuild": "true", "opt": "false"}.get(ctx.var["COMPILATION_MODE"], "true"),
368        "PROFILE": {"dbg": "debug", "fastbuild": "debug", "opt": "release"}.get(ctx.var["COMPILATION_MODE"], "unknown"),
369    })
370
371    if ctx.attr.version:
372        version = ctx.attr.version.split("+")[0].split(".")
373        patch = version[2].split("-") if len(version) > 2 else [""]
374        env["CARGO_PKG_VERSION_MAJOR"] = version[0]
375        env["CARGO_PKG_VERSION_MINOR"] = version[1] if len(version) > 1 else ""
376        env["CARGO_PKG_VERSION_PATCH"] = patch[0]
377        env["CARGO_PKG_VERSION_PRE"] = patch[1] if len(patch) > 1 else ""
378        env["CARGO_PKG_VERSION"] = ctx.attr.version
379
380    # Pull in env vars which may be required for the cc_toolchain to work (e.g. on OSX, the SDK version).
381    # We hope that the linker env is sufficient for the whole cc_toolchain.
382    cc_toolchain, feature_configuration = find_cc_toolchain(ctx)
383    linker, link_args, linker_env = get_linker_and_args(ctx, "bin", cc_toolchain, feature_configuration, None)
384    env.update(**linker_env)
385    env["LD"] = linker
386    env["LDFLAGS"] = " ".join(_pwd_flags(link_args))
387
388    # MSVC requires INCLUDE to be set
389    cc_c_args, cc_cxx_args, cc_env = get_cc_compile_args_and_env(cc_toolchain, feature_configuration)
390    include = cc_env.get("INCLUDE")
391    if include:
392        env["INCLUDE"] = include
393
394    if cc_toolchain:
395        toolchain_tools.append(cc_toolchain.all_files)
396
397        env["CC"] = cc_common.get_tool_for_action(
398            feature_configuration = feature_configuration,
399            action_name = ACTION_NAMES.c_compile,
400        )
401        env["CXX"] = cc_common.get_tool_for_action(
402            feature_configuration = feature_configuration,
403            action_name = ACTION_NAMES.cpp_compile,
404        )
405        env["AR"] = cc_common.get_tool_for_action(
406            feature_configuration = feature_configuration,
407            action_name = ACTION_NAMES.cpp_link_static_library,
408        )
409
410        # Populate CFLAGS and CXXFLAGS that cc-rs relies on when building from source, in particular
411        # to determine the deployment target when building for apple platforms (`macosx-version-min`
412        # for example, itself derived from the `macos_minimum_os` Bazel argument).
413        env["CFLAGS"] = " ".join(_pwd_flags(cc_c_args))
414        env["CXXFLAGS"] = " ".join(_pwd_flags(cc_cxx_args))
415
416    # Inform build scripts of rustc flags
417    # https://github.com/rust-lang/cargo/issues/9600
418    env["CARGO_ENCODED_RUSTFLAGS"] = "\\x1f".join([
419        # Allow build scripts to locate the generated sysroot
420        "--sysroot=${{pwd}}/{}".format(toolchain.sysroot),
421    ] + ctx.attr.rustc_flags)
422
423    for f in ctx.attr.crate_features:
424        env["CARGO_FEATURE_" + f.upper().replace("-", "_")] = "1"
425
426    links = ctx.attr.links or ""
427    if links:
428        env["CARGO_MANIFEST_LINKS"] = links
429
430    # Add environment variables from the Rust toolchain.
431    env.update(toolchain.env)
432
433    known_variables = {}
434
435    # Gather data from the `toolchains` attribute.
436    for target in ctx.attr.toolchains:
437        if DefaultInfo in target:
438            toolchain_tools.extend([
439                target[DefaultInfo].files,
440                target[DefaultInfo].default_runfiles.files,
441            ])
442        if platform_common.ToolchainInfo in target:
443            all_files = getattr(target[platform_common.ToolchainInfo], "all_files", depset([]))
444            if type(all_files) == "list":
445                all_files = depset(all_files)
446            toolchain_tools.append(all_files)
447        if platform_common.TemplateVariableInfo in target:
448            variables = getattr(target[platform_common.TemplateVariableInfo], "variables", depset([]))
449            known_variables.update(variables)
450
451    _merge_env_dict(env, expand_dict_value_locations(
452        ctx,
453        ctx.attr.build_script_env,
454        getattr(ctx.attr, "data", []) +
455        getattr(ctx.attr, "compile_data", []) +
456        getattr(ctx.attr, "tools", []) +
457        script_info.data +
458        script_info.tools,
459        known_variables,
460    ))
461
462    tools = depset(
463        direct = [
464            script,
465            ctx.executable._cargo_build_script_runner,
466        ] + ([toolchain.target_json] if toolchain.target_json else []),
467        transitive = script_data + script_tools + toolchain_tools,
468    )
469
470    # dep_env_file contains additional environment variables coming from
471    # direct dependency sys-crates' build scripts. These need to be made
472    # available to the current crate build script.
473    # See https://doc.rust-lang.org/cargo/reference/build-scripts.html#-sys-packages
474    # for details.
475    args = ctx.actions.args()
476    args.add(script, format = "--script=%s")
477    args.add(links, format = "--links=%s")
478    args.add(out_dir.path, format = "--out_dir=%s")
479    args.add(env_out, format = "--env_out=%s")
480    args.add(flags_out, format = "--flags_out=%s")
481    args.add(link_flags, format = "--link_flags=%s")
482    args.add(link_search_paths, format = "--link_search_paths=%s")
483    args.add(dep_env_out, format = "--dep_env_out=%s")
484    args.add(ctx.attr.rundir, format = "--rundir=%s")
485
486    output_groups = {
487        "out_dir": depset([out_dir]),
488    }
489
490    debug_std_streams_output_group = ctx.attr._debug_std_streams_output_group[BuildSettingInfo].value
491    if debug_std_streams_output_group:
492        debug_stdout = ctx.actions.declare_file(ctx.label.name + ".stdout.log")
493        debug_stderr = ctx.actions.declare_file(ctx.label.name + ".stderr.log")
494        args.add(debug_stdout, format = "--stdout=%s")
495        args.add(debug_stderr, format = "--stderr=%s")
496        extra_output.append(debug_stdout)
497        extra_output.append(debug_stderr)
498        output_groups["streams"] = depset([debug_stdout, debug_stderr])
499
500    build_script_inputs = []
501
502    for dep in ctx.attr.link_deps:
503        if rust_common.dep_info in dep and dep[rust_common.dep_info].dep_env:
504            dep_env_file = dep[rust_common.dep_info].dep_env
505            args.add(dep_env_file.path, format = "--input_dep_env_path=%s")
506            build_script_inputs.append(dep_env_file)
507            for dep_build_info in dep[rust_common.dep_info].transitive_build_infos.to_list():
508                build_script_inputs.append(dep_build_info.out_dir)
509
510    for dep in ctx.attr.deps:
511        for dep_build_info in dep[rust_common.dep_info].transitive_build_infos.to_list():
512            build_script_inputs.append(dep_build_info.out_dir)
513
514    experimental_symlink_execroot = ctx.attr._experimental_symlink_execroot[BuildSettingInfo].value or \
515                                    _feature_enabled(ctx, "symlink-exec-root")
516
517    if experimental_symlink_execroot:
518        env["RULES_RUST_SYMLINK_EXEC_ROOT"] = "1"
519
520    ctx.actions.run(
521        executable = ctx.executable._cargo_build_script_runner,
522        arguments = [args] + extra_args,
523        outputs = [
524            out_dir,
525            env_out,
526            flags_out,
527            link_flags,
528            link_search_paths,
529            dep_env_out,
530        ] + extra_output,
531        tools = tools,
532        inputs = depset(build_script_inputs, transitive = extra_inputs),
533        mnemonic = "CargoBuildScriptRun",
534        progress_message = "Running Cargo build script {}".format(pkg_name),
535        env = env,
536        toolchain = None,
537        # Set use_default_shell_env so that $PATH is set, as tools like Cmake
538        # may want to probe $PATH for helper tools.
539        use_default_shell_env = True,
540    )
541
542    return [
543        # Although this isn't used anywhere, without this, `bazel build`'ing
544        # the cargo_build_script label won't actually run the build script
545        # since bazel is lazy.
546        DefaultInfo(files = depset([out_dir])),
547        BuildInfo(
548            out_dir = out_dir,
549            rustc_env = env_out,
550            dep_env = dep_env_out,
551            flags = flags_out,
552            linker_flags = link_flags,
553            link_search_paths = link_search_paths,
554            compile_data = depset(extra_output, transitive = script_data),
555        ),
556        OutputGroupInfo(
557            **output_groups
558        ),
559    ]
560
561cargo_build_script = rule(
562    doc = (
563        "A rule for running a crate's `build.rs` files to generate build information " +
564        "which is then used to determine how to compile said crate."
565    ),
566    implementation = _cargo_build_script_impl,
567    attrs = {
568        "build_script_env": attr.string_dict(
569            doc = "Environment variables for build scripts.",
570        ),
571        "crate_features": attr.string_list(
572            doc = "The list of rust features that the build script should consider activated.",
573        ),
574        "deps": attr.label_list(
575            doc = "The Rust build-dependencies of the crate",
576            providers = [rust_common.dep_info],
577            cfg = "exec",
578        ),
579        "link_deps": attr.label_list(
580            doc = dedent("""\
581                The subset of the Rust (normal) dependencies of the crate that
582                have the links attribute and therefore provide environment
583                variables to this build script.
584            """),
585            providers = [rust_common.dep_info],
586        ),
587        "links": attr.string(
588            doc = "The name of the native library this crate links against.",
589        ),
590        "pkg_name": attr.string(
591            doc = "The name of package being compiled, if not derived from `name`.",
592        ),
593        "rundir": attr.string(
594            default = "",
595            doc = dedent("""\
596                A directory to cd to before the cargo_build_script is run.
597
598                This should be a pathrelative to the exec root. The default behaviour (and the
599                behaviour if rundir is set to the empty string) is to change to the relative
600                path corresponding to the cargo manifest directory, which replicates the
601                normal behaviour of cargo so it is easy to write compatible build scripts.
602
603                If set to `.`, the cargo build script will run in the exec root.
604            """),
605        ),
606        "rustc_flags": attr.string_list(
607            doc = dedent("""\
608                List of compiler flags passed to `rustc`.
609
610                These strings are subject to Make variable expansion for predefined
611                source/output path variables like `$location`, `$execpath`, and
612                `$rootpath`. This expansion is useful if you wish to pass a generated
613                file of arguments to rustc: `@$(location //package:target)`.
614            """),
615        ),
616        "script": attr.label(
617            doc = "The binary script to run, generally a `rust_binary` target.",
618            executable = True,
619            mandatory = True,
620            cfg = "target",
621            providers = [CargoBuildScriptRunfilesInfo],
622        ),
623        "tools": attr.label_list(
624            doc = "Tools required by the build script.",
625            allow_files = True,
626            cfg = "exec",
627        ),
628        "version": attr.string(
629            doc = "The semantic version (semver) of the crate",
630        ),
631        "_cargo_build_script_runner": attr.label(
632            executable = True,
633            allow_files = True,
634            default = Label("//cargo/cargo_build_script_runner:cargo_build_script_runner"),
635            cfg = "exec",
636        ),
637        "_cargo_manifest_dir_filename_suffixes_to_retain": attr.label(
638            default = Label("//cargo/settings:cargo_manifest_dir_filename_suffixes_to_retain"),
639        ),
640        "_cc_toolchain": attr.label(
641            default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
642        ),
643        "_debug_std_streams_output_group": attr.label(
644            default = Label("//cargo/settings:debug_std_streams_output_group"),
645        ),
646        "_experimental_symlink_execroot": attr.label(
647            default = Label("//cargo/settings:experimental_symlink_execroot"),
648        ),
649        "_incompatible_runfiles_cargo_manifest_dir": attr.label(
650            default = Label("//cargo/settings:incompatible_runfiles_cargo_manifest_dir"),
651        ),
652    },
653    fragments = ["cpp"],
654    toolchains = [
655        str(Label("//rust:toolchain_type")),
656        "@bazel_tools//tools/cpp:toolchain_type",
657    ],
658)
659
660def _merge_env_dict(prefix_dict, suffix_dict):
661    """Merges suffix_dict into prefix_dict, appending rather than replacing certain env vars."""
662    for key in ["CFLAGS", "CXXFLAGS", "LDFLAGS"]:
663        if key in prefix_dict and key in suffix_dict and prefix_dict[key]:
664            prefix_dict[key] += " " + suffix_dict.pop(key)
665    prefix_dict.update(suffix_dict)
666
667def name_to_pkg_name(name):
668    """Sanitize the name of cargo_build_script targets.
669
670    Args:
671        name (str): The name value pass to the `cargo_build_script` wrapper.
672
673    Returns:
674        str: A cleaned up name for a build script target.
675    """
676    if name.endswith("_bs"):
677        return name[:-len("_bs")]
678    return name