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