1use std::cell::Cell;
7use std::slice;
8
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::{Diag, LintBuffer, LintDiagnostic, MultiSpan};
15use rustc_feature::Features;
16use rustc_hir::def::Res;
17use rustc_hir::def_id::{CrateNum, DefId};
18use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
19use rustc_hir::{Pat, PatKind};
20use rustc_middle::bug;
21use rustc_middle::lint::LevelAndSource;
22use rustc_middle::middle::privacy::EffectiveVisibilities;
23use rustc_middle::ty::layout::{LayoutError, LayoutOfHelpers, TyAndLayout};
24use rustc_middle::ty::print::{PrintError, PrintTraitRefExt as _, Printer, with_no_trimmed_paths};
25use rustc_middle::ty::{self, GenericArg, RegisteredTools, Ty, TyCtxt, TypingEnv, TypingMode};
26use rustc_session::lint::{FutureIncompatibleInfo, Lint, LintExpectationId, LintId};
27use rustc_session::{DynLintStore, Session};
28use rustc_span::edit_distance::find_best_match_for_names;
29use rustc_span::{Ident, Span, Symbol, sym};
30use tracing::debug;
31use {rustc_abi as abi, rustc_hir as hir};
32
33use self::TargetLint::*;
34use crate::levels::LintLevelsBuilder;
35use crate::passes::{EarlyLintPassObject, LateLintPassObject};
36
37type EarlyLintPassFactory = dyn Fn() -> EarlyLintPassObject + sync::DynSend + sync::DynSync;
38type LateLintPassFactory =
39 dyn for<'tcx> Fn(TyCtxt<'tcx>) -> LateLintPassObject<'tcx> + sync::DynSend + sync::DynSync;
40
41pub struct LintStore {
43 lints: Vec<&'static Lint>,
45
46 pub pre_expansion_passes: Vec<Box<EarlyLintPassFactory>>,
53 pub early_passes: Vec<Box<EarlyLintPassFactory>>,
54 pub late_passes: Vec<Box<LateLintPassFactory>>,
55 pub late_module_passes: Vec<Box<LateLintPassFactory>>,
57
58 by_name: UnordMap<String, TargetLint>,
60
61 lint_groups: FxIndexMap<&'static str, LintGroup>,
63}
64
65impl DynLintStore for LintStore {
66 fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = rustc_session::LintGroup> + '_> {
67 Box::new(self.get_lint_groups().map(|(name, lints, is_externally_loaded)| {
68 rustc_session::LintGroup { name, lints, is_externally_loaded }
69 }))
70 }
71}
72
73#[derive(#[automatically_derived]
impl ::core::fmt::Debug for TargetLint {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TargetLint::Id(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Id",
&__self_0),
TargetLint::Renamed(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Renamed", __self_0, &__self_1),
TargetLint::Removed(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Removed", &__self_0),
TargetLint::Ignored =>
::core::fmt::Formatter::write_str(f, "Ignored"),
}
}
}Debug)]
75enum TargetLint {
76 Id(LintId),
78
79 Renamed(String, LintId),
81
82 Removed(String),
85
86 Ignored,
91}
92
93struct LintAlias {
94 name: &'static str,
95 silent: bool,
97}
98
99struct LintGroup {
100 lint_ids: Vec<LintId>,
101 is_externally_loaded: bool,
102 depr: Option<LintAlias>,
103}
104
105#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for CheckLintNameResult<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
CheckLintNameResult::Ok(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ok",
&__self_0),
CheckLintNameResult::NoLint(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "NoLint",
&__self_0),
CheckLintNameResult::NoTool =>
::core::fmt::Formatter::write_str(f, "NoTool"),
CheckLintNameResult::Renamed(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Renamed", &__self_0),
CheckLintNameResult::Removed(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Removed", &__self_0),
CheckLintNameResult::Tool(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Tool",
__self_0, &__self_1),
CheckLintNameResult::MissingTool =>
::core::fmt::Formatter::write_str(f, "MissingTool"),
}
}
}Debug)]
106pub enum CheckLintNameResult<'a> {
107 Ok(&'a [LintId]),
108 NoLint(Option<(Symbol, bool)>),
110 NoTool,
112 Renamed(String),
114 Removed(String),
116
117 Tool(&'a [LintId], Option<String>),
121
122 MissingTool,
126}
127
128impl LintStore {
129 pub fn new() -> LintStore {
130 LintStore {
131 lints: ::alloc::vec::Vec::new()vec![],
132 pre_expansion_passes: ::alloc::vec::Vec::new()vec![],
133 early_passes: ::alloc::vec::Vec::new()vec![],
134 late_passes: ::alloc::vec::Vec::new()vec![],
135 late_module_passes: ::alloc::vec::Vec::new()vec![],
136 by_name: Default::default(),
137 lint_groups: Default::default(),
138 }
139 }
140
141 pub fn get_lints<'t>(&'t self) -> &'t [&'static Lint] {
142 &self.lints
143 }
144
145 pub fn get_lint_groups(&self) -> impl Iterator<Item = (&'static str, Vec<LintId>, bool)> {
146 self.lint_groups
147 .iter()
148 .filter(|(_, LintGroup { depr, .. })| {
149 depr.is_none()
151 })
152 .map(|(k, LintGroup { lint_ids, is_externally_loaded, .. })| {
153 (*k, lint_ids.clone(), *is_externally_loaded)
154 })
155 }
156
157 pub fn register_early_pass(
158 &mut self,
159 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::DynSend + sync::DynSync,
160 ) {
161 self.early_passes.push(Box::new(pass));
162 }
163
164 pub fn register_pre_expansion_pass(
171 &mut self,
172 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::DynSend + sync::DynSync,
173 ) {
174 self.pre_expansion_passes.push(Box::new(pass));
175 }
176
177 pub fn register_late_pass(
178 &mut self,
179 pass: impl for<'tcx> Fn(TyCtxt<'tcx>) -> LateLintPassObject<'tcx>
180 + 'static
181 + sync::DynSend
182 + sync::DynSync,
183 ) {
184 self.late_passes.push(Box::new(pass));
185 }
186
187 pub fn register_late_mod_pass(
188 &mut self,
189 pass: impl for<'tcx> Fn(TyCtxt<'tcx>) -> LateLintPassObject<'tcx>
190 + 'static
191 + sync::DynSend
192 + sync::DynSync,
193 ) {
194 self.late_module_passes.push(Box::new(pass));
195 }
196
197 pub fn register_lints(&mut self, lints: &[&'static Lint]) {
199 for lint in lints {
200 self.lints.push(lint);
201
202 let id = LintId::of(lint);
203 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
204 ::rustc_middle::util::bug::bug_fmt(format_args!("duplicate specification of lint {0}",
lint.name_lower()))bug!("duplicate specification of lint {}", lint.name_lower())
205 }
206
207 if let Some(FutureIncompatibleInfo { reason, .. }) = lint.future_incompatible {
208 if let Some(edition) = reason.edition() {
209 self.lint_groups
210 .entry(edition.lint_name())
211 .or_insert(LintGroup {
212 lint_ids: ::alloc::vec::Vec::new()vec![],
213 is_externally_loaded: lint.is_externally_loaded,
214 depr: None,
215 })
216 .lint_ids
217 .push(id);
218 } else {
219 self.lint_groups
223 .entry("future_incompatible")
224 .or_insert(LintGroup {
225 lint_ids: ::alloc::vec::Vec::new()vec![],
226 is_externally_loaded: lint.is_externally_loaded,
227 depr: None,
228 })
229 .lint_ids
230 .push(id);
231 }
232 }
233 }
234 }
235
236 fn insert_group(&mut self, name: &'static str, group: LintGroup) {
237 let previous = self.lint_groups.insert(name, group);
238 if previous.is_some() {
239 ::rustc_middle::util::bug::bug_fmt(format_args!("group {0:?} already exists",
name));bug!("group {name:?} already exists");
240 }
241 }
242
243 pub fn register_group_alias(&mut self, group_name: &'static str, alias: &'static str) {
244 let Some(LintGroup { lint_ids, .. }) = self.lint_groups.get(group_name) else {
245 ::rustc_middle::util::bug::bug_fmt(format_args!("group alias {0:?} points to unregistered group {1:?}",
alias, group_name))bug!("group alias {alias:?} points to unregistered group {group_name:?}")
246 };
247
248 self.insert_group(
249 alias,
250 LintGroup {
251 lint_ids: lint_ids.clone(),
252 is_externally_loaded: false,
253 depr: Some(LintAlias { name: group_name, silent: true }),
254 },
255 );
256 }
257
258 pub fn register_group(
259 &mut self,
260 is_externally_loaded: bool,
261 name: &'static str,
262 deprecated_name: Option<&'static str>,
263 to: Vec<LintId>,
264 ) {
265 if let Some(deprecated) = deprecated_name {
266 self.insert_group(
267 deprecated,
268 LintGroup {
269 lint_ids: to.clone(),
270 is_externally_loaded,
271 depr: Some(LintAlias { name, silent: false }),
272 },
273 );
274 }
275 self.insert_group(name, LintGroup { lint_ids: to, is_externally_loaded, depr: None });
276 }
277
278 #[track_caller]
282 pub fn register_ignored(&mut self, name: &str) {
283 if self.by_name.insert(name.to_string(), Ignored).is_some() {
284 ::rustc_middle::util::bug::bug_fmt(format_args!("duplicate specification of lint {0}",
name));bug!("duplicate specification of lint {}", name);
285 }
286 }
287
288 #[track_caller]
290 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
291 let Some(&Id(target)) = self.by_name.get(new_name) else {
292 ::rustc_middle::util::bug::bug_fmt(format_args!("invalid lint renaming of {0} to {1}",
old_name, new_name));bug!("invalid lint renaming of {} to {}", old_name, new_name);
293 };
294 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
295 }
296
297 pub fn register_removed(&mut self, name: &str, reason: &str) {
298 self.by_name.insert(name.into(), Removed(reason.into()));
299 }
300
301 pub fn find_lints(&self, lint_name: &str) -> Option<&[LintId]> {
302 match self.by_name.get(lint_name) {
303 Some(Id(lint_id)) => Some(slice::from_ref(lint_id)),
304 Some(Renamed(_, lint_id)) => Some(slice::from_ref(lint_id)),
305 Some(Removed(_)) => None,
306 Some(Ignored) => Some(&[]),
307 None => match self.lint_groups.get(lint_name) {
308 Some(LintGroup { lint_ids, .. }) => Some(lint_ids),
309 None => None,
310 },
311 }
312 }
313
314 pub fn is_lint_group(&self, lint_name: Symbol) -> bool {
316 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_lint/src/context.rs:316",
"rustc_lint::context", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/context.rs"),
::tracing_core::__macro_support::Option::Some(316u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::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 Value))])
});
} else { ; }
};debug!(
317 "is_lint_group(lint_name={:?}, lint_groups={:?})",
318 lint_name,
319 self.lint_groups.keys().collect::<Vec<_>>()
320 );
321 let lint_name_str = lint_name.as_str();
322 self.lint_groups.contains_key(lint_name_str) || {
323 let warnings_name_str = crate::WARNINGS.name_lower();
324 lint_name_str == warnings_name_str
325 }
326 }
327
328 pub fn check_lint_name(
336 &self,
337 lint_name: &str,
338 tool_name: Option<Symbol>,
339 registered_tools: &RegisteredTools,
340 ) -> CheckLintNameResult<'_> {
341 if let Some(tool_name) = tool_name {
342 if tool_name != sym::rustc
344 && tool_name != sym::rustdoc
345 && !registered_tools.contains(&Ident::with_dummy_span(tool_name))
346 {
347 return CheckLintNameResult::NoTool;
348 }
349 }
350
351 let complete_name = if let Some(tool_name) = tool_name {
352 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}", tool_name, lint_name))
})format!("{tool_name}::{lint_name}")
353 } else {
354 lint_name.to_string()
355 };
356 if let Some(tool_name) = tool_name {
358 match self.by_name.get(&complete_name) {
359 None => match self.lint_groups.get(&*complete_name) {
360 None => {
362 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_lint/src/context.rs:364",
"rustc_lint::context", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/context.rs"),
::tracing_core::__macro_support::Option::Some(364u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("lints={0:?}",
self.by_name) as &dyn Value))])
});
} else { ; }
};debug!("lints={:?}", self.by_name);
365 let tool_prefix = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::", tool_name))
})format!("{tool_name}::");
366
367 return if self.by_name.keys().any(|lint| lint.starts_with(&tool_prefix)) {
368 self.no_lint_suggestion(&complete_name, tool_name.as_str())
369 } else {
370 CheckLintNameResult::MissingTool
373 };
374 }
375 Some(LintGroup { lint_ids, depr, .. }) => {
376 return if let &Some(LintAlias { name, silent: false }) = depr {
377 CheckLintNameResult::Tool(lint_ids, Some(name.to_string()))
378 } else {
379 CheckLintNameResult::Tool(lint_ids, None)
380 };
381 }
382 },
383 Some(Id(id)) => return CheckLintNameResult::Tool(slice::from_ref(id), None),
384 _ => {}
387 }
388 }
389 match self.by_name.get(&complete_name) {
390 Some(Renamed(new_name, _)) => CheckLintNameResult::Renamed(new_name.to_string()),
391 Some(Removed(reason)) => CheckLintNameResult::Removed(reason.to_string()),
392 None => match self.lint_groups.get(&*complete_name) {
393 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
396 Some(LintGroup { lint_ids, depr, .. }) => {
397 if let &Some(LintAlias { name, silent: false }) = depr {
399 CheckLintNameResult::Tool(lint_ids, Some(name.to_string()))
400 } else {
401 CheckLintNameResult::Ok(lint_ids)
402 }
403 }
404 },
405 Some(Id(id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
406 Some(&Ignored) => CheckLintNameResult::Ok(&[]),
407 }
408 }
409
410 fn no_lint_suggestion(&self, lint_name: &str, tool_name: &str) -> CheckLintNameResult<'_> {
411 let name_lower = lint_name.to_lowercase();
412
413 if lint_name.chars().any(char::is_uppercase) && self.find_lints(&name_lower).is_some() {
414 return CheckLintNameResult::NoLint(Some((Symbol::intern(&name_lower), false)));
416 }
417
418 #[allow(rustc::potential_query_instability)]
424 let mut groups: Vec<_> = self
425 .lint_groups
426 .iter()
427 .filter_map(|(k, LintGroup { depr, .. })| depr.is_none().then_some(k))
428 .collect();
429 groups.sort();
430 let groups = groups.iter().map(|k| Symbol::intern(k));
431 let lints = self.lints.iter().map(|l| Symbol::intern(&l.name_lower()));
432 let names: Vec<Symbol> = groups.chain(lints).collect();
433 let mut lookups = <[_]>::into_vec(::alloc::boxed::box_new([Symbol::intern(&name_lower)]))vec![Symbol::intern(&name_lower)];
434 if let Some(stripped) = name_lower.split("::").last() {
435 lookups.push(Symbol::intern(stripped));
436 }
437 let res = find_best_match_for_names(&names, &lookups, None);
438 let is_rustc = res.map_or_else(
439 || false,
440 |s| name_lower.contains("::") && !s.as_str().starts_with(tool_name),
441 );
442 let suggestion = res.map(|s| (s, is_rustc));
443 CheckLintNameResult::NoLint(suggestion)
444 }
445
446 fn check_tool_name_for_backwards_compat(
447 &self,
448 lint_name: &str,
449 tool_name: &str,
450 ) -> CheckLintNameResult<'_> {
451 let complete_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}", tool_name, lint_name))
})format!("{tool_name}::{lint_name}");
452 match self.by_name.get(&complete_name) {
453 None => match self.lint_groups.get(&*complete_name) {
454 None => self.no_lint_suggestion(lint_name, tool_name),
456 Some(LintGroup { lint_ids, .. }) => {
457 CheckLintNameResult::Tool(lint_ids, Some(complete_name))
458 }
459 },
460 Some(Id(id)) => CheckLintNameResult::Tool(slice::from_ref(id), Some(complete_name)),
461 Some(other) => {
462 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_lint/src/context.rs:462",
"rustc_lint::context", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_lint/src/context.rs"),
::tracing_core::__macro_support::Option::Some(462u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("got renamed lint {0:?}",
other) as &dyn Value))])
});
} else { ; }
};debug!("got renamed lint {:?}", other);
463 CheckLintNameResult::NoLint(None)
464 }
465 }
466 }
467}
468
469pub struct LateContext<'tcx> {
471 pub tcx: TyCtxt<'tcx>,
473
474 pub enclosing_body: Option<hir::BodyId>,
476
477 pub(super) cached_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
482
483 pub param_env: ty::ParamEnv<'tcx>,
485
486 pub effective_visibilities: &'tcx EffectiveVisibilities,
488
489 pub last_node_with_lint_attrs: hir::HirId,
490
491 pub generics: Option<&'tcx hir::Generics<'tcx>>,
493
494 pub only_module: bool,
496}
497
498pub struct EarlyContext<'a> {
500 pub builder: LintLevelsBuilder<'a, crate::levels::TopDown>,
501 pub buffered: LintBuffer,
502}
503
504pub trait LintContext {
505 fn sess(&self) -> &Session;
506
507 #[track_caller]
513 fn opt_span_lint<S: Into<MultiSpan>>(
514 &self,
515 lint: &'static Lint,
516 span: Option<S>,
517 decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
518 );
519
520 fn emit_span_lint<S: Into<MultiSpan>>(
523 &self,
524 lint: &'static Lint,
525 span: S,
526 decorator: impl for<'a> LintDiagnostic<'a, ()>,
527 ) {
528 self.opt_span_lint(lint, Some(span), |lint| {
529 decorator.decorate_lint(lint);
530 });
531 }
532
533 fn emit_span_lint_lazy<S: Into<MultiSpan>, L: for<'a> LintDiagnostic<'a, ()>>(
536 &self,
537 lint: &'static Lint,
538 span: S,
539 decorator: impl FnOnce() -> L,
540 ) {
541 self.opt_span_lint(lint, Some(span), |lint| {
542 let decorator = decorator();
543 decorator.decorate_lint(lint);
544 });
545 }
546
547 #[track_caller]
551 fn span_lint<S: Into<MultiSpan>>(
552 &self,
553 lint: &'static Lint,
554 span: S,
555 decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
556 ) {
557 self.opt_span_lint(lint, Some(span), decorate);
558 }
559
560 fn emit_lint(&self, lint: &'static Lint, decorator: impl for<'a> LintDiagnostic<'a, ()>) {
563 self.opt_span_lint(lint, None as Option<Span>, |lint| {
564 decorator.decorate_lint(lint);
565 });
566 }
567
568 fn lint(&self, lint: &'static Lint, decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>)) {
572 self.opt_span_lint(lint, None as Option<Span>, decorate);
573 }
574
575 fn get_lint_level(&self, lint: &'static Lint) -> LevelAndSource;
577
578 fn fulfill_expectation(&self, expectation: LintExpectationId) {
586 self.sess()
591 .dcx()
592 .struct_expect(
593 "this is a dummy diagnostic, to submit and store an expectation",
594 expectation,
595 )
596 .emit();
597 }
598}
599
600impl<'a> EarlyContext<'a> {
601 pub(crate) fn new(
602 sess: &'a Session,
603 features: &'a Features,
604 lint_added_lints: bool,
605 lint_store: &'a LintStore,
606 registered_tools: &'a RegisteredTools,
607 buffered: LintBuffer,
608 ) -> EarlyContext<'a> {
609 EarlyContext {
610 builder: LintLevelsBuilder::new(
611 sess,
612 features,
613 lint_added_lints,
614 lint_store,
615 registered_tools,
616 ),
617 buffered,
618 }
619 }
620}
621
622impl<'tcx> LintContext for LateContext<'tcx> {
623 fn sess(&self) -> &Session {
625 self.tcx.sess
626 }
627
628 fn opt_span_lint<S: Into<MultiSpan>>(
629 &self,
630 lint: &'static Lint,
631 span: Option<S>,
632 decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
633 ) {
634 let hir_id = self.last_node_with_lint_attrs;
635
636 match span {
637 Some(s) => self.tcx.node_span_lint(lint, hir_id, s, decorate),
638 None => self.tcx.node_lint(lint, hir_id, decorate),
639 }
640 }
641
642 fn get_lint_level(&self, lint: &'static Lint) -> LevelAndSource {
643 self.tcx.lint_level_at_node(lint, self.last_node_with_lint_attrs)
644 }
645}
646
647impl LintContext for EarlyContext<'_> {
648 fn sess(&self) -> &Session {
650 self.builder.sess()
651 }
652
653 fn opt_span_lint<S: Into<MultiSpan>>(
654 &self,
655 lint: &'static Lint,
656 span: Option<S>,
657 decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
658 ) {
659 self.builder.opt_span_lint(lint, span.map(|s| s.into()), decorate)
660 }
661
662 fn get_lint_level(&self, lint: &'static Lint) -> LevelAndSource {
663 self.builder.lint_level(lint)
664 }
665}
666
667impl<'tcx> LateContext<'tcx> {
668 pub fn typing_mode(&self) -> TypingMode<'tcx> {
671 TypingMode::non_body_analysis()
674 }
675
676 pub fn typing_env(&self) -> TypingEnv<'tcx> {
677 TypingEnv { typing_mode: self.typing_mode(), param_env: self.param_env }
678 }
679
680 pub fn type_is_copy_modulo_regions(&self, ty: Ty<'tcx>) -> bool {
681 self.tcx.type_is_copy_modulo_regions(self.typing_env(), ty)
682 }
683
684 pub fn type_is_use_cloned_modulo_regions(&self, ty: Ty<'tcx>) -> bool {
685 self.tcx.type_is_use_cloned_modulo_regions(self.typing_env(), ty)
686 }
687
688 pub fn maybe_typeck_results(&self) -> Option<&'tcx ty::TypeckResults<'tcx>> {
691 self.cached_typeck_results.get().or_else(|| {
692 self.enclosing_body.map(|body| {
693 let typeck_results = self.tcx.typeck_body(body);
694 self.cached_typeck_results.set(Some(typeck_results));
695 typeck_results
696 })
697 })
698 }
699
700 #[track_caller]
704 pub fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
705 self.maybe_typeck_results().expect("`LateContext::typeck_results` called outside of body")
706 }
707
708 pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
712 match *qpath {
713 hir::QPath::Resolved(_, path) => path.res,
714 hir::QPath::TypeRelative(..) => self
715 .maybe_typeck_results()
716 .filter(|typeck_results| typeck_results.hir_owner == id.owner)
717 .or_else(|| {
718 self.tcx
719 .has_typeck_results(id.owner.def_id)
720 .then(|| self.tcx.typeck(id.owner.def_id))
721 })
722 .and_then(|typeck_results| typeck_results.type_dependent_def(id))
723 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
724 }
725 }
726
727 pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
747 struct LintPathPrinter<'tcx> {
748 tcx: TyCtxt<'tcx>,
749 path: Vec<Symbol>,
750 }
751
752 impl<'tcx> Printer<'tcx> for LintPathPrinter<'tcx> {
753 fn tcx(&self) -> TyCtxt<'tcx> {
754 self.tcx
755 }
756
757 fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> {
758 ::core::panicking::panic("internal error: entered unreachable code");unreachable!(); }
760
761 fn print_type(&mut self, _ty: Ty<'tcx>) -> Result<(), PrintError> {
762 ::core::panicking::panic("internal error: entered unreachable code");unreachable!(); }
764
765 fn print_dyn_existential(
766 &mut self,
767 _predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
768 ) -> Result<(), PrintError> {
769 ::core::panicking::panic("internal error: entered unreachable code");unreachable!(); }
771
772 fn print_const(&mut self, _ct: ty::Const<'tcx>) -> Result<(), PrintError> {
773 ::core::panicking::panic("internal error: entered unreachable code");unreachable!(); }
775
776 fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
777 self.path = <[_]>::into_vec(::alloc::boxed::box_new([self.tcx.crate_name(cnum)]))vec![self.tcx.crate_name(cnum)];
778 Ok(())
779 }
780
781 fn print_path_with_qualified(
782 &mut self,
783 self_ty: Ty<'tcx>,
784 trait_ref: Option<ty::TraitRef<'tcx>>,
785 ) -> Result<(), PrintError> {
786 if trait_ref.is_none()
787 && let ty::Adt(def, args) = self_ty.kind()
788 {
789 return self.print_def_path(def.did(), args);
790 }
791
792 {
let _guard = NoTrimmedGuard::new();
{
self.path =
<[_]>::into_vec(::alloc::boxed::box_new([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!({
794 self.path = vec![match trait_ref {
795 Some(trait_ref) => Symbol::intern(&format!("{trait_ref:?}")),
796 None => Symbol::intern(&format!("<{self_ty}>")),
797 }];
798 Ok(())
799 })
800 }
801
802 fn print_path_with_impl(
803 &mut self,
804 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
805 self_ty: Ty<'tcx>,
806 trait_ref: Option<ty::TraitRef<'tcx>>,
807 ) -> Result<(), PrintError> {
808 print_prefix(self)?;
809
810 self.path.push(match trait_ref {
812 Some(trait_ref) => {
813 {
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!(
814 "<impl {} for {}>",
815 trait_ref.print_only_trait_path(),
816 self_ty
817 )))
818 }
819 None => {
820 {
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}>")))
821 }
822 });
823
824 Ok(())
825 }
826
827 fn print_path_with_simple(
828 &mut self,
829 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
830 disambiguated_data: &DisambiguatedDefPathData,
831 ) -> Result<(), PrintError> {
832 print_prefix(self)?;
833
834 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
836 return Ok(());
837 }
838
839 self.path.push(match disambiguated_data.data.get_opt_name() {
840 Some(sym) => sym,
841 None => Symbol::intern(&disambiguated_data.data.to_string()),
842 });
843 Ok(())
844 }
845
846 fn print_path_with_generic_args(
847 &mut self,
848 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
849 _args: &[GenericArg<'tcx>],
850 ) -> Result<(), PrintError> {
851 print_prefix(self)
852 }
853 }
854
855 let mut p = LintPathPrinter { tcx: self.tcx, path: ::alloc::vec::Vec::new()vec![] };
856 p.print_def_path(def_id, &[]).unwrap();
857 p.path
858 }
859
860 pub fn get_associated_type(
863 &self,
864 self_ty: Ty<'tcx>,
865 trait_id: DefId,
866 name: Symbol,
867 ) -> Option<Ty<'tcx>> {
868 let tcx = self.tcx;
869 tcx.associated_items(trait_id)
870 .find_by_ident_and_kind(tcx, Ident::with_dummy_span(name), ty::AssocTag::Type, trait_id)
871 .and_then(|assoc| {
872 let proj = Ty::new_projection(tcx, assoc.def_id, [self_ty]);
873 tcx.try_normalize_erasing_regions(self.typing_env(), proj).ok()
874 })
875 }
876
877 pub fn precedence(&self, expr: &hir::Expr<'_>) -> ExprPrecedence {
881 let has_attr = |id: hir::HirId| -> bool {
882 for attr in self.tcx.hir_attrs(id) {
883 if attr.span().desugaring_kind().is_none() {
884 return true;
885 }
886 }
887 false
888 };
889 expr.precedence(&has_attr)
890 }
891
892 pub fn expr_or_init<'a>(&self, mut expr: &'a hir::Expr<'tcx>) -> &'a hir::Expr<'tcx> {
908 expr = expr.peel_blocks();
909
910 while let hir::ExprKind::Path(ref qpath) = expr.kind
911 && let Some(parent_node) = match self.qpath_res(qpath, expr.hir_id) {
912 Res::Local(hir_id) => Some(self.tcx.parent_hir_node(hir_id)),
913 _ => None,
914 }
915 && let Some(init) = match parent_node {
916 hir::Node::Expr(expr) => Some(expr),
917 hir::Node::LetStmt(hir::LetStmt {
918 init,
919 pat: Pat { kind: PatKind::Binding(BindingMode::NONE, ..), .. },
921 ..
922 }) => *init,
923 _ => None,
924 }
925 {
926 expr = init.peel_blocks();
927 }
928 expr
929 }
930
931 pub fn expr_or_init_with_outside_body<'a>(
954 &self,
955 mut expr: &'a hir::Expr<'tcx>,
956 ) -> &'a hir::Expr<'tcx> {
957 expr = expr.peel_blocks();
958
959 while let hir::ExprKind::Path(ref qpath) = expr.kind
960 && let Some(parent_node) = match self.qpath_res(qpath, expr.hir_id) {
961 Res::Local(hir_id) => Some(self.tcx.parent_hir_node(hir_id)),
962 Res::Def(_, def_id) => self.tcx.hir_get_if_local(def_id),
963 _ => None,
964 }
965 && let Some(init) = match parent_node {
966 hir::Node::Expr(expr) => Some(expr),
967 hir::Node::LetStmt(hir::LetStmt {
968 init,
969 pat: Pat { kind: PatKind::Binding(BindingMode::NONE, ..), .. },
971 ..
972 }) => *init,
973 hir::Node::Item(item) => match item.kind {
974 hir::ItemKind::Const(.., hir::ConstItemRhs::Body(body_id))
976 | hir::ItemKind::Static(.., body_id) => Some(self.tcx.hir_body(body_id).value),
977 _ => None,
978 },
979 _ => None,
980 }
981 {
982 expr = init.peel_blocks();
983 }
984 expr
985 }
986}
987
988impl<'tcx> abi::HasDataLayout for LateContext<'tcx> {
989 #[inline]
990 fn data_layout(&self) -> &abi::TargetDataLayout {
991 &self.tcx.data_layout
992 }
993}
994
995impl<'tcx> ty::layout::HasTyCtxt<'tcx> for LateContext<'tcx> {
996 #[inline]
997 fn tcx(&self) -> TyCtxt<'tcx> {
998 self.tcx
999 }
1000}
1001
1002impl<'tcx> ty::layout::HasTypingEnv<'tcx> for LateContext<'tcx> {
1003 #[inline]
1004 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
1005 self.typing_env()
1006 }
1007}
1008
1009impl<'tcx> LayoutOfHelpers<'tcx> for LateContext<'tcx> {
1010 type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
1011
1012 #[inline]
1013 fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
1014 err
1015 }
1016}