Skip to content

Implement Clippy Aspect & Build Rule #339

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Jun 17, 2020
Merged
Show file tree
Hide file tree
Changes from 7 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
167 changes: 167 additions & 0 deletions rust/private/clippy.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
# Copyright 2020 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

load(
"@io_bazel_rules_rust//rust:private/rustc.bzl",
"CrateInfo",
"collect_deps",
"collect_inputs",
"construct_arguments",
"construct_compile_command",
)
load(
"@io_bazel_rules_rust//rust:private/rust.bzl",
"crate_root_src",
"get_edition"
)
load("@io_bazel_rules_rust//rust:private/utils.bzl", "find_toolchain")

_rust_extensions = [
"rs",
]

def _is_rust_target(srcs):
return any([src.extension in _rust_extensions for src in srcs])

def _all_sources(target, rule):
srcs = []
if "srcs" in dir(rule.attr):
srcs += [f for src in rule.attr.srcs for f in src.files.to_list()]
if "hdrs" in dir(rule.attr):
srcs += [f for src in rule.attr.hdrs for f in src.files.to_list()]
return srcs

def _rust_sources(target, rule):
srcs = _all_sources(target, rule)
srcs = [src for src in srcs if src.extension in _rust_extensions]
return srcs

def _clippy_aspect_impl(target, ctx):
if CrateInfo not in target:
return []
rust_srcs = _rust_sources(target, ctx.rule)
if rust_srcs == []:
return []

toolchain = find_toolchain(ctx)
crate_name = ctx.label.name.replace("-", "_")
crate_type = getattr(ctx.rule.attr, "crate_type") if hasattr(ctx.rule.attr, "crate_type") else "lib"
crate_info = CrateInfo(
name = crate_name,
type = crate_type,
root = crate_root_src(ctx, srcs = rust_srcs),
srcs = rust_srcs,
deps = ctx.rule.attr.deps,
proc_macro_deps = ctx.rule.attr.proc_macro_deps,
aliases = ctx.rule.attr.aliases,
output = None,
edition = get_edition(ctx.rule.attr, toolchain),
rustc_env = ctx.rule.attr.rustc_env,
)

dep_info, build_info = collect_deps(
ctx.label,
crate_info.deps,
crate_info.proc_macro_deps,
crate_info.aliases,
toolchain,
)

compile_inputs, out_dir = collect_inputs(
ctx,
toolchain,
crate_info,
dep_info,
build_info
)

args, env = construct_arguments(
ctx,
toolchain,
crate_info,
dep_info,
output_hash = None,
rust_flags = [])

# A marker file indicating clang tidy has executed successfully.
# This file is necessary because "ctx.actions.run" mandates an output.
clippy_marker = ctx.actions.declare_file(ctx.label.name + "_clippy.ok")

command = construct_compile_command(
ctx,
toolchain.clippy_driver.path,
toolchain,
crate_info,
build_info,
out_dir,
) + (" && touch %s" % clippy_marker.path)

# Deny the default-on clippy warning levels.
#
# If these are left as warnings, then Bazel will consider the execution
# result of the aspect to be "success", and Clippy won't be re-triggered
# unless the source file is modified.
args.add("-Dclippy::style")
args.add("-Dclippy::correctness");
args.add("-Dclippy::complexity");
args.add("-Dclippy::perf");

ctx.actions.run_shell(
command = command,
inputs = compile_inputs,
outputs = [clippy_marker],
env = env,
tools = [toolchain.clippy_driver],
arguments = [args],
mnemonic = "Clippy",
)

return [
OutputGroupInfo(clippy_checks = depset([clippy_marker])),
]

# Executes a "compile command" on all specified targets.
#
# Example: Run the clang-tidy checker on all targets in the codebase.
# bazel build --aspects=@rules_rust//rust:clippy.bzl%rust_clippy_aspect \
# --output_groups=clippy_checks \
# //...
rust_clippy_aspect = aspect(
attr_aspects = ["deps"],
fragments = ["cpp"],
host_fragments = ["cpp"],
attrs = {
"_cc_toolchain": attr.label(
default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
),
},
toolchains = [
"@io_bazel_rules_rust//rust:toolchain",
"@bazel_tools//tools/cpp:toolchain_type"
],
implementation = _clippy_aspect_impl,
)

def _rust_clippy_rule_impl(ctx):
checks = depset([])
for dep in ctx.attr.deps:
checks = depset(dep[OutputGroupInfo].clippy_checks.to_list(), transitive = checks.to_list())
return [DefaultInfo(files = checks)]

rust_clippy = rule(
implementation = _rust_clippy_rule_impl,
attrs = {
'deps': attr.label_list(aspects = [rust_clippy_aspect]),
},
)
37 changes: 20 additions & 17 deletions rust/private/rust.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -71,22 +71,25 @@ def _determine_lib_name(name, crate_type, toolchain, lib_hash = ""):
extension = extension,
)

def _get_edition(ctx, toolchain):
if getattr(ctx.attr, "edition"):
return ctx.attr.edition
def get_edition(attr, toolchain):
if getattr(attr, "edition"):
return attr.edition
else:
return toolchain.default_edition

def _crate_root_src(ctx, file_name = "lib.rs"):
def crate_root_src(ctx, srcs, file_name = "lib.rs"):
"""Finds the source file for the crate root."""
srcs = ctx.files.srcs

crate_root = (
ctx.file.crate_root or
(srcs[0] if len(srcs) == 1 else None) or
_shortest_src_with_basename(srcs, file_name) or
_shortest_src_with_basename(srcs, ctx.attr.name + ".rs")
)
crate_root = None
if hasattr(ctx.file, "crate_root"):
crate_root = ctx.file.crate_root

if not crate_root:
crate_root = (
(srcs[0] if len(srcs) == 1 else None) or
_shortest_src_with_basename(srcs, file_name) or
_shortest_src_with_basename(srcs, ctx.attr.name + ".rs")
)
if not crate_root:
file_names = [file_name, ctx.attr.name + ".rs"]
fail("No {} source file found.".format(" or ".join(file_names)), "srcs")
Expand All @@ -105,7 +108,7 @@ def _shortest_src_with_basename(srcs, basename):

def _rust_library_impl(ctx):
# Find lib.rs
lib_rs = _crate_root_src(ctx)
lib_rs = crate_root_src(ctx, ctx.files.srcs)

toolchain = find_toolchain(ctx)

Expand Down Expand Up @@ -133,7 +136,7 @@ def _rust_library_impl(ctx):
proc_macro_deps = ctx.attr.proc_macro_deps,
aliases = ctx.attr.aliases,
output = rust_lib,
edition = _get_edition(ctx, toolchain),
edition = get_edition(ctx.attr, toolchain),
rustc_env = ctx.attr.rustc_env,
),
output_hash = output_hash,
Expand All @@ -156,13 +159,13 @@ def _rust_binary_impl(ctx):
crate_info = CrateInfo(
name = crate_name,
type = crate_type,
root = _crate_root_src(ctx, "main.rs"),
root = crate_root_src(ctx, ctx.files.srcs, file_name = "main.rs"),
srcs = ctx.files.srcs,
deps = ctx.attr.deps,
proc_macro_deps = ctx.attr.proc_macro_deps,
aliases = ctx.attr.aliases,
output = output,
edition = _get_edition(ctx, toolchain),
edition = get_edition(ctx.attr, toolchain),
rustc_env = ctx.attr.rustc_env,
),
)
Expand Down Expand Up @@ -205,13 +208,13 @@ def _rust_test_common(ctx, test_binary):
target = CrateInfo(
name = test_binary.basename,
type = "lib",
root = _crate_root_src(ctx),
root = crate_root_src(ctx, ctx.files.srcs),
srcs = ctx.files.srcs,
deps = ctx.attr.deps,
proc_macro_deps = ctx.attr.proc_macro_deps,
aliases = ctx.attr.aliases,
output = test_binary,
edition = _get_edition(ctx, toolchain),
edition = get_edition(ctx.attr, toolchain),
rustc_env = ctx.attr.rustc_env,
)

Expand Down
28 changes: 16 additions & 12 deletions rust/private/rustc.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ def _add_out_dir_to_compile_inputs(
compile_inputs = depset([out_dir], transitive = [compile_inputs])
return compile_inputs, out_dir

def _collect_inputs(
def collect_inputs(
ctx,
toolchain,
crate_info,
Expand Down Expand Up @@ -272,14 +272,14 @@ def _collect_inputs(
)
return _add_out_dir_to_compile_inputs(ctx, build_info, compile_inputs)

def _construct_arguments(
def construct_arguments(
ctx,
toolchain,
crate_info,
dep_info,
output_hash,
rust_flags):
output_dir = crate_info.output.dirname
output_dir = getattr(crate_info.output, "dirname") if hasattr(crate_info.output, "dirname") else None

linker_script = getattr(ctx.file, "linker_script") if hasattr(ctx.file, "linker_script") else None

Expand All @@ -293,7 +293,8 @@ def _construct_arguments(
# Mangle symbols to disambiguate crates with the same name
extra_filename = "-" + output_hash if output_hash else ""
args.add("--codegen=metadata=" + extra_filename)
args.add("--out-dir=" + output_dir)
if output_dir:
args.add("--out-dir=" + output_dir)
args.add("--codegen=extra-filename=" + extra_filename)

compilation_mode = _get_compilation_mode_opts(ctx, toolchain)
Expand All @@ -310,7 +311,6 @@ def _construct_arguments(

# Gets the paths to the folders containing the standard library (or libcore)
rust_lib_paths = depset([file.dirname for file in toolchain.rust_lib.files.to_list()]).to_list()

# Tell Rustc where to find the standard library
args.add_all(rust_lib_paths, before_each = "-L", format_each = "%s")

Expand Down Expand Up @@ -374,9 +374,13 @@ def _create_command_env(ctx, out_dir):
package_dir = ctx.build_file_path[:ctx.build_file_path.rfind("/")]
manifest_dir_env = "CARGO_MANIFEST_DIR=$(pwd)/{} ".format(package_dir)

return out_dir_env + manifest_dir_env
# This empty value satisfies Clippy, which otherwise complains about the
# sysroot being undefined.
sysroot_env= "SYSROOT= "

return out_dir_env + manifest_dir_env + sysroot_env

def _construct_compile_command(
def construct_compile_command(
ctx,
command,
toolchain,
Expand All @@ -396,7 +400,7 @@ def _construct_compile_command(
# not the _ version. So we rename the rustc-generated file (with _s) to
# have -s if needed.
maybe_rename = ""
if crate_info.type == "bin":
if crate_info.type == "bin" and crate_info.output != None:
generated_file = crate_info.name
if toolchain.target_arch == "wasm32":
generated_file = generated_file + ".wasm"
Expand All @@ -408,7 +412,7 @@ def _construct_compile_command(
return '{}{}{} "$@" --remap-path-prefix="$(pwd)"=__bazel_redacted_pwd{}{}'.format(
rustc_env_expansion,
command_env,
toolchain.rustc.path,
command,
build_flags_expansion,
maybe_rename,
)
Expand Down Expand Up @@ -436,15 +440,15 @@ def rustc_compile_action(
toolchain,
)

compile_inputs, out_dir = _collect_inputs(
compile_inputs, out_dir = collect_inputs(
ctx,
toolchain,
crate_info,
dep_info,
build_info
)

args, env = _construct_arguments(
args, env = construct_arguments(
ctx,
toolchain,
crate_info,
Expand All @@ -453,7 +457,7 @@ def rustc_compile_action(
rust_flags
)

command = _construct_compile_command(
command = construct_compile_command(
ctx,
toolchain.rustc.path,
toolchain,
Expand Down
13 changes: 12 additions & 1 deletion rust/rust.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ load(
"@io_bazel_rules_rust//rust:private/rustdoc_test.bzl",
_rust_doc_test = "rust_doc_test",
)
load(
"@io_bazel_rules_rust//rust:private/clippy.bzl",
_rust_clippy_aspect = "rust_clippy_aspect",
_rust_clippy = "rust_clippy",
)

rust_library = _rust_library
""" See @io_bazel_rules_rust//rust:private/rust.bzl for a complete description. """
Expand All @@ -48,4 +53,10 @@ rust_doc = _rust_doc
""" See @io_bazel_rules_rust//rust:private/rustdoc.bzl for a complete description. """

rust_doc_test = _rust_doc_test
""" See @io_bazel_rules_rust//rust:private/rustdoc.bzl for a complete description. """
""" See @io_bazel_rules_rust//rust:private/rustdoc_test.bzl for a complete description. """

rust_clippy_aspect = _rust_clippy_aspect
""" See @io_bazel_rules_rust//rust:private/clippy.bzl for a complete description. """

rust_clippy = _rust_clippy
""" See @io_bazel_rules_rust//rust:private/clippy.bzl for a complete description. """
Loading