]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/lint.rs
CTFE engine: Scalar: expose size-generic to_(u)int methods
[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::{DiagnosticBuilder, DiagnosticId};
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, LintId,
12 };
13 use rustc_session::{DiagnosticMessageId, Session};
14 use rustc_span::hygiene::MacroKind;
15 use rustc_span::source_map::{DesugaringKind, ExpnKind, MultiSpan};
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     pub sets: LintLevelSets,
157     pub id_to_set: FxHashMap<HirId, LintStackIndex>,
158 }
159
160 impl LintLevelMap {
161     /// If the `id` was previously registered with `register_id` when building
162     /// this `LintLevelMap` this returns the corresponding lint level and source
163     /// of the lint level for the lint provided.
164     ///
165     /// If the `id` was not previously registered, returns `None`. If `None` is
166     /// returned then the parent of `id` should be acquired and this function
167     /// should be called again.
168     pub fn level_and_source(
169         &self,
170         lint: &'static Lint,
171         id: HirId,
172         session: &Session,
173     ) -> Option<LevelAndSource> {
174         self.id_to_set.get(&id).map(|idx| self.sets.get_lint_level(lint, *idx, None, session))
175     }
176 }
177
178 impl<'a> HashStable<StableHashingContext<'a>> for LintLevelMap {
179     #[inline]
180     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
181         let LintLevelMap { ref sets, ref id_to_set } = *self;
182
183         id_to_set.hash_stable(hcx, hasher);
184
185         hcx.while_hashing_spans(true, |hcx| sets.hash_stable(hcx, hasher))
186     }
187 }
188
189 pub struct LintDiagnosticBuilder<'a>(DiagnosticBuilder<'a>);
190
191 impl<'a> LintDiagnosticBuilder<'a> {
192     /// Return the inner DiagnosticBuilder, first setting the primary message to `msg`.
193     pub fn build(mut self, msg: &str) -> DiagnosticBuilder<'a> {
194         self.0.set_primary_message(msg);
195         self.0.set_is_lint();
196         self.0
197     }
198
199     /// Create a LintDiagnosticBuilder from some existing DiagnosticBuilder.
200     pub fn new(err: DiagnosticBuilder<'a>) -> LintDiagnosticBuilder<'a> {
201         LintDiagnosticBuilder(err)
202     }
203 }
204
205 pub fn explain_lint_level_source<'s>(
206     sess: &'s Session,
207     lint: &'static Lint,
208     level: Level,
209     src: LintLevelSource,
210     err: &mut DiagnosticBuilder<'s>,
211 ) {
212     let name = lint.name_lower();
213     match src {
214         LintLevelSource::Default => {
215             sess.diag_note_once(
216                 err,
217                 DiagnosticMessageId::from(lint),
218                 &format!("`#[{}({})]` on by default", level.as_str(), name),
219             );
220         }
221         LintLevelSource::CommandLine(lint_flag_val, orig_level) => {
222             let flag = match orig_level {
223                 Level::Warn => "-W",
224                 Level::Deny => "-D",
225                 Level::Forbid => "-F",
226                 Level::Allow => "-A",
227                 Level::ForceWarn => "--force-warn",
228             };
229             let hyphen_case_lint_name = name.replace('_', "-");
230             if lint_flag_val.as_str() == name {
231                 sess.diag_note_once(
232                     err,
233                     DiagnosticMessageId::from(lint),
234                     &format!(
235                         "requested on the command line with `{} {}`",
236                         flag, hyphen_case_lint_name
237                     ),
238                 );
239             } else {
240                 let hyphen_case_flag_val = lint_flag_val.as_str().replace('_', "-");
241                 sess.diag_note_once(
242                     err,
243                     DiagnosticMessageId::from(lint),
244                     &format!(
245                         "`{} {}` implied by `{} {}`",
246                         flag, hyphen_case_lint_name, flag, hyphen_case_flag_val
247                     ),
248                 );
249             }
250         }
251         LintLevelSource::Node(lint_attr_name, src, reason) => {
252             if let Some(rationale) = reason {
253                 err.note(rationale.as_str());
254             }
255             sess.diag_span_note_once(
256                 err,
257                 DiagnosticMessageId::from(lint),
258                 src,
259                 "the lint level is defined here",
260             );
261             if lint_attr_name.as_str() != name {
262                 let level_str = level.as_str();
263                 sess.diag_note_once(
264                     err,
265                     DiagnosticMessageId::from(lint),
266                     &format!(
267                         "`#[{}({})]` implied by `#[{}({})]`",
268                         level_str, name, level_str, lint_attr_name
269                     ),
270                 );
271             }
272         }
273     }
274 }
275
276 pub fn struct_lint_level<'s, 'd>(
277     sess: &'s Session,
278     lint: &'static Lint,
279     level: Level,
280     src: LintLevelSource,
281     span: Option<MultiSpan>,
282     decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>) + 'd,
283 ) {
284     // Avoid codegen bloat from monomorphization by immediately doing dyn dispatch of `decorate` to
285     // the "real" work.
286     fn struct_lint_level_impl<'s, 'd>(
287         sess: &'s Session,
288         lint: &'static Lint,
289         level: Level,
290         src: LintLevelSource,
291         span: Option<MultiSpan>,
292         decorate: Box<dyn for<'b> FnOnce(LintDiagnosticBuilder<'b>) + 'd>,
293     ) {
294         // Check for future incompatibility lints and issue a stronger warning.
295         let future_incompatible = lint.future_incompatible;
296
297         let has_future_breakage = future_incompatible.map_or(
298             // Default allow lints trigger too often for testing.
299             sess.opts.debugging_opts.future_incompat_test && lint.default_level != Level::Allow,
300             |incompat| {
301                 matches!(incompat.reason, FutureIncompatibilityReason::FutureReleaseErrorReportNow)
302             },
303         );
304
305         let mut err = match (level, span) {
306             (Level::Allow, span) => {
307                 if has_future_breakage {
308                     if let Some(span) = span {
309                         sess.struct_span_allow(span, "")
310                     } else {
311                         sess.struct_allow("")
312                     }
313                 } else {
314                     return;
315                 }
316             }
317             (Level::Warn, Some(span)) => sess.struct_span_warn(span, ""),
318             (Level::Warn, None) => sess.struct_warn(""),
319             (Level::ForceWarn, Some(span)) => sess.struct_span_force_warn(span, ""),
320             (Level::ForceWarn, None) => sess.struct_force_warn(""),
321             (Level::Deny | Level::Forbid, Some(span)) => {
322                 let mut builder = sess.diagnostic().struct_err_lint("");
323                 builder.set_span(span);
324                 builder
325             }
326             (Level::Deny | Level::Forbid, None) => sess.diagnostic().struct_err_lint(""),
327         };
328
329         // If this code originates in a foreign macro, aka something that this crate
330         // did not itself author, then it's likely that there's nothing this crate
331         // can do about it. We probably want to skip the lint entirely.
332         if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
333             // Any suggestions made here are likely to be incorrect, so anything we
334             // emit shouldn't be automatically fixed by rustfix.
335             err.disable_suggestions();
336
337             // If this is a future incompatible that is not an edition fixing lint
338             // it'll become a hard error, so we have to emit *something*. Also,
339             // if this lint occurs in the expansion of a macro from an external crate,
340             // allow individual lints to opt-out from being reported.
341             let not_future_incompatible =
342                 future_incompatible.map(|f| f.reason.edition().is_some()).unwrap_or(true);
343             if not_future_incompatible && !lint.report_in_external_macro {
344                 err.cancel();
345                 // Don't continue further, since we don't want to have
346                 // `diag_span_note_once` called for a diagnostic that isn't emitted.
347                 return;
348             }
349         }
350
351         explain_lint_level_source(sess, lint, level, src, &mut err);
352
353         let name = lint.name_lower();
354         let is_force_warn = matches!(level, Level::ForceWarn);
355         err.code(DiagnosticId::Lint { name, has_future_breakage, is_force_warn });
356
357         if let Some(future_incompatible) = future_incompatible {
358             let explanation = match future_incompatible.reason {
359                 FutureIncompatibilityReason::FutureReleaseError
360                 | FutureIncompatibilityReason::FutureReleaseErrorReportNow => {
361                     "this was previously accepted by the compiler but is being phased out; \
362                          it will become a hard error in a future release!"
363                         .to_owned()
364                 }
365                 FutureIncompatibilityReason::FutureReleaseSemanticsChange => {
366                     "this will change its meaning in a future release!".to_owned()
367                 }
368                 FutureIncompatibilityReason::EditionError(edition) => {
369                     let current_edition = sess.edition();
370                     format!(
371                         "this is accepted in the current edition (Rust {}) but is a hard error in Rust {}!",
372                         current_edition, edition
373                     )
374                 }
375                 FutureIncompatibilityReason::EditionSemanticsChange(edition) => {
376                     format!("this changes meaning in Rust {}", edition)
377                 }
378                 FutureIncompatibilityReason::Custom(reason) => reason.to_owned(),
379             };
380
381             if future_incompatible.explain_reason {
382                 err.warn(&explanation);
383             }
384             if !future_incompatible.reference.is_empty() {
385                 let citation =
386                     format!("for more information, see {}", future_incompatible.reference);
387                 err.note(&citation);
388             }
389         }
390
391         // Finally, run `decorate`. This function is also responsible for emitting the diagnostic.
392         decorate(LintDiagnosticBuilder::new(err));
393     }
394     struct_lint_level_impl(sess, lint, level, src, span, Box::new(decorate))
395 }
396
397 /// Returns whether `span` originates in a foreign crate's external macro.
398 ///
399 /// This is used to test whether a lint should not even begin to figure out whether it should
400 /// be reported on the current node.
401 pub fn in_external_macro(sess: &Session, span: Span) -> bool {
402     let expn_data = span.ctxt().outer_expn_data();
403     match expn_data.kind {
404         ExpnKind::Inlined
405         | ExpnKind::Root
406         | ExpnKind::Desugaring(DesugaringKind::ForLoop | DesugaringKind::WhileLoop) => false,
407         ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
408         ExpnKind::Macro(MacroKind::Bang, _) => {
409             // Dummy span for the `def_site` means it's an external macro.
410             expn_data.def_site.is_dummy() || sess.source_map().is_imported(expn_data.def_site)
411         }
412         ExpnKind::Macro { .. } => true, // definitely a plugin
413     }
414 }