1 //! Implementation of lint checking.
3 //! The lint checking is mostly consolidated into one pass which runs
4 //! after all other analyses. Throughout compilation, lint warnings
5 //! can be added via the `add_lint` method on the Session structure. This
6 //! requires a span and an ID of the node that the lint is being added to. The
7 //! lint isn't actually emitted at that time because it is unknown what the
8 //! actual lint level at that location is.
10 //! To actually emit lint warnings/errors, a separate pass is used.
11 //! A context keeps track of the current state of all lint levels.
12 //! Upon entering a node of the ast which can modify the lint settings, the
13 //! previous lint state is pushed onto a stack and the ast is then recursed
14 //! upon. As the ast is traversed, this keeps track of the current lint level
15 //! for all lint attributes.
17 use self::TargetLint::*;
19 use crate::levels::LintLevelsBuilder;
20 use crate::passes::{EarlyLintPassObject, LateLintPassObject};
22 use rustc_ast::util::lev_distance::find_best_match_for_name;
23 use rustc_data_structures::fx::FxHashMap;
24 use rustc_data_structures::sync;
25 use rustc_errors::{struct_span_err, Applicability};
27 use rustc_hir::def::Res;
28 use rustc_hir::def_id::{CrateNum, DefId};
29 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
30 use rustc_middle::lint::LintDiagnosticBuilder;
31 use rustc_middle::middle::privacy::AccessLevels;
32 use rustc_middle::middle::stability;
33 use rustc_middle::ty::layout::{LayoutError, TyAndLayout};
34 use rustc_middle::ty::{self, print::Printer, subst::GenericArg, Ty, TyCtxt};
35 use rustc_session::lint::{add_elided_lifetime_in_path_suggestion, BuiltinLintDiagnostics};
36 use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId};
37 use rustc_session::Session;
38 use rustc_span::{symbol::Symbol, MultiSpan, Span, DUMMY_SP};
39 use rustc_target::abi::LayoutOf;
44 /// Information about the registered lints.
46 /// This is basically the subset of `Context` that we can
47 /// build early in the compile pipeline.
48 pub struct LintStore {
50 lints: Vec<&'static Lint>,
52 /// Constructor functions for each variety of lint pass.
54 /// These should only be called once, but since we want to avoid locks or
55 /// interior mutability, we don't enforce this (and lints should, in theory,
56 /// be compatible with being constructed more than once, though not
57 /// necessarily in a sane manner. This is safe though.)
58 pub pre_expansion_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
59 pub early_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
60 pub late_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
61 /// This is unique in that we construct them per-module, so not once.
62 pub late_module_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
64 /// Lints indexed by name.
65 by_name: FxHashMap<String, TargetLint>,
67 /// Map of registered lint groups to what lints they expand to.
68 lint_groups: FxHashMap<&'static str, LintGroup>,
71 /// The target of the `by_name` map, which accounts for renaming/deprecation.
73 /// A direct lint target
76 /// Temporary renaming, used for easing migration pain; see #16545
77 Renamed(String, LintId),
79 /// Lint with this name existed previously, but has been removed/deprecated.
80 /// The string argument is the reason for removal.
84 pub enum FindLintError {
91 /// Whether deprecation warnings should be suppressed for this alias.
96 lint_ids: Vec<LintId>,
98 depr: Option<LintAlias>,
101 pub enum CheckLintNameResult<'a> {
103 /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name.
104 NoLint(Option<Symbol>),
105 /// The lint is either renamed or removed. This is the warning
106 /// message, and an optional new name (`None` if removed).
107 Warning(String, Option<String>),
108 /// The lint is from a tool. If the Option is None, then either
109 /// the lint does not exist in the tool or the code was not
110 /// compiled with the tool and therefore the lint was never
111 /// added to the `LintStore`. Otherwise the `LintId` will be
112 /// returned as if it where a rustc lint.
113 Tool(Result<&'a [LintId], (Option<&'a [LintId]>, String)>),
117 pub fn new() -> LintStore {
120 pre_expansion_passes: vec![],
121 early_passes: vec![],
123 late_module_passes: vec![],
124 by_name: Default::default(),
125 lint_groups: Default::default(),
129 pub fn get_lints<'t>(&'t self) -> &'t [&'static Lint] {
133 pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
136 .filter(|(_, LintGroup { depr, .. })| {
137 // Don't display deprecated lint groups.
140 .map(|(k, LintGroup { lint_ids, from_plugin, .. })| {
141 (*k, lint_ids.clone(), *from_plugin)
146 pub fn register_early_pass(
148 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
150 self.early_passes.push(Box::new(pass));
153 pub fn register_pre_expansion_pass(
155 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
157 self.pre_expansion_passes.push(Box::new(pass));
160 pub fn register_late_pass(
162 pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
164 self.late_passes.push(Box::new(pass));
167 pub fn register_late_mod_pass(
169 pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
171 self.late_module_passes.push(Box::new(pass));
174 // Helper method for register_early/late_pass
175 pub fn register_lints(&mut self, lints: &[&'static Lint]) {
177 self.lints.push(lint);
179 let id = LintId::of(lint);
180 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
181 bug!("duplicate specification of lint {}", lint.name_lower())
184 if let Some(FutureIncompatibleInfo { edition, .. }) = lint.future_incompatible {
185 if let Some(edition) = edition {
187 .entry(edition.lint_name())
188 .or_insert(LintGroup {
190 from_plugin: lint.is_plugin,
198 .entry("future_incompatible")
199 .or_insert(LintGroup {
201 from_plugin: lint.is_plugin,
210 pub fn register_group_alias(&mut self, lint_name: &'static str, alias: &'static str) {
211 self.lint_groups.insert(
216 depr: Some(LintAlias { name: lint_name, silent: true }),
221 pub fn register_group(
225 deprecated_name: Option<&'static str>,
230 .insert(name, LintGroup { lint_ids: to, from_plugin, depr: None })
232 if let Some(deprecated) = deprecated_name {
233 self.lint_groups.insert(
238 depr: Some(LintAlias { name, silent: false }),
244 bug!("duplicate specification of lint group {}", name);
248 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
249 let target = match self.by_name.get(new_name) {
250 Some(&Id(lint_id)) => lint_id,
251 _ => bug!("invalid lint renaming of {} to {}", old_name, new_name),
253 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
256 pub fn register_removed(&mut self, name: &str, reason: &str) {
257 self.by_name.insert(name.into(), Removed(reason.into()));
260 pub fn find_lints(&self, mut lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
261 match self.by_name.get(lint_name) {
262 Some(&Id(lint_id)) => Ok(vec![lint_id]),
263 Some(&Renamed(_, lint_id)) => Ok(vec![lint_id]),
264 Some(&Removed(_)) => Err(FindLintError::Removed),
266 return match self.lint_groups.get(lint_name) {
267 Some(LintGroup { lint_ids, depr, .. }) => {
268 if let Some(LintAlias { name, .. }) = depr {
274 None => Err(FindLintError::Removed),
280 /// Checks the validity of lint names derived from the command line
281 pub fn check_lint_name_cmdline(&self, sess: &Session, lint_name: &str, level: Level) {
282 let db = match self.check_lint_name(lint_name, None) {
283 CheckLintNameResult::Ok(_) => None,
284 CheckLintNameResult::Warning(ref msg, _) => Some(sess.struct_warn(msg)),
285 CheckLintNameResult::NoLint(suggestion) => {
287 struct_span_err!(sess, DUMMY_SP, E0602, "unknown lint: `{}`", lint_name);
289 if let Some(suggestion) = suggestion {
290 err.help(&format!("did you mean: `{}`", suggestion));
295 CheckLintNameResult::Tool(result) => match result {
296 Err((Some(_), new_name)) => Some(sess.struct_warn(&format!(
297 "lint name `{}` is deprecated \
298 and does not have an effect anymore. \
306 if let Some(mut db) = db {
308 "requested on the command line with `{} {}`",
310 Level::Allow => "-A",
313 Level::Forbid => "-F",
322 /// Checks the name of a lint for its existence, and whether it was
323 /// renamed or removed. Generates a DiagnosticBuilder containing a
324 /// warning for renamed and removed lints. This is over both lint
325 /// names from attributes and those passed on the command line. Since
326 /// it emits non-fatal warnings and there are *two* lint passes that
327 /// inspect attributes, this is only run from the late pass to avoid
328 /// printing duplicate warnings.
329 pub fn check_lint_name(
332 tool_name: Option<Symbol>,
333 ) -> CheckLintNameResult<'_> {
334 let complete_name = if let Some(tool_name) = tool_name {
335 format!("{}::{}", tool_name, lint_name)
337 lint_name.to_string()
339 // If the lint was scoped with `tool::` check if the tool lint exists
340 if tool_name.is_some() {
341 match self.by_name.get(&complete_name) {
342 None => match self.lint_groups.get(&*complete_name) {
343 None => return CheckLintNameResult::Tool(Err((None, String::new()))),
344 Some(LintGroup { lint_ids, .. }) => {
345 return CheckLintNameResult::Tool(Ok(&lint_ids));
348 Some(&Id(ref id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))),
349 // If the lint was registered as removed or renamed by the lint tool, we don't need
350 // to treat tool_lints and rustc lints different and can use the code below.
354 match self.by_name.get(&complete_name) {
355 Some(&Renamed(ref new_name, _)) => CheckLintNameResult::Warning(
356 format!("lint `{}` has been renamed to `{}`", complete_name, new_name),
357 Some(new_name.to_owned()),
359 Some(&Removed(ref reason)) => CheckLintNameResult::Warning(
360 format!("lint `{}` has been removed: `{}`", complete_name, reason),
363 None => match self.lint_groups.get(&*complete_name) {
364 // If neither the lint, nor the lint group exists check if there is a `clippy::`
365 // variant of this lint
366 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
367 Some(LintGroup { lint_ids, depr, .. }) => {
368 // Check if the lint group name is deprecated
369 if let Some(LintAlias { name, silent }) = depr {
370 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
372 CheckLintNameResult::Ok(&lint_ids)
374 CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
377 CheckLintNameResult::Ok(&lint_ids)
380 Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
384 fn check_tool_name_for_backwards_compat(
388 ) -> CheckLintNameResult<'_> {
389 let complete_name = format!("{}::{}", tool_name, lint_name);
390 match self.by_name.get(&complete_name) {
391 None => match self.lint_groups.get(&*complete_name) {
392 // Now we are sure, that this lint exists nowhere
395 self.by_name.keys().map(|name| Symbol::intern(&name)).collect::<Vec<_>>();
398 find_best_match_for_name(symbols.iter(), &lint_name.to_lowercase(), None);
400 CheckLintNameResult::NoLint(suggestion)
402 Some(LintGroup { lint_ids, depr, .. }) => {
403 // Reaching this would be weird, but let's cover this case anyway
404 if let Some(LintAlias { name, silent }) = depr {
405 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
407 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
409 CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
412 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
415 Some(&Id(ref id)) => {
416 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
418 _ => CheckLintNameResult::NoLint(None),
423 /// Context for lint checking after type checking.
424 pub struct LateContext<'tcx> {
425 /// Type context we're checking in.
426 pub tcx: TyCtxt<'tcx>,
428 /// Current body, or `None` if outside a body.
429 pub enclosing_body: Option<hir::BodyId>,
431 /// Type-checking side-tables for the current body. Access using the `tables`
432 /// and `maybe_tables` methods, which handle querying the tables on demand.
433 // FIXME(eddyb) move all the code accessing internal fields like this,
434 // to this module, to avoid exposing it to lint logic.
435 pub(super) cached_typeck_tables: Cell<Option<&'tcx ty::TypeckTables<'tcx>>>,
437 /// Parameter environment for the item we are in.
438 pub param_env: ty::ParamEnv<'tcx>,
440 /// Items accessible from the crate being checked.
441 pub access_levels: &'tcx AccessLevels,
443 /// The store of registered lints and the lint levels.
444 pub lint_store: &'tcx LintStore,
446 pub last_node_with_lint_attrs: hir::HirId,
448 /// Generic type parameters in scope for the item we are in.
449 pub generics: Option<&'tcx hir::Generics<'tcx>>,
451 /// We are only looking at one module
452 pub only_module: bool,
455 /// Context for lint checking of the AST, after expansion, before lowering to
457 pub struct EarlyContext<'a> {
458 /// Type context we're checking in.
459 pub sess: &'a Session,
461 /// The crate being checked.
462 pub krate: &'a ast::Crate,
464 pub builder: LintLevelsBuilder<'a>,
466 /// The store of registered lints and the lint levels.
467 pub lint_store: &'a LintStore,
469 pub buffered: LintBuffer,
472 pub trait LintPassObject: Sized {}
474 impl LintPassObject for EarlyLintPassObject {}
476 impl LintPassObject for LateLintPassObject {}
478 pub trait LintContext: Sized {
479 type PassObject: LintPassObject;
481 fn sess(&self) -> &Session;
482 fn lints(&self) -> &LintStore;
484 fn lookup_with_diagnostics(
487 span: Option<impl Into<MultiSpan>>,
488 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
489 diagnostic: BuiltinLintDiagnostics,
491 self.lookup(lint, span, |lint| {
492 // We first generate a blank diagnostic.
493 let mut db = lint.build("");
495 // Now, set up surrounding context.
496 let sess = self.sess();
498 BuiltinLintDiagnostics::Normal => (),
499 BuiltinLintDiagnostics::BareTraitObject(span, is_global) => {
500 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
501 Ok(s) if is_global => {
502 (format!("dyn ({})", s), Applicability::MachineApplicable)
504 Ok(s) => (format!("dyn {}", s), Applicability::MachineApplicable),
505 Err(_) => ("dyn <type>".to_string(), Applicability::HasPlaceholders),
507 db.span_suggestion(span, "use `dyn`", sugg, app);
509 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
510 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
512 // FIXME(Manishearth) ideally the emitting code
513 // can tell us whether or not this is global
515 if s.trim_start().starts_with("::") { "" } else { "::" };
517 (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
519 Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
521 db.span_suggestion(span, "use `crate`", sugg, app);
523 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
526 "names from parent modules are not accessible without an explicit import",
529 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(
532 db.span_note(span_def, "the macro is defined here");
534 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
541 add_elided_lifetime_in_path_suggestion(
551 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
552 db.span_suggestion(span, ¬e, sugg, Applicability::MaybeIncorrect);
554 BuiltinLintDiagnostics::UnusedImports(message, replaces) => {
555 if !replaces.is_empty() {
556 db.tool_only_multipart_suggestion(
559 Applicability::MachineApplicable,
563 BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
564 for (span, is_imported) in spans {
565 let introduced = if is_imported { "imported" } else { "defined" };
568 format!("the item `{}` is already {} here", ident, introduced),
572 BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => {
573 stability::deprecation_suggestion(&mut db, suggestion, span)
575 BuiltinLintDiagnostics::UnusedDocComment(span) => {
576 db.span_label(span, "rustdoc does not generate documentation for macro invocations");
577 db.help("to document an item produced by a macro, \
578 the macro must produce the documentation as part of its expansion");
581 // Rewrap `db`, and pass control to the user.
582 decorate(LintDiagnosticBuilder::new(db));
586 // FIXME: These methods should not take an Into<MultiSpan> -- instead, callers should need to
587 // set the span in their `decorate` function (preferably using set_span).
588 fn lookup<S: Into<MultiSpan>>(
592 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
595 fn struct_span_lint<S: Into<MultiSpan>>(
599 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
601 self.lookup(lint, Some(span), decorate);
603 /// Emit a lint at the appropriate level, with no associated span.
604 fn lint(&self, lint: &'static Lint, decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>)) {
605 self.lookup(lint, None as Option<Span>, decorate);
609 impl<'a> EarlyContext<'a> {
612 lint_store: &'a LintStore,
613 krate: &'a ast::Crate,
614 buffered: LintBuffer,
615 warn_about_weird_lints: bool,
616 ) -> EarlyContext<'a> {
621 builder: LintLevelsBuilder::new(sess, warn_about_weird_lints, lint_store),
627 impl LintContext for LateContext<'_> {
628 type PassObject = LateLintPassObject;
630 /// Gets the overall compiler `Session` object.
631 fn sess(&self) -> &Session {
635 fn lints(&self) -> &LintStore {
639 fn lookup<S: Into<MultiSpan>>(
643 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
645 let hir_id = self.last_node_with_lint_attrs;
648 Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, decorate),
649 None => self.tcx.struct_lint_node(lint, hir_id, decorate),
654 impl LintContext for EarlyContext<'_> {
655 type PassObject = EarlyLintPassObject;
657 /// Gets the overall compiler `Session` object.
658 fn sess(&self) -> &Session {
662 fn lints(&self) -> &LintStore {
666 fn lookup<S: Into<MultiSpan>>(
670 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
672 self.builder.struct_lint(lint, span.map(|s| s.into()), decorate)
676 impl<'tcx> LateContext<'tcx> {
677 /// Gets the type-checking side-tables for the current body,
678 /// or `None` if outside a body.
679 pub fn maybe_typeck_tables(&self) -> Option<&'tcx ty::TypeckTables<'tcx>> {
680 self.cached_typeck_tables.get().or_else(|| {
681 self.enclosing_body.map(|body| {
682 let tables = self.tcx.body_tables(body);
683 self.cached_typeck_tables.set(Some(tables));
689 /// Gets the type-checking side-tables for the current body.
690 /// As this will ICE if called outside bodies, only call when working with
691 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
693 pub fn tables(&self) -> &'tcx ty::TypeckTables<'tcx> {
694 self.maybe_typeck_tables().expect("`LateContext::tables` called outside of body")
697 /// Returns the final resolution of a `QPath`, or `Res::Err` if unavailable.
698 /// Unlike `.tables().qpath_res(qpath, id)`, this can be used even outside
699 /// bodies (e.g. for paths in `hir::Ty`), without any risk of ICE-ing.
700 pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
702 hir::QPath::Resolved(_, ref path) => path.res,
703 hir::QPath::TypeRelative(..) => self
704 .maybe_typeck_tables()
705 .and_then(|tables| tables.type_dependent_def(id))
706 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
710 pub fn current_lint_root(&self) -> hir::HirId {
711 self.last_node_with_lint_attrs
714 /// Check if a `DefId`'s path matches the given absolute type path usage.
716 /// Anonymous scopes such as `extern` imports are matched with `kw::Invalid`;
717 /// inherent `impl` blocks are matched with the name of the type.
721 /// ```rust,ignore (no context or def id available)
722 /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
723 /// // The given `def_id` is that of an `Option` type
726 pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
727 let names = self.get_def_path(def_id);
729 names.len() == path.len() && names.into_iter().zip(path.iter()).all(|(a, &b)| a == b)
732 /// Gets the absolute path of `def_id` as a vector of `Symbol`.
736 /// ```rust,ignore (no context or def id available)
737 /// let def_path = cx.get_def_path(def_id);
738 /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
739 /// // The given `def_id` is that of an `Option` type
742 pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
743 pub struct AbsolutePathPrinter<'tcx> {
744 pub tcx: TyCtxt<'tcx>,
747 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
750 type Path = Vec<Symbol>;
753 type DynExistential = ();
756 fn tcx(&self) -> TyCtxt<'tcx> {
760 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
764 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
768 fn print_dyn_existential(
770 _predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
771 ) -> Result<Self::DynExistential, Self::Error> {
775 fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
779 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
780 Ok(vec![self.tcx.original_crate_name(cnum)])
786 trait_ref: Option<ty::TraitRef<'tcx>>,
787 ) -> Result<Self::Path, Self::Error> {
788 if trait_ref.is_none() {
789 if let ty::Adt(def, substs) = self_ty.kind {
790 return self.print_def_path(def.did, substs);
794 // This shouldn't ever be needed, but just in case:
795 Ok(vec![match trait_ref {
796 Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
797 None => Symbol::intern(&format!("<{}>", self_ty)),
803 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
804 _disambiguated_data: &DisambiguatedDefPathData,
806 trait_ref: Option<ty::TraitRef<'tcx>>,
807 ) -> Result<Self::Path, Self::Error> {
808 let mut path = print_prefix(self)?;
810 // This shouldn't ever be needed, but just in case:
811 path.push(match trait_ref {
812 Some(trait_ref) => Symbol::intern(&format!(
814 trait_ref.print_only_trait_path(),
817 None => Symbol::intern(&format!("<impl {}>", self_ty)),
825 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
826 disambiguated_data: &DisambiguatedDefPathData,
827 ) -> Result<Self::Path, Self::Error> {
828 let mut path = print_prefix(self)?;
830 // Skip `::{{constructor}}` on tuple/unit structs.
831 if let DefPathData::Ctor = disambiguated_data.data {
835 path.push(disambiguated_data.data.as_symbol());
839 fn path_generic_args(
841 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
842 _args: &[GenericArg<'tcx>],
843 ) -> Result<Self::Path, Self::Error> {
848 AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
852 impl<'tcx> LayoutOf for LateContext<'tcx> {
854 type TyAndLayout = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
856 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
857 self.tcx.layout_of(self.param_env.and(ty))