Skip to main content

rustc_lint/
context.rs

1//! Basic types for managing and implementing lints.
2//!
3//! See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for an
4//! overview of how lints are implemented.
5
6use std::slice;
7
8use rustc_abi as abi;
9use rustc_ast::BindingMode;
10use rustc_ast::util::parser::ExprPrecedence;
11use rustc_data_structures::fx::FxIndexMap;
12use rustc_data_structures::sync;
13use rustc_data_structures::unord::UnordMap;
14use rustc_errors::{Diagnostic, LintBuffer, MultiSpan};
15use rustc_feature::Features;
16use rustc_hir as hir;
17use rustc_hir::def::Res;
18use rustc_hir::def_id::{CrateNum, DefId};
19use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
20use rustc_hir::{Pat, PatKind};
21use rustc_lint_defs::{
22    CheckLintNameResult, FutureIncompatibleInfo, Lint, LintExpectationId, LintId, LintName,
23    StableLintExpectationId, UnstableLintExpectationId,
24};
25use rustc_middle::lint::{LevelSpec, StableLevelSpec, UnstableLevelSpec};
26use rustc_middle::middle::privacy::EffectiveVisibilities;
27use rustc_middle::ty::layout::{LayoutError, LayoutOfHelpers, TyAndLayout};
28use rustc_middle::ty::print::{PrintError, PrintTraitRefExt as _, Printer, with_no_trimmed_paths};
29use rustc_middle::ty::{self, RegisteredTools, Ty, TyCtxt, TypingEnv, TypingMode, Unnormalized};
30use rustc_session::{DynLintStore, Session};
31use rustc_span::edit_distance::find_best_match_for_names;
32use rustc_span::{Ident, Span, Symbol, bug, sym};
33use tracing::debug;
34
35use self::TargetLint::*;
36use crate::levels::LintLevelsBuilder;
37use crate::passes::{EarlyLintPassObject, LateLintPassObject};
38
39pub(crate) type EarlyLintPassFactory =
40    Box<dyn Fn() -> EarlyLintPassObject + sync::DynSend + sync::DynSync>;
41type LateLintPassFactory =
42    Box<dyn for<'tcx> Fn(TyCtxt<'tcx>) -> LateLintPassObject<'tcx> + sync::DynSend + sync::DynSync>;
43
44/// Information about the registered lints.
45//
46// About the pass factories: these should only be called once, but since we
47// want to avoid locks or interior mutability, we don't enforce this. Lints
48// should, in theory, be compatible with being constructed more than once,
49// though not necessarily in a sane manner. This is safe though.
50pub struct LintStore {
51    /// Registered lints.
52    lints: Vec<&'static Lint>,
53
54    /// This lint pass kind is softly deprecated. It misses expanded code and has caused a few
55    /// errors in the past. Currently, it is only used in Clippy. New implementations
56    /// should avoid using this interface, as it might be removed in the future.
57    ///
58    /// * See [rust#69838](https://github.com/rust-lang/rust/pull/69838)
59    /// * See [rust-clippy#5518](https://github.com/rust-lang/rust-clippy/pull/5518)
60    pub(crate) pre_expansion_lint_passes: Vec<EarlyLintPassFactory>,
61
62    /// These lint passes run on AST nodes.
63    pub(crate) early_lint_passes: Vec<EarlyLintPassFactory>,
64
65    /// These lint passes run on HIR nodes. Each one processes an entire crate. They don't benefit
66    /// from incremental compilation. `late_lint_mod_passes` should be used in preference where
67    /// possible; only use `late_lint_passes` for lints that implement `check_crate` and/or
68    /// `check_crate_post` and accumulate cross-module state.
69    ///
70    /// The exception is Clippy, which uses `late_lint_passes` for all late lint passes. It needs
71    /// `check_crate`/`check_crate_post` for some of its lints and uses late lint passes throughout
72    /// for consistency. This is ok because Clippy isn't wired for incremental compilation.
73    pub(crate) late_lint_passes: Vec<LateLintPassFactory>,
74
75    /// These lint passes run on HIR nodes, and are constructed per-module (i.e. multiple times).
76    /// They benefit from incremental compilation.
77    pub(crate) late_lint_mod_passes: Vec<LateLintPassFactory>,
78
79    /// Lints indexed by name.
80    by_name: UnordMap<LintName, TargetLint>,
81
82    /// Map of registered lint groups to what lints they expand to.
83    lint_groups: FxIndexMap<LintName, LintGroup>,
84}
85
86impl DynLintStore for LintStore {
87    fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = rustc_session::LintGroup> + '_> {
88        Box::new(self.get_lint_groups().map(|(name, lints, is_externally_loaded)| {
89            rustc_session::LintGroup { name, lints, is_externally_loaded }
90        }))
91    }
92
93    fn check_attribute_lint_name(
94        &self,
95        lint_name: LintName,
96        lint_tools: &RegisteredTools,
97    ) -> CheckLintNameResult<'_> {
98        self.check_lint_name(lint_name, lint_tools)
99    }
100}
101
102/// The target of the `by_name` map, which accounts for renaming/deprecation.
103#[derive(#[automatically_derived]impl ::core::fmt::Debug for TargetLint {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Id(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Id",
                    &__self_0),
            Self::Renamed(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Renamed", __self_0, &__self_1),
            Self::Removed(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Removed", &__self_0),
            Self::Ignored => ::core::fmt::Formatter::write_str(f, "Ignored"),
        }
    }
}Debug)]
104enum TargetLint {
105    /// A direct lint target
106    Id(LintId),
107
108    /// Temporary renaming, used for easing migration pain; see #16545
109    Renamed(LintName, LintId),
110
111    /// Lint with this name existed previously, but has been removed/deprecated.
112    /// The string argument is the reason for removal.
113    Removed(String),
114
115    /// A lint name that should give no warnings and have no effect.
116    ///
117    /// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers
118    /// them as tool lints.
119    Ignored,
120}
121
122struct LintAlias {
123    name: LintName,
124    /// Whether deprecation warnings should be suppressed for this alias.
125    silent: bool,
126}
127
128struct LintGroup {
129    lint_ids: Vec<LintId>,
130    is_externally_loaded: bool,
131    depr: Option<LintAlias>,
132}
133
134impl LintStore {
135    pub fn new() -> LintStore {
136        LintStore {
137            lints: ::alloc::vec::Vec::new()vec![],
138            pre_expansion_lint_passes: ::alloc::vec::Vec::new()vec![],
139            early_lint_passes: ::alloc::vec::Vec::new()vec![],
140            late_lint_passes: ::alloc::vec::Vec::new()vec![],
141            late_lint_mod_passes: ::alloc::vec::Vec::new()vec![],
142            by_name: Default::default(),
143            lint_groups: Default::default(),
144        }
145    }
146
147    pub fn get_lints<'t>(&'t self) -> &'t [&'static Lint] {
148        &self.lints
149    }
150
151    pub fn get_lint_groups(&self) -> impl Iterator<Item = (LintName, Vec<LintId>, bool)> {
152        self.lint_groups
153            .iter()
154            .filter(|(_, LintGroup { depr, .. })| {
155                // Don't display deprecated lint groups.
156                depr.is_none()
157            })
158            .map(|(k, LintGroup { lint_ids, is_externally_loaded, .. })| {
159                (k.clone(), lint_ids.clone(), *is_externally_loaded)
160            })
161    }
162
163    /// Returns all lint group names, including deprecated/aliased groups
164    pub fn get_all_group_names(&self) -> impl Iterator<Item = LintName> {
165        self.lint_groups.keys().copied()
166    }
167
168    /// See the comment on `LintStore::pre_expansion_lint_passes`.
169    pub fn register_pre_expansion_lint_pass(&mut self, pass: EarlyLintPassFactory) {
170        self.pre_expansion_lint_passes.push(pass);
171    }
172
173    /// See the comment on `LintStore::early_lint_passes`.
174    pub fn register_early_lint_pass(&mut self, pass: EarlyLintPassFactory) {
175        self.early_lint_passes.push(pass);
176    }
177
178    /// See the comment on `LintStore::late_lint_passes`.
179    pub fn register_late_lint_pass(&mut self, pass: LateLintPassFactory) {
180        self.late_lint_passes.push(pass);
181    }
182
183    /// See the comment on `LintStore::late_lint_mod_passes`.
184    pub fn register_late_lint_mod_pass(&mut self, pass: LateLintPassFactory) {
185        self.late_lint_mod_passes.push(pass);
186    }
187
188    /// Helper method for register_early/late_pass
189    pub fn register_lints(&mut self, lints: &[&'static Lint]) {
190        for lint in lints {
191            self.lints.push(lint);
192
193            let id = LintId::of(lint);
194            if self.by_name.insert(LintName::from_str(&lint.name_lower()), Id(id)).is_some() {
195                ::rustc_span::macros::bug_impl(None,
    format_args!("duplicate specification of lint {0}", lint.name_lower()),
    Location::caller())bug!("duplicate specification of lint {}", lint.name_lower())
196            }
197
198            if let Some(FutureIncompatibleInfo { reason, .. }) = lint.future_incompatible {
199                if let Some(edition) = reason.edition() {
200                    self.lint_groups
201                        .entry(LintName::from_str(edition.lint_name()))
202                        .or_insert(LintGroup {
203                            lint_ids: ::alloc::vec::Vec::new()vec![],
204                            is_externally_loaded: lint.is_externally_loaded,
205                            depr: None,
206                        })
207                        .lint_ids
208                        .push(id);
209                } else {
210                    // Lints belonging to the `future_incompatible` lint group are lints where a
211                    // future version of rustc will cause existing code to stop compiling.
212                    // Lints tied to an edition don't count because they are opt-in.
213                    self.lint_groups
214                        .entry(LintName::from_str("future_incompatible"))
215                        .or_insert(LintGroup {
216                            lint_ids: ::alloc::vec::Vec::new()vec![],
217                            is_externally_loaded: lint.is_externally_loaded,
218                            depr: None,
219                        })
220                        .lint_ids
221                        .push(id);
222                }
223            }
224        }
225    }
226
227    fn insert_group(&mut self, name: LintName, group: LintGroup) {
228        let previous = self.lint_groups.insert(name, group);
229        if previous.is_some() {
230            ::rustc_span::macros::bug_impl(None,
    format_args!("group {0} already exists", name), Location::caller());bug!("group {name} already exists");
231        }
232    }
233
234    pub fn register_group_alias(&mut self, group_name: &str, alias: &str) {
235        let group_name = LintName::from_str(group_name);
236        let alias = LintName::from_str(alias);
237        let Some(LintGroup { lint_ids, .. }) = self.lint_groups.get(&group_name) else {
238            ::rustc_span::macros::bug_impl(None,
    format_args!("group alias {0:?} points to unregistered group {1:?}",
        alias, group_name), Location::caller())bug!("group alias {alias:?} points to unregistered group {group_name:?}")
239        };
240
241        self.insert_group(
242            alias,
243            LintGroup {
244                lint_ids: lint_ids.clone(),
245                is_externally_loaded: false,
246                depr: Some(LintAlias { name: group_name, silent: true }),
247            },
248        );
249    }
250
251    pub fn register_group(
252        &mut self,
253        is_externally_loaded: bool,
254        name: &str,
255        deprecated_name: Option<&str>,
256        to: Vec<LintId>,
257    ) {
258        let name = LintName::from_str(name);
259        if let Some(deprecated) = deprecated_name {
260            let deprecated = LintName::from_str(deprecated);
261            self.insert_group(
262                deprecated,
263                LintGroup {
264                    lint_ids: to.clone(),
265                    is_externally_loaded,
266                    depr: Some(LintAlias { name, silent: false }),
267                },
268            );
269        }
270        self.insert_group(name, LintGroup { lint_ids: to, is_externally_loaded, depr: None });
271    }
272
273    /// This lint should give no warning and have no effect.
274    ///
275    /// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers them as tool lints.
276    #[track_caller]
277    pub fn register_ignored(&mut self, name: &str) {
278        if self.by_name.insert(LintName::from_str(name), Ignored).is_some() {
279            ::rustc_span::macros::bug_impl(None,
    format_args!("duplicate specification of lint {0}", name),
    Location::caller());bug!("duplicate specification of lint {}", name);
280        }
281    }
282
283    /// This lint has been renamed; warn about using the new name and apply the lint.
284    #[track_caller]
285    pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
286        let old_name = LintName::from_str(old_name);
287        let new_name = LintName::from_str(new_name);
288        let Some(&Id(target)) = self.by_name.get(&new_name) else {
289            ::rustc_span::macros::bug_impl(None,
    format_args!("invalid lint renaming of {0} to {1}", old_name, new_name),
    Location::caller());bug!("invalid lint renaming of {old_name} to {new_name}");
290        };
291        self.by_name.insert(old_name, Renamed(new_name, target));
292    }
293
294    pub fn register_removed(&mut self, name: &str, reason: &str) {
295        self.by_name.insert(LintName::from_str(name), Removed(reason.into()));
296    }
297
298    pub fn find_lints(&self, lint_name: LintName) -> Option<&[LintId]> {
299        match self.by_name.get(&lint_name) {
300            Some(Id(lint_id)) => Some(slice::from_ref(lint_id)),
301            Some(Renamed(_, lint_id)) => Some(slice::from_ref(lint_id)),
302            Some(Removed(_)) => None,
303            Some(Ignored) => Some(&[]),
304            None => match self.lint_groups.get(&lint_name) {
305                Some(LintGroup { lint_ids, .. }) => Some(lint_ids),
306                None => None,
307            },
308        }
309    }
310
311    /// True if this symbol represents a lint group name.
312    pub fn is_lint_group(&self, lint_name: LintName) -> bool {
313        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/852931e6d0b2fc1b2f3f353f1f004b77cc02409f/compiler/rustc_lint/src/context.rs:313",
                        "rustc_lint::context", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/852931e6d0b2fc1b2f3f353f1f004b77cc02409f/compiler/rustc_lint/src/context.rs"),
                        ::tracing_core::__macro_support::Option::Some(313u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_lint::context"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("is_lint_group(lint_name={0:?}, lint_groups={1:?})",
                                                    lint_name, self.lint_groups.keys().collect::<Vec<_>>()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
314            "is_lint_group(lint_name={:?}, lint_groups={:?})",
315            lint_name,
316            self.lint_groups.keys().collect::<Vec<_>>()
317        );
318        self.lint_groups.contains_key(&lint_name) || lint_name.is(sym::warnings)
319    }
320
321    /// Checks the name of a lint for its existence, and whether it was
322    /// renamed or removed. Generates a `Diag` containing a
323    /// warning for renamed and removed lints. This is over both lint
324    /// names from attributes and those passed on the command line. Since
325    /// it emits non-fatal warnings and there are *two* lint passes that
326    /// inspect attributes, this is only run from the late pass to avoid
327    /// printing duplicate warnings.
328    pub fn check_lint_name(
329        &self,
330        lint_name: LintName,
331        registered_lint_tools: &RegisteredTools,
332    ) -> CheckLintNameResult<'_> {
333        let tool_name = lint_name.tool;
334
335        if let Some(tool_name) = tool_name {
336            // FIXME: rustc and rustdoc are considered tools for lints, but not for attributes.
337            if tool_name != sym::rustc
338                && tool_name != sym::rustdoc
339                && !registered_lint_tools.contains_key(&Ident::with_dummy_span(tool_name))
340            {
341                return CheckLintNameResult::NoTool(tool_name);
342            }
343        }
344
345        // If the lint was scoped with `tool::` check if the tool lint exists
346        if let Some(tool_name) = tool_name {
347            match self.by_name.get(&lint_name) {
348                None => match self.lint_groups.get(&lint_name) {
349                    // If the lint isn't registered, there are two possibilities:
350                    None => {
351                        // 1. The tool is currently running, so this lint really doesn't exist.
352                        // FIXME: should this handle tools that never register a lint, like rustfmt?
353                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/852931e6d0b2fc1b2f3f353f1f004b77cc02409f/compiler/rustc_lint/src/context.rs:353",
                        "rustc_lint::context", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/852931e6d0b2fc1b2f3f353f1f004b77cc02409f/compiler/rustc_lint/src/context.rs"),
                        ::tracing_core::__macro_support::Option::Some(353u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_lint::context"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("lints={0:?}",
                                                    self.by_name) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("lints={:?}", self.by_name);
354
355                        return if self.by_name.keys().any(|lint| lint.tool == Some(tool_name)) {
356                            self.no_lint_suggestion(lint_name)
357                        } else {
358                            // 2. The tool isn't currently running, so no lints will be registered.
359                            // To avoid giving a false positive, ignore all unknown lints.
360                            CheckLintNameResult::MissingTool
361                        };
362                    }
363                    Some(LintGroup { lint_ids, depr, .. }) => {
364                        return if let Some(LintAlias { name, silent: false }) = depr {
365                            CheckLintNameResult::Tool(lint_ids, Some(*name))
366                        } else {
367                            CheckLintNameResult::Tool(lint_ids, None)
368                        };
369                    }
370                },
371                Some(Id(id)) => return CheckLintNameResult::Tool(slice::from_ref(id), None),
372                // If the lint was registered as removed or renamed by the lint tool, we don't need
373                // to treat tool_lints and rustc lints different and can use the code below.
374                _ => {}
375            }
376        }
377        match self.by_name.get(&lint_name) {
378            Some(Renamed(new_name, _)) => CheckLintNameResult::Renamed(*new_name),
379            Some(Removed(reason)) => CheckLintNameResult::Removed(reason.to_string()),
380            None => match self.lint_groups.get(&lint_name) {
381                None => self.no_lint_suggestion(lint_name),
382                Some(LintGroup { lint_ids, depr, .. }) => {
383                    // Check if the lint group name is deprecated
384                    if let Some(LintAlias { name, silent: false }) = depr {
385                        CheckLintNameResult::Tool(lint_ids, Some(*name))
386                    } else {
387                        CheckLintNameResult::Ok(lint_ids)
388                    }
389                }
390            },
391            Some(Id(id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
392            Some(&Ignored) => CheckLintNameResult::Ok(&[]),
393        }
394    }
395
396    fn no_lint_suggestion(&self, lint_name: LintName) -> CheckLintNameResult<'_> {
397        let name_lower = lint_name.to_lowercase();
398
399        if self.find_lints(name_lower).is_some() {
400            // First check if the lint name is (partly) in upper case instead of lower case...
401            return CheckLintNameResult::NoLint(Some((name_lower, false)));
402        }
403
404        // ...if not, search for lints with a similar name
405        // Note: find_best_match_for_name depends on the sort order of its input vector.
406        // To ensure deterministic output, sort elements of the lint_groups hash map.
407        // Also, never suggest deprecated lint groups.
408        // We will soon sort, so the initial order does not matter.
409        #[allow(rustc::potential_query_instability)]
410        let mut groups: Vec<_> = self
411            .lint_groups
412            .iter()
413            .filter_map(|(k, LintGroup { depr, .. })| depr.is_none().then_some(k))
414            .collect();
415        groups.sort();
416        let groups = groups.iter().map(|k| Symbol::intern(&k.to_string()));
417        let lints = self.lints.iter().map(|l| Symbol::intern(&l.name_lower()));
418        let names: Vec<Symbol> = groups.chain(lints).collect();
419        let mut lookups = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Symbol::intern(&name_lower.to_string())]))vec![Symbol::intern(&name_lower.to_string())];
420        if let Some(stripped) = name_lower.name.as_str().split("::").last() {
421            lookups.push(Symbol::intern(stripped));
422        }
423        let res = find_best_match_for_names(&names, &lookups, None);
424        let res = res.map(|s| LintName::from_str(s.as_str()));
425        let is_builtin =
426            res.as_ref().map(|s| lint_name.tool.is_some() && s.tool.is_none()).unwrap_or(false);
427        let suggestion = res.map(|s| (s, is_builtin));
428        CheckLintNameResult::NoLint(suggestion)
429    }
430}
431
432/// Context for lint checking outside of type inference.
433pub struct LateContext<'tcx> {
434    /// Type context we're checking in.
435    pub tcx: TyCtxt<'tcx>,
436
437    /// Current body, or `None` if outside a body.
438    pub enclosing_body: Option<hir::BodyId>,
439
440    /// Type-checking results for the current body.
441    pub typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
442
443    /// Parameter environment for the item we are in.
444    pub param_env: ty::ParamEnv<'tcx>,
445
446    /// Items accessible from the crate being checked.
447    pub effective_visibilities: &'tcx EffectiveVisibilities,
448
449    pub last_node_with_lint_attrs: hir::HirId,
450
451    /// Generic type parameters in scope for the item we are in.
452    pub generics: Option<&'tcx hir::Generics<'tcx>>,
453
454    /// We are only looking at one module
455    pub only_module: bool,
456}
457
458/// Context for lint checking of the AST, after expansion, before lowering to HIR.
459pub struct EarlyContext<'a> {
460    pub builder: LintLevelsBuilder<'a, crate::levels::TopDown>,
461    pub buffered: LintBuffer,
462    /// Whether an enclosing item comes from an external macro. Derives copy tokens of their input
463    /// into the items they generate, so the span a lint reports does not show this.
464    pub(crate) in_external_macro_item: bool,
465}
466
467pub trait LintContext {
468    type LintExpectationId: Copy + Into<LintExpectationId>;
469
470    fn sess(&self) -> &Session;
471
472    // FIXME: These methods should not take an Into<MultiSpan> -- instead, callers should need to
473    // set the span in their `decorate` function (preferably using set_span).
474    /// Emit a lint at the appropriate level, with an optional associated span.
475    ///
476    /// [`emit_lint_base`]: rustc_middle::lint::emit_lint_base#decorate-signature
477    #[track_caller]
478    fn opt_span_lint<S: Into<MultiSpan>>(
479        &self,
480        lint: &'static Lint,
481        span: Option<S>,
482        decorate: impl for<'a> Diagnostic<'a>,
483    );
484
485    /// Emit a lint at `span` from a lint struct (some type that implements `Diagnostic`,
486    /// typically generated by `#[derive(Diagnostic)]`).
487    #[track_caller]
488    fn emit_span_lint<S: Into<MultiSpan>>(
489        &self,
490        lint: &'static Lint,
491        span: S,
492        decorator: impl for<'a> Diagnostic<'a>,
493    ) {
494        self.opt_span_lint(lint, Some(span), decorator);
495    }
496
497    /// This returns the lint level spec for the given lint at the current location.
498    fn get_lint_level_spec(&self, lint: &'static Lint) -> LevelSpec<Self::LintExpectationId>;
499
500    /// This function can be used to manually fulfill an expectation. This can
501    /// be used for lints which contain several spans, and should be suppressed,
502    /// if either location was marked with an expectation.
503    ///
504    /// Note that this function should only be called for [`LintExpectationId`]s
505    /// retrieved from the current lint pass. Buffered or manually created ids can
506    /// cause ICEs.
507    fn fulfill_expectation(&self, expectation: Self::LintExpectationId) {
508        self.sess().dcx().fulfill_expectation(expectation);
509    }
510}
511
512impl<'a> EarlyContext<'a> {
513    pub(crate) fn new(
514        sess: &'a Session,
515        features: &'a Features,
516        lint_added_lints: bool,
517        lint_store: &'a LintStore,
518        registered_lint_tools: &'a RegisteredTools,
519        buffered: LintBuffer,
520    ) -> EarlyContext<'a> {
521        EarlyContext {
522            builder: LintLevelsBuilder::new(
523                sess,
524                features,
525                lint_added_lints,
526                lint_store,
527                registered_lint_tools,
528            ),
529            buffered,
530            in_external_macro_item: false,
531        }
532    }
533}
534
535impl<'tcx> LintContext for LateContext<'tcx> {
536    type LintExpectationId = StableLintExpectationId;
537
538    /// Gets the overall compiler `Session` object.
539    fn sess(&self) -> &Session {
540        self.tcx.sess
541    }
542
543    fn opt_span_lint<S: Into<MultiSpan>>(
544        &self,
545        lint: &'static Lint,
546        span: Option<S>,
547        decorate: impl for<'a> Diagnostic<'a>,
548    ) {
549        let hir_id = self.last_node_with_lint_attrs;
550
551        match span {
552            Some(s) => self.tcx.emit_node_span_lint(lint, hir_id, s, decorate),
553            None => self.tcx.emit_node_lint(lint, hir_id, decorate),
554        }
555    }
556
557    fn get_lint_level_spec(&self, lint: &'static Lint) -> StableLevelSpec {
558        self.tcx.lint_level_spec_at_node(lint, self.last_node_with_lint_attrs)
559    }
560}
561
562impl LintContext for EarlyContext<'_> {
563    type LintExpectationId = UnstableLintExpectationId;
564
565    /// Gets the overall compiler `Session` object.
566    fn sess(&self) -> &Session {
567        self.builder.sess()
568    }
569
570    fn opt_span_lint<S: Into<MultiSpan>>(
571        &self,
572        lint: &'static Lint,
573        span: Option<S>,
574        decorator: impl for<'a> Diagnostic<'a>,
575    ) {
576        self.builder.opt_span_lint(lint, span.map(|s| s.into()), decorator)
577    }
578
579    fn get_lint_level_spec(&self, lint: &'static Lint) -> UnstableLevelSpec {
580        self.builder.lint_level_spec(lint)
581    }
582}
583
584impl<'tcx> LateContext<'tcx> {
585    /// The typing mode of the currently visited node. Use this when
586    /// building a new `InferCtxt`.
587    pub fn typing_mode(&self) -> TypingMode<'tcx> {
588        if let Some(body_id) = self.enclosing_body
589            && self.tcx.use_typing_mode_post_typeck_through_borrowck()
590        {
591            let def_id = self.tcx.hir_enclosing_body_owner(body_id.hir_id);
592            TypingMode::post_borrowck_analysis(self.tcx, def_id)
593        } else {
594            TypingMode::non_body_analysis()
595        }
596    }
597
598    pub fn typing_env(&self) -> TypingEnv<'tcx> {
599        TypingEnv::new(self.param_env, self.typing_mode())
600    }
601
602    pub fn type_is_copy_modulo_regions(&self, ty: Ty<'tcx>) -> bool {
603        self.tcx.type_is_copy_modulo_regions(self.typing_env(), ty)
604    }
605
606    pub fn type_is_use_cloned_modulo_regions(&self, ty: Ty<'tcx>) -> bool {
607        self.tcx.type_is_use_cloned_modulo_regions(self.typing_env(), ty)
608    }
609
610    /// Gets the type-checking results for the current body.
611    /// As this will ICE if called outside bodies, only call when working with
612    /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
613    #[inline]
614    #[track_caller]
615    pub fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
616        self.typeck_results.expect("`LateContext::typeck_results` called outside of body")
617    }
618
619    /// Returns the final resolution of a `QPath`, or `Res::Err` if unavailable.
620    /// Unlike `.typeck_results().qpath_res(qpath, id)`, this can be used even outside
621    /// bodies (e.g. for paths in `hir::Ty`), without any risk of ICE-ing.
622    pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
623        match *qpath {
624            hir::QPath::Resolved(_, path) => path.res,
625            hir::QPath::TypeRelative(..) => self
626                .typeck_results
627                .filter(|typeck_results| typeck_results.hir_owner == id.owner)
628                .or_else(|| {
629                    self.tcx
630                        .has_typeck_results(id.owner.def_id)
631                        .then(|| self.tcx.typeck(id.owner.def_id))
632                })
633                .and_then(|typeck_results| typeck_results.type_dependent_def(id))
634                .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
635        }
636    }
637
638    /// Gets the absolute path of `def_id` as a vector of `Symbol`.
639    ///
640    /// Note that this is kinda expensive because it has to
641    /// travel the tree and pretty-print. Use sparingly.
642    ///
643    /// If you're trying to match for an item given by its path, use a
644    /// diagnostic item. If you're only interested in given sections, use more
645    /// specific functions, such as [`TyCtxt::crate_name`]
646    ///
647    /// FIXME: It would be great if this could be optimized.
648    ///
649    /// # Examples
650    ///
651    /// ```rust,ignore (no context or def id available)
652    /// let def_path = cx.get_def_path(def_id);
653    /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
654    ///     // The given `def_id` is that of an `Option` type
655    /// }
656    /// ```
657    pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
658        struct LintPathPrinter<'tcx> {
659            tcx: TyCtxt<'tcx>,
660            path: Vec<Symbol>,
661        }
662
663        impl<'tcx> Printer<'tcx> for LintPathPrinter<'tcx> {
664            fn tcx(&self) -> TyCtxt<'tcx> {
665                self.tcx
666            }
667
668            fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> {
669                ::core::panicking::unreachable_default_msg();unreachable!(); // because `print_path_with_generic_args` ignores the `GenericArgs`
670            }
671
672            fn print_type(&mut self, _ty: Ty<'tcx>) -> Result<(), PrintError> {
673                ::core::panicking::unreachable_default_msg();unreachable!(); // because `print_path_with_generic_args` ignores the `GenericArgs`
674            }
675
676            fn print_dyn_existential(
677                &mut self,
678                _predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
679            ) -> Result<(), PrintError> {
680                ::core::panicking::unreachable_default_msg();unreachable!(); // because `print_path_with_generic_args` ignores the `GenericArgs`
681            }
682
683            fn print_const(&mut self, _ct: ty::Const<'tcx>) -> Result<(), PrintError> {
684                ::core::panicking::unreachable_default_msg();unreachable!(); // because `print_path_with_generic_args` ignores the `GenericArgs`
685            }
686
687            fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
688                self.path = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.tcx.crate_name(cnum)]))vec![self.tcx.crate_name(cnum)];
689                Ok(())
690            }
691
692            fn print_path_with_qualified(
693                &mut self,
694                self_ty: Ty<'tcx>,
695                trait_ref: Option<ty::TraitRef<'tcx>>,
696            ) -> Result<(), PrintError> {
697                if trait_ref.is_none()
698                    && let ty::Adt(def, args) = self_ty.kind()
699                {
700                    return self.print_def_path(def.did(), *args);
701                }
702
703                // This shouldn't ever be needed, but just in case:
704                {
    let _guard = NoTrimmedGuard::new();
    {
        self.path =
            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [match trait_ref {
                                Some(trait_ref) =>
                                    Symbol::intern(&::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("{0:?}", trait_ref))
                                                })),
                                None =>
                                    Symbol::intern(&::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("<{0}>", self_ty))
                                                })),
                            }]));
        Ok(())
    }
}with_no_trimmed_paths!({
705                    self.path = vec![match trait_ref {
706                        Some(trait_ref) => Symbol::intern(&format!("{trait_ref:?}")),
707                        None => Symbol::intern(&format!("<{self_ty}>")),
708                    }];
709                    Ok(())
710                })
711            }
712
713            fn print_path_with_impl(
714                &mut self,
715                print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
716                self_ty: Ty<'tcx>,
717                trait_ref: Option<ty::TraitRef<'tcx>>,
718            ) -> Result<(), PrintError> {
719                print_prefix(self)?;
720
721                // This shouldn't ever be needed, but just in case:
722                self.path.push(match trait_ref {
723                    Some(trait_ref) => {
724                        {
    let _guard = NoTrimmedGuard::new();
    Symbol::intern(&::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("<impl {0} for {1}>",
                            trait_ref.print_only_trait_path(), self_ty))
                }))
}with_no_trimmed_paths!(Symbol::intern(&format!(
725                            "<impl {} for {}>",
726                            trait_ref.print_only_trait_path(),
727                            self_ty
728                        )))
729                    }
730                    None => {
731                        {
    let _guard = NoTrimmedGuard::new();
    Symbol::intern(&::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("<impl {0}>", self_ty))
                }))
}with_no_trimmed_paths!(Symbol::intern(&format!("<impl {self_ty}>")))
732                    }
733                });
734
735                Ok(())
736            }
737
738            fn print_path_with_simple(
739                &mut self,
740                print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
741                disambiguated_data: &DisambiguatedDefPathData,
742            ) -> Result<(), PrintError> {
743                print_prefix(self)?;
744
745                // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
746                if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
747                    return Ok(());
748                }
749
750                self.path.push(match disambiguated_data.data.get_opt_name() {
751                    Some(sym) => sym,
752                    None => Symbol::intern(&disambiguated_data.data.to_string()),
753                });
754                Ok(())
755            }
756
757            fn print_path_with_generic_args(
758                &mut self,
759                print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
760                _args: ty::GenericArgs<'tcx>,
761            ) -> Result<(), PrintError> {
762                print_prefix(self)
763            }
764        }
765
766        let mut p = LintPathPrinter { tcx: self.tcx, path: ::alloc::vec::Vec::new()vec![] };
767        p.print_def_path(def_id, ty::GenericArgs::empty()).unwrap();
768        p.path
769    }
770
771    /// Returns the associated type `name` for `self_ty` as an implementation of `trait_id`.
772    /// Do not invoke without first verifying that the type implements the trait.
773    pub fn get_associated_type(
774        &self,
775        self_ty: Ty<'tcx>,
776        trait_id: DefId,
777        name: Symbol,
778    ) -> Option<Ty<'tcx>> {
779        let tcx = self.tcx;
780        tcx.associated_items(trait_id)
781            .find_by_ident_and_kind(tcx, Ident::with_dummy_span(name), ty::AssocTag::Type, trait_id)
782            .and_then(|assoc| {
783                let proj = Ty::new_projection(tcx, ty::IsRigid::No, assoc.def_id, [self_ty]);
784                tcx.try_normalize_erasing_regions(self.typing_env(), Unnormalized::new_wip(proj))
785                    .ok()
786            })
787    }
788
789    /// Returns the effective precedence of an expression for the purpose of
790    /// rendering diagnostic. This is not the same as the precedence that would
791    /// be used for pretty-printing HIR by rustc_hir_pretty.
792    pub fn precedence(&self, expr: &hir::Expr<'_>) -> ExprPrecedence {
793        let has_attr = |id: hir::HirId| -> bool {
794            self.tcx
795                .hir_attrs(id)
796                .iter()
797                .any(rustc_attr_ir::Attribute::is_prefix_attr_for_suggestions)
798        };
799        expr.precedence(&has_attr)
800    }
801
802    /// If the given expression is a local binding, find the initializer expression.
803    /// If that initializer expression is another local binding, find its initializer again.
804    ///
805    /// This process repeats as long as possible (but usually no more than once).
806    /// Type-check adjustments are not taken in account in this function.
807    ///
808    /// Examples:
809    /// ```
810    /// let abc = 1;
811    /// let def = abc + 2;
812    /// //        ^^^^^^^ output
813    /// let def = def;
814    /// dbg!(def);
815    /// //   ^^^ input
816    /// ```
817    pub fn expr_or_init<'a>(&self, mut expr: &'a hir::Expr<'tcx>) -> &'a hir::Expr<'tcx> {
818        expr = expr.peel_blocks();
819
820        while let hir::ExprKind::Path(ref qpath) = expr.kind
821            && let Some(parent_node) = match self.qpath_res(qpath, expr.hir_id) {
822                Res::Local(hir_id) => Some(self.tcx.parent_hir_node(hir_id)),
823                _ => None,
824            }
825            && let Some(init) = match parent_node {
826                hir::Node::Expr(expr) => Some(expr),
827                hir::Node::LetStmt(hir::LetStmt {
828                    init,
829                    // Binding is immutable, init cannot be re-assigned
830                    pat: Pat { kind: PatKind::Binding(BindingMode::NONE, ..), .. },
831                    ..
832                }) => *init,
833                _ => None,
834            }
835        {
836            expr = init.peel_blocks();
837        }
838        expr
839    }
840
841    /// If the given expression is a local binding, find the initializer expression.
842    /// If that initializer expression is another local or **outside** (`const`/`static`)
843    /// binding, find its initializer again.
844    ///
845    /// This process repeats as long as possible (but usually no more than once).
846    /// Type-check adjustments are not taken in account in this function.
847    ///
848    /// Examples:
849    /// ```
850    /// const ABC: i32 = 1;
851    /// //               ^ output
852    /// let def = ABC;
853    /// dbg!(def);
854    /// //   ^^^ input
855    ///
856    /// // or...
857    /// let abc = 1;
858    /// let def = abc + 2;
859    /// //        ^^^^^^^ output
860    /// dbg!(def);
861    /// //   ^^^ input
862    /// ```
863    pub fn expr_or_init_with_outside_body<'a>(
864        &self,
865        mut expr: &'a hir::Expr<'tcx>,
866    ) -> &'a hir::Expr<'tcx> {
867        expr = expr.peel_blocks();
868
869        while let hir::ExprKind::Path(ref qpath) = expr.kind
870            && let Some(parent_node) = match self.qpath_res(qpath, expr.hir_id) {
871                Res::Local(hir_id) => Some(self.tcx.parent_hir_node(hir_id)),
872                Res::Def(_, def_id) => self.tcx.hir_get_if_local(def_id),
873                _ => None,
874            }
875            && let Some(init) = match parent_node {
876                hir::Node::Expr(expr) => Some(expr),
877                hir::Node::LetStmt(hir::LetStmt {
878                    init,
879                    // Binding is immutable, init cannot be re-assigned
880                    pat: Pat { kind: PatKind::Binding(BindingMode::NONE, ..), .. },
881                    ..
882                }) => *init,
883                hir::Node::Item(item) => match item.kind {
884                    // FIXME(mgca): figure out how to handle ConstArgKind::Path (or don't but add warning in docs here)
885                    hir::ItemKind::Const(.., hir::ConstItemRhs::Body(body_id))
886                    | hir::ItemKind::Static(.., body_id) => Some(self.tcx.hir_body(body_id).value),
887                    _ => None,
888                },
889                _ => None,
890            }
891        {
892            expr = init.peel_blocks();
893        }
894        expr
895    }
896}
897
898impl<'tcx> abi::HasDataLayout for LateContext<'tcx> {
899    #[inline]
900    fn data_layout(&self) -> &abi::TargetDataLayout {
901        &self.tcx.data_layout
902    }
903}
904
905impl<'tcx> ty::layout::HasTyCtxt<'tcx> for LateContext<'tcx> {
906    #[inline]
907    fn tcx(&self) -> TyCtxt<'tcx> {
908        self.tcx
909    }
910}
911
912impl<'tcx> ty::layout::HasTypingEnv<'tcx> for LateContext<'tcx> {
913    #[inline]
914    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
915        self.typing_env()
916    }
917}
918
919impl<'tcx> LayoutOfHelpers<'tcx> for LateContext<'tcx> {
920    type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
921
922    #[inline]
923    fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
924        err
925    }
926}