rustc_lint/early/
diagnostics.rs

1use std::borrow::Cow;
2
3use rustc_ast::util::unicode::TEXT_FLOW_CONTROL_CHARS;
4use rustc_errors::{
5    Applicability, Diag, DiagArgValue, LintDiagnostic, elided_lifetime_in_path_suggestion,
6};
7use rustc_middle::middle::stability;
8use rustc_middle::ty::TyCtxt;
9use rustc_session::Session;
10use rustc_session::lint::BuiltinLintDiag;
11use rustc_span::BytePos;
12use tracing::debug;
13
14use crate::lints;
15
16mod check_cfg;
17
18pub fn decorate_builtin_lint(
19    sess: &Session,
20    tcx: Option<TyCtxt<'_>>,
21    diagnostic: BuiltinLintDiag,
22    diag: &mut Diag<'_, ()>,
23) {
24    match diagnostic {
25        BuiltinLintDiag::UnicodeTextFlow(comment_span, content) => {
26            let spans: Vec<_> = content
27                .char_indices()
28                .filter_map(|(i, c)| {
29                    TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| {
30                        let lo = comment_span.lo() + BytePos(2 + i as u32);
31                        (c, comment_span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32)))
32                    })
33                })
34                .collect();
35            let characters = spans
36                .iter()
37                .map(|&(c, span)| lints::UnicodeCharNoteSub { span, c_debug: format!("{c:?}") })
38                .collect();
39            let suggestions = (!spans.is_empty()).then_some(lints::UnicodeTextFlowSuggestion {
40                spans: spans.iter().map(|(_c, span)| *span).collect(),
41            });
42
43            lints::UnicodeTextFlow {
44                comment_span,
45                characters,
46                suggestions,
47                num_codepoints: spans.len(),
48            }
49            .decorate_lint(diag);
50        }
51        BuiltinLintDiag::AbsPathWithModule(mod_span) => {
52            let (replacement, applicability) = match sess.source_map().span_to_snippet(mod_span) {
53                Ok(ref s) => {
54                    // FIXME(Manishearth) ideally the emitting code
55                    // can tell us whether or not this is global
56                    let opt_colon = if s.trim_start().starts_with("::") { "" } else { "::" };
57
58                    (format!("crate{opt_colon}{s}"), Applicability::MachineApplicable)
59                }
60                Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
61            };
62            lints::AbsPathWithModule {
63                sugg: lints::AbsPathWithModuleSugg { span: mod_span, applicability, replacement },
64            }
65            .decorate_lint(diag);
66        }
67        BuiltinLintDiag::ProcMacroDeriveResolutionFallback { span: macro_span, ns, ident } => {
68            lints::ProcMacroDeriveResolutionFallback { span: macro_span, ns, ident }
69                .decorate_lint(diag)
70        }
71        BuiltinLintDiag::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def) => {
72            lints::MacroExpandedMacroExportsAccessedByAbsolutePaths { definition: span_def }
73                .decorate_lint(diag)
74        }
75
76        BuiltinLintDiag::ElidedLifetimesInPaths(n, path_span, incl_angl_brckt, insertion_span) => {
77            lints::ElidedLifetimesInPaths {
78                subdiag: elided_lifetime_in_path_suggestion(
79                    sess.source_map(),
80                    n,
81                    path_span,
82                    incl_angl_brckt,
83                    insertion_span,
84                ),
85            }
86            .decorate_lint(diag);
87        }
88        BuiltinLintDiag::UnknownCrateTypes { span, candidate } => {
89            let sugg = candidate.map(|candidate| lints::UnknownCrateTypesSub { span, candidate });
90            lints::UnknownCrateTypes { sugg }.decorate_lint(diag);
91        }
92        BuiltinLintDiag::UnusedImports {
93            remove_whole_use,
94            num_to_remove,
95            remove_spans,
96            test_module_span,
97            span_snippets,
98        } => {
99            let sugg = if remove_whole_use {
100                lints::UnusedImportsSugg::RemoveWholeUse { span: remove_spans[0] }
101            } else {
102                lints::UnusedImportsSugg::RemoveImports { remove_spans, num_to_remove }
103            };
104            let test_module_span =
105                test_module_span.map(|span| sess.source_map().guess_head_span(span));
106
107            lints::UnusedImports {
108                sugg,
109                test_module_span,
110                num_snippets: span_snippets.len(),
111                span_snippets: DiagArgValue::StrListSepByAnd(
112                    span_snippets.into_iter().map(Cow::Owned).collect(),
113                ),
114            }
115            .decorate_lint(diag);
116        }
117        BuiltinLintDiag::RedundantImport(spans, ident) => {
118            let subs = spans
119                .into_iter()
120                .map(|(span, is_imported)| {
121                    (match (span.is_dummy(), is_imported) {
122                        (false, true) => lints::RedundantImportSub::ImportedHere,
123                        (false, false) => lints::RedundantImportSub::DefinedHere,
124                        (true, true) => lints::RedundantImportSub::ImportedPrelude,
125                        (true, false) => lints::RedundantImportSub::DefinedPrelude,
126                    })(span)
127                })
128                .collect();
129            lints::RedundantImport { subs, ident }.decorate_lint(diag);
130        }
131        BuiltinLintDiag::DeprecatedMacro {
132            suggestion,
133            suggestion_span,
134            note,
135            path,
136            since_kind,
137        } => {
138            let sub = suggestion.map(|suggestion| stability::DeprecationSuggestion {
139                span: suggestion_span,
140                kind: "macro".to_owned(),
141                suggestion,
142            });
143
144            stability::Deprecated { sub, kind: "macro".to_owned(), path, note, since_kind }
145                .decorate_lint(diag);
146        }
147        BuiltinLintDiag::UnusedDocComment(attr_span) => {
148            lints::UnusedDocComment { span: attr_span }.decorate_lint(diag);
149        }
150        BuiltinLintDiag::PatternsInFnsWithoutBody { span: remove_span, ident, is_foreign } => {
151            let sub = lints::PatternsInFnsWithoutBodySub { ident, span: remove_span };
152            if is_foreign {
153                lints::PatternsInFnsWithoutBody::Foreign { sub }
154            } else {
155                lints::PatternsInFnsWithoutBody::Bodiless { sub }
156            }
157            .decorate_lint(diag);
158        }
159        BuiltinLintDiag::MissingAbi(label_span, default_abi) => {
160            lints::MissingAbi { span: label_span, default_abi }.decorate_lint(diag);
161        }
162        BuiltinLintDiag::LegacyDeriveHelpers(label_span) => {
163            lints::LegacyDeriveHelpers { span: label_span }.decorate_lint(diag);
164        }
165        BuiltinLintDiag::OrPatternsBackCompat(suggestion_span, suggestion) => {
166            lints::OrPatternsBackCompat { span: suggestion_span, suggestion }.decorate_lint(diag);
167        }
168        BuiltinLintDiag::ReservedPrefix(label_span, prefix) => {
169            lints::ReservedPrefix {
170                label: label_span,
171                suggestion: label_span.shrink_to_hi(),
172                prefix,
173            }
174            .decorate_lint(diag);
175        }
176        BuiltinLintDiag::RawPrefix(label_span) => {
177            lints::RawPrefix { label: label_span, suggestion: label_span.shrink_to_hi() }
178                .decorate_lint(diag);
179        }
180        BuiltinLintDiag::ReservedString { is_string, suggestion } => {
181            if is_string {
182                lints::ReservedString { suggestion }.decorate_lint(diag);
183            } else {
184                lints::ReservedMultihash { suggestion }.decorate_lint(diag);
185            }
186        }
187        BuiltinLintDiag::HiddenUnicodeCodepoints {
188            label,
189            count,
190            span_label,
191            labels,
192            escape,
193            spans,
194        } => {
195            lints::HiddenUnicodeCodepointsDiag {
196                label: &label,
197                count,
198                span_label,
199                labels: labels.map(|spans| lints::HiddenUnicodeCodepointsDiagLabels { spans }),
200                sub: if escape {
201                    lints::HiddenUnicodeCodepointsDiagSub::Escape { spans }
202                } else {
203                    lints::HiddenUnicodeCodepointsDiagSub::NoEscape { spans }
204                },
205            }
206            .decorate_lint(diag);
207        }
208        BuiltinLintDiag::UnusedBuiltinAttribute { attr_name, macro_name, invoc_span } => {
209            lints::UnusedBuiltinAttribute { invoc_span, attr_name, macro_name }.decorate_lint(diag);
210        }
211        BuiltinLintDiag::TrailingMacro(is_trailing, name) => {
212            lints::TrailingMacro { is_trailing, name }.decorate_lint(diag);
213        }
214        BuiltinLintDiag::BreakWithLabelAndLoop(sugg_span) => {
215            lints::BreakWithLabelAndLoop {
216                sub: lints::BreakWithLabelAndLoopSub {
217                    left: sugg_span.shrink_to_lo(),
218                    right: sugg_span.shrink_to_hi(),
219                },
220            }
221            .decorate_lint(diag);
222        }
223        BuiltinLintDiag::UnexpectedCfgName(name, value) => {
224            check_cfg::unexpected_cfg_name(sess, tcx, name, value).decorate_lint(diag);
225        }
226        BuiltinLintDiag::UnexpectedCfgValue(name, value) => {
227            check_cfg::unexpected_cfg_value(sess, tcx, name, value).decorate_lint(diag);
228        }
229        BuiltinLintDiag::DeprecatedWhereclauseLocation(left_sp, sugg) => {
230            let suggestion = match sugg {
231                Some((right_sp, sugg)) => lints::DeprecatedWhereClauseLocationSugg::MoveToEnd {
232                    left: left_sp,
233                    right: right_sp,
234                    sugg,
235                },
236                None => lints::DeprecatedWhereClauseLocationSugg::RemoveWhere { span: left_sp },
237            };
238            lints::DeprecatedWhereClauseLocation { suggestion }.decorate_lint(diag);
239        }
240        BuiltinLintDiag::MissingUnsafeOnExtern { suggestion } => {
241            lints::MissingUnsafeOnExtern { suggestion }.decorate_lint(diag);
242        }
243        BuiltinLintDiag::SingleUseLifetime {
244            param_span,
245            use_span: Some((use_span, elide)),
246            deletion_span,
247            ident,
248        } => {
249            debug!(?param_span, ?use_span, ?deletion_span);
250            let suggestion = if let Some(deletion_span) = deletion_span {
251                let (use_span, replace_lt) = if elide {
252                    let use_span = sess.source_map().span_extend_while_whitespace(use_span);
253                    (use_span, String::new())
254                } else {
255                    (use_span, "'_".to_owned())
256                };
257                debug!(?deletion_span, ?use_span);
258
259                // issue 107998 for the case such as a wrong function pointer type
260                // `deletion_span` is empty and there is no need to report lifetime uses here
261                let deletion_span =
262                    if deletion_span.is_empty() { None } else { Some(deletion_span) };
263                Some(lints::SingleUseLifetimeSugg { deletion_span, use_span, replace_lt })
264            } else {
265                None
266            };
267
268            lints::SingleUseLifetime { suggestion, param_span, use_span, ident }
269                .decorate_lint(diag);
270        }
271        BuiltinLintDiag::SingleUseLifetime { use_span: None, deletion_span, ident, .. } => {
272            debug!(?deletion_span);
273            lints::UnusedLifetime { deletion_span, ident }.decorate_lint(diag);
274        }
275        BuiltinLintDiag::NamedArgumentUsedPositionally {
276            position_sp_to_replace,
277            position_sp_for_msg,
278            named_arg_sp,
279            named_arg_name,
280            is_formatting_arg,
281        } => {
282            let (suggestion, name) = if let Some(positional_arg_to_replace) = position_sp_to_replace
283            {
284                let mut name = named_arg_name.clone();
285                if is_formatting_arg {
286                    name.push('$')
287                };
288                let span_to_replace = if let Ok(positional_arg_content) =
289                    sess.source_map().span_to_snippet(positional_arg_to_replace)
290                    && positional_arg_content.starts_with(':')
291                {
292                    positional_arg_to_replace.shrink_to_lo()
293                } else {
294                    positional_arg_to_replace
295                };
296                (Some(span_to_replace), name)
297            } else {
298                (None, String::new())
299            };
300
301            lints::NamedArgumentUsedPositionally {
302                named_arg_sp,
303                position_label_sp: position_sp_for_msg,
304                suggestion,
305                name,
306                named_arg_name,
307            }
308            .decorate_lint(diag);
309        }
310        BuiltinLintDiag::ByteSliceInPackedStructWithDerive { ty } => {
311            lints::ByteSliceInPackedStructWithDerive { ty }.decorate_lint(diag);
312        }
313        BuiltinLintDiag::UnusedExternCrate { span, removal_span } => {
314            lints::UnusedExternCrate { span, removal_span }.decorate_lint(diag);
315        }
316        BuiltinLintDiag::ExternCrateNotIdiomatic { vis_span, ident_span } => {
317            let suggestion_span = vis_span.between(ident_span);
318            let code = if vis_span.is_empty() { "use " } else { " use " };
319
320            lints::ExternCrateNotIdiomatic { span: suggestion_span, code }.decorate_lint(diag);
321        }
322        BuiltinLintDiag::AmbiguousGlobImports { diag: ambiguity } => {
323            lints::AmbiguousGlobImports { ambiguity }.decorate_lint(diag);
324        }
325        BuiltinLintDiag::AmbiguousGlobReexports {
326            name,
327            namespace,
328            first_reexport_span,
329            duplicate_reexport_span,
330        } => {
331            lints::AmbiguousGlobReexports {
332                first_reexport: first_reexport_span,
333                duplicate_reexport: duplicate_reexport_span,
334                name,
335                namespace,
336            }
337            .decorate_lint(diag);
338        }
339        BuiltinLintDiag::HiddenGlobReexports {
340            name,
341            namespace,
342            glob_reexport_span,
343            private_item_span,
344        } => {
345            lints::HiddenGlobReexports {
346                glob_reexport: glob_reexport_span,
347                private_item: private_item_span,
348
349                name,
350                namespace,
351            }
352            .decorate_lint(diag);
353        }
354        BuiltinLintDiag::UnusedQualifications { removal_span } => {
355            lints::UnusedQualifications { removal_span }.decorate_lint(diag);
356        }
357        BuiltinLintDiag::UnsafeAttrOutsideUnsafe {
358            attribute_name_span,
359            sugg_spans: (left, right),
360        } => {
361            lints::UnsafeAttrOutsideUnsafe {
362                span: attribute_name_span,
363                suggestion: lints::UnsafeAttrOutsideUnsafeSuggestion { left, right },
364            }
365            .decorate_lint(diag);
366        }
367        BuiltinLintDiag::AssociatedConstElidedLifetime {
368            elided,
369            span: lt_span,
370            lifetimes_in_scope,
371        } => {
372            let lt_span = if elided { lt_span.shrink_to_hi() } else { lt_span };
373            let code = if elided { "'static " } else { "'static" };
374            lints::AssociatedConstElidedLifetime {
375                span: lt_span,
376                code,
377                elided,
378                lifetimes_in_scope,
379            }
380            .decorate_lint(diag);
381        }
382        BuiltinLintDiag::RedundantImportVisibility { max_vis, span: vis_span, import_vis } => {
383            lints::RedundantImportVisibility { span: vis_span, help: (), max_vis, import_vis }
384                .decorate_lint(diag);
385        }
386        BuiltinLintDiag::UnknownDiagnosticAttribute { span: typo_span, typo_name } => {
387            let typo = typo_name.map(|typo_name| lints::UnknownDiagnosticAttributeTypoSugg {
388                span: typo_span,
389                typo_name,
390            });
391            lints::UnknownDiagnosticAttribute { typo }.decorate_lint(diag);
392        }
393        BuiltinLintDiag::MacroUseDeprecated => {
394            lints::MacroUseDeprecated.decorate_lint(diag);
395        }
396        BuiltinLintDiag::UnusedMacroUse => lints::UnusedMacroUse.decorate_lint(diag),
397        BuiltinLintDiag::PrivateExternCrateReexport { source: ident, extern_crate_span } => {
398            lints::PrivateExternCrateReexport { ident, sugg: extern_crate_span.shrink_to_lo() }
399                .decorate_lint(diag);
400        }
401        BuiltinLintDiag::UnusedLabel => lints::UnusedLabel.decorate_lint(diag),
402        BuiltinLintDiag::MacroIsPrivate(ident) => {
403            lints::MacroIsPrivate { ident }.decorate_lint(diag);
404        }
405        BuiltinLintDiag::UnusedMacroDefinition(name) => {
406            lints::UnusedMacroDefinition { name }.decorate_lint(diag);
407        }
408        BuiltinLintDiag::MacroRuleNeverUsed(n, name) => {
409            lints::MacroRuleNeverUsed { n: n + 1, name }.decorate_lint(diag);
410        }
411        BuiltinLintDiag::UnstableFeature(msg) => {
412            lints::UnstableFeature { msg }.decorate_lint(diag);
413        }
414        BuiltinLintDiag::AvoidUsingIntelSyntax => {
415            lints::AvoidIntelSyntax.decorate_lint(diag);
416        }
417        BuiltinLintDiag::AvoidUsingAttSyntax => {
418            lints::AvoidAttSyntax.decorate_lint(diag);
419        }
420        BuiltinLintDiag::IncompleteInclude => {
421            lints::IncompleteInclude.decorate_lint(diag);
422        }
423        BuiltinLintDiag::UnnameableTestItems => {
424            lints::UnnameableTestItems.decorate_lint(diag);
425        }
426        BuiltinLintDiag::DuplicateMacroAttribute => {
427            lints::DuplicateMacroAttribute.decorate_lint(diag);
428        }
429        BuiltinLintDiag::CfgAttrNoAttributes => {
430            lints::CfgAttrNoAttributes.decorate_lint(diag);
431        }
432        BuiltinLintDiag::MetaVariableStillRepeating(name) => {
433            lints::MetaVariableStillRepeating { name }.decorate_lint(diag);
434        }
435        BuiltinLintDiag::MetaVariableWrongOperator => {
436            lints::MetaVariableWrongOperator.decorate_lint(diag);
437        }
438        BuiltinLintDiag::DuplicateMatcherBinding => {
439            lints::DuplicateMatcherBinding.decorate_lint(diag);
440        }
441        BuiltinLintDiag::UnknownMacroVariable(name) => {
442            lints::UnknownMacroVariable { name }.decorate_lint(diag);
443        }
444        BuiltinLintDiag::UnusedCrateDependency { extern_crate, local_crate } => {
445            lints::UnusedCrateDependency { extern_crate, local_crate }.decorate_lint(diag)
446        }
447        BuiltinLintDiag::IllFormedAttributeInput { suggestions } => {
448            lints::IllFormedAttributeInput {
449                num_suggestions: suggestions.len(),
450                suggestions: DiagArgValue::StrListSepByAnd(
451                    suggestions.into_iter().map(|s| format!("`{s}`").into()).collect(),
452                ),
453            }
454            .decorate_lint(diag)
455        }
456        BuiltinLintDiag::InnerAttributeUnstable { is_macro } => if is_macro {
457            lints::InnerAttributeUnstable::InnerMacroAttribute
458        } else {
459            lints::InnerAttributeUnstable::CustomInnerAttribute
460        }
461        .decorate_lint(diag),
462        BuiltinLintDiag::OutOfScopeMacroCalls { span, path, location } => {
463            lints::OutOfScopeMacroCalls { span, path, location }.decorate_lint(diag)
464        }
465        BuiltinLintDiag::UnexpectedBuiltinCfg { cfg, cfg_name, controlled_by } => {
466            lints::UnexpectedBuiltinCfg { cfg, cfg_name, controlled_by }.decorate_lint(diag)
467        }
468    }
469}