]> git.lizzy.rs Git - rust.git/blob - src/librustc_middle/lint.rs
Rollup merge of #71459 - divergentdave:pointer-offset-0x, r=RalfJung
[rust.git] / src / librustc_middle / lint.rs
1 use std::cmp;
2
3 use crate::ich::StableHashingContext;
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
6 use rustc_errors::{DiagnosticBuilder, DiagnosticId};
7 use rustc_hir::HirId;
8 use rustc_session::lint::{builtin, Level, Lint, LintId};
9 use rustc_session::{DiagnosticMessageId, Session};
10 use rustc_span::hygiene::MacroKind;
11 use rustc_span::source_map::{DesugaringKind, ExpnKind, MultiSpan};
12 use rustc_span::{Span, Symbol};
13
14 /// How a lint level was set.
15 #[derive(Clone, Copy, PartialEq, Eq, HashStable)]
16 pub enum LintSource {
17     /// Lint is at the default level as declared
18     /// in rustc or a plugin.
19     Default,
20
21     /// Lint level was set by an attribute.
22     Node(Symbol, Span, Option<Symbol> /* RFC 2383 reason */),
23
24     /// Lint level was set by a command-line flag.
25     CommandLine(Symbol),
26 }
27
28 pub type LevelSource = (Level, LintSource);
29
30 pub struct LintLevelSets {
31     pub list: Vec<LintSet>,
32     pub lint_cap: Level,
33 }
34
35 pub enum LintSet {
36     CommandLine {
37         // -A,-W,-D flags, a `Symbol` for the flag itself and `Level` for which
38         // flag.
39         specs: FxHashMap<LintId, LevelSource>,
40     },
41
42     Node {
43         specs: FxHashMap<LintId, LevelSource>,
44         parent: u32,
45     },
46 }
47
48 impl LintLevelSets {
49     pub fn new() -> Self {
50         LintLevelSets { list: Vec::new(), lint_cap: Level::Forbid }
51     }
52
53     pub fn get_lint_level(
54         &self,
55         lint: &'static Lint,
56         idx: u32,
57         aux: Option<&FxHashMap<LintId, LevelSource>>,
58         sess: &Session,
59     ) -> LevelSource {
60         let (level, mut src) = self.get_lint_id_level(LintId::of(lint), idx, aux);
61
62         // If `level` is none then we actually assume the default level for this
63         // lint.
64         let mut level = level.unwrap_or_else(|| lint.default_level(sess.edition()));
65
66         // If we're about to issue a warning, check at the last minute for any
67         // directives against the warnings "lint". If, for example, there's an
68         // `allow(warnings)` in scope then we want to respect that instead.
69         if level == Level::Warn {
70             let (warnings_level, warnings_src) =
71                 self.get_lint_id_level(LintId::of(builtin::WARNINGS), idx, aux);
72             if let Some(configured_warning_level) = warnings_level {
73                 if configured_warning_level != Level::Warn {
74                     level = configured_warning_level;
75                     src = warnings_src;
76                 }
77             }
78         }
79
80         // Ensure that we never exceed the `--cap-lints` argument.
81         level = cmp::min(level, self.lint_cap);
82
83         if let Some(driver_level) = sess.driver_lint_caps.get(&LintId::of(lint)) {
84             // Ensure that we never exceed driver level.
85             level = cmp::min(*driver_level, level);
86         }
87
88         (level, src)
89     }
90
91     pub fn get_lint_id_level(
92         &self,
93         id: LintId,
94         mut idx: u32,
95         aux: Option<&FxHashMap<LintId, LevelSource>>,
96     ) -> (Option<Level>, LintSource) {
97         if let Some(specs) = aux {
98             if let Some(&(level, src)) = specs.get(&id) {
99                 return (Some(level), src);
100             }
101         }
102         loop {
103             match self.list[idx as usize] {
104                 LintSet::CommandLine { ref specs } => {
105                     if let Some(&(level, src)) = specs.get(&id) {
106                         return (Some(level), src);
107                     }
108                     return (None, LintSource::Default);
109                 }
110                 LintSet::Node { ref specs, parent } => {
111                     if let Some(&(level, src)) = specs.get(&id) {
112                         return (Some(level), src);
113                     }
114                     idx = parent;
115                 }
116             }
117         }
118     }
119 }
120
121 pub struct LintLevelMap {
122     pub sets: LintLevelSets,
123     pub id_to_set: FxHashMap<HirId, u32>,
124 }
125
126 impl LintLevelMap {
127     /// If the `id` was previously registered with `register_id` when building
128     /// this `LintLevelMap` this returns the corresponding lint level and source
129     /// of the lint level for the lint provided.
130     ///
131     /// If the `id` was not previously registered, returns `None`. If `None` is
132     /// returned then the parent of `id` should be acquired and this function
133     /// should be called again.
134     pub fn level_and_source(
135         &self,
136         lint: &'static Lint,
137         id: HirId,
138         session: &Session,
139     ) -> Option<LevelSource> {
140         self.id_to_set.get(&id).map(|idx| self.sets.get_lint_level(lint, *idx, None, session))
141     }
142 }
143
144 impl<'a> HashStable<StableHashingContext<'a>> for LintLevelMap {
145     #[inline]
146     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
147         let LintLevelMap { ref sets, ref id_to_set } = *self;
148
149         id_to_set.hash_stable(hcx, hasher);
150
151         let LintLevelSets { ref list, lint_cap } = *sets;
152
153         lint_cap.hash_stable(hcx, hasher);
154
155         hcx.while_hashing_spans(true, |hcx| {
156             list.len().hash_stable(hcx, hasher);
157
158             // We are working under the assumption here that the list of
159             // lint-sets is built in a deterministic order.
160             for lint_set in list {
161                 ::std::mem::discriminant(lint_set).hash_stable(hcx, hasher);
162
163                 match *lint_set {
164                     LintSet::CommandLine { ref specs } => {
165                         specs.hash_stable(hcx, hasher);
166                     }
167                     LintSet::Node { ref specs, parent } => {
168                         specs.hash_stable(hcx, hasher);
169                         parent.hash_stable(hcx, hasher);
170                     }
171                 }
172             }
173         })
174     }
175 }
176
177 pub struct LintDiagnosticBuilder<'a>(DiagnosticBuilder<'a>);
178
179 impl<'a> LintDiagnosticBuilder<'a> {
180     /// Return the inner DiagnosticBuilder, first setting the primary message to `msg`.
181     pub fn build(mut self, msg: &str) -> DiagnosticBuilder<'a> {
182         self.0.set_primary_message(msg);
183         self.0
184     }
185
186     /// Create a LintDiagnosticBuilder from some existing DiagnosticBuilder.
187     pub fn new(err: DiagnosticBuilder<'a>) -> LintDiagnosticBuilder<'a> {
188         LintDiagnosticBuilder(err)
189     }
190 }
191
192 pub fn struct_lint_level<'s, 'd>(
193     sess: &'s Session,
194     lint: &'static Lint,
195     level: Level,
196     src: LintSource,
197     span: Option<MultiSpan>,
198     decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>) + 'd,
199 ) {
200     // Avoid codegen bloat from monomorphization by immediately doing dyn dispatch of `decorate` to
201     // the "real" work.
202     fn struct_lint_level_impl(
203         sess: &'s Session,
204         lint: &'static Lint,
205         level: Level,
206         src: LintSource,
207         span: Option<MultiSpan>,
208         decorate: Box<dyn for<'b> FnOnce(LintDiagnosticBuilder<'b>) + 'd>,
209     ) {
210         let mut err = match (level, span) {
211             (Level::Allow, _) => {
212                 return;
213             }
214             (Level::Warn, Some(span)) => sess.struct_span_warn(span, ""),
215             (Level::Warn, None) => sess.struct_warn(""),
216             (Level::Deny | Level::Forbid, Some(span)) => sess.struct_span_err(span, ""),
217             (Level::Deny | Level::Forbid, None) => sess.struct_err(""),
218         };
219
220         // Check for future incompatibility lints and issue a stronger warning.
221         let lint_id = LintId::of(lint);
222         let future_incompatible = lint.future_incompatible;
223
224         // If this code originates in a foreign macro, aka something that this crate
225         // did not itself author, then it's likely that there's nothing this crate
226         // can do about it. We probably want to skip the lint entirely.
227         if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
228             // Any suggestions made here are likely to be incorrect, so anything we
229             // emit shouldn't be automatically fixed by rustfix.
230             err.allow_suggestions(false);
231
232             // If this is a future incompatible lint it'll become a hard error, so
233             // we have to emit *something*. Also allow lints to whitelist themselves
234             // on a case-by-case basis for emission in a foreign macro.
235             if future_incompatible.is_none() && !lint.report_in_external_macro {
236                 err.cancel();
237                 // Don't continue further, since we don't want to have
238                 // `diag_span_note_once` called for a diagnostic that isn't emitted.
239                 return;
240             }
241         }
242
243         let name = lint.name_lower();
244         match src {
245             LintSource::Default => {
246                 sess.diag_note_once(
247                     &mut err,
248                     DiagnosticMessageId::from(lint),
249                     &format!("`#[{}({})]` on by default", level.as_str(), name),
250                 );
251             }
252             LintSource::CommandLine(lint_flag_val) => {
253                 let flag = match level {
254                     Level::Warn => "-W",
255                     Level::Deny => "-D",
256                     Level::Forbid => "-F",
257                     Level::Allow => panic!(),
258                 };
259                 let hyphen_case_lint_name = name.replace("_", "-");
260                 if lint_flag_val.as_str() == name {
261                     sess.diag_note_once(
262                         &mut err,
263                         DiagnosticMessageId::from(lint),
264                         &format!(
265                             "requested on the command line with `{} {}`",
266                             flag, hyphen_case_lint_name
267                         ),
268                     );
269                 } else {
270                     let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
271                     sess.diag_note_once(
272                         &mut err,
273                         DiagnosticMessageId::from(lint),
274                         &format!(
275                             "`{} {}` implied by `{} {}`",
276                             flag, hyphen_case_lint_name, flag, hyphen_case_flag_val
277                         ),
278                     );
279                 }
280             }
281             LintSource::Node(lint_attr_name, src, reason) => {
282                 if let Some(rationale) = reason {
283                     err.note(&rationale.as_str());
284                 }
285                 sess.diag_span_note_once(
286                     &mut err,
287                     DiagnosticMessageId::from(lint),
288                     src,
289                     "the lint level is defined here",
290                 );
291                 if lint_attr_name.as_str() != name {
292                     let level_str = level.as_str();
293                     sess.diag_note_once(
294                         &mut err,
295                         DiagnosticMessageId::from(lint),
296                         &format!(
297                             "`#[{}({})]` implied by `#[{}({})]`",
298                             level_str, name, level_str, lint_attr_name
299                         ),
300                     );
301                 }
302             }
303         }
304
305         err.code(DiagnosticId::Lint(name));
306
307         if let Some(future_incompatible) = future_incompatible {
308             const STANDARD_MESSAGE: &str = "this was previously accepted by the compiler but is being phased out; \
309                  it will become a hard error";
310
311             let explanation = if lint_id == LintId::of(builtin::UNSTABLE_NAME_COLLISIONS) {
312                 "once this method is added to the standard library, \
313                  the ambiguity may cause an error or change in behavior!"
314                     .to_owned()
315             } else if lint_id == LintId::of(builtin::MUTABLE_BORROW_RESERVATION_CONFLICT) {
316                 "this borrowing pattern was not meant to be accepted, \
317                  and may become a hard error in the future"
318                     .to_owned()
319             } else if let Some(edition) = future_incompatible.edition {
320                 format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
321             } else {
322                 format!("{} in a future release!", STANDARD_MESSAGE)
323             };
324             let citation = format!("for more information, see {}", future_incompatible.reference);
325             err.warn(&explanation);
326             err.note(&citation);
327         }
328
329         // Finally, run `decorate`. This function is also responsible for emitting the diagnostic.
330         decorate(LintDiagnosticBuilder::new(err));
331     }
332     struct_lint_level_impl(sess, lint, level, src, span, Box::new(decorate))
333 }
334
335 /// Returns whether `span` originates in a foreign crate's external macro.
336 ///
337 /// This is used to test whether a lint should not even begin to figure out whether it should
338 /// be reported on the current node.
339 pub fn in_external_macro(sess: &Session, span: Span) -> bool {
340     let expn_data = span.ctxt().outer_expn_data();
341     match expn_data.kind {
342         ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => false,
343         ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
344         ExpnKind::Macro(MacroKind::Bang, _) => {
345             // Dummy span for the `def_site` means it's an external macro.
346             expn_data.def_site.is_dummy() || sess.source_map().is_imported(expn_data.def_site)
347         }
348         ExpnKind::Macro(..) => true, // definitely a plugin
349     }
350 }