diff --git a/mojo/mojo_library.bzl b/mojo/mojo_library.bzl index d19b56c..c9b6764 100644 --- a/mojo/mojo_library.bzl +++ b/mojo/mojo_library.bzl @@ -5,7 +5,7 @@ load("@bazel_skylib//lib:paths.bzl", "paths") load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//mojo:providers.bzl", "MojoInfo") -load("//mojo/private:utils.bzl", "MOJO_EXTENSIONS", "collect_mojoinfo", "format_import", "handle_copt", "is_exec_config") +load("//mojo/private:utils.bzl", "MOJO_EXTENSIONS", "collect_mojoinfo", "format_import", "handle_copt", "env_shim_attrs", "is_exec_config", "shim_args") def _format_include(arg): return ["-I", arg.dirname] @@ -86,18 +86,18 @@ def _mojo_library_implementation(ctx): file_args.add_all(import_paths, map_each = format_import) file_args.add_all([ctx.files.srcs[0]], map_each = _format_root) ctx.actions.run( - executable = mojo_toolchain.mojo, + executable = ctx.executable._env_shim, inputs = depset(ctx.files.srcs + ctx.files.additional_compiler_inputs, transitive = [transitive_mojodeps]), tools = mojo_toolchain.precompile_tools, outputs = precompile_outputs, - arguments = [args, file_args], + arguments = [shim_args(ctx, mojo_toolchain.mojo, mojo_toolchain.preprocessed_precompile_env), args, file_args], mnemonic = "MojoPrecompile", progress_message = "%{label} precompiling mojo file", env = { "MODULAR_CRASH_REPORTING_ENABLED": "false", "PATH": "/dev/null", # Avoid using the host's PATH "TEST_TMPDIR": ".", # Make sure any cache files are written to somewhere bazel will cleanup - } | mojo_toolchain.build_env, + }, use_default_shell_env = True, toolchain = "//:toolchain_type", execution_requirements = { @@ -186,6 +186,6 @@ Note: If anything other than ".", implies a `-namespace`. "_export_fixits": attr.label( default = Label("@rules_mojo//:experimental_export_fixits"), ), - }, + } | env_shim_attrs(), toolchains = ["//:toolchain_type"], ) diff --git a/mojo/private/BUILD.bazel b/mojo/private/BUILD.bazel index e69de29..70b2e96 100644 --- a/mojo/private/BUILD.bazel +++ b/mojo/private/BUILD.bazel @@ -0,0 +1,4 @@ +exports_files( + ["env_shim.sh"], + visibility = ["//visibility:public"], +) diff --git a/mojo/private/env_shim.sh b/mojo/private/env_shim.sh new file mode 100755 index 0000000..1a13681 --- /dev/null +++ b/mojo/private/env_shim.sh @@ -0,0 +1,36 @@ +#!/bin/sh +# Runs a command with some environment variables set. +# +# Bazel doesn't path map the values of an action's `env`, but it does path map +# command line arguments. So instead of passing environment variables to the +# action, they are passed as arguments to this shim, which exports them and then +# execs the real command. +# +# Usage: env_shim.sh [--env=NAME=VALUE]... -- command [args...] +# +# NOTE: This only uses shell builtins, since the PATH is generally not available. +set -eu + +while [ "$#" -gt 0 ]; do + case "$1" in + --env=*) + export "${1#--env=}" + shift + ;; + --) + shift + break + ;; + *) + echo "env_shim.sh: unexpected argument: $1" >&2 + exit 1 + ;; + esac +done + +if [ "$#" -eq 0 ]; then + echo "env_shim.sh: no command given" >&2 + exit 1 +fi + +exec "$@" diff --git a/mojo/private/mojo_binary_test.bzl b/mojo/private/mojo_binary_test.bzl index 06bba5c..90419d7 100644 --- a/mojo/private/mojo_binary_test.bzl +++ b/mojo/private/mojo_binary_test.bzl @@ -9,7 +9,7 @@ load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("@rules_python//python:py_info.bzl", "PyInfo") load("//mojo:providers.bzl", "MojoInfo") load(":transitions.bzl", "python_version_transition") -load(":utils.bzl", "MOJO_EXTENSIONS", "collect_mojoinfo", "format_import", "handle_copt", "is_exec_config") +load(":utils.bzl", "MOJO_EXTENSIONS", "collect_mojoinfo", "env_shim_attrs", "format_import", "handle_copt", "is_exec_config", "resolve_env", "shim_args") _PYTHON_TOOLCHAIN_TYPE = "@rules_python//python:toolchain_type" _ATTRS = { @@ -55,7 +55,7 @@ by bazel. "_export_fixits": attr.label( default = Label("@rules_mojo//:experimental_export_fixits"), ), -} +} | env_shim_attrs("mojo_compile") _TOOLCHAINS = use_cpp_toolchain() + [ _PYTHON_TOOLCHAIN_TYPE, @@ -143,11 +143,11 @@ def _mojo_binary_test_implementation(ctx, *, shared_library = False): args.add("--experimental-export-fixit", fixits_file) ctx.actions.run( - executable = mojo_toolchain.mojo, + executable = ctx.executable._env_shim, tools = mojo_toolchain.build_tools, inputs = depset(ctx.files.srcs + ctx.files.additional_compiler_inputs, transitive = [transitive_mojodeps]), outputs = compile_outputs, - arguments = [args], + arguments = [shim_args(ctx, mojo_toolchain.mojo, mojo_toolchain.preprocessed_build_env), args], mnemonic = "MojoCompile", progress_message = "%{label} compiling mojo object", env = { @@ -157,7 +157,7 @@ def _mojo_binary_test_implementation(ctx, *, shared_library = False): "MODULAR_MOJO_MAX_LLD_PATH": "/dev/null", # Make sure this fails if accessed "PATH": "/dev/null", # Avoid using the host's PATH "TEST_TMPDIR": ".", - } | mojo_toolchain.build_env, + }, use_default_shell_env = True, exec_group = "mojo_compile", toolchain = "//:toolchain_type", @@ -255,7 +255,7 @@ def _mojo_binary_test_implementation(ctx, *, shared_library = False): "PYTHONPATH": python_path, "PYTHONSAFEPATH": "affirmative", } - runtime_env.update(mojo_toolchain.runtime_env) + runtime_env.update(resolve_env(mojo_toolchain.preprocessed_runtime_env, is_runtime = True)) for key, value in runtime_env.items(): runtime_env[key] = ctx.expand_make_variables( "env", diff --git a/mojo/private/utils.bzl b/mojo/private/utils.bzl index 4db6f73..f95ac21 100644 --- a/mojo/private/utils.bzl +++ b/mojo/private/utils.bzl @@ -79,40 +79,6 @@ def _package_relative_label(ctx, label): label = "@" + label return Label(label) -def _extract_label(ctx, copt): - # type: (ctx, string) -> tuple[string, Label] - """Split a copt into a format string and a label. - - Take something like `--foo=$(location :bar)` and get `:bar` as a label - This is a minimum working version, there are likely cases that don't work, - but there are currently no uses for those extra cases. - """ - - start = -1 - labelstart = -1 - labelend = -1 - end = -1 - - # Not sure if we should even support all of these. - for var in ["execpath", "rootpath", "rlocationpath", "location"]: - start = copt.find("$(" + var) - if start != -1: - # Add the "$(" and a space at the end - labelstart = start + 2 + len(var) + 1 - break - if start == -1: - fail("expected one of $(execpath), $(rootpath), $(rlocationpath), or $(location)") - end = start + copt[start:].find(")") - if end == -1: - fail("expected closing )") - labelend = end - label_string = copt[labelstart:labelend] - format_string = copt[:start] + "%s" + copt[end + 1:] - - label = _package_relative_label(ctx, label_string) - - return format_string, label - def _labels_similar(label1, label2): """Without the full repo mapping, determine if two labels are close enough to count them as equal. @@ -126,6 +92,18 @@ def _labels_similar(label1, label2): return False return True +def _find_file(label, targets): + # type: (Label, list[Target]) -> File + """Finds a label in a list of targets. Asserts that it exists and maps to exactly one file.""" + for target in targets: + if label != target.label and not _labels_similar(label, target.label): + continue + files = target.files.to_list() + if len(files) != 1: + fail("expected {} to expand to exactly one file, got {}".format(label, len(files))) + return files[0] + fail("unable to map {} to an input".format(label)) + def handle_copt(ctx, copt, args): # type: (ctx, string, Args) -> None """Handles make variable expansion in copts @@ -138,16 +116,134 @@ def handle_copt(ctx, copt, args): copt: the copt args: Args object to add to """ - if "$(" in copt: - format_string, label = _extract_label(ctx, copt) - for input in ctx.attr.additional_compiler_inputs: - if label != input.label and not _labels_similar(label, input.label): - continue - files = input.files.to_list() - if len(files) != 1: - fail("expected exactly one file") - args.add(files[0], format = format_string) - return - fail("input {} not found in additional_compiler_inputs".format(label)) - else: - args.add(copt) + args.add_joined( + parse_value(ctx, copt, ctx.attr.additional_compiler_inputs), + join_with = "", + map_each = _arg_piece_to_string, # Formatting Files here is what lets Bazel path map them + omit_if_empty = False, + ) + +_LOCATION_VARS = ["execpath", "rootpath", "rlocationpath", "location"] + +def parse_value(ctx, value, targets): + # type: (ctx, string, list[Target]) -> list[string | File] + """Parses a string without expanding paths. + + ctx.expand_location can't be used for this since it doesn't support path + mapping, so $(location), $(execpath), $(rootpath) and $(rlocationpath) are + instead turned into File references, which are expanded by Args once the + action is being constructed. + + `a$(location :b)c$(location :d)` becomes `["a", , "c", ]`. + + Args: + ctx: The rule context, used to resolve labels. + value: A string that may contain any number of $(location