]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/lint.rs
Rollup merge of #101740 - andrewpollack:add-ignore-fuchsia-ui-tests, r=tmandry
[rust.git] / compiler / rustc_middle / src / lint.rs
1 use std::cmp;
2
3 use rustc_data_structures::fx::FxHashMap;
4 use rustc_errors::{Diagnostic, DiagnosticId, LintDiagnosticBuilder, MultiSpan};
5 use rustc_hir::HirId;
6 use rustc_session::lint::{
7     builtin::{self, FORBIDDEN_LINT_GROUPS},
8     FutureIncompatibilityReason, Level, Lint, LintId,
9 };
10 use rustc_session::Session;
11 use rustc_span::hygiene::MacroKind;
12 use rustc_span::source_map::{DesugaringKind, ExpnKind};
13 use rustc_span::{symbol, Span, Symbol, DUMMY_SP};
14
15 use crate::ty::TyCtxt;
16
17 /// How a lint level was set.
18 #[derive(Clone, Copy, PartialEq, Eq, HashStable, Debug)]
19 pub enum LintLevelSource {
20     /// Lint is at the default level as declared
21     /// in rustc or a plugin.
22     Default,
23
24     /// Lint level was set by an attribute.
25     Node {
26         name: Symbol,
27         span: Span,
28         /// RFC 2383 reason
29         reason: Option<Symbol>,
30     },
31
32     /// Lint level was set by a command-line flag.
33     /// The provided `Level` is the level specified on the command line.
34     /// (The actual level may be lower due to `--cap-lints`.)
35     CommandLine(Symbol, Level),
36 }
37
38 impl LintLevelSource {
39     pub fn name(&self) -> Symbol {
40         match *self {
41             LintLevelSource::Default => symbol::kw::Default,
42             LintLevelSource::Node { name, .. } => name,
43             LintLevelSource::CommandLine(name, _) => name,
44         }
45     }
46
47     pub fn span(&self) -> Span {
48         match *self {
49             LintLevelSource::Default => DUMMY_SP,
50             LintLevelSource::Node { span, .. } => span,
51             LintLevelSource::CommandLine(_, _) => DUMMY_SP,
52         }
53     }
54 }
55
56 /// A tuple of a lint level and its source.
57 pub type LevelAndSource = (Level, LintLevelSource);
58
59 /// Return type for the `shallow_lint_levels_on` query.
60 ///
61 /// This map represents the set of allowed lints and allowance levels given
62 /// by the attributes for *a single HirId*.
63 #[derive(Default, Debug, HashStable)]
64 pub struct ShallowLintLevelMap {
65     pub specs: FxHashMap<LintId, LevelAndSource>,
66 }
67
68 /// From an initial level and source, verify the effect of special annotations:
69 /// `warnings` lint level and lint caps.
70 ///
71 /// The return of this function is suitable for diagnostics.
72 pub fn reveal_actual_level(
73     level: Option<Level>,
74     src: &mut LintLevelSource,
75     sess: &Session,
76     lint: LintId,
77     probe_for_lint_level: impl FnOnce(LintId) -> (Option<Level>, LintLevelSource),
78 ) -> Level {
79     // If `level` is none then we actually assume the default level for this lint.
80     let mut level = level.unwrap_or_else(|| lint.lint.default_level(sess.edition()));
81
82     // If we're about to issue a warning, check at the last minute for any
83     // directives against the warnings "lint". If, for example, there's an
84     // `allow(warnings)` in scope then we want to respect that instead.
85     //
86     // We exempt `FORBIDDEN_LINT_GROUPS` from this because it specifically
87     // triggers in cases (like #80988) where you have `forbid(warnings)`,
88     // and so if we turned that into an error, it'd defeat the purpose of the
89     // future compatibility warning.
90     if level == Level::Warn && lint != LintId::of(FORBIDDEN_LINT_GROUPS) {
91         let (warnings_level, warnings_src) = probe_for_lint_level(LintId::of(builtin::WARNINGS));
92         if let Some(configured_warning_level) = warnings_level {
93             if configured_warning_level != Level::Warn {
94                 level = configured_warning_level;
95                 *src = warnings_src;
96             }
97         }
98     }
99
100     // Ensure that we never exceed the `--cap-lints` argument unless the source is a --force-warn
101     level = if let LintLevelSource::CommandLine(_, Level::ForceWarn(_)) = src {
102         level
103     } else {
104         cmp::min(level, sess.opts.lint_cap.unwrap_or(Level::Forbid))
105     };
106
107     if let Some(driver_level) = sess.driver_lint_caps.get(&lint) {
108         // Ensure that we never exceed driver level.
109         level = cmp::min(*driver_level, level);
110     }
111
112     level
113 }
114
115 impl ShallowLintLevelMap {
116     /// Perform a deep probe in the HIR tree looking for the actual level for the lint.
117     /// This lint level is not usable for diagnostics, it needs to be corrected by
118     /// `reveal_actual_level` beforehand.
119     fn probe_for_lint_level(
120         &self,
121         tcx: TyCtxt<'_>,
122         id: LintId,
123         start: HirId,
124     ) -> (Option<Level>, LintLevelSource) {
125         if let Some(&(level, src)) = self.specs.get(&id) {
126             return (Some(level), src);
127         }
128
129         for (parent, _) in tcx.hir().parent_iter(start) {
130             let specs = tcx.shallow_lint_levels_on(parent);
131             if let Some(&(level, src)) = specs.specs.get(&id) {
132                 return (Some(level), src);
133             }
134         }
135         (None, LintLevelSource::Default)
136     }
137
138     /// Fetch and return the user-visible lint level for the given lint at the given HirId.
139     pub fn lint_level_id_at_node(
140         &self,
141         tcx: TyCtxt<'_>,
142         lint: LintId,
143         id: HirId,
144     ) -> (Level, LintLevelSource) {
145         let (level, mut src) = self.probe_for_lint_level(tcx, lint, id);
146         let level = reveal_actual_level(level, &mut src, tcx.sess, lint, |lint| {
147             self.probe_for_lint_level(tcx, lint, id)
148         });
149         debug!(?id, ?level, ?src);
150         (level, src)
151     }
152 }
153
154 impl TyCtxt<'_> {
155     /// Fetch and return the user-visible lint level for the given lint at the given HirId.
156     pub fn lint_level_at_node(self, lint: &'static Lint, id: HirId) -> (Level, LintLevelSource) {
157         self.shallow_lint_levels_on(id).lint_level_id_at_node(self, LintId::of(lint), id)
158     }
159
160     /// Walks upwards from `id` to find a node which might change lint levels with attributes.
161     /// It stops at `bound` and just returns it if reached.
162     pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId {
163         let hir = self.hir();
164         while id != bound && self.shallow_lint_levels_on(id).specs.is_empty() {
165             id = hir.get_parent_node(id)
166         }
167         id
168     }
169 }
170
171 /// This struct represents a lint expectation and holds all required information
172 /// to emit the `unfulfilled_lint_expectations` lint if it is unfulfilled after
173 /// the `LateLintPass` has completed.
174 #[derive(Clone, Debug, HashStable)]
175 pub struct LintExpectation {
176     /// The reason for this expectation that can optionally be added as part of
177     /// the attribute. It will be displayed as part of the lint message.
178     pub reason: Option<Symbol>,
179     /// The [`Span`] of the attribute that this expectation originated from.
180     pub emission_span: Span,
181     /// Lint messages for the `unfulfilled_lint_expectations` lint will be
182     /// adjusted to include an additional note. Therefore, we have to track if
183     /// the expectation is for the lint.
184     pub is_unfulfilled_lint_expectations: bool,
185     /// This will hold the name of the tool that this lint belongs to. For
186     /// the lint `clippy::some_lint` the tool would be `clippy`, the same
187     /// goes for `rustdoc`. This will be `None` for rustc lints
188     pub lint_tool: Option<Symbol>,
189 }
190
191 impl LintExpectation {
192     pub fn new(
193         reason: Option<Symbol>,
194         emission_span: Span,
195         is_unfulfilled_lint_expectations: bool,
196         lint_tool: Option<Symbol>,
197     ) -> Self {
198         Self { reason, emission_span, is_unfulfilled_lint_expectations, lint_tool }
199     }
200 }
201
202 pub fn explain_lint_level_source(
203     lint: &'static Lint,
204     level: Level,
205     src: LintLevelSource,
206     err: &mut Diagnostic,
207 ) {
208     let name = lint.name_lower();
209     match src {
210         LintLevelSource::Default => {
211             err.note_once(&format!("`#[{}({})]` on by default", level.as_str(), name));
212         }
213         LintLevelSource::CommandLine(lint_flag_val, orig_level) => {
214             let flag = match orig_level {
215                 Level::Warn => "-W",
216                 Level::Deny => "-D",
217                 Level::Forbid => "-F",
218                 Level::Allow => "-A",
219                 Level::ForceWarn(_) => "--force-warn",
220                 Level::Expect(_) => {
221                     unreachable!("the expect level does not have a commandline flag")
222                 }
223             };
224             let hyphen_case_lint_name = name.replace('_', "-");
225             if lint_flag_val.as_str() == name {
226                 err.note_once(&format!(
227                     "requested on the command line with `{} {}`",
228                     flag, hyphen_case_lint_name
229                 ));
230             } else {
231                 let hyphen_case_flag_val = lint_flag_val.as_str().replace('_', "-");
232                 err.note_once(&format!(
233                     "`{} {}` implied by `{} {}`",
234                     flag, hyphen_case_lint_name, flag, hyphen_case_flag_val
235                 ));
236             }
237         }
238         LintLevelSource::Node { name: lint_attr_name, span, reason, .. } => {
239             if let Some(rationale) = reason {
240                 err.note(rationale.as_str());
241             }
242             err.span_note_once(span, "the lint level is defined here");
243             if lint_attr_name.as_str() != name {
244                 let level_str = level.as_str();
245                 err.note_once(&format!(
246                     "`#[{}({})]` implied by `#[{}({})]`",
247                     level_str, name, level_str, lint_attr_name
248                 ));
249             }
250         }
251     }
252 }
253
254 pub fn struct_lint_level<'s, 'd>(
255     sess: &'s Session,
256     lint: &'static Lint,
257     level: Level,
258     src: LintLevelSource,
259     span: Option<MultiSpan>,
260     decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>) + 'd,
261 ) {
262     // Avoid codegen bloat from monomorphization by immediately doing dyn dispatch of `decorate` to
263     // the "real" work.
264     fn struct_lint_level_impl<'s, 'd>(
265         sess: &'s Session,
266         lint: &'static Lint,
267         level: Level,
268         src: LintLevelSource,
269         span: Option<MultiSpan>,
270         decorate: Box<dyn for<'b> FnOnce(LintDiagnosticBuilder<'b, ()>) + 'd>,
271     ) {
272         // Check for future incompatibility lints and issue a stronger warning.
273         let future_incompatible = lint.future_incompatible;
274
275         let has_future_breakage = future_incompatible.map_or(
276             // Default allow lints trigger too often for testing.
277             sess.opts.unstable_opts.future_incompat_test && lint.default_level != Level::Allow,
278             |incompat| {
279                 matches!(incompat.reason, FutureIncompatibilityReason::FutureReleaseErrorReportNow)
280             },
281         );
282
283         let mut err = match (level, span) {
284             (Level::Allow, span) => {
285                 if has_future_breakage {
286                     if let Some(span) = span {
287                         sess.struct_span_allow(span, "")
288                     } else {
289                         sess.struct_allow("")
290                     }
291                 } else {
292                     return;
293                 }
294             }
295             (Level::Expect(expect_id), _) => {
296                 // This case is special as we actually allow the lint itself in this context, but
297                 // we can't return early like in the case for `Level::Allow` because we still
298                 // need the lint diagnostic to be emitted to `rustc_error::HandlerInner`.
299                 //
300                 // We can also not mark the lint expectation as fulfilled here right away, as it
301                 // can still be cancelled in the decorate function. All of this means that we simply
302                 // create a `DiagnosticBuilder` and continue as we would for warnings.
303                 sess.struct_expect("", expect_id)
304             }
305             (Level::ForceWarn(Some(expect_id)), Some(span)) => {
306                 sess.struct_span_warn_with_expectation(span, "", expect_id)
307             }
308             (Level::ForceWarn(Some(expect_id)), None) => {
309                 sess.struct_warn_with_expectation("", expect_id)
310             }
311             (Level::Warn | Level::ForceWarn(None), Some(span)) => sess.struct_span_warn(span, ""),
312             (Level::Warn | Level::ForceWarn(None), None) => sess.struct_warn(""),
313             (Level::Deny | Level::Forbid, Some(span)) => {
314                 let mut builder = sess.diagnostic().struct_err_lint("");
315                 builder.set_span(span);
316                 builder
317             }
318             (Level::Deny | Level::Forbid, None) => sess.diagnostic().struct_err_lint(""),
319         };
320
321         // If this code originates in a foreign macro, aka something that this crate
322         // did not itself author, then it's likely that there's nothing this crate
323         // can do about it. We probably want to skip the lint entirely.
324         if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
325             // Any suggestions made here are likely to be incorrect, so anything we
326             // emit shouldn't be automatically fixed by rustfix.
327             err.disable_suggestions();
328
329             // If this is a future incompatible that is not an edition fixing lint
330             // it'll become a hard error, so we have to emit *something*. Also,
331             // if this lint occurs in the expansion of a macro from an external crate,
332             // allow individual lints to opt-out from being reported.
333             let not_future_incompatible =
334                 future_incompatible.map(|f| f.reason.edition().is_some()).unwrap_or(true);
335             if not_future_incompatible && !lint.report_in_external_macro {
336                 err.cancel();
337                 // Don't continue further, since we don't want to have
338                 // `diag_span_note_once` called for a diagnostic that isn't emitted.
339                 return;
340             }
341         }
342
343         // Lint diagnostics that are covered by the expect level will not be emitted outside
344         // the compiler. It is therefore not necessary to add any information for the user.
345         // This will therefore directly call the decorate function which will in turn emit
346         // the `Diagnostic`.
347         if let Level::Expect(_) = level {
348             let name = lint.name_lower();
349             err.code(DiagnosticId::Lint { name, has_future_breakage, is_force_warn: false });
350             decorate(LintDiagnosticBuilder::new(err));
351             return;
352         }
353
354         explain_lint_level_source(lint, level, src, &mut err);
355
356         let name = lint.name_lower();
357         let is_force_warn = matches!(level, Level::ForceWarn(_));
358         err.code(DiagnosticId::Lint { name, has_future_breakage, is_force_warn });
359
360         if let Some(future_incompatible) = future_incompatible {
361             let explanation = match future_incompatible.reason {
362                 FutureIncompatibilityReason::FutureReleaseError
363                 | FutureIncompatibilityReason::FutureReleaseErrorReportNow => {
364                     "this was previously accepted by the compiler but is being phased out; \
365                          it will become a hard error in a future release!"
366                         .to_owned()
367                 }
368                 FutureIncompatibilityReason::FutureReleaseSemanticsChange => {
369                     "this will change its meaning in a future release!".to_owned()
370                 }
371                 FutureIncompatibilityReason::EditionError(edition) => {
372                     let current_edition = sess.edition();
373                     format!(
374                         "this is accepted in the current edition (Rust {}) but is a hard error in Rust {}!",
375                         current_edition, edition
376                     )
377                 }
378                 FutureIncompatibilityReason::EditionSemanticsChange(edition) => {
379                     format!("this changes meaning in Rust {}", edition)
380                 }
381                 FutureIncompatibilityReason::Custom(reason) => reason.to_owned(),
382             };
383
384             if future_incompatible.explain_reason {
385                 err.warn(&explanation);
386             }
387             if !future_incompatible.reference.is_empty() {
388                 let citation =
389                     format!("for more information, see {}", future_incompatible.reference);
390                 err.note(&citation);
391             }
392         }
393
394         // Finally, run `decorate`. This function is also responsible for emitting the diagnostic.
395         decorate(LintDiagnosticBuilder::new(err));
396     }
397     struct_lint_level_impl(sess, lint, level, src, span, Box::new(decorate))
398 }
399
400 /// Returns whether `span` originates in a foreign crate's external macro.
401 ///
402 /// This is used to test whether a lint should not even begin to figure out whether it should
403 /// be reported on the current node.
404 pub fn in_external_macro(sess: &Session, span: Span) -> bool {
405     let expn_data = span.ctxt().outer_expn_data();
406     match expn_data.kind {
407         ExpnKind::Inlined
408         | ExpnKind::Root
409         | ExpnKind::Desugaring(DesugaringKind::ForLoop | DesugaringKind::WhileLoop) => false,
410         ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
411         ExpnKind::Macro(MacroKind::Bang, _) => {
412             // Dummy span for the `def_site` means it's an external macro.
413             expn_data.def_site.is_dummy() || sess.source_map().is_imported(expn_data.def_site)
414         }
415         ExpnKind::Macro { .. } => true, // definitely a plugin
416     }
417 }