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, 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, LintBuffer, LintExpectationId, LintId};
27use rustc_session::{LintStoreMarker, 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 LintStoreMarker for LintStore {}
66
67#[derive(Debug)]
69enum TargetLint {
70 Id(LintId),
72
73 Renamed(String, LintId),
75
76 Removed(String),
79
80 Ignored,
85}
86
87struct LintAlias {
88 name: &'static str,
89 silent: bool,
91}
92
93struct LintGroup {
94 lint_ids: Vec<LintId>,
95 is_externally_loaded: bool,
96 depr: Option<LintAlias>,
97}
98
99#[derive(Debug)]
100pub enum CheckLintNameResult<'a> {
101 Ok(&'a [LintId]),
102 NoLint(Option<(Symbol, bool)>),
104 NoTool,
106 Renamed(String),
108 Removed(String),
110
111 Tool(&'a [LintId], Option<String>),
115
116 MissingTool,
120}
121
122impl LintStore {
123 pub fn new() -> LintStore {
124 LintStore {
125 lints: vec![],
126 pre_expansion_passes: vec![],
127 early_passes: vec![],
128 late_passes: vec![],
129 late_module_passes: vec![],
130 by_name: Default::default(),
131 lint_groups: Default::default(),
132 }
133 }
134
135 pub fn get_lints<'t>(&'t self) -> &'t [&'static Lint] {
136 &self.lints
137 }
138
139 pub fn get_lint_groups(&self) -> impl Iterator<Item = (&'static str, Vec<LintId>, bool)> {
140 self.lint_groups
141 .iter()
142 .filter(|(_, LintGroup { depr, .. })| {
143 depr.is_none()
145 })
146 .map(|(k, LintGroup { lint_ids, is_externally_loaded, .. })| {
147 (*k, lint_ids.clone(), *is_externally_loaded)
148 })
149 }
150
151 pub fn register_early_pass(
152 &mut self,
153 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::DynSend + sync::DynSync,
154 ) {
155 self.early_passes.push(Box::new(pass));
156 }
157
158 pub fn register_pre_expansion_pass(
165 &mut self,
166 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::DynSend + sync::DynSync,
167 ) {
168 self.pre_expansion_passes.push(Box::new(pass));
169 }
170
171 pub fn register_late_pass(
172 &mut self,
173 pass: impl for<'tcx> Fn(TyCtxt<'tcx>) -> LateLintPassObject<'tcx>
174 + 'static
175 + sync::DynSend
176 + sync::DynSync,
177 ) {
178 self.late_passes.push(Box::new(pass));
179 }
180
181 pub fn register_late_mod_pass(
182 &mut self,
183 pass: impl for<'tcx> Fn(TyCtxt<'tcx>) -> LateLintPassObject<'tcx>
184 + 'static
185 + sync::DynSend
186 + sync::DynSync,
187 ) {
188 self.late_module_passes.push(Box::new(pass));
189 }
190
191 pub fn register_lints(&mut self, lints: &[&'static Lint]) {
193 for lint in lints {
194 self.lints.push(lint);
195
196 let id = LintId::of(lint);
197 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
198 bug!("duplicate specification of lint {}", lint.name_lower())
199 }
200
201 if let Some(FutureIncompatibleInfo { reason, .. }) = lint.future_incompatible {
202 if let Some(edition) = reason.edition() {
203 self.lint_groups
204 .entry(edition.lint_name())
205 .or_insert(LintGroup {
206 lint_ids: vec![],
207 is_externally_loaded: lint.is_externally_loaded,
208 depr: None,
209 })
210 .lint_ids
211 .push(id);
212 } else {
213 self.lint_groups
217 .entry("future_incompatible")
218 .or_insert(LintGroup {
219 lint_ids: vec![],
220 is_externally_loaded: lint.is_externally_loaded,
221 depr: None,
222 })
223 .lint_ids
224 .push(id);
225 }
226 }
227 }
228 }
229
230 fn insert_group(&mut self, name: &'static str, group: LintGroup) {
231 let previous = self.lint_groups.insert(name, group);
232 if previous.is_some() {
233 bug!("group {name:?} already exists");
234 }
235 }
236
237 pub fn register_group_alias(&mut self, group_name: &'static str, alias: &'static str) {
238 let Some(LintGroup { lint_ids, .. }) = self.lint_groups.get(group_name) else {
239 bug!("group alias {alias:?} points to unregistered group {group_name:?}")
240 };
241
242 self.insert_group(
243 alias,
244 LintGroup {
245 lint_ids: lint_ids.clone(),
246 is_externally_loaded: false,
247 depr: Some(LintAlias { name: group_name, silent: true }),
248 },
249 );
250 }
251
252 pub fn register_group(
253 &mut self,
254 is_externally_loaded: bool,
255 name: &'static str,
256 deprecated_name: Option<&'static str>,
257 to: Vec<LintId>,
258 ) {
259 if let Some(deprecated) = deprecated_name {
260 self.insert_group(
261 deprecated,
262 LintGroup {
263 lint_ids: to.clone(),
264 is_externally_loaded,
265 depr: Some(LintAlias { name, silent: false }),
266 },
267 );
268 }
269 self.insert_group(name, LintGroup { lint_ids: to, is_externally_loaded, depr: None });
270 }
271
272 #[track_caller]
276 pub fn register_ignored(&mut self, name: &str) {
277 if self.by_name.insert(name.to_string(), Ignored).is_some() {
278 bug!("duplicate specification of lint {}", name);
279 }
280 }
281
282 #[track_caller]
284 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
285 let Some(&Id(target)) = self.by_name.get(new_name) else {
286 bug!("invalid lint renaming of {} to {}", old_name, new_name);
287 };
288 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
289 }
290
291 pub fn register_removed(&mut self, name: &str, reason: &str) {
292 self.by_name.insert(name.into(), Removed(reason.into()));
293 }
294
295 pub fn find_lints(&self, lint_name: &str) -> Option<&[LintId]> {
296 match self.by_name.get(lint_name) {
297 Some(Id(lint_id)) => Some(slice::from_ref(lint_id)),
298 Some(Renamed(_, lint_id)) => Some(slice::from_ref(lint_id)),
299 Some(Removed(_)) => None,
300 Some(Ignored) => Some(&[]),
301 None => match self.lint_groups.get(lint_name) {
302 Some(LintGroup { lint_ids, .. }) => Some(lint_ids),
303 None => None,
304 },
305 }
306 }
307
308 pub fn is_lint_group(&self, lint_name: Symbol) -> bool {
310 debug!(
311 "is_lint_group(lint_name={:?}, lint_groups={:?})",
312 lint_name,
313 self.lint_groups.keys().collect::<Vec<_>>()
314 );
315 let lint_name_str = lint_name.as_str();
316 self.lint_groups.contains_key(lint_name_str) || {
317 let warnings_name_str = crate::WARNINGS.name_lower();
318 lint_name_str == warnings_name_str
319 }
320 }
321
322 pub fn check_lint_name(
330 &self,
331 lint_name: &str,
332 tool_name: Option<Symbol>,
333 registered_tools: &RegisteredTools,
334 ) -> CheckLintNameResult<'_> {
335 if let Some(tool_name) = tool_name {
336 if tool_name != sym::rustc
338 && tool_name != sym::rustdoc
339 && !registered_tools.contains(&Ident::with_dummy_span(tool_name))
340 {
341 return CheckLintNameResult::NoTool;
342 }
343 }
344
345 let complete_name = if let Some(tool_name) = tool_name {
346 format!("{tool_name}::{lint_name}")
347 } else {
348 lint_name.to_string()
349 };
350 if let Some(tool_name) = tool_name {
352 match self.by_name.get(&complete_name) {
353 None => match self.lint_groups.get(&*complete_name) {
354 None => {
356 debug!("lints={:?}", self.by_name);
359 let tool_prefix = format!("{tool_name}::");
360
361 return if self.by_name.keys().any(|lint| lint.starts_with(&tool_prefix)) {
362 self.no_lint_suggestion(&complete_name, tool_name.as_str())
363 } else {
364 CheckLintNameResult::MissingTool
367 };
368 }
369 Some(LintGroup { lint_ids, depr, .. }) => {
370 return if let &Some(LintAlias { name, silent: false }) = depr {
371 CheckLintNameResult::Tool(lint_ids, Some(name.to_string()))
372 } else {
373 CheckLintNameResult::Tool(lint_ids, None)
374 };
375 }
376 },
377 Some(Id(id)) => return CheckLintNameResult::Tool(slice::from_ref(id), None),
378 _ => {}
381 }
382 }
383 match self.by_name.get(&complete_name) {
384 Some(Renamed(new_name, _)) => CheckLintNameResult::Renamed(new_name.to_string()),
385 Some(Removed(reason)) => CheckLintNameResult::Removed(reason.to_string()),
386 None => match self.lint_groups.get(&*complete_name) {
387 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
390 Some(LintGroup { lint_ids, depr, .. }) => {
391 if let &Some(LintAlias { name, silent: false }) = depr {
393 CheckLintNameResult::Tool(lint_ids, Some(name.to_string()))
394 } else {
395 CheckLintNameResult::Ok(lint_ids)
396 }
397 }
398 },
399 Some(Id(id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
400 Some(&Ignored) => CheckLintNameResult::Ok(&[]),
401 }
402 }
403
404 fn no_lint_suggestion(&self, lint_name: &str, tool_name: &str) -> CheckLintNameResult<'_> {
405 let name_lower = lint_name.to_lowercase();
406
407 if lint_name.chars().any(char::is_uppercase) && self.find_lints(&name_lower).is_some() {
408 return CheckLintNameResult::NoLint(Some((Symbol::intern(&name_lower), false)));
410 }
411
412 #[allow(rustc::potential_query_instability)]
418 let mut groups: Vec<_> = self
419 .lint_groups
420 .iter()
421 .filter_map(|(k, LintGroup { depr, .. })| depr.is_none().then_some(k))
422 .collect();
423 groups.sort();
424 let groups = groups.iter().map(|k| Symbol::intern(k));
425 let lints = self.lints.iter().map(|l| Symbol::intern(&l.name_lower()));
426 let names: Vec<Symbol> = groups.chain(lints).collect();
427 let mut lookups = vec![Symbol::intern(&name_lower)];
428 if let Some(stripped) = name_lower.split("::").last() {
429 lookups.push(Symbol::intern(stripped));
430 }
431 let res = find_best_match_for_names(&names, &lookups, None);
432 let is_rustc = res.map_or_else(
433 || false,
434 |s| name_lower.contains("::") && !s.as_str().starts_with(tool_name),
435 );
436 let suggestion = res.map(|s| (s, is_rustc));
437 CheckLintNameResult::NoLint(suggestion)
438 }
439
440 fn check_tool_name_for_backwards_compat(
441 &self,
442 lint_name: &str,
443 tool_name: &str,
444 ) -> CheckLintNameResult<'_> {
445 let complete_name = format!("{tool_name}::{lint_name}");
446 match self.by_name.get(&complete_name) {
447 None => match self.lint_groups.get(&*complete_name) {
448 None => self.no_lint_suggestion(lint_name, tool_name),
450 Some(LintGroup { lint_ids, .. }) => {
451 CheckLintNameResult::Tool(lint_ids, Some(complete_name))
452 }
453 },
454 Some(Id(id)) => CheckLintNameResult::Tool(slice::from_ref(id), Some(complete_name)),
455 Some(other) => {
456 debug!("got renamed lint {:?}", other);
457 CheckLintNameResult::NoLint(None)
458 }
459 }
460 }
461}
462
463pub struct LateContext<'tcx> {
465 pub tcx: TyCtxt<'tcx>,
467
468 pub enclosing_body: Option<hir::BodyId>,
470
471 pub(super) cached_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
476
477 pub param_env: ty::ParamEnv<'tcx>,
479
480 pub effective_visibilities: &'tcx EffectiveVisibilities,
482
483 pub last_node_with_lint_attrs: hir::HirId,
484
485 pub generics: Option<&'tcx hir::Generics<'tcx>>,
487
488 pub only_module: bool,
490}
491
492pub struct EarlyContext<'a> {
494 pub builder: LintLevelsBuilder<'a, crate::levels::TopDown>,
495 pub buffered: LintBuffer,
496}
497
498pub trait LintContext {
499 fn sess(&self) -> &Session;
500
501 #[rustc_lint_diagnostics]
507 fn opt_span_lint<S: Into<MultiSpan>>(
508 &self,
509 lint: &'static Lint,
510 span: Option<S>,
511 decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
512 );
513
514 fn emit_span_lint<S: Into<MultiSpan>>(
517 &self,
518 lint: &'static Lint,
519 span: S,
520 decorator: impl for<'a> LintDiagnostic<'a, ()>,
521 ) {
522 self.opt_span_lint(lint, Some(span), |lint| {
523 decorator.decorate_lint(lint);
524 });
525 }
526
527 fn emit_span_lint_lazy<S: Into<MultiSpan>, L: for<'a> LintDiagnostic<'a, ()>>(
530 &self,
531 lint: &'static Lint,
532 span: S,
533 decorator: impl FnOnce() -> L,
534 ) {
535 self.opt_span_lint(lint, Some(span), |lint| {
536 let decorator = decorator();
537 decorator.decorate_lint(lint);
538 });
539 }
540
541 #[rustc_lint_diagnostics]
545 fn span_lint<S: Into<MultiSpan>>(
546 &self,
547 lint: &'static Lint,
548 span: S,
549 decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
550 ) {
551 self.opt_span_lint(lint, Some(span), decorate);
552 }
553
554 fn emit_lint(&self, lint: &'static Lint, decorator: impl for<'a> LintDiagnostic<'a, ()>) {
557 self.opt_span_lint(lint, None as Option<Span>, |lint| {
558 decorator.decorate_lint(lint);
559 });
560 }
561
562 #[rustc_lint_diagnostics]
566 fn lint(&self, lint: &'static Lint, decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>)) {
567 self.opt_span_lint(lint, None as Option<Span>, decorate);
568 }
569
570 fn get_lint_level(&self, lint: &'static Lint) -> LevelAndSource;
572
573 fn fulfill_expectation(&self, expectation: LintExpectationId) {
581 #[allow(rustc::diagnostic_outside_of_impl)]
586 #[allow(rustc::untranslatable_diagnostic)]
587 self.sess()
588 .dcx()
589 .struct_expect(
590 "this is a dummy diagnostic, to submit and store an expectation",
591 expectation,
592 )
593 .emit();
594 }
595}
596
597impl<'a> EarlyContext<'a> {
598 pub(crate) fn new(
599 sess: &'a Session,
600 features: &'a Features,
601 lint_added_lints: bool,
602 lint_store: &'a LintStore,
603 registered_tools: &'a RegisteredTools,
604 buffered: LintBuffer,
605 ) -> EarlyContext<'a> {
606 EarlyContext {
607 builder: LintLevelsBuilder::new(
608 sess,
609 features,
610 lint_added_lints,
611 lint_store,
612 registered_tools,
613 ),
614 buffered,
615 }
616 }
617}
618
619impl<'tcx> LintContext for LateContext<'tcx> {
620 fn sess(&self) -> &Session {
622 self.tcx.sess
623 }
624
625 #[rustc_lint_diagnostics]
626 fn opt_span_lint<S: Into<MultiSpan>>(
627 &self,
628 lint: &'static Lint,
629 span: Option<S>,
630 decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
631 ) {
632 let hir_id = self.last_node_with_lint_attrs;
633
634 match span {
635 Some(s) => self.tcx.node_span_lint(lint, hir_id, s, decorate),
636 None => self.tcx.node_lint(lint, hir_id, decorate),
637 }
638 }
639
640 fn get_lint_level(&self, lint: &'static Lint) -> LevelAndSource {
641 self.tcx.lint_level_at_node(lint, self.last_node_with_lint_attrs)
642 }
643}
644
645impl LintContext for EarlyContext<'_> {
646 fn sess(&self) -> &Session {
648 self.builder.sess()
649 }
650
651 #[rustc_lint_diagnostics]
652 fn opt_span_lint<S: Into<MultiSpan>>(
653 &self,
654 lint: &'static Lint,
655 span: Option<S>,
656 decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
657 ) {
658 self.builder.opt_span_lint(lint, span.map(|s| s.into()), decorate)
659 }
660
661 fn get_lint_level(&self, lint: &'static Lint) -> LevelAndSource {
662 self.builder.lint_level(lint)
663 }
664}
665
666impl<'tcx> LateContext<'tcx> {
667 pub fn typing_mode(&self) -> TypingMode<'tcx> {
670 TypingMode::non_body_analysis()
673 }
674
675 pub fn typing_env(&self) -> TypingEnv<'tcx> {
676 TypingEnv { typing_mode: self.typing_mode(), param_env: self.param_env }
677 }
678
679 pub fn type_is_copy_modulo_regions(&self, ty: Ty<'tcx>) -> bool {
680 self.tcx.type_is_copy_modulo_regions(self.typing_env(), ty)
681 }
682
683 pub fn type_is_use_cloned_modulo_regions(&self, ty: Ty<'tcx>) -> bool {
684 self.tcx.type_is_use_cloned_modulo_regions(self.typing_env(), ty)
685 }
686
687 pub fn maybe_typeck_results(&self) -> Option<&'tcx ty::TypeckResults<'tcx>> {
690 self.cached_typeck_results.get().or_else(|| {
691 self.enclosing_body.map(|body| {
692 let typeck_results = self.tcx.typeck_body(body);
693 self.cached_typeck_results.set(Some(typeck_results));
694 typeck_results
695 })
696 })
697 }
698
699 #[track_caller]
703 pub fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
704 self.maybe_typeck_results().expect("`LateContext::typeck_results` called outside of body")
705 }
706
707 pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
711 match *qpath {
712 hir::QPath::Resolved(_, path) => path.res,
713 hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
714 .maybe_typeck_results()
715 .filter(|typeck_results| typeck_results.hir_owner == id.owner)
716 .or_else(|| {
717 self.tcx
718 .has_typeck_results(id.owner.def_id)
719 .then(|| self.tcx.typeck(id.owner.def_id))
720 })
721 .and_then(|typeck_results| typeck_results.type_dependent_def(id))
722 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
723 }
724 }
725
726 pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
746 struct AbsolutePathPrinter<'tcx> {
747 tcx: TyCtxt<'tcx>,
748 path: Vec<Symbol>,
749 }
750
751 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
752 fn tcx(&self) -> TyCtxt<'tcx> {
753 self.tcx
754 }
755
756 fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> {
757 Ok(())
758 }
759
760 fn print_type(&mut self, _ty: Ty<'tcx>) -> Result<(), PrintError> {
761 Ok(())
762 }
763
764 fn print_dyn_existential(
765 &mut self,
766 _predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
767 ) -> Result<(), PrintError> {
768 Ok(())
769 }
770
771 fn print_const(&mut self, _ct: ty::Const<'tcx>) -> Result<(), PrintError> {
772 Ok(())
773 }
774
775 fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
776 self.path = vec![self.tcx.crate_name(cnum)];
777 Ok(())
778 }
779
780 fn path_qualified(
781 &mut self,
782 self_ty: Ty<'tcx>,
783 trait_ref: Option<ty::TraitRef<'tcx>>,
784 ) -> Result<(), PrintError> {
785 if trait_ref.is_none() {
786 if let ty::Adt(def, args) = self_ty.kind() {
787 return self.print_def_path(def.did(), args);
788 }
789 }
790
791 with_no_trimmed_paths!({
793 self.path = vec![match trait_ref {
794 Some(trait_ref) => Symbol::intern(&format!("{trait_ref:?}")),
795 None => Symbol::intern(&format!("<{self_ty}>")),
796 }];
797 Ok(())
798 })
799 }
800
801 fn path_append_impl(
802 &mut self,
803 print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
804 _disambiguated_data: &DisambiguatedDefPathData,
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 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 with_no_trimmed_paths!(Symbol::intern(&format!("<impl {self_ty}>")))
821 }
822 });
823
824 Ok(())
825 }
826
827 fn path_append(
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 path_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 printer = AbsolutePathPrinter { tcx: self.tcx, path: vec![] };
856 printer.print_def_path(def_id, &[]).unwrap();
857 printer.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(.., body_id) | hir::ItemKind::Static(.., body_id) => {
975 Some(self.tcx.hir_body(body_id).value)
976 }
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}