fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
30e68b49
0.7.0
1# Copyright 2020 The Bazel Authors. All rights reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""A module defining clippy rules""" 16 17load ( "//rust/private:common.bzl" , "rust_common" ) 18load ( "//rust/private:providers.bzl" , "CaptureClippyOutputInfo" , "ClippyInfo" ) 19load ( 20"//rust/private:rustc.bzl" , 21"collect_deps" , 22"collect_inputs" , 23"construct_arguments" , 24) 25load ( 26"//rust/private:utils.bzl" , 27"determine_output_hash" , 28"find_cc_toolchain" , 29"find_toolchain" , 30) 31 32ClippyFlagsInfo = provider ( 33doc = "Pass each value as an additional flag to clippy invocations" , 34fields = { "clippy_flags" : "List[string] Flags to pass to clippy" }, 35) 36 37def _clippy_flags_impl ( ctx ): 38return ClippyFlagsInfo ( clippy_flags = ctx . build_setting_value ) 39 40clippy_flags = rule ( 41doc = ( 42"Add custom clippy flags from the command line with `--@rules_rust//:clippy_flags`." 43), 44implementation = _clippy_flags_impl , 45build_setting = config . string_list ( flag = True ), 46) 47 48def _get_clippy_ready_crate_info ( target , aspect_ctx ): 49"""Check that a target is suitable for clippy and extract the `CrateInfo` provider from it. 50 51Args: 52target (Target): The target the aspect is running on. 53aspect_ctx (ctx, optional): The aspect's context object. 54 55Returns: 56CrateInfo, optional: A `CrateInfo` provider if clippy should be run or `None`. 57""" 58 59# Ignore external targets 60if target . label . workspace_root . startswith ( "external" ): 61return None 62 63# Targets with specific tags will not be formatted 64if aspect_ctx : 65ignore_tags = [ 66"noclippy" , 67"no-clippy" , 68] 69 70for tag in ignore_tags : 71if tag in aspect_ctx . rule . attr . tags : 72return None 73 74# Obviously ignore any targets that don't contain `CrateInfo` 75if rust_common . crate_info not in target : 76return None 77 78return target [ rust_common . crate_info ] 79 80def _clippy_aspect_impl ( target , ctx ): 81crate_info = _get_clippy_ready_crate_info ( target , ctx ) 82if not crate_info : 83return [ ClippyInfo ( output = depset ([]))] 84 85toolchain = find_toolchain ( ctx ) 86cc_toolchain , feature_configuration = find_cc_toolchain ( ctx ) 87 88dep_info , build_info , linkstamps = collect_deps ( 89deps = crate_info . deps , 90proc_macro_deps = crate_info . proc_macro_deps , 91aliases = crate_info . aliases , 92# Clippy doesn't need to invoke transitive linking, therefore doesn't need linkstamps. 93are_linkstamps_supported = False , 94) 95 96compile_inputs , out_dir , build_env_files , build_flags_files , linkstamp_outs , ambiguous_libs = collect_inputs ( 97ctx , 98ctx . rule . file , 99ctx . rule . files , 100linkstamps , 101toolchain , 102cc_toolchain , 103feature_configuration , 104crate_info , 105dep_info , 106build_info , 107) 108 109args , env = construct_arguments ( 110ctx = ctx , 111attr = ctx . rule . attr , 112file = ctx . file , 113toolchain = toolchain , 114tool_path = toolchain . clippy_driver . path , 115cc_toolchain = cc_toolchain , 116feature_configuration = feature_configuration , 117crate_info = crate_info , 118dep_info = dep_info , 119linkstamp_outs = linkstamp_outs , 120ambiguous_libs = ambiguous_libs , 121output_hash = determine_output_hash ( crate_info . root , ctx . label ), 122rust_flags = [], 123out_dir = out_dir , 124build_env_files = build_env_files , 125build_flags_files = build_flags_files , 126emit = [ "dep-info" , "metadata" ], 127) 128 129if crate_info . is_test : 130args . rustc_flags . add ( "--test" ) 131 132clippy_flags = ctx . attr . _clippy_flags [ ClippyFlagsInfo ]. clippy_flags 133 134# For remote execution purposes, the clippy_out file must be a sibling of crate_info.output 135# or rustc may fail to create intermediate output files because the directory does not exist. 136if ctx . attr . _capture_output [ CaptureClippyOutputInfo ]. capture_output : 137clippy_out = ctx . actions . declare_file ( ctx . label . name + ".clippy.out" , sibling = crate_info . output ) 138args . process_wrapper_flags . add ( "--stderr-file" , clippy_out . path ) 139 140if clippy_flags : 141fail ( """Combining @rules_rust//:clippy_flags with @rules_rust//:capture_clippy_output=true is currently not supported. 142See https://github.com/bazelbuild/rules_rust/pull/1264#discussion_r853241339 for more detail.""" ) 143 144# If we are capturing the output, we want the build system to be able to keep going 145# and consume the output. Some clippy lints are denials, so we treat them as warnings. 146args . rustc_flags . add ( "-Wclippy::all" ) 147else : 148# A marker file indicating clippy has executed successfully. 149# This file is necessary because "ctx.actions.run" mandates an output. 150clippy_out = ctx . actions . declare_file ( ctx . label . name + ".clippy.ok" , sibling = crate_info . output ) 151args . process_wrapper_flags . add ( "--touch-file" , clippy_out . path ) 152 153if clippy_flags : 154args . rustc_flags . add_all ( clippy_flags ) 155else : 156# The user didn't provide any clippy flags explicitly so we apply conservative defaults. 157 158# Turn any warnings from clippy or rustc into an error, as otherwise 159# Bazel will consider the execution result of the aspect to be "success", 160# and Clippy won't be re-triggered unless the source file is modified. 161args . rustc_flags . add ( "-Dwarnings" ) 162 163# Upstream clippy requires one of these two filenames or it silently uses 164# the default config. Enforce the naming so users are not confused. 165valid_config_file_names = [ ".clippy.toml" , "clippy.toml" ] 166if ctx . file . _config . basename not in valid_config_file_names : 167fail ( "The clippy config file must be named one of: {}" . format ( valid_config_file_names )) 168env [ "CLIPPY_CONF_DIR" ] = "${{pwd}}/{}" . format ( ctx . file . _config . dirname ) 169compile_inputs = depset ([ ctx . file . _config ], transitive = [ compile_inputs ]) 170 171ctx . actions . run ( 172executable = ctx . executable . _process_wrapper , 173inputs = compile_inputs , 174outputs = [ clippy_out ], 175env = env , 176tools = [ toolchain . clippy_driver ], 177arguments = args . all , 178mnemonic = "Clippy" , 179) 180 181return [ 182OutputGroupInfo ( clippy_checks = depset ([ clippy_out ])), 183ClippyInfo ( output = depset ([ clippy_out ])), 184] 185 186# Example: Run the clippy checker on all targets in the codebase. 187# bazel build --aspects=@rules_rust//rust:defs.bzl%rust_clippy_aspect \ 188# --output_groups=clippy_checks \ 189# //... 190rust_clippy_aspect = aspect ( 191fragments = [ "cpp" ], 192host_fragments = [ "cpp" ], 193attrs = { 194"_capture_output" : attr . label ( 195doc = "Value of the `capture_clippy_output` build setting" , 196default = Label ( "//:capture_clippy_output" ), 197), 198"_cc_toolchain" : attr . label ( 199doc = ( 200"Required attribute to access the cc_toolchain. See [Accessing the C++ toolchain]" + 201"(https://docs.bazel.build/versions/master/integrating-with-rules-cc.html#accessing-the-c-toolchain)" 202), 203default = Label ( "@bazel_tools//tools/cpp:current_cc_toolchain" ), 204), 205"_clippy_flags" : attr . label ( 206doc = "Arguments to pass to clippy" , 207default = Label ( "//:clippy_flags" ), 208), 209"_config" : attr . label ( 210doc = "The `clippy.toml` file used for configuration" , 211allow_single_file = True , 212default = Label ( "//:clippy.toml" ), 213), 214"_error_format" : attr . label ( 215doc = "The desired `--error-format` flags for clippy" , 216default = "//:error_format" , 217), 218"_extra_rustc_flags" : attr . label ( default = "//:extra_rustc_flags" ), 219"_process_wrapper" : attr . label ( 220doc = "A process wrapper for running clippy on all platforms" , 221default = Label ( "//util/process_wrapper" ), 222executable = True , 223cfg = "exec" , 224), 225}, 226provides = [ ClippyInfo ], 227toolchains = [ 228str ( Label ( "//rust:toolchain" )), 229"@bazel_tools//tools/cpp:toolchain_type" , 230], 231incompatible_use_toolchain_transition = True , 232implementation = _clippy_aspect_impl , 233doc = """\ 234Executes the clippy checker on specified targets. 235 236This aspect applies to existing rust_library, rust_test, and rust_binary rules. 237 238As an example, if the following is defined in `examples/hello_lib/BUILD.bazel`: 239 240```python 241load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test") 242 243rust_library( 244name = "hello_lib", 245srcs = ["src/lib.rs"], 246) 247 248rust_test( 249name = "greeting_test", 250srcs = ["tests/greeting.rs"], 251deps = [":hello_lib"], 252) 253``` 254 255Then the targets can be analyzed with clippy using the following command: 256 257```output 258$ bazel build --aspects=@rules_rust//rust:defs.bzl%rust_clippy_aspect \ 259--output_groups=clippy_checks //hello_lib:all 260``` 261""" , 262) 263 264def _rust_clippy_rule_impl ( ctx ): 265clippy_ready_targets = [ dep for dep in ctx . attr . deps if "clippy_checks" in dir ( dep [ OutputGroupInfo ])] 266files = depset ([], transitive = [ dep [ OutputGroupInfo ]. clippy_checks for dep in clippy_ready_targets ]) 267return [ DefaultInfo ( files = files )] 268 269rust_clippy = rule ( 270implementation = _rust_clippy_rule_impl , 271attrs = { 272"deps" : attr . label_list ( 273doc = "Rust targets to run clippy on." , 274providers = [ rust_common . crate_info ], 275aspects = [ rust_clippy_aspect ], 276), 277}, 278doc = """\ 279Executes the clippy checker on a specific target. 280 281Similar to `rust_clippy_aspect`, but allows specifying a list of dependencies \ 282within the build system. 283 284For example, given the following example targets: 285 286```python 287load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test") 288 289rust_library( 290name = "hello_lib", 291srcs = ["src/lib.rs"], 292) 293 294rust_test( 295name = "greeting_test", 296srcs = ["tests/greeting.rs"], 297deps = [":hello_lib"], 298) 299``` 300 301Rust clippy can be set as a build target with the following: 302 303```python 304load("@rules_rust//rust:defs.bzl", "rust_clippy") 305 306rust_clippy( 307name = "hello_library_clippy", 308testonly = True, 309deps = [ 310":hello_lib", 311":greeting_test", 312], 313) 314``` 315""" , 316) 317 318def _capture_clippy_output_impl ( ctx ): 319"""Implementation of the `capture_clippy_output` rule 320 321Args: 322ctx (ctx): The rule's context object 323 324Returns: 325list: A list containing the CaptureClippyOutputInfo provider 326""" 327return [ CaptureClippyOutputInfo ( capture_output = ctx . build_setting_value )] 328 329capture_clippy_output = rule ( 330doc = "Control whether to print clippy output or store it to a file, using the configured error_format." , 331implementation = _capture_clippy_output_impl , 332build_setting = config . bool ( flag = True ), 333)