fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
c3d71edd
main
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_flag_impl ( ctx ): 38return ClippyFlagsInfo ( clippy_flags = [ f for f in ctx . build_setting_value if f != "" ]) 39 40clippy_flag = rule ( 41doc = ( 42"Add a custom clippy flag from the command line with `--@rules_rust//rust/settings:clippy_flag`." + 43"Multiple uses are accumulated and appended after the extra_rustc_flags." 44), 45implementation = _clippy_flag_impl , 46build_setting = config . string_list ( flag = True , repeatable = True ), 47) 48 49def _clippy_flags_impl ( ctx ): 50return ClippyFlagsInfo ( clippy_flags = ctx . build_setting_value ) 51 52clippy_flags = rule ( 53doc = ( 54"Add custom clippy flags from the command line with `--@rules_rust//rust/settings:clippy_flags`." 55), 56implementation = _clippy_flags_impl , 57build_setting = config . string_list ( flag = True ), 58) 59 60def _get_clippy_ready_crate_info ( target , aspect_ctx = None ): 61"""Check that a target is suitable for clippy and extract the `CrateInfo` provider from it. 62 63Args: 64target (Target): The target the aspect is running on. 65aspect_ctx (ctx, optional): The aspect's context object. 66 67Returns: 68CrateInfo, optional: A `CrateInfo` provider if clippy should be run or `None`. 69""" 70 71# Ignore external targets 72if target . label . workspace_root . startswith ( "external" ): 73return None 74 75# Targets with specific tags will not be formatted 76if aspect_ctx : 77ignore_tags = [ 78"no_clippy" , 79"no_lint" , 80"noclippy" , 81] 82for tag in aspect_ctx . rule . attr . tags : 83if tag . replace ( "-" , "_" ). lower () in ignore_tags : 84return None 85 86# Obviously ignore any targets that don't contain `CrateInfo` 87if rust_common . crate_info in target : 88return target [ rust_common . crate_info ] 89elif rust_common . test_crate_info in target : 90return target [ rust_common . test_crate_info ]. crate 91else : 92return None 93 94def _clippy_aspect_impl ( target , ctx ): 95crate_info = _get_clippy_ready_crate_info ( target , ctx ) 96if not crate_info : 97return [ ClippyInfo ( output = depset ([]))] 98 99toolchain = find_toolchain ( ctx ) 100cc_toolchain , feature_configuration = find_cc_toolchain ( ctx ) 101 102dep_info , build_info , _ = collect_deps ( 103deps = crate_info . deps , 104proc_macro_deps = crate_info . proc_macro_deps , 105aliases = crate_info . aliases , 106) 107 108compile_inputs , out_dir , build_env_files , build_flags_files , linkstamp_outs , ambiguous_libs = collect_inputs ( 109ctx , 110ctx . rule . file , 111ctx . rule . files , 112# Clippy doesn't need to invoke transitive linking, therefore doesn't need linkstamps. 113depset ([]), 114toolchain , 115cc_toolchain , 116feature_configuration , 117crate_info , 118dep_info , 119build_info , 120) 121 122args , env = construct_arguments ( 123ctx = ctx , 124attr = ctx . rule . attr , 125file = ctx . file , 126toolchain = toolchain , 127tool_path = toolchain . clippy_driver . path , 128cc_toolchain = cc_toolchain , 129feature_configuration = feature_configuration , 130crate_info = crate_info , 131dep_info = dep_info , 132linkstamp_outs = linkstamp_outs , 133ambiguous_libs = ambiguous_libs , 134output_hash = determine_output_hash ( crate_info . root , ctx . label ), 135rust_flags = [], 136out_dir = out_dir , 137build_env_files = build_env_files , 138build_flags_files = build_flags_files , 139emit = [ "dep-info" , "metadata" ], 140skip_expanding_rustc_env = True , 141) 142 143if crate_info . is_test : 144args . rustc_flags . add ( "--test" ) 145 146clippy_flags = ctx . attr . _clippy_flags [ ClippyFlagsInfo ]. clippy_flags 147 148if hasattr ( ctx . attr , "_clippy_flag" ): 149clippy_flags = clippy_flags + ctx . attr . _clippy_flag [ ClippyFlagsInfo ]. clippy_flags 150 151# For remote execution purposes, the clippy_out file must be a sibling of crate_info.output 152# or rustc may fail to create intermediate output files because the directory does not exist. 153if ctx . attr . _capture_output [ CaptureClippyOutputInfo ]. capture_output : 154clippy_out = ctx . actions . declare_file ( ctx . label . name + ".clippy.out" , sibling = crate_info . output ) 155args . process_wrapper_flags . add ( "--stderr-file" , clippy_out ) 156 157if clippy_flags : 158args . rustc_flags . add_all ( clippy_flags ) 159 160# If we are capturing the output, we want the build system to be able to keep going 161# and consume the output. Some clippy lints are denials, so we cap everything at warn. 162args . rustc_flags . add ( "--cap-lints=warn" ) 163else : 164# A marker file indicating clippy has executed successfully. 165# This file is necessary because "ctx.actions.run" mandates an output. 166clippy_out = ctx . actions . declare_file ( ctx . label . name + ".clippy.ok" , sibling = crate_info . output ) 167args . process_wrapper_flags . add ( "--touch-file" , clippy_out ) 168 169if clippy_flags : 170args . rustc_flags . add_all ( clippy_flags ) 171else : 172# The user didn't provide any clippy flags explicitly so we apply conservative defaults. 173 174# Turn any warnings from clippy or rustc into an error, as otherwise 175# Bazel will consider the execution result of the aspect to be "success", 176# and Clippy won't be re-triggered unless the source file is modified. 177args . rustc_flags . add ( "-Dwarnings" ) 178 179# Upstream clippy requires one of these two filenames or it silently uses 180# the default config. Enforce the naming so users are not confused. 181valid_config_file_names = [ ".clippy.toml" , "clippy.toml" ] 182if ctx . file . _config . basename not in valid_config_file_names : 183fail ( "The clippy config file must be named one of: {}" . format ( valid_config_file_names )) 184env [ "CLIPPY_CONF_DIR" ] = "${{pwd}}/{}" . format ( ctx . file . _config . dirname ) 185compile_inputs = depset ([ ctx . file . _config ], transitive = [ compile_inputs ]) 186 187ctx . actions . run ( 188executable = ctx . executable . _process_wrapper , 189inputs = compile_inputs , 190outputs = [ clippy_out ], 191env = env , 192tools = [ toolchain . clippy_driver ], 193arguments = args . all , 194mnemonic = "Clippy" , 195progress_message = "Clippy %{label}" , 196toolchain = "@rules_rust//rust:toolchain_type" , 197) 198 199return [ 200OutputGroupInfo ( clippy_checks = depset ([ clippy_out ])), 201ClippyInfo ( output = depset ([ clippy_out ])), 202] 203 204# Example: Run the clippy checker on all targets in the codebase. 205# bazel build --aspects=@rules_rust//rust:defs.bzl%rust_clippy_aspect \ 206# --output_groups=clippy_checks \ 207# //... 208rust_clippy_aspect = aspect ( 209fragments = [ "cpp" ], 210attrs = { 211"_capture_output" : attr . label ( 212doc = "Value of the `capture_clippy_output` build setting" , 213default = Label ( "//rust/settings:capture_clippy_output" ), 214), 215"_cc_toolchain" : attr . label ( 216doc = ( 217"Required attribute to access the cc_toolchain. See [Accessing the C++ toolchain]" + 218"(https://docs.bazel.build/versions/master/integrating-with-rules-cc.html#accessing-the-c-toolchain)" 219), 220default = Label ( "@bazel_tools//tools/cpp:current_cc_toolchain" ), 221), 222"_clippy_flag" : attr . label ( 223doc = "Arguments to pass to clippy." + 224"Multiple uses are accumulated and appended after the extra_rustc_flags." , 225default = Label ( "//rust/settings:clippy_flag" ), 226), 227"_clippy_flags" : attr . label ( 228doc = "Arguments to pass to clippy" , 229default = Label ( "//rust/settings:clippy_flags" ), 230), 231"_config" : attr . label ( 232doc = "The `clippy.toml` file used for configuration" , 233allow_single_file = True , 234default = Label ( "//rust/settings:clippy.toml" ), 235), 236"_error_format" : attr . label ( 237doc = "The desired `--error-format` flags for clippy" , 238default = "//rust/settings:error_format" , 239), 240"_extra_rustc_flag" : attr . label ( 241default = Label ( "//rust/settings:extra_rustc_flag" ), 242), 243"_per_crate_rustc_flag" : attr . label ( 244default = Label ( "//rust/settings:experimental_per_crate_rustc_flag" ), 245), 246"_process_wrapper" : attr . label ( 247doc = "A process wrapper for running clippy on all platforms" , 248default = Label ( "//util/process_wrapper" ), 249executable = True , 250cfg = "exec" , 251), 252}, 253provides = [ ClippyInfo ], 254required_providers = [ 255[ rust_common . crate_info ], 256[ rust_common . test_crate_info ], 257], 258toolchains = [ 259str ( Label ( "//rust:toolchain_type" )), 260"@bazel_tools//tools/cpp:toolchain_type" , 261], 262implementation = _clippy_aspect_impl , 263doc = """\ 264Executes the clippy checker on specified targets. 265 266This aspect applies to existing rust_library, rust_test, and rust_binary rules. 267 268As an example, if the following is defined in `examples/hello_lib/BUILD.bazel`: 269 270```python 271load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test") 272 273rust_library( 274name = "hello_lib", 275srcs = ["src/lib.rs"], 276) 277 278rust_test( 279name = "greeting_test", 280srcs = ["tests/greeting.rs"], 281deps = [":hello_lib"], 282) 283``` 284 285Then the targets can be analyzed with clippy using the following command: 286 287```output 288$ bazel build --aspects=@rules_rust//rust:defs.bzl%rust_clippy_aspect \ 289--output_groups=clippy_checks //hello_lib:all 290``` 291""" , 292) 293 294def _rust_clippy_rule_impl ( ctx ): 295clippy_ready_targets = [ dep for dep in ctx . attr . deps if "clippy_checks" in dir ( dep [ OutputGroupInfo ])] 296files = depset ([], transitive = [ dep [ OutputGroupInfo ]. clippy_checks for dep in clippy_ready_targets ]) 297return [ DefaultInfo ( files = files )] 298 299rust_clippy = rule ( 300implementation = _rust_clippy_rule_impl , 301attrs = { 302"deps" : attr . label_list ( 303doc = "Rust targets to run clippy on." , 304providers = [ 305[ rust_common . crate_info ], 306[ rust_common . test_crate_info ], 307], 308aspects = [ rust_clippy_aspect ], 309), 310}, 311doc = """\ 312Executes the clippy checker on a specific target. 313 314Similar to `rust_clippy_aspect`, but allows specifying a list of dependencies \ 315within the build system. 316 317For example, given the following example targets: 318 319```python 320load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test") 321 322rust_library( 323name = "hello_lib", 324srcs = ["src/lib.rs"], 325) 326 327rust_test( 328name = "greeting_test", 329srcs = ["tests/greeting.rs"], 330deps = [":hello_lib"], 331) 332``` 333 334Rust clippy can be set as a build target with the following: 335 336```python 337load("@rules_rust//rust:defs.bzl", "rust_clippy") 338 339rust_clippy( 340name = "hello_library_clippy", 341testonly = True, 342deps = [ 343":hello_lib", 344":greeting_test", 345], 346) 347``` 348""" , 349) 350 351def _capture_clippy_output_impl ( ctx ): 352"""Implementation of the `capture_clippy_output` rule 353 354Args: 355ctx (ctx): The rule's context object 356 357Returns: 358list: A list containing the CaptureClippyOutputInfo provider 359""" 360return [ CaptureClippyOutputInfo ( capture_output = ctx . build_setting_value )] 361 362capture_clippy_output = rule ( 363doc = "Control whether to print clippy output or store it to a file, using the configured error_format." , 364implementation = _capture_clippy_output_impl , 365build_setting = config . bool ( flag = True ), 366)