3 use rustc_data_structures::fx::FxHashMap;
4 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
6 Diagnostic, DiagnosticBuilder, DiagnosticId, DiagnosticMessage, EmissionGuarantee,
7 ErrorGuaranteed, MultiSpan,
10 use rustc_index::vec::IndexVec;
11 use rustc_query_system::ich::StableHashingContext;
12 use rustc_session::lint::{
13 builtin::{self, FORBIDDEN_LINT_GROUPS},
14 FutureIncompatibilityReason, Level, Lint, LintExpectationId, LintId,
16 use rustc_session::Session;
17 use rustc_span::hygiene::MacroKind;
18 use rustc_span::source_map::{DesugaringKind, ExpnKind};
19 use rustc_span::{symbol, Span, Symbol, DUMMY_SP};
21 /// How a lint level was set.
22 #[derive(Clone, Copy, PartialEq, Eq, HashStable, Debug)]
23 pub enum LintLevelSource {
24 /// Lint is at the default level as declared
25 /// in rustc or a plugin.
28 /// Lint level was set by an attribute.
29 Node(Symbol, Span, Option<Symbol> /* RFC 2383 reason */),
31 /// Lint level was set by a command-line flag.
32 /// The provided `Level` is the level specified on the command line.
33 /// (The actual level may be lower due to `--cap-lints`.)
34 CommandLine(Symbol, Level),
37 impl LintLevelSource {
38 pub fn name(&self) -> Symbol {
40 LintLevelSource::Default => symbol::kw::Default,
41 LintLevelSource::Node(name, _, _) => name,
42 LintLevelSource::CommandLine(name, _) => name,
46 pub fn span(&self) -> Span {
48 LintLevelSource::Default => DUMMY_SP,
49 LintLevelSource::Node(_, span, _) => span,
50 LintLevelSource::CommandLine(_, _) => DUMMY_SP,
55 /// A tuple of a lint level and its source.
56 pub type LevelAndSource = (Level, LintLevelSource);
58 #[derive(Debug, HashStable)]
59 pub struct LintLevelSets {
60 pub list: IndexVec<LintStackIndex, LintSet>,
64 rustc_index::newtype_index! {
66 pub struct LintStackIndex {
67 const COMMAND_LINE = 0,
71 #[derive(Debug, HashStable)]
73 // -A,-W,-D flags, a `Symbol` for the flag itself and `Level` for which
75 pub specs: FxHashMap<LintId, LevelAndSource>,
77 pub parent: LintStackIndex,
81 pub fn new() -> Self {
82 LintLevelSets { list: IndexVec::new(), lint_cap: Level::Forbid }
85 pub fn get_lint_level(
89 aux: Option<&FxHashMap<LintId, LevelAndSource>>,
92 let (level, mut src) = self.get_lint_id_level(LintId::of(lint), idx, aux);
94 // If `level` is none then we actually assume the default level for this
96 let mut level = level.unwrap_or_else(|| lint.default_level(sess.edition()));
98 // If we're about to issue a warning, check at the last minute for any
99 // directives against the warnings "lint". If, for example, there's an
100 // `allow(warnings)` in scope then we want to respect that instead.
102 // We exempt `FORBIDDEN_LINT_GROUPS` from this because it specifically
103 // triggers in cases (like #80988) where you have `forbid(warnings)`,
104 // and so if we turned that into an error, it'd defeat the purpose of the
105 // future compatibility warning.
106 if level == Level::Warn && LintId::of(lint) != LintId::of(FORBIDDEN_LINT_GROUPS) {
107 let (warnings_level, warnings_src) =
108 self.get_lint_id_level(LintId::of(builtin::WARNINGS), idx, aux);
109 if let Some(configured_warning_level) = warnings_level {
110 if configured_warning_level != Level::Warn {
111 level = configured_warning_level;
117 // Ensure that we never exceed the `--cap-lints` argument
118 // unless the source is a --force-warn
119 level = if let LintLevelSource::CommandLine(_, Level::ForceWarn(_)) = src {
122 cmp::min(level, self.lint_cap)
125 if let Some(driver_level) = sess.driver_lint_caps.get(&LintId::of(lint)) {
126 // Ensure that we never exceed driver level.
127 level = cmp::min(*driver_level, level);
133 pub fn get_lint_id_level(
136 mut idx: LintStackIndex,
137 aux: Option<&FxHashMap<LintId, LevelAndSource>>,
138 ) -> (Option<Level>, LintLevelSource) {
139 if let Some(specs) = aux {
140 if let Some(&(level, src)) = specs.get(&id) {
141 return (Some(level), src);
145 let LintSet { ref specs, parent } = self.list[idx];
146 if let Some(&(level, src)) = specs.get(&id) {
147 return (Some(level), src);
149 if idx == COMMAND_LINE {
150 return (None, LintLevelSource::Default);
158 pub struct LintLevelMap {
159 /// This is a collection of lint expectations as described in RFC 2383, that
160 /// can be fulfilled during this compilation session. This means that at least
161 /// one expected lint is currently registered in the lint store.
163 /// The [`LintExpectationId`] is stored as a part of the [`Expect`](Level::Expect)
165 pub lint_expectations: Vec<(LintExpectationId, LintExpectation)>,
166 pub sets: LintLevelSets,
167 pub id_to_set: FxHashMap<HirId, LintStackIndex>,
171 /// If the `id` was previously registered with `register_id` when building
172 /// this `LintLevelMap` this returns the corresponding lint level and source
173 /// of the lint level for the lint provided.
175 /// If the `id` was not previously registered, returns `None`. If `None` is
176 /// returned then the parent of `id` should be acquired and this function
177 /// should be called again.
178 pub fn level_and_source(
183 ) -> Option<LevelAndSource> {
184 self.id_to_set.get(&id).map(|idx| self.sets.get_lint_level(lint, *idx, None, session))
188 impl<'a> HashStable<StableHashingContext<'a>> for LintLevelMap {
190 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
191 let LintLevelMap { ref sets, ref id_to_set, ref lint_expectations } = *self;
193 id_to_set.hash_stable(hcx, hasher);
194 lint_expectations.hash_stable(hcx, hasher);
196 hcx.while_hashing_spans(true, |hcx| sets.hash_stable(hcx, hasher))
200 /// This struct represents a lint expectation and holds all required information
201 /// to emit the `unfulfilled_lint_expectations` lint if it is unfulfilled after
202 /// the `LateLintPass` has completed.
203 #[derive(Clone, Debug, HashStable)]
204 pub struct LintExpectation {
205 /// The reason for this expectation that can optionally be added as part of
206 /// the attribute. It will be displayed as part of the lint message.
207 pub reason: Option<Symbol>,
208 /// The [`Span`] of the attribute that this expectation originated from.
209 pub emission_span: Span,
210 /// Lint messages for the `unfulfilled_lint_expectations` lint will be
211 /// adjusted to include an additional note. Therefore, we have to track if
212 /// the expectation is for the lint.
213 pub is_unfulfilled_lint_expectations: bool,
214 /// This will hold the name of the tool that this lint belongs to. For
215 /// the lint `clippy::some_lint` the tool would be `clippy`, the same
216 /// goes for `rustdoc`. This will be `None` for rustc lints
217 pub lint_tool: Option<Symbol>,
220 impl LintExpectation {
222 reason: Option<Symbol>,
224 is_unfulfilled_lint_expectations: bool,
225 lint_tool: Option<Symbol>,
227 Self { reason, emission_span, is_unfulfilled_lint_expectations, lint_tool }
231 pub struct LintDiagnosticBuilder<'a, G: EmissionGuarantee>(DiagnosticBuilder<'a, G>);
233 impl<'a, G: EmissionGuarantee> LintDiagnosticBuilder<'a, G> {
234 /// Return the inner `DiagnosticBuilder`, first setting the primary message to `msg`.
235 pub fn build(mut self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'a, G> {
236 self.0.set_primary_message(msg);
237 self.0.set_is_lint();
241 /// Create a `LintDiagnosticBuilder` from some existing `DiagnosticBuilder`.
242 pub fn new(err: DiagnosticBuilder<'a, G>) -> LintDiagnosticBuilder<'a, G> {
243 LintDiagnosticBuilder(err)
247 impl<'a> LintDiagnosticBuilder<'a, ErrorGuaranteed> {
248 pub fn forget_guarantee(self) -> LintDiagnosticBuilder<'a, ()> {
249 LintDiagnosticBuilder(self.0.forget_guarantee())
253 pub fn explain_lint_level_source(
256 src: LintLevelSource,
257 err: &mut Diagnostic,
259 let name = lint.name_lower();
261 LintLevelSource::Default => {
262 err.note_once(&format!("`#[{}({})]` on by default", level.as_str(), name));
264 LintLevelSource::CommandLine(lint_flag_val, orig_level) => {
265 let flag = match orig_level {
268 Level::Forbid => "-F",
269 Level::Allow => "-A",
270 Level::ForceWarn(_) => "--force-warn",
271 Level::Expect(_) => {
272 unreachable!("the expect level does not have a commandline flag")
275 let hyphen_case_lint_name = name.replace('_', "-");
276 if lint_flag_val.as_str() == name {
277 err.note_once(&format!(
278 "requested on the command line with `{} {}`",
279 flag, hyphen_case_lint_name
282 let hyphen_case_flag_val = lint_flag_val.as_str().replace('_', "-");
283 err.note_once(&format!(
284 "`{} {}` implied by `{} {}`",
285 flag, hyphen_case_lint_name, flag, hyphen_case_flag_val
289 LintLevelSource::Node(lint_attr_name, src, reason) => {
290 if let Some(rationale) = reason {
291 err.note(rationale.as_str());
293 err.span_note_once(src, "the lint level is defined here");
294 if lint_attr_name.as_str() != name {
295 let level_str = level.as_str();
296 err.note_once(&format!(
297 "`#[{}({})]` implied by `#[{}({})]`",
298 level_str, name, level_str, lint_attr_name
305 pub fn struct_lint_level<'s, 'd>(
309 src: LintLevelSource,
310 span: Option<MultiSpan>,
311 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>) + 'd,
313 // Avoid codegen bloat from monomorphization by immediately doing dyn dispatch of `decorate` to
315 fn struct_lint_level_impl<'s, 'd>(
319 src: LintLevelSource,
320 span: Option<MultiSpan>,
321 decorate: Box<dyn for<'b> FnOnce(LintDiagnosticBuilder<'b, ()>) + 'd>,
323 // Check for future incompatibility lints and issue a stronger warning.
324 let future_incompatible = lint.future_incompatible;
326 let has_future_breakage = future_incompatible.map_or(
327 // Default allow lints trigger too often for testing.
328 sess.opts.debugging_opts.future_incompat_test && lint.default_level != Level::Allow,
330 matches!(incompat.reason, FutureIncompatibilityReason::FutureReleaseErrorReportNow)
334 let mut err = match (level, span) {
335 (Level::Allow, span) => {
336 if has_future_breakage {
337 if let Some(span) = span {
338 sess.struct_span_allow(span, "")
340 sess.struct_allow("")
346 (Level::Expect(expect_id), _) => {
347 // This case is special as we actually allow the lint itself in this context, but
348 // we can't return early like in the case for `Level::Allow` because we still
349 // need the lint diagnostic to be emitted to `rustc_error::HandlerInner`.
351 // We can also not mark the lint expectation as fulfilled here right away, as it
352 // can still be cancelled in the decorate function. All of this means that we simply
353 // create a `DiagnosticBuilder` and continue as we would for warnings.
354 sess.struct_expect("", expect_id)
356 (Level::ForceWarn(Some(expect_id)), Some(span)) => {
357 sess.struct_span_warn_with_expectation(span, "", expect_id)
359 (Level::ForceWarn(Some(expect_id)), None) => {
360 sess.struct_warn_with_expectation("", expect_id)
362 (Level::Warn | Level::ForceWarn(None), Some(span)) => sess.struct_span_warn(span, ""),
363 (Level::Warn | Level::ForceWarn(None), None) => sess.struct_warn(""),
364 (Level::Deny | Level::Forbid, Some(span)) => {
365 let mut builder = sess.diagnostic().struct_err_lint("");
366 builder.set_span(span);
369 (Level::Deny | Level::Forbid, None) => sess.diagnostic().struct_err_lint(""),
372 // If this code originates in a foreign macro, aka something that this crate
373 // did not itself author, then it's likely that there's nothing this crate
374 // can do about it. We probably want to skip the lint entirely.
375 if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
376 // Any suggestions made here are likely to be incorrect, so anything we
377 // emit shouldn't be automatically fixed by rustfix.
378 err.disable_suggestions();
380 // If this is a future incompatible that is not an edition fixing lint
381 // it'll become a hard error, so we have to emit *something*. Also,
382 // if this lint occurs in the expansion of a macro from an external crate,
383 // allow individual lints to opt-out from being reported.
384 let not_future_incompatible =
385 future_incompatible.map(|f| f.reason.edition().is_some()).unwrap_or(true);
386 if not_future_incompatible && !lint.report_in_external_macro {
388 // Don't continue further, since we don't want to have
389 // `diag_span_note_once` called for a diagnostic that isn't emitted.
394 // Lint diagnostics that are covered by the expect level will not be emitted outside
395 // the compiler. It is therefore not necessary to add any information for the user.
396 // This will therefore directly call the decorate function which will in turn emit
398 if let Level::Expect(_) = level {
399 let name = lint.name_lower();
400 err.code(DiagnosticId::Lint { name, has_future_breakage, is_force_warn: false });
401 decorate(LintDiagnosticBuilder::new(err));
405 explain_lint_level_source(lint, level, src, &mut err);
407 let name = lint.name_lower();
408 let is_force_warn = matches!(level, Level::ForceWarn(_));
409 err.code(DiagnosticId::Lint { name, has_future_breakage, is_force_warn });
411 if let Some(future_incompatible) = future_incompatible {
412 let explanation = match future_incompatible.reason {
413 FutureIncompatibilityReason::FutureReleaseError
414 | FutureIncompatibilityReason::FutureReleaseErrorReportNow => {
415 "this was previously accepted by the compiler but is being phased out; \
416 it will become a hard error in a future release!"
419 FutureIncompatibilityReason::FutureReleaseSemanticsChange => {
420 "this will change its meaning in a future release!".to_owned()
422 FutureIncompatibilityReason::EditionError(edition) => {
423 let current_edition = sess.edition();
425 "this is accepted in the current edition (Rust {}) but is a hard error in Rust {}!",
426 current_edition, edition
429 FutureIncompatibilityReason::EditionSemanticsChange(edition) => {
430 format!("this changes meaning in Rust {}", edition)
432 FutureIncompatibilityReason::Custom(reason) => reason.to_owned(),
435 if future_incompatible.explain_reason {
436 err.warn(&explanation);
438 if !future_incompatible.reference.is_empty() {
440 format!("for more information, see {}", future_incompatible.reference);
445 // Finally, run `decorate`. This function is also responsible for emitting the diagnostic.
446 decorate(LintDiagnosticBuilder::new(err));
448 struct_lint_level_impl(sess, lint, level, src, span, Box::new(decorate))
451 /// Returns whether `span` originates in a foreign crate's external macro.
453 /// This is used to test whether a lint should not even begin to figure out whether it should
454 /// be reported on the current node.
455 pub fn in_external_macro(sess: &Session, span: Span) -> bool {
456 let expn_data = span.ctxt().outer_expn_data();
457 match expn_data.kind {
460 | ExpnKind::Desugaring(DesugaringKind::ForLoop | DesugaringKind::WhileLoop) => false,
461 ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
462 ExpnKind::Macro(MacroKind::Bang, _) => {
463 // Dummy span for the `def_site` means it's an external macro.
464 expn_data.def_site.is_dummy() || sess.source_map().is_imported(expn_data.def_site)
466 ExpnKind::Macro { .. } => true, // definitely a plugin