1 //! This lint is used to collect metadata about clippy lints. This metadata is exported as a json
2 //! file and then used to generate the [clippy lint list](https://rust-lang.github.io/rust-clippy/master/index.html)
4 //! This module and therefore the entire lint is guarded by a feature flag called `internal`
6 //! The module transforms all lint names to ascii lowercase to ensure that we don't have mismatches
7 //! during any comparison or mapping. (Please take care of this, it's not fun to spend time on such
10 use crate::renamed_lints::RENAMED_LINTS;
11 use crate::utils::internal_lints::lint_without_lint_pass::{extract_clippy_version_value, is_lint_ref_type};
13 use clippy_utils::diagnostics::span_lint;
14 use clippy_utils::ty::{match_type, walk_ptrs_ty_depth};
15 use clippy_utils::{last_path_segment, match_def_path, match_function_call, match_path, paths};
16 use if_chain::if_chain;
18 use rustc_data_structures::fx::FxHashMap;
20 self as hir, def::DefKind, intravisit, intravisit::Visitor, Closure, ExprKind, Item, ItemKind, Mutability, QPath,
22 use rustc_lint::{CheckLintNameResult, LateContext, LateLintPass, LintContext, LintId};
23 use rustc_middle::hir::nested_filter;
24 use rustc_session::{declare_tool_lint, impl_lint_pass};
25 use rustc_span::symbol::Ident;
26 use rustc_span::{sym, Loc, Span, Symbol};
27 use serde::{ser::SerializeStruct, Serialize, Serializer};
28 use std::collections::BinaryHeap;
30 use std::fmt::Write as _;
31 use std::fs::{self, OpenOptions};
32 use std::io::prelude::*;
34 use std::path::PathBuf;
35 use std::process::Command;
37 /// This is the output file of the lint collector.
38 const OUTPUT_FILE: &str = "../util/gh-pages/lints.json";
39 /// These lints are excluded from the export.
40 const BLACK_LISTED_LINTS: &[&str] = &["lint_author", "dump_hir", "internal_metadata_collector"];
41 /// These groups will be ignored by the lint group matcher. This is useful for collections like
43 const IGNORED_LINT_GROUPS: [&str; 1] = ["clippy::all"];
44 /// Lints within this group will be excluded from the collection. These groups
45 /// have to be defined without the `clippy::` prefix.
46 const EXCLUDED_LINT_GROUPS: [&str; 1] = ["internal"];
47 /// Collected deprecated lint will be assigned to this group in the JSON output
48 const DEPRECATED_LINT_GROUP_STR: &str = "deprecated";
49 /// This is the lint level for deprecated lints that will be displayed in the lint list
50 const DEPRECATED_LINT_LEVEL: &str = "none";
51 /// This array holds Clippy's lint groups with their corresponding default lint level. The
52 /// lint level for deprecated lints is set in `DEPRECATED_LINT_LEVEL`.
53 const DEFAULT_LINT_LEVELS: &[(&str, &str)] = &[
54 ("correctness", "deny"),
55 ("suspicious", "warn"),
56 ("restriction", "allow"),
58 ("pedantic", "allow"),
59 ("complexity", "warn"),
64 /// This prefix is in front of the lint groups in the lint store. The prefix will be trimmed
65 /// to only keep the actual lint group in the output.
66 const CLIPPY_LINT_GROUP_PREFIX: &str = "clippy::";
67 const LINT_EMISSION_FUNCTIONS: [&[&str]; 7] = [
68 &["clippy_utils", "diagnostics", "span_lint"],
69 &["clippy_utils", "diagnostics", "span_lint_and_help"],
70 &["clippy_utils", "diagnostics", "span_lint_and_note"],
71 &["clippy_utils", "diagnostics", "span_lint_hir"],
72 &["clippy_utils", "diagnostics", "span_lint_and_sugg"],
73 &["clippy_utils", "diagnostics", "span_lint_and_then"],
74 &["clippy_utils", "diagnostics", "span_lint_hir_and_then"],
76 const SUGGESTION_DIAGNOSTIC_BUILDER_METHODS: [(&str, bool); 9] = [
77 ("span_suggestion", false),
78 ("span_suggestion_short", false),
79 ("span_suggestion_verbose", false),
80 ("span_suggestion_hidden", false),
81 ("tool_only_span_suggestion", false),
82 ("multipart_suggestion", true),
83 ("multipart_suggestions", true),
84 ("tool_only_multipart_suggestion", true),
85 ("span_suggestions", true),
87 const SUGGESTION_FUNCTIONS: [&[&str]; 2] = [
88 &["clippy_utils", "diagnostics", "multispan_sugg"],
89 &["clippy_utils", "diagnostics", "multispan_sugg_with_applicability"],
91 const DEPRECATED_LINT_TYPE: [&str; 3] = ["clippy_lints", "deprecated_lints", "ClippyDeprecatedLint"];
93 /// The index of the applicability name of `paths::APPLICABILITY_VALUES`
94 const APPLICABILITY_NAME_INDEX: usize = 2;
95 /// This applicability will be set for unresolved applicability values.
96 const APPLICABILITY_UNRESOLVED_STR: &str = "Unresolved";
97 /// The version that will be displayed if none has been defined
98 const VERSION_DEFAULT_STR: &str = "Unknown";
100 declare_clippy_lint! {
102 /// Collects metadata about clippy lints for the website.
104 /// This lint will be used to report problems of syntax parsing. You should hopefully never
105 /// see this but never say never I guess ^^
107 /// ### Why is this bad?
108 /// This is not a bad thing but definitely a hacky way to do it. See
109 /// issue [#4310](https://github.com/rust-lang/rust-clippy/issues/4310) for a discussion
110 /// about the implementation.
112 /// ### Known problems
113 /// Hopefully none. It would be pretty uncool to have a problem here :)
115 /// ### Example output
118 /// "id": "internal_metadata_collector",
120 /// "path": "clippy_lints/src/utils/internal_lints/metadata_collector.rs",
123 /// "group": "clippy::internal",
124 /// "docs": " ### What it does\nCollects metadata about clippy lints for the website. [...] "
127 #[clippy::version = "1.56.0"]
128 pub INTERNAL_METADATA_COLLECTOR,
130 "A busy bee collection metadata about lints"
133 impl_lint_pass!(MetadataCollector => [INTERNAL_METADATA_COLLECTOR]);
135 #[allow(clippy::module_name_repetitions)]
136 #[derive(Debug, Clone)]
137 pub struct MetadataCollector {
138 /// All collected lints
140 /// We use a Heap here to have the lints added in alphabetic order in the export
141 lints: BinaryHeap<LintMetadata>,
142 applicability_info: FxHashMap<String, ApplicabilityInfo>,
143 config: Vec<ClippyConfiguration>,
144 clippy_project_root: PathBuf,
147 impl MetadataCollector {
148 pub fn new() -> Self {
150 lints: BinaryHeap::<LintMetadata>::default(),
151 applicability_info: FxHashMap::<String, ApplicabilityInfo>::default(),
152 config: collect_configs(),
153 clippy_project_root: std::env::current_dir()
154 .expect("failed to get current dir")
157 .expect("failed to get project root")
162 fn get_lint_configs(&self, lint_name: &str) -> Option<String> {
165 .filter(|config| config.lints.iter().any(|lint| lint == lint_name))
166 .map(ToString::to_string)
167 .reduce(|acc, x| acc + &x)
168 .map(|configurations| {
172 This lint has the following configuration variables:
181 impl Drop for MetadataCollector {
182 /// You might ask: How hacky is this?
185 // The metadata collector gets dropped twice, this makes sure that we only write
186 // when the list is full
187 if self.lints.is_empty() {
191 let mut applicability_info = std::mem::take(&mut self.applicability_info);
193 // Mapping the final data
194 let mut lints = std::mem::take(&mut self.lints).into_sorted_vec();
195 for x in &mut lints {
196 x.applicability = Some(applicability_info.remove(&x.id).unwrap_or_default());
197 replace_produces(&x.id, &mut x.docs, &self.clippy_project_root);
200 collect_renames(&mut lints);
203 if Path::new(OUTPUT_FILE).exists() {
204 fs::remove_file(OUTPUT_FILE).unwrap();
206 let mut file = OpenOptions::new().write(true).create(true).open(OUTPUT_FILE).unwrap();
207 writeln!(file, "{}", serde_json::to_string_pretty(&lints).unwrap()).unwrap();
211 #[derive(Debug, Clone, Serialize, PartialEq, Eq, PartialOrd, Ord)]
212 struct LintMetadata {
214 id_span: SerializableSpan,
219 /// This field is only used in the output and will only be
220 /// mapped shortly before the actual output.
221 applicability: Option<ApplicabilityInfo>,
227 id_span: SerializableSpan,
237 level: level.to_string(),
245 fn replace_produces(lint_name: &str, docs: &mut String, clippy_project_root: &Path) {
246 let mut doc_lines = docs.lines().map(ToString::to_string).collect::<Vec<_>>();
247 let mut lines = doc_lines.iter_mut();
250 // Find the start of the example
255 Some(line) if line.trim_start().starts_with("```rust") => {
256 if line.contains("ignore") || line.contains("no_run") {
257 // A {{produces}} marker may have been put on a ignored code block by mistake,
258 // just seek to the end of the code block and continue checking.
259 if lines.any(|line| line.trim_start().starts_with("```")) {
263 panic!("lint `{lint_name}` has an unterminated code block")
268 Some(line) if line.trim_start() == "{{produces}}" => {
269 panic!("lint `{lint_name}` has marker {{{{produces}}}} with an ignored or missing code block")
272 let line = line.trim();
273 // These are the two most common markers of the corrections section
274 if line.eq_ignore_ascii_case("Use instead:") || line.eq_ignore_ascii_case("Could be written as:") {
278 None => break 'outer,
282 // Collect the example
283 let mut example = Vec::new();
286 Some(line) if line.trim_start() == "```" => break,
287 Some(line) => example.push(line),
288 None => panic!("lint `{lint_name}` has an unterminated code block"),
292 // Find the {{produces}} and attempt to generate the output
295 Some(line) if line.is_empty() => {},
296 Some(line) if line.trim() == "{{produces}}" => {
297 let output = get_lint_output(lint_name, &example, clippy_project_root);
302 <summary>Produces</summary>\n\
313 // No {{produces}}, we can move on to the next example
315 None => break 'outer,
320 *docs = cleanup_docs(&doc_lines);
323 fn get_lint_output(lint_name: &str, example: &[&mut String], clippy_project_root: &Path) -> String {
324 let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("failed to create temp dir: {e}"));
325 let file = dir.path().join("lint_example.rs");
327 let mut source = String::new();
328 let unhidden = example
330 .map(|line| line.trim_start().strip_prefix("# ").unwrap_or(line));
332 // Get any attributes
333 let mut lines = unhidden.peekable();
334 while let Some(line) = lines.peek() {
335 if line.starts_with("#!") {
336 source.push_str(line);
344 let needs_main = !example.iter().any(|line| line.contains("fn main"));
346 source.push_str("fn main() {\n");
350 source.push_str(line);
355 source.push_str("}\n");
358 if let Err(e) = fs::write(&file, &source) {
359 panic!("failed to write to `{}`: {e}", file.as_path().to_string_lossy());
362 let prefixed_name = format!("{CLIPPY_LINT_GROUP_PREFIX}{lint_name}");
364 let mut cmd = Command::new("cargo");
366 cmd.current_dir(clippy_project_root)
367 .env("CARGO_INCREMENTAL", "0")
368 .env("CLIPPY_ARGS", "")
369 .env("CLIPPY_DISABLE_DOCS_LINKS", "1")
370 // We need to disable this to enable all lints
371 .env("ENABLE_METADATA_COLLECTION", "0")
372 .args(["run", "--bin", "clippy-driver"])
373 .args(["--target-dir", "./clippy_lints/target"])
374 .args(["--", "--error-format=json"])
375 .args(["--edition", "2021"])
376 .arg("-Cdebuginfo=0")
377 .args(["-A", "clippy::all"])
378 .args(["-W", &prefixed_name])
379 .args(["-L", "./target/debug"])
380 .args(["-Z", "no-codegen"]);
385 .unwrap_or_else(|e| panic!("failed to run `{cmd:?}`: {e}"));
387 let tmp_file_path = file.to_string_lossy();
388 let stderr = std::str::from_utf8(&output.stderr).unwrap();
391 .filter(|line| line.starts_with('{'))
392 .map(|line| serde_json::from_str(line).unwrap())
393 .collect::<Vec<serde_json::Value>>();
395 let mut rendered = String::new();
398 .filter(|msg| matches!(&msg["code"]["code"], serde_json::Value::String(s) if s == &prefixed_name));
400 for message in iter {
401 let rendered_part = message["rendered"].as_str().expect("rendered field should exist");
402 rendered.push_str(rendered_part);
405 if rendered.is_empty() {
406 let rendered: Vec<&str> = msgs.iter().filter_map(|msg| msg["rendered"].as_str()).collect();
407 let non_json: Vec<&str> = stderr.lines().filter(|line| !line.starts_with('{')).collect();
409 "did not find lint `{lint_name}` in output of example, got:\n{}\n{}",
415 // The reader doesn't need to see `/tmp/.tmpfiy2Qd/lint_example.rs` :)
416 rendered.trim_end().replace(&*tmp_file_path, "lint_example.rs")
419 #[derive(Debug, Clone, Serialize, PartialEq, Eq, PartialOrd, Ord)]
420 struct SerializableSpan {
425 impl fmt::Display for SerializableSpan {
426 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427 write!(f, "{}:{}", self.path.rsplit('/').next().unwrap_or_default(), self.line)
431 impl SerializableSpan {
432 fn from_item(cx: &LateContext<'_>, item: &Item<'_>) -> Self {
433 Self::from_span(cx, item.ident.span)
436 fn from_span(cx: &LateContext<'_>, span: Span) -> Self {
437 let loc: Loc = cx.sess().source_map().lookup_char_pos(span.lo());
440 path: format!("{}", loc.file.name.prefer_remapped()),
446 #[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
447 struct ApplicabilityInfo {
448 /// Indicates if any of the lint emissions uses multiple spans. This is related to
449 /// [rustfix#141](https://github.com/rust-lang/rustfix/issues/141) as such suggestions can
450 /// currently not be applied automatically.
451 is_multi_part_suggestion: bool,
452 applicability: Option<usize>,
455 impl Serialize for ApplicabilityInfo {
456 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
460 let mut s = serializer.serialize_struct("ApplicabilityInfo", 2)?;
461 s.serialize_field("is_multi_part_suggestion", &self.is_multi_part_suggestion)?;
462 if let Some(index) = self.applicability {
465 &paths::APPLICABILITY_VALUES[index][APPLICABILITY_NAME_INDEX],
468 s.serialize_field("applicability", APPLICABILITY_UNRESOLVED_STR)?;
474 // ==================================================================
476 // ==================================================================
477 #[derive(Debug, Clone, Default)]
478 pub struct ClippyConfiguration {
480 config_type: &'static str,
485 deprecation_reason: Option<&'static str>,
488 impl ClippyConfiguration {
491 config_type: &'static str,
493 doc_comment: &'static str,
494 deprecation_reason: Option<&'static str>,
496 let (lints, doc) = parse_config_field_doc(doc_comment)
497 .unwrap_or_else(|| (vec![], "[ERROR] MALFORMED DOC COMMENT".to_string()));
500 name: to_kebab(name),
510 fn collect_configs() -> Vec<ClippyConfiguration> {
511 crate::utils::conf::metadata::get_configuration_metadata()
514 /// This parses the field documentation of the config struct.
517 /// parse_config_field_doc(cx, "Lint: LINT_NAME_1, LINT_NAME_2. Papa penguin, papa penguin")
522 /// Some(["lint_name_1", "lint_name_2"], "Papa penguin, papa penguin")
524 fn parse_config_field_doc(doc_comment: &str) -> Option<(Vec<String>, String)> {
525 const DOC_START: &str = " Lint: ";
527 if doc_comment.starts_with(DOC_START);
528 if let Some(split_pos) = doc_comment.find('.');
530 let mut doc_comment = doc_comment.to_string();
531 let mut documentation = doc_comment.split_off(split_pos);
534 doc_comment.make_ascii_lowercase();
535 let lints: Vec<String> = doc_comment
536 .split_off(DOC_START.len())
541 // Format documentation correctly
542 // split off leading `.` from lint name list and indent for correct formatting
543 documentation = documentation.trim_start_matches('.').trim().replace("\n ", "\n ");
545 Some((lints, documentation))
552 /// Transforms a given `snake_case_string` to a tasty `kebab-case-string`
553 fn to_kebab(config_name: &str) -> String {
554 config_name.replace('_', "-")
557 impl fmt::Display for ClippyConfiguration {
558 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
561 "* `{}`: `{}`(defaults to `{}`): {}",
562 self.name, self.config_type, self.default, self.doc
567 // ==================================================================
569 // ==================================================================
570 impl<'hir> LateLintPass<'hir> for MetadataCollector {
571 /// Collecting lint declarations like:
573 /// declare_clippy_lint! {
574 /// /// ### What it does
575 /// /// Something IDK.
581 fn check_item(&mut self, cx: &LateContext<'hir>, item: &'hir Item<'_>) {
582 if let ItemKind::Static(ty, Mutability::Not, _) = item.kind {
586 if is_lint_ref_type(cx, ty);
588 let lint_name = sym_to_string(item.ident.name).to_ascii_lowercase();
589 if !BLACK_LISTED_LINTS.contains(&lint_name.as_str());
590 // metadata extraction
591 if let Some((group, level)) = get_lint_group_and_level_or_lint(cx, &lint_name, item);
592 if let Some(mut raw_docs) = extract_attr_docs_or_lint(cx, item);
594 if let Some(configuration_section) = self.get_lint_configs(&lint_name) {
595 raw_docs.push_str(&configuration_section);
597 let version = get_lint_version(cx, item);
599 self.lints.push(LintMetadata::new(
601 SerializableSpan::from_item(cx, item),
611 if is_deprecated_lint(cx, ty);
613 let lint_name = sym_to_string(item.ident.name).to_ascii_lowercase();
614 if !BLACK_LISTED_LINTS.contains(&lint_name.as_str());
615 // Metadata the little we can get from a deprecated lint
616 if let Some(raw_docs) = extract_attr_docs_or_lint(cx, item);
618 let version = get_lint_version(cx, item);
620 self.lints.push(LintMetadata::new(
622 SerializableSpan::from_item(cx, item),
623 DEPRECATED_LINT_GROUP_STR.to_string(),
624 DEPRECATED_LINT_LEVEL,
633 /// Collecting constant applicability from the actual lint emissions
637 /// span_lint_and_sugg(
641 /// "Le lint message",
642 /// "Here comes help:",
643 /// "#![allow(clippy::all)]",
644 /// Applicability::MachineApplicable, // <-- Extracts this constant value
647 fn check_expr(&mut self, cx: &LateContext<'hir>, expr: &'hir hir::Expr<'_>) {
648 if let Some(args) = match_lint_emission(cx, expr) {
649 let emission_info = extract_emission_info(cx, args);
650 if emission_info.is_empty() {
652 // - src/misc.rs:734:9
653 // - src/methods/mod.rs:3545:13
654 // - src/methods/mod.rs:3496:13
655 // We are basically unable to resolve the lint name itself.
659 for (lint_name, applicability, is_multi_part) in emission_info {
660 let app_info = self.applicability_info.entry(lint_name).or_default();
661 app_info.applicability = applicability;
662 app_info.is_multi_part_suggestion = is_multi_part;
668 // ==================================================================
669 // Lint definition extraction
670 // ==================================================================
671 fn sym_to_string(sym: Symbol) -> String {
672 sym.as_str().to_string()
675 fn extract_attr_docs_or_lint(cx: &LateContext<'_>, item: &Item<'_>) -> Option<String> {
676 extract_attr_docs(cx, item).or_else(|| {
677 lint_collection_error_item(cx, item, "could not collect the lint documentation");
682 /// This function collects all documentation that has been added to an item using
683 /// `#[doc = r""]` attributes. Several attributes are aggravated using line breaks
686 /// #[doc = r"Hello world!"]
687 /// #[doc = r"=^.^="]
688 /// struct SomeItem {}
691 /// Would result in `Hello world!\n=^.^=\n`
692 fn extract_attr_docs(cx: &LateContext<'_>, item: &Item<'_>) -> Option<String> {
693 let attrs = cx.tcx.hir().attrs(item.hir_id());
694 let mut lines = attrs.iter().filter_map(ast::Attribute::doc_str);
696 if let Some(line) = lines.next() {
697 let raw_docs = lines.fold(String::from(line.as_str()) + "\n", |s, line| s + line.as_str() + "\n");
698 return Some(raw_docs);
704 /// This function may modify the doc comment to ensure that the string can be displayed using a
705 /// markdown viewer in Clippy's lint list. The following modifications could be applied:
706 /// * Removal of leading space after a new line. (Important to display tables)
707 /// * Ensures that code blocks only contain language information
708 fn cleanup_docs(docs_collection: &Vec<String>) -> String {
709 let mut in_code_block = false;
710 let mut is_code_block_rust = false;
712 let mut docs = String::new();
713 for line in docs_collection {
714 // Rustdoc hides code lines starting with `# ` and this removes them from Clippy's lint list :)
715 if is_code_block_rust && line.trim_start().starts_with("# ") {
719 // The line should be represented in the lint list, even if it's just an empty line
721 if let Some(info) = line.trim_start().strip_prefix("```") {
722 in_code_block = !in_code_block;
723 is_code_block_rust = false;
728 // remove rustdoc directives
729 .find(|&s| !matches!(s, "" | "ignore" | "no_run" | "should_panic"))
730 // if no language is present, fill in "rust"
732 docs.push_str("```");
735 is_code_block_rust = lang == "rust";
739 // This removes the leading space that the macro translation introduces
740 if let Some(stripped_doc) = line.strip_prefix(' ') {
741 docs.push_str(stripped_doc);
742 } else if !line.is_empty() {
750 fn get_lint_version(cx: &LateContext<'_>, item: &Item<'_>) -> String {
751 extract_clippy_version_value(cx, item).map_or_else(
752 || VERSION_DEFAULT_STR.to_string(),
753 |version| version.as_str().to_string(),
757 fn get_lint_group_and_level_or_lint(
758 cx: &LateContext<'_>,
761 ) -> Option<(String, &'static str)> {
762 let result = cx.lint_store.check_lint_name(
765 &std::iter::once(Ident::with_dummy_span(sym::clippy)).collect(),
767 if let CheckLintNameResult::Tool(Ok(lint_lst)) = result {
768 if let Some(group) = get_lint_group(cx, lint_lst[0]) {
769 if EXCLUDED_LINT_GROUPS.contains(&group.as_str()) {
773 if let Some(level) = get_lint_level_from_group(&group) {
776 lint_collection_error_item(
779 &format!("Unable to determine lint level for found group `{group}`"),
784 lint_collection_error_item(cx, item, "Unable to determine lint group");
788 lint_collection_error_item(cx, item, "Unable to find lint in lint_store");
793 fn get_lint_group(cx: &LateContext<'_>, lint_id: LintId) -> Option<String> {
794 for (group_name, lints, _) in cx.lint_store.get_lint_groups() {
795 if IGNORED_LINT_GROUPS.contains(&group_name) {
799 if lints.iter().any(|group_lint| *group_lint == lint_id) {
800 let group = group_name.strip_prefix(CLIPPY_LINT_GROUP_PREFIX).unwrap_or(group_name);
801 return Some((*group).to_string());
808 fn get_lint_level_from_group(lint_group: &str) -> Option<&'static str> {
811 .find_map(|(group_name, group_level)| (*group_name == lint_group).then_some(*group_level))
814 pub(super) fn is_deprecated_lint(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> bool {
815 if let hir::TyKind::Path(ref path) = ty.kind {
816 if let hir::def::Res::Def(DefKind::Struct, def_id) = cx.qpath_res(path, ty.hir_id) {
817 return match_def_path(cx, def_id, &DEPRECATED_LINT_TYPE);
824 fn collect_renames(lints: &mut Vec<LintMetadata>) {
826 let mut collected = String::new();
827 let mut names = vec![lint.id.clone()];
830 if let Some(lint_name) = names.pop() {
831 for (k, v) in RENAMED_LINTS {
833 if let Some(name) = v.strip_prefix(CLIPPY_LINT_GROUP_PREFIX);
834 if name == lint_name;
835 if let Some(past_name) = k.strip_prefix(CLIPPY_LINT_GROUP_PREFIX);
837 writeln!(collected, "* `{past_name}`").unwrap();
838 names.push(past_name.to_string());
849 if !collected.is_empty() {
863 // ==================================================================
865 // ==================================================================
866 fn lint_collection_error_item(cx: &LateContext<'_>, item: &Item<'_>, message: &str) {
869 INTERNAL_METADATA_COLLECTOR,
871 &format!("metadata collection error for `{}`: {message}", item.ident.name),
875 // ==================================================================
877 // ==================================================================
878 /// This function checks if a given expression is equal to a simple lint emission function call.
879 /// It will return the function arguments if the emission matched any function.
880 fn match_lint_emission<'hir>(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'_>) -> Option<&'hir [hir::Expr<'hir>]> {
881 LINT_EMISSION_FUNCTIONS
883 .find_map(|emission_fn| match_function_call(cx, expr, emission_fn))
886 fn take_higher_applicability(a: Option<usize>, b: Option<usize>) -> Option<usize> {
887 a.map_or(b, |a| a.max(b.unwrap_or_default()).into())
890 fn extract_emission_info<'hir>(
891 cx: &LateContext<'hir>,
892 args: &'hir [hir::Expr<'hir>],
893 ) -> Vec<(String, Option<usize>, bool)> {
894 let mut lints = Vec::new();
895 let mut applicability = None;
896 let mut multi_part = false;
899 let (arg_ty, _) = walk_ptrs_ty_depth(cx.typeck_results().expr_ty(arg));
901 if match_type(cx, arg_ty, &paths::LINT) {
902 // If we found the lint arg, extract the lint name
903 let mut resolved_lints = resolve_lints(cx, arg);
904 lints.append(&mut resolved_lints);
905 } else if match_type(cx, arg_ty, &paths::APPLICABILITY) {
906 applicability = resolve_applicability(cx, arg);
907 } else if arg_ty.is_closure() {
908 multi_part |= check_is_multi_part(cx, arg);
909 applicability = applicability.or_else(|| resolve_applicability(cx, arg));
915 .map(|lint_name| (lint_name, applicability, multi_part))
919 /// Resolves the possible lints that this expression could reference
920 fn resolve_lints<'hir>(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'hir>) -> Vec<String> {
921 let mut resolver = LintResolver::new(cx);
922 resolver.visit_expr(expr);
926 /// This function tries to resolve the linked applicability to the given expression.
927 fn resolve_applicability<'hir>(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'hir>) -> Option<usize> {
928 let mut resolver = ApplicabilityResolver::new(cx);
929 resolver.visit_expr(expr);
933 fn check_is_multi_part<'hir>(cx: &LateContext<'hir>, closure_expr: &'hir hir::Expr<'hir>) -> bool {
934 if let ExprKind::Closure(&Closure { body, .. }) = closure_expr.kind {
935 let mut scanner = IsMultiSpanScanner::new(cx);
936 intravisit::walk_body(&mut scanner, cx.tcx.hir().body(body));
937 return scanner.is_multi_part();
938 } else if let Some(local) = get_parent_local(cx, closure_expr) {
939 if let Some(local_init) = local.init {
940 return check_is_multi_part(cx, local_init);
947 struct LintResolver<'a, 'hir> {
948 cx: &'a LateContext<'hir>,
952 impl<'a, 'hir> LintResolver<'a, 'hir> {
953 fn new(cx: &'a LateContext<'hir>) -> Self {
956 lints: Vec::<String>::default(),
961 impl<'a, 'hir> intravisit::Visitor<'hir> for LintResolver<'a, 'hir> {
962 type NestedFilter = nested_filter::All;
964 fn nested_visit_map(&mut self) -> Self::Map {
968 fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) {
970 if let ExprKind::Path(qpath) = &expr.kind;
971 if let QPath::Resolved(_, path) = qpath;
973 let (expr_ty, _) = walk_ptrs_ty_depth(self.cx.typeck_results().expr_ty(expr));
974 if match_type(self.cx, expr_ty, &paths::LINT);
976 if let hir::def::Res::Def(DefKind::Static(..), _) = path.res {
977 let lint_name = last_path_segment(qpath).ident.name;
978 self.lints.push(sym_to_string(lint_name).to_ascii_lowercase());
979 } else if let Some(local) = get_parent_local(self.cx, expr) {
980 if let Some(local_init) = local.init {
981 intravisit::walk_expr(self, local_init);
987 intravisit::walk_expr(self, expr);
991 /// This visitor finds the highest applicability value in the visited expressions
992 struct ApplicabilityResolver<'a, 'hir> {
993 cx: &'a LateContext<'hir>,
994 /// This is the index of highest `Applicability` for `paths::APPLICABILITY_VALUES`
995 applicability_index: Option<usize>,
998 impl<'a, 'hir> ApplicabilityResolver<'a, 'hir> {
999 fn new(cx: &'a LateContext<'hir>) -> Self {
1002 applicability_index: None,
1006 fn add_new_index(&mut self, new_index: usize) {
1007 self.applicability_index = take_higher_applicability(self.applicability_index, Some(new_index));
1010 fn complete(self) -> Option<usize> {
1011 self.applicability_index
1015 impl<'a, 'hir> intravisit::Visitor<'hir> for ApplicabilityResolver<'a, 'hir> {
1016 type NestedFilter = nested_filter::All;
1018 fn nested_visit_map(&mut self) -> Self::Map {
1022 fn visit_path(&mut self, path: &hir::Path<'hir>, _id: hir::HirId) {
1023 for (index, enum_value) in paths::APPLICABILITY_VALUES.iter().enumerate() {
1024 if match_path(path, enum_value) {
1025 self.add_new_index(index);
1031 fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) {
1032 let (expr_ty, _) = walk_ptrs_ty_depth(self.cx.typeck_results().expr_ty(expr));
1035 if match_type(self.cx, expr_ty, &paths::APPLICABILITY);
1036 if let Some(local) = get_parent_local(self.cx, expr);
1037 if let Some(local_init) = local.init;
1039 intravisit::walk_expr(self, local_init);
1043 intravisit::walk_expr(self, expr);
1047 /// This returns the parent local node if the expression is a reference one
1048 fn get_parent_local<'hir>(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'hir>) -> Option<&'hir hir::Local<'hir>> {
1049 if let ExprKind::Path(QPath::Resolved(_, path)) = expr.kind {
1050 if let hir::def::Res::Local(local_hir) = path.res {
1051 return get_parent_local_hir_id(cx, local_hir);
1058 fn get_parent_local_hir_id<'hir>(cx: &LateContext<'hir>, hir_id: hir::HirId) -> Option<&'hir hir::Local<'hir>> {
1059 let map = cx.tcx.hir();
1061 match map.find_parent(hir_id) {
1062 Some(hir::Node::Local(local)) => Some(local),
1063 Some(hir::Node::Pat(pattern)) => get_parent_local_hir_id(cx, pattern.hir_id),
1068 /// This visitor finds the highest applicability value in the visited expressions
1069 struct IsMultiSpanScanner<'a, 'hir> {
1070 cx: &'a LateContext<'hir>,
1071 suggestion_count: usize,
1074 impl<'a, 'hir> IsMultiSpanScanner<'a, 'hir> {
1075 fn new(cx: &'a LateContext<'hir>) -> Self {
1078 suggestion_count: 0,
1082 /// Add a new single expression suggestion to the counter
1083 fn add_single_span_suggestion(&mut self) {
1084 self.suggestion_count += 1;
1087 /// Signals that a suggestion with possible multiple spans was found
1088 fn add_multi_part_suggestion(&mut self) {
1089 self.suggestion_count += 2;
1092 /// Checks if the suggestions include multiple spans
1093 fn is_multi_part(&self) -> bool {
1094 self.suggestion_count > 1
1098 impl<'a, 'hir> intravisit::Visitor<'hir> for IsMultiSpanScanner<'a, 'hir> {
1099 type NestedFilter = nested_filter::All;
1101 fn nested_visit_map(&mut self) -> Self::Map {
1105 fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) {
1106 // Early return if the lint is already multi span
1107 if self.is_multi_part() {
1112 ExprKind::Call(fn_expr, _args) => {
1113 let found_function = SUGGESTION_FUNCTIONS
1115 .any(|func_path| match_function_call(self.cx, fn_expr, func_path).is_some());
1117 // These functions are all multi part suggestions
1118 self.add_single_span_suggestion();
1121 ExprKind::MethodCall(path, recv, _, _arg_span) => {
1122 let (self_ty, _) = walk_ptrs_ty_depth(self.cx.typeck_results().expr_ty(recv));
1123 if match_type(self.cx, self_ty, &paths::DIAGNOSTIC_BUILDER) {
1124 let called_method = path.ident.name.as_str().to_string();
1125 for (method_name, is_multi_part) in &SUGGESTION_DIAGNOSTIC_BUILDER_METHODS {
1126 if *method_name == called_method {
1128 self.add_multi_part_suggestion();
1130 self.add_single_span_suggestion();
1140 intravisit::walk_expr(self, expr);