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 therefor the entire lint is guarded by a feature flag called
5 //! `metadata-collector-lint`
7 //! The module transforms all lint names to ascii lowercase to ensure that we don't have mismatches
8 //! during any comparison or mapping. (Please take care of this, it's not fun to spend time on such
11 use if_chain::if_chain;
13 use rustc_data_structures::fx::FxHashMap;
15 self as hir, def::DefKind, intravisit, intravisit::Visitor, ExprKind, Item, ItemKind, Mutability, QPath,
17 use rustc_lint::{CheckLintNameResult, LateContext, LateLintPass, LintContext, LintId};
18 use rustc_middle::hir::map::Map;
19 use rustc_session::{declare_tool_lint, impl_lint_pass};
20 use rustc_span::{sym, Loc, Span, Symbol};
21 use serde::{ser::SerializeStruct, Serialize, Serializer};
22 use std::collections::BinaryHeap;
24 use std::fs::{self, OpenOptions};
25 use std::io::prelude::*;
28 use crate::utils::internal_lints::is_lint_ref_type;
30 diagnostics::span_lint, last_path_segment, match_def_path, match_function_call, match_path, paths, ty::match_type,
31 ty::walk_ptrs_ty_depth,
34 /// This is the output file of the lint collector.
35 const OUTPUT_FILE: &str = "../util/gh-pages/lints.json";
36 /// These lints are excluded from the export.
37 const BLACK_LISTED_LINTS: [&str; 3] = ["lint_author", "deep_code_inspection", "internal_metadata_collector"];
38 /// These groups will be ignored by the lint group matcher. This is useful for collections like
40 const IGNORED_LINT_GROUPS: [&str; 1] = ["clippy::all"];
41 /// Lints within this group will be excluded from the collection. These groups
42 /// have to be defined without the `clippy::` prefix.
43 const EXCLUDED_LINT_GROUPS: [&str; 1] = ["internal"];
44 /// Collected deprecated lint will be assigned to this group in the JSON output
45 const DEPRECATED_LINT_GROUP_STR: &str = "deprecated";
46 /// This is the lint level for deprecated lints that will be displayed in the lint list
47 const DEPRECATED_LINT_LEVEL: &str = "none";
48 /// This array holds Clippy's lint groups with their corresponding default lint level. The
49 /// lint level for deprecated lints is set in `DEPRECATED_LINT_LEVEL`.
50 const DEFAULT_LINT_LEVELS: &[(&str, &str)] = &[
51 ("correctness", "deny"),
52 ("suspicious", "warn"),
53 ("restriction", "allow"),
55 ("pedantic", "allow"),
56 ("complexity", "warn"),
61 /// This prefix is in front of the lint groups in the lint store. The prefix will be trimmed
62 /// to only keep the actual lint group in the output.
63 const CLIPPY_LINT_GROUP_PREFIX: &str = "clippy::";
65 /// This template will be used to format the configuration section in the lint documentation.
66 /// The `configurations` parameter will be replaced with one or multiple formatted
67 /// `ClippyConfiguration` instances. See `CONFIGURATION_VALUE_TEMPLATE` for further customizations
68 macro_rules! CONFIGURATION_SECTION_TEMPLATE {
72 This lint has the following configuration variables:
78 /// This template will be used to format an individual `ClippyConfiguration` instance in the
79 /// lint documentation.
81 /// The format function will provide strings for the following parameters: `name`, `ty`, `doc` and
83 macro_rules! CONFIGURATION_VALUE_TEMPLATE {
85 "* `{name}`: `{ty}`: {doc} (defaults to `{default}`)\n"
89 const LINT_EMISSION_FUNCTIONS: [&[&str]; 7] = [
90 &["clippy_utils", "diagnostics", "span_lint"],
91 &["clippy_utils", "diagnostics", "span_lint_and_help"],
92 &["clippy_utils", "diagnostics", "span_lint_and_note"],
93 &["clippy_utils", "diagnostics", "span_lint_hir"],
94 &["clippy_utils", "diagnostics", "span_lint_and_sugg"],
95 &["clippy_utils", "diagnostics", "span_lint_and_then"],
96 &["clippy_utils", "diagnostics", "span_lint_hir_and_then"],
98 const SUGGESTION_DIAGNOSTIC_BUILDER_METHODS: [(&str, bool); 9] = [
99 ("span_suggestion", false),
100 ("span_suggestion_short", false),
101 ("span_suggestion_verbose", false),
102 ("span_suggestion_hidden", false),
103 ("tool_only_span_suggestion", false),
104 ("multipart_suggestion", true),
105 ("multipart_suggestions", true),
106 ("tool_only_multipart_suggestion", true),
107 ("span_suggestions", true),
109 const SUGGESTION_FUNCTIONS: [&[&str]; 2] = [
110 &["clippy_utils", "diagnostics", "multispan_sugg"],
111 &["clippy_utils", "diagnostics", "multispan_sugg_with_applicability"],
113 const DEPRECATED_LINT_TYPE: [&str; 3] = ["clippy_lints", "deprecated_lints", "ClippyDeprecatedLint"];
115 /// The index of the applicability name of `paths::APPLICABILITY_VALUES`
116 const APPLICABILITY_NAME_INDEX: usize = 2;
117 /// This applicability will be set for unresolved applicability values.
118 const APPLICABILITY_UNRESOLVED_STR: &str = "Unresolved";
120 declare_clippy_lint! {
122 /// Collects metadata about clippy lints for the website.
124 /// This lint will be used to report problems of syntax parsing. You should hopefully never
125 /// see this but never say never I guess ^^
127 /// ### Why is this bad?
128 /// This is not a bad thing but definitely a hacky way to do it. See
129 /// issue [#4310](https://github.com/rust-lang/rust-clippy/issues/4310) for a discussion
130 /// about the implementation.
132 /// ### Known problems
133 /// Hopefully none. It would be pretty uncool to have a problem here :)
135 /// ### Example output
138 /// "id": "internal_metadata_collector",
140 /// "path": "clippy_lints/src/utils/internal_lints/metadata_collector.rs",
143 /// "group": "clippy::internal",
144 /// "docs": " ### What it does\nCollects metadata about clippy lints for the website. [...] "
147 pub INTERNAL_METADATA_COLLECTOR,
149 "A busy bee collection metadata about lints"
152 impl_lint_pass!(MetadataCollector => [INTERNAL_METADATA_COLLECTOR]);
154 #[allow(clippy::module_name_repetitions)]
155 #[derive(Debug, Clone)]
156 pub struct MetadataCollector {
157 /// All collected lints
159 /// We use a Heap here to have the lints added in alphabetic order in the export
160 lints: BinaryHeap<LintMetadata>,
161 applicability_info: FxHashMap<String, ApplicabilityInfo>,
162 config: Vec<ClippyConfiguration>,
165 impl MetadataCollector {
166 pub fn new() -> Self {
168 lints: BinaryHeap::<LintMetadata>::default(),
169 applicability_info: FxHashMap::<String, ApplicabilityInfo>::default(),
170 config: collect_configs(),
174 fn get_lint_configs(&self, lint_name: &str) -> Option<String> {
177 .filter(|config| config.lints.iter().any(|lint| lint == lint_name))
178 .map(ToString::to_string)
179 .reduce(|acc, x| acc + &x)
180 .map(|configurations| format!(CONFIGURATION_SECTION_TEMPLATE!(), configurations = configurations))
184 impl Drop for MetadataCollector {
185 /// You might ask: How hacky is this?
188 // The metadata collector gets dropped twice, this makes sure that we only write
189 // when the list is full
190 if self.lints.is_empty() {
194 let mut applicability_info = std::mem::take(&mut self.applicability_info);
196 // Mapping the final data
197 let mut lints = std::mem::take(&mut self.lints).into_sorted_vec();
200 .for_each(|x| x.applicability = Some(applicability_info.remove(&x.id).unwrap_or_default()));
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,
218 /// This field is only used in the output and will only be
219 /// mapped shortly before the actual output.
220 applicability: Option<ApplicabilityInfo>,
224 fn new(id: String, id_span: SerializableSpan, group: String, level: &'static str, docs: String) -> Self {
229 level: level.to_string(),
236 #[derive(Debug, Clone, Serialize, PartialEq, Eq, PartialOrd, Ord)]
237 struct SerializableSpan {
242 impl std::fmt::Display for SerializableSpan {
243 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
244 write!(f, "{}:{}", self.path.rsplit('/').next().unwrap_or_default(), self.line)
248 impl SerializableSpan {
249 fn from_item(cx: &LateContext<'_>, item: &Item<'_>) -> Self {
250 Self::from_span(cx, item.ident.span)
253 fn from_span(cx: &LateContext<'_>, span: Span) -> Self {
254 let loc: Loc = cx.sess().source_map().lookup_char_pos(span.lo());
257 path: format!("{}", loc.file.name.prefer_remapped()),
263 #[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
264 struct ApplicabilityInfo {
265 /// Indicates if any of the lint emissions uses multiple spans. This is related to
266 /// [rustfix#141](https://github.com/rust-lang/rustfix/issues/141) as such suggestions can
267 /// currently not be applied automatically.
268 is_multi_part_suggestion: bool,
269 applicability: Option<usize>,
272 impl Serialize for ApplicabilityInfo {
273 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
277 let mut s = serializer.serialize_struct("ApplicabilityInfo", 2)?;
278 s.serialize_field("is_multi_part_suggestion", &self.is_multi_part_suggestion)?;
279 if let Some(index) = self.applicability {
282 &paths::APPLICABILITY_VALUES[index][APPLICABILITY_NAME_INDEX],
285 s.serialize_field("applicability", APPLICABILITY_UNRESOLVED_STR)?;
291 // ==================================================================
293 // ==================================================================
294 #[derive(Debug, Clone, Default)]
295 pub struct ClippyConfiguration {
297 config_type: &'static str,
302 deprecation_reason: Option<&'static str>,
305 impl ClippyConfiguration {
308 config_type: &'static str,
310 doc_comment: &'static str,
311 deprecation_reason: Option<&'static str>,
313 let (lints, doc) = parse_config_field_doc(doc_comment)
314 .unwrap_or_else(|| (vec![], "[ERROR] MALFORMED DOC COMMENT".to_string()));
317 name: to_kebab(name),
327 fn collect_configs() -> Vec<ClippyConfiguration> {
328 crate::utils::conf::metadata::get_configuration_metadata()
331 /// This parses the field documentation of the config struct.
334 /// parse_config_field_doc(cx, "Lint: LINT_NAME_1, LINT_NAME_2. Papa penguin, papa penguin")
339 /// Some(["lint_name_1", "lint_name_2"], "Papa penguin, papa penguin")
341 fn parse_config_field_doc(doc_comment: &str) -> Option<(Vec<String>, String)> {
342 const DOC_START: &str = " Lint: ";
344 if doc_comment.starts_with(DOC_START);
345 if let Some(split_pos) = doc_comment.find('.');
347 let mut doc_comment = doc_comment.to_string();
348 let mut documentation = doc_comment.split_off(split_pos);
351 doc_comment.make_ascii_lowercase();
352 let lints: Vec<String> = doc_comment.split_off(DOC_START.len()).split(", ").map(str::to_string).collect();
354 // Format documentation correctly
355 // split off leading `.` from lint name list and indent for correct formatting
356 documentation = documentation.trim_start_matches('.').trim().replace("\n ", "\n ");
358 Some((lints, documentation))
365 /// Transforms a given `snake_case_string` to a tasty `kebab-case-string`
366 fn to_kebab(config_name: &str) -> String {
367 config_name.replace('_', "-")
370 impl fmt::Display for ClippyConfiguration {
371 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
374 CONFIGURATION_VALUE_TEMPLATE!(),
376 ty = self.config_type,
378 default = self.default
383 // ==================================================================
385 // ==================================================================
386 impl<'hir> LateLintPass<'hir> for MetadataCollector {
387 /// Collecting lint declarations like:
389 /// declare_clippy_lint! {
390 /// /// ### What it does
391 /// /// Something IDK.
397 fn check_item(&mut self, cx: &LateContext<'hir>, item: &'hir Item<'_>) {
398 if let ItemKind::Static(ty, Mutability::Not, _) = item.kind {
402 if is_lint_ref_type(cx, ty);
404 let lint_name = sym_to_string(item.ident.name).to_ascii_lowercase();
405 if !BLACK_LISTED_LINTS.contains(&lint_name.as_str());
406 // metadata extraction
407 if let Some((group, level)) = get_lint_group_and_level_or_lint(cx, &lint_name, item);
408 if let Some(mut docs) = extract_attr_docs_or_lint(cx, item);
410 if let Some(configuration_section) = self.get_lint_configs(&lint_name) {
411 docs.push_str(&configuration_section);
414 self.lints.push(LintMetadata::new(
416 SerializableSpan::from_item(cx, item),
425 if is_deprecated_lint(cx, ty);
427 let lint_name = sym_to_string(item.ident.name).to_ascii_lowercase();
428 if !BLACK_LISTED_LINTS.contains(&lint_name.as_str());
429 // Metadata the little we can get from a deprecated lint
430 if let Some(docs) = extract_attr_docs_or_lint(cx, item);
432 self.lints.push(LintMetadata::new(
434 SerializableSpan::from_item(cx, item),
435 DEPRECATED_LINT_GROUP_STR.to_string(),
436 DEPRECATED_LINT_LEVEL,
444 /// Collecting constant applicability from the actual lint emissions
448 /// span_lint_and_sugg(
452 /// "Le lint message",
453 /// "Here comes help:",
454 /// "#![allow(clippy::all)]",
455 /// Applicability::MachineApplicable, // <-- Extracts this constant value
458 fn check_expr(&mut self, cx: &LateContext<'hir>, expr: &'hir hir::Expr<'_>) {
459 if let Some(args) = match_lint_emission(cx, expr) {
460 let mut emission_info = extract_emission_info(cx, args);
461 if emission_info.is_empty() {
463 // - src/misc.rs:734:9
464 // - src/methods/mod.rs:3545:13
465 // - src/methods/mod.rs:3496:13
466 // We are basically unable to resolve the lint name itself.
470 for (lint_name, applicability, is_multi_part) in emission_info.drain(..) {
471 let app_info = self.applicability_info.entry(lint_name).or_default();
472 app_info.applicability = applicability;
473 app_info.is_multi_part_suggestion = is_multi_part;
479 // ==================================================================
480 // Lint definition extraction
481 // ==================================================================
482 fn sym_to_string(sym: Symbol) -> String {
483 sym.as_str().to_string()
486 fn extract_attr_docs_or_lint(cx: &LateContext<'_>, item: &Item<'_>) -> Option<String> {
487 extract_attr_docs(cx, item).or_else(|| {
488 lint_collection_error_item(cx, item, "could not collect the lint documentation");
493 /// This function collects all documentation that has been added to an item using
494 /// `#[doc = r""]` attributes. Several attributes are aggravated using line breaks
497 /// #[doc = r"Hello world!"]
498 /// #[doc = r"=^.^="]
499 /// struct SomeItem {}
502 /// Would result in `Hello world!\n=^.^=\n`
506 /// This function may modify the doc comment to ensure that the string can be displayed using a
507 /// markdown viewer in Clippy's lint list. The following modifications could be applied:
508 /// * Removal of leading space after a new line. (Important to display tables)
509 /// * Ensures that code blocks only contain language information
510 fn extract_attr_docs(cx: &LateContext<'_>, item: &Item<'_>) -> Option<String> {
511 let attrs = cx.tcx.hir().attrs(item.hir_id());
512 let mut lines = attrs.iter().filter_map(ast::Attribute::doc_str);
513 let mut docs = String::from(&*lines.next()?.as_str());
514 let mut in_code_block = false;
515 let mut is_code_block_rust = false;
517 let line = line.as_str();
520 // Rustdoc hides code lines starting with `# ` and this removes them from Clippy's lint list :)
521 if is_code_block_rust && line.trim_start().starts_with("# ") {
525 // The line should be represented in the lint list, even if it's just an empty line
527 if let Some(info) = line.trim_start().strip_prefix("```") {
528 in_code_block = !in_code_block;
529 is_code_block_rust = false;
534 // remove rustdoc directives
535 .find(|&s| !matches!(s, "" | "ignore" | "no_run" | "should_panic"))
536 // if no language is present, fill in "rust"
538 docs.push_str("```");
541 is_code_block_rust = lang == "rust";
545 // This removes the leading space that the macro translation introduces
546 if let Some(stripped_doc) = line.strip_prefix(' ') {
547 docs.push_str(stripped_doc);
548 } else if !line.is_empty() {
555 fn get_lint_group_and_level_or_lint(
556 cx: &LateContext<'_>,
558 item: &'hir Item<'_>,
559 ) -> Option<(String, &'static str)> {
562 .check_lint_name(cx.sess(), lint_name, Some(sym::clippy), &[]);
563 if let CheckLintNameResult::Tool(Ok(lint_lst)) = result {
564 if let Some(group) = get_lint_group(cx, lint_lst[0]) {
565 if EXCLUDED_LINT_GROUPS.contains(&group.as_str()) {
569 if let Some(level) = get_lint_level_from_group(&group) {
572 lint_collection_error_item(
575 &format!("Unable to determine lint level for found group `{}`", group),
580 lint_collection_error_item(cx, item, "Unable to determine lint group");
584 lint_collection_error_item(cx, item, "Unable to find lint in lint_store");
589 fn get_lint_group(cx: &LateContext<'_>, lint_id: LintId) -> Option<String> {
590 for (group_name, lints, _) in &cx.lint_store.get_lint_groups() {
591 if IGNORED_LINT_GROUPS.contains(group_name) {
595 if lints.iter().any(|group_lint| *group_lint == lint_id) {
596 let group = group_name.strip_prefix(CLIPPY_LINT_GROUP_PREFIX).unwrap_or(group_name);
597 return Some((*group).to_string());
604 fn get_lint_level_from_group(lint_group: &str) -> Option<&'static str> {
607 .find_map(|(group_name, group_level)| (*group_name == lint_group).then(|| *group_level))
610 fn is_deprecated_lint(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> bool {
611 if let hir::TyKind::Path(ref path) = ty.kind {
612 if let hir::def::Res::Def(DefKind::Struct, def_id) = cx.qpath_res(path, ty.hir_id) {
613 return match_def_path(cx, def_id, &DEPRECATED_LINT_TYPE);
620 // ==================================================================
622 // ==================================================================
623 fn lint_collection_error_item(cx: &LateContext<'_>, item: &Item<'_>, message: &str) {
626 INTERNAL_METADATA_COLLECTOR,
628 &format!("metadata collection error for `{}`: {}", item.ident.name, message),
632 // ==================================================================
634 // ==================================================================
635 /// This function checks if a given expression is equal to a simple lint emission function call.
636 /// It will return the function arguments if the emission matched any function.
637 fn match_lint_emission<'hir>(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'_>) -> Option<&'hir [hir::Expr<'hir>]> {
638 LINT_EMISSION_FUNCTIONS
640 .find_map(|emission_fn| match_function_call(cx, expr, emission_fn))
643 fn take_higher_applicability(a: Option<usize>, b: Option<usize>) -> Option<usize> {
644 a.map_or(b, |a| a.max(b.unwrap_or_default()).into())
647 fn extract_emission_info<'hir>(
648 cx: &LateContext<'hir>,
649 args: &'hir [hir::Expr<'hir>],
650 ) -> Vec<(String, Option<usize>, bool)> {
651 let mut lints = Vec::new();
652 let mut applicability = None;
653 let mut multi_part = false;
656 let (arg_ty, _) = walk_ptrs_ty_depth(cx.typeck_results().expr_ty(arg));
658 if match_type(cx, arg_ty, &paths::LINT) {
659 // If we found the lint arg, extract the lint name
660 let mut resolved_lints = resolve_lints(cx, arg);
661 lints.append(&mut resolved_lints);
662 } else if match_type(cx, arg_ty, &paths::APPLICABILITY) {
663 applicability = resolve_applicability(cx, arg);
664 } else if arg_ty.is_closure() {
665 multi_part |= check_is_multi_part(cx, arg);
666 // TODO xFrednet 2021-03-01: don't use or_else but rather a comparison
667 applicability = applicability.or_else(|| resolve_applicability(cx, arg));
673 .map(|lint_name| (lint_name, applicability, multi_part))
677 /// Resolves the possible lints that this expression could reference
678 fn resolve_lints(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'hir>) -> Vec<String> {
679 let mut resolver = LintResolver::new(cx);
680 resolver.visit_expr(expr);
684 /// This function tries to resolve the linked applicability to the given expression.
685 fn resolve_applicability(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'hir>) -> Option<usize> {
686 let mut resolver = ApplicabilityResolver::new(cx);
687 resolver.visit_expr(expr);
691 fn check_is_multi_part(cx: &LateContext<'hir>, closure_expr: &'hir hir::Expr<'hir>) -> bool {
692 if let ExprKind::Closure(_, _, body_id, _, _) = closure_expr.kind {
693 let mut scanner = IsMultiSpanScanner::new(cx);
694 intravisit::walk_body(&mut scanner, cx.tcx.hir().body(body_id));
695 return scanner.is_multi_part();
696 } else if let Some(local) = get_parent_local(cx, closure_expr) {
697 if let Some(local_init) = local.init {
698 return check_is_multi_part(cx, local_init);
705 struct LintResolver<'a, 'hir> {
706 cx: &'a LateContext<'hir>,
710 impl<'a, 'hir> LintResolver<'a, 'hir> {
711 fn new(cx: &'a LateContext<'hir>) -> Self {
714 lints: Vec::<String>::default(),
719 impl<'a, 'hir> intravisit::Visitor<'hir> for LintResolver<'a, 'hir> {
720 type Map = Map<'hir>;
722 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
723 intravisit::NestedVisitorMap::All(self.cx.tcx.hir())
726 fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) {
728 if let ExprKind::Path(qpath) = &expr.kind;
729 if let QPath::Resolved(_, path) = qpath;
731 let (expr_ty, _) = walk_ptrs_ty_depth(self.cx.typeck_results().expr_ty(expr));
732 if match_type(self.cx, expr_ty, &paths::LINT);
734 if let hir::def::Res::Def(DefKind::Static, _) = path.res {
735 let lint_name = last_path_segment(qpath).ident.name;
736 self.lints.push(sym_to_string(lint_name).to_ascii_lowercase());
737 } else if let Some(local) = get_parent_local(self.cx, expr) {
738 if let Some(local_init) = local.init {
739 intravisit::walk_expr(self, local_init);
745 intravisit::walk_expr(self, expr);
749 /// This visitor finds the highest applicability value in the visited expressions
750 struct ApplicabilityResolver<'a, 'hir> {
751 cx: &'a LateContext<'hir>,
752 /// This is the index of hightest `Applicability` for `paths::APPLICABILITY_VALUES`
753 applicability_index: Option<usize>,
756 impl<'a, 'hir> ApplicabilityResolver<'a, 'hir> {
757 fn new(cx: &'a LateContext<'hir>) -> Self {
760 applicability_index: None,
764 fn add_new_index(&mut self, new_index: usize) {
765 self.applicability_index = take_higher_applicability(self.applicability_index, Some(new_index));
768 fn complete(self) -> Option<usize> {
769 self.applicability_index
773 impl<'a, 'hir> intravisit::Visitor<'hir> for ApplicabilityResolver<'a, 'hir> {
774 type Map = Map<'hir>;
776 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
777 intravisit::NestedVisitorMap::All(self.cx.tcx.hir())
780 fn visit_path(&mut self, path: &'hir hir::Path<'hir>, _id: hir::HirId) {
781 for (index, enum_value) in paths::APPLICABILITY_VALUES.iter().enumerate() {
782 if match_path(path, enum_value) {
783 self.add_new_index(index);
789 fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) {
790 let (expr_ty, _) = walk_ptrs_ty_depth(self.cx.typeck_results().expr_ty(expr));
793 if match_type(self.cx, expr_ty, &paths::APPLICABILITY);
794 if let Some(local) = get_parent_local(self.cx, expr);
795 if let Some(local_init) = local.init;
797 intravisit::walk_expr(self, local_init);
801 intravisit::walk_expr(self, expr);
805 /// This returns the parent local node if the expression is a reference one
806 fn get_parent_local(cx: &LateContext<'hir>, expr: &'hir hir::Expr<'hir>) -> Option<&'hir hir::Local<'hir>> {
807 if let ExprKind::Path(QPath::Resolved(_, path)) = expr.kind {
808 if let hir::def::Res::Local(local_hir) = path.res {
809 return get_parent_local_hir_id(cx, local_hir);
816 fn get_parent_local_hir_id(cx: &LateContext<'hir>, hir_id: hir::HirId) -> Option<&'hir hir::Local<'hir>> {
817 let map = cx.tcx.hir();
819 match map.find(map.get_parent_node(hir_id)) {
820 Some(hir::Node::Local(local)) => Some(local),
821 Some(hir::Node::Pat(pattern)) => get_parent_local_hir_id(cx, pattern.hir_id),
826 /// This visitor finds the highest applicability value in the visited expressions
827 struct IsMultiSpanScanner<'a, 'hir> {
828 cx: &'a LateContext<'hir>,
829 suggestion_count: usize,
832 impl<'a, 'hir> IsMultiSpanScanner<'a, 'hir> {
833 fn new(cx: &'a LateContext<'hir>) -> Self {
840 /// Add a new single expression suggestion to the counter
841 fn add_single_span_suggestion(&mut self) {
842 self.suggestion_count += 1;
845 /// Signals that a suggestion with possible multiple spans was found
846 fn add_multi_part_suggestion(&mut self) {
847 self.suggestion_count += 2;
850 /// Checks if the suggestions include multiple spanns
851 fn is_multi_part(&self) -> bool {
852 self.suggestion_count > 1
856 impl<'a, 'hir> intravisit::Visitor<'hir> for IsMultiSpanScanner<'a, 'hir> {
857 type Map = Map<'hir>;
859 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
860 intravisit::NestedVisitorMap::All(self.cx.tcx.hir())
863 fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) {
864 // Early return if the lint is already multi span
865 if self.is_multi_part() {
870 ExprKind::Call(fn_expr, _args) => {
871 let found_function = SUGGESTION_FUNCTIONS
873 .any(|func_path| match_function_call(self.cx, fn_expr, func_path).is_some());
875 // These functions are all multi part suggestions
876 self.add_single_span_suggestion();
879 ExprKind::MethodCall(path, _path_span, arg, _arg_span) => {
880 let (self_ty, _) = walk_ptrs_ty_depth(self.cx.typeck_results().expr_ty(&arg[0]));
881 if match_type(self.cx, self_ty, &paths::DIAGNOSTIC_BUILDER) {
882 let called_method = path.ident.name.as_str().to_string();
883 for (method_name, is_multi_part) in &SUGGESTION_DIAGNOSTIC_BUILDER_METHODS {
884 if *method_name == called_method {
886 self.add_multi_part_suggestion();
888 self.add_single_span_suggestion();
898 intravisit::walk_expr(self, expr);