Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions mojo/mojo_library.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -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"],
)
4 changes: 4 additions & 0 deletions mojo/private/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
exports_files(
["env_shim.sh"],
visibility = ["//visibility:public"],
)
36 changes: 36 additions & 0 deletions mojo/private/env_shim.sh
Original file line number Diff line number Diff line change
@@ -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 "$@"
12 changes: 6 additions & 6 deletions mojo/private/mojo_binary_test.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 = {
Expand All @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
190 changes: 143 additions & 47 deletions mojo/private/utils.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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
Expand All @@ -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,
Comment thread
Ahajha marked this conversation as resolved.
Resolved
)

_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", <File b>, "c", <File d>]`.

Args:
ctx: The rule context, used to resolve labels.
value: A string that may contain any number of $(location <label>) style
references, each expanding to exactly one file.
targets: Targets that labels in value may refer to.

Returns:
A list of pieces, each of which is either a literal string or a File.
The value is the concatenation of all pieces.
"""
pieces = []
rest = value
for _ in range(len(value) + 1):
start = rest.find("$(")
if start == -1:
break
end = rest.find(")", start)
if end == -1:
fail("expected closing ) in {}".format(value))
variable, _, label = rest[start + 2:end].partition(" ")
if variable not in _LOCATION_VARS:
fail("unsupported variable $({}) in {}, expected one of {}".format(variable, value, _LOCATION_VARS))
if rest[:start]:
pieces.append(rest[:start])
pieces.append(_find_file(_package_relative_label(ctx, label.strip()), targets))
rest = rest[end + 1:]
if rest:
pieces.append(rest)
return pieces

def parse_env(ctx, env, targets):
# type: (ctx, dict[string, string], list[Target]) -> dict[string, list[string | File]]
"""Applies parse_value to each value of an env dict."""
return {key: parse_value(ctx, value, targets) for key, value in env.items()}

def _piece_to_string(piece, is_runtime = False):
# type: (string | File, bool) -> string
if type(piece) == "string":
return piece
return piece.short_path if is_runtime else piece.path

def _arg_piece_to_string(piece):
# NOTE: Not _piece_to_string directly, since Args passes extra arguments to map_each functions that accept them.
return _piece_to_string(piece)

def resolve_env(env, is_runtime = False):
# type: (dict[string, list[string | File]], bool) -> dict[string, string]
"""Turns the output of parse_env into plain strings.

NOTE: This does not support path mapping, the paths are always the unmapped
ones. Only use for envs that can't be path mapped.

Args:
env: Output of parse_env.
is_runtime: Whether the paths are for runtime, in which case all
file references are runfiles-relative.

Returns:
Dict of str -> str.
"""
return {
key: "".join([_piece_to_string(piece, is_runtime) if type(piece) == "File" else piece for piece in pieces])
for key, pieces in env.items()
}

def shim_args(ctx, mojo, env):
# type: (ctx, File, dict[string, list[string | File]]) -> Args
"""Creates the args that make env_shim.sh run mojo with the given env.

The result should be passed first in `arguments`, with env_shim.sh as the
action's executable.

Args:
ctx: The rule context.
mojo: The real mojo executable.
env: Output of parse_env, to set when running mojo.

Returns:
An Args object.
"""
args = ctx.actions.args()
for key, pieces in sorted(env.items()):
# Only the (escaped) variable name goes in the format string.
args.add_joined(
pieces,
join_with = "",
map_each = _arg_piece_to_string, # Formatting Files here is what lets Bazel path map them
format_joined = "--env=" + key.replace("%", "%%") + "=%s", # Only the (escaped) name goes in the format string
omit_if_empty = False,
)
args.add("--")
args.add(mojo)
return args

def env_shim_attrs(exec_group = None):
"""Private attributes a rule needs to run mojo through the env shim.

Args:
exec_group: The exec group the shim runs in, or None for the default one.

Returns:
Dict of attributes to merge into the rule's attrs.
"""
return {
"_env_shim": attr.label(
default = Label("//mojo/private:env_shim.sh"),
allow_single_file = True,
executable = True,
cfg = config.exec(exec_group) if exec_group else "exec",
),
}
3 changes: 3 additions & 0 deletions mojo/providers.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,17 @@ MojoToolchainInfo = provider(
fields = {
"copts": "Additional compiler options to pass to the Mojo compiler.",
"build_env": "Dict of environment variables to set during compilation. Additive on precompile_env.",
"preprocessed_build_env": "Like build_env, but as a `dict[string, list[string | File]]` of pieces whose concatenation is the value. Useful for manual path mapping.",
"build_tools": "Extra files to make available to the compiler during compilation. Additive on precompile_tools.",
"precompile_copts": "Additional compiler options to pass to the Mojo compiler when running 'mojo precompile'.",
"precompile_env": "Dict of environment variables to set during precompilation.",
"preprocessed_precompile_env": "Like precompile_env, but as a `dict[string, list[string | File]]` of pieces whose concatenation is the value. Useful for manual path mapping.",
"precompile_tools": "Extra files to make available to the compiler during precompilation.",
"lld": "The lld compiler executable to link with",
"mojo": "The mojo compiler executable to build with",
"implicit_deps": "Implicit dependencies that every target should depend on, providing either CcInfo, or MojoInfo",
"runtime_env": "Dict of environment variables to set during runtime.",
"preprocessed_runtime_env": "Like runtime_env, but as a `dict[string, list[string | File]]` of pieces whose concatenation is the value. Useful for manual path mapping.",
"extra_runfiles": "Extra files to make available during runtime.",
},
)
Expand Down
Loading
Loading