1use 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
44pub struct LintStore {
51 lints: Vec<&'static Lint>,
53
54 pub(crate) pre_expansion_lint_passes: Vec<EarlyLintPassFactory>,
61
62 pub(crate) early_lint_passes: Vec<EarlyLintPassFactory>,
64
65 pub(crate) late_lint_passes: Vec<LateLintPassFactory>,
74
75 pub(crate) late_lint_mod_passes: Vec<LateLintPassFactory>,
78
79 by_name: UnordMap<LintName, TargetLint>,
81
82 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#[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 Id(LintId),
107
108 Renamed(LintName, LintId),
110
111 Removed(String),
114
115 Ignored,
120}
121
122struct LintAlias {
123 name: LintName,
124 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 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 pub fn get_all_group_names(&self) -> impl Iterator<Item = LintName> {
165 self.lint_groups.keys().copied()
166 }
167
168 pub fn register_pre_expansion_lint_pass(&mut self, pass: EarlyLintPassFactory) {
170 self.pre_expansion_lint_passes.push(pass);
171 }
172
173 pub fn register_early_lint_pass(&mut self, pass: EarlyLintPassFactory) {
175 self.early_lint_passes.push(pass);
176 }
177
178 pub fn register_late_lint_pass(&mut self, pass: LateLintPassFactory) {
180 self.late_lint_passes.push(pass);
181 }
182
183 pub fn register_late_lint_mod_pass(&mut self, pass: LateLintPassFactory) {
185 self.late_lint_mod_passes.push(pass);
186 }
187
188 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 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 #[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 #[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 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 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 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 let Some(tool_name) = tool_name {
347 match self.by_name.get(&lint_name) {
348 None => match self.lint_groups.get(&lint_name) {
349 None => {
351 {
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 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 _ => {}
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 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 return CheckLintNameResult::NoLint(Some((name_lower, false)));
402 }
403
404 #[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
432pub struct LateContext<'tcx> {
434 pub tcx: TyCtxt<'tcx>,
436
437 pub enclosing_body: Option<hir::BodyId>,
439
440 pub typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
442
443 pub param_env: ty::ParamEnv<'tcx>,
445
446 pub effective_visibilities: &'tcx EffectiveVisibilities,
448
449 pub last_node_with_lint_attrs: hir::HirId,
450
451 pub generics: Option<&'tcx hir::Generics<'tcx>>,
453
454 pub only_module: bool,
456}
457
458pub struct EarlyContext<'a> {
460 pub builder: LintLevelsBuilder<'a, crate::levels::TopDown>,
461 pub buffered: LintBuffer,
462 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 #[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 #[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 fn get_lint_level_spec(&self, lint: &'static Lint) -> LevelSpec<Self::LintExpectationId>;
499
500 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 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 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 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 #[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 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 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!(); }
671
672 fn print_type(&mut self, _ty: Ty<'tcx>) -> Result<(), PrintError> {
673 ::core::panicking::unreachable_default_msg();unreachable!(); }
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!(); }
682
683 fn print_const(&mut self, _ct: ty::Const<'tcx>) -> Result<(), PrintError> {
684 ::core::panicking::unreachable_default_msg();unreachable!(); }
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 {
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 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 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 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 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 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 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 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 pat: Pat { kind: PatKind::Binding(BindingMode::NONE, ..), .. },
881 ..
882 }) => *init,
883 hir::Node::Item(item) => match item.kind {
884 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}