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<_>>();
397 let suggestion = find_best_match_for_name(
399 Symbol::intern(&lint_name.to_lowercase()),
403 CheckLintNameResult::NoLint(suggestion)
405 Some(LintGroup { lint_ids, depr, .. }) => {
406 // Reaching this would be weird, but let's cover this case anyway
407 if let Some(LintAlias { name, silent }) = depr {
408 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
410 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
412 CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
415 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
418 Some(&Id(ref id)) => {
419 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
421 _ => CheckLintNameResult::NoLint(None),
426 /// Context for lint checking after type checking.
427 pub struct LateContext<'tcx> {
428 /// Type context we're checking in.
429 pub tcx: TyCtxt<'tcx>,
431 /// Current body, or `None` if outside a body.
432 pub enclosing_body: Option<hir::BodyId>,
434 /// Type-checking results for the current body. Access using the `typeck_results`
435 /// and `maybe_typeck_results` methods, which handle querying the typeck results on demand.
436 // FIXME(eddyb) move all the code accessing internal fields like this,
437 // to this module, to avoid exposing it to lint logic.
438 pub(super) cached_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
440 /// Parameter environment for the item we are in.
441 pub param_env: ty::ParamEnv<'tcx>,
443 /// Items accessible from the crate being checked.
444 pub access_levels: &'tcx AccessLevels,
446 /// The store of registered lints and the lint levels.
447 pub lint_store: &'tcx LintStore,
449 pub last_node_with_lint_attrs: hir::HirId,
451 /// Generic type parameters in scope for the item we are in.
452 pub generics: Option<&'tcx hir::Generics<'tcx>>,
454 /// We are only looking at one module
455 pub only_module: bool,
458 /// Context for lint checking of the AST, after expansion, before lowering to
460 pub struct EarlyContext<'a> {
461 /// Type context we're checking in.
462 pub sess: &'a Session,
464 /// The crate being checked.
465 pub krate: &'a ast::Crate,
467 pub builder: LintLevelsBuilder<'a>,
469 /// The store of registered lints and the lint levels.
470 pub lint_store: &'a LintStore,
472 pub buffered: LintBuffer,
475 pub trait LintPassObject: Sized {}
477 impl LintPassObject for EarlyLintPassObject {}
479 impl LintPassObject for LateLintPassObject {}
481 pub trait LintContext: Sized {
482 type PassObject: LintPassObject;
484 fn sess(&self) -> &Session;
485 fn lints(&self) -> &LintStore;
487 fn lookup_with_diagnostics(
490 span: Option<impl Into<MultiSpan>>,
491 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
492 diagnostic: BuiltinLintDiagnostics,
494 self.lookup(lint, span, |lint| {
495 // We first generate a blank diagnostic.
496 let mut db = lint.build("");
498 // Now, set up surrounding context.
499 let sess = self.sess();
501 BuiltinLintDiagnostics::Normal => (),
502 BuiltinLintDiagnostics::BareTraitObject(span, is_global) => {
503 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
504 Ok(s) if is_global => {
505 (format!("dyn ({})", s), Applicability::MachineApplicable)
507 Ok(s) => (format!("dyn {}", s), Applicability::MachineApplicable),
508 Err(_) => ("dyn <type>".to_string(), Applicability::HasPlaceholders),
510 db.span_suggestion(span, "use `dyn`", sugg, app);
512 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
513 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
515 // FIXME(Manishearth) ideally the emitting code
516 // can tell us whether or not this is global
518 if s.trim_start().starts_with("::") { "" } else { "::" };
520 (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
522 Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
524 db.span_suggestion(span, "use `crate`", sugg, app);
526 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
529 "names from parent modules are not accessible without an explicit import",
532 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(
535 db.span_note(span_def, "the macro is defined here");
537 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
544 add_elided_lifetime_in_path_suggestion(
554 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
555 db.span_suggestion(span, ¬e, sugg, Applicability::MaybeIncorrect);
557 BuiltinLintDiagnostics::UnusedImports(message, replaces) => {
558 if !replaces.is_empty() {
559 db.tool_only_multipart_suggestion(
562 Applicability::MachineApplicable,
566 BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
567 for (span, is_imported) in spans {
568 let introduced = if is_imported { "imported" } else { "defined" };
571 format!("the item `{}` is already {} here", ident, introduced),
575 BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => {
576 stability::deprecation_suggestion(&mut db, suggestion, span)
578 BuiltinLintDiagnostics::UnusedDocComment(span) => {
579 db.span_label(span, "rustdoc does not generate documentation for macro invocations");
580 db.help("to document an item produced by a macro, \
581 the macro must produce the documentation as part of its expansion");
584 // Rewrap `db`, and pass control to the user.
585 decorate(LintDiagnosticBuilder::new(db));
589 // FIXME: These methods should not take an Into<MultiSpan> -- instead, callers should need to
590 // set the span in their `decorate` function (preferably using set_span).
591 fn lookup<S: Into<MultiSpan>>(
595 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
598 fn struct_span_lint<S: Into<MultiSpan>>(
602 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
604 self.lookup(lint, Some(span), decorate);
606 /// Emit a lint at the appropriate level, with no associated span.
607 fn lint(&self, lint: &'static Lint, decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>)) {
608 self.lookup(lint, None as Option<Span>, decorate);
612 impl<'a> EarlyContext<'a> {
615 lint_store: &'a LintStore,
616 krate: &'a ast::Crate,
617 buffered: LintBuffer,
618 warn_about_weird_lints: bool,
619 ) -> EarlyContext<'a> {
624 builder: LintLevelsBuilder::new(sess, warn_about_weird_lints, lint_store),
630 impl LintContext for LateContext<'_> {
631 type PassObject = LateLintPassObject;
633 /// Gets the overall compiler `Session` object.
634 fn sess(&self) -> &Session {
638 fn lints(&self) -> &LintStore {
642 fn lookup<S: Into<MultiSpan>>(
646 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
648 let hir_id = self.last_node_with_lint_attrs;
651 Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, decorate),
652 None => self.tcx.struct_lint_node(lint, hir_id, decorate),
657 impl LintContext for EarlyContext<'_> {
658 type PassObject = EarlyLintPassObject;
660 /// Gets the overall compiler `Session` object.
661 fn sess(&self) -> &Session {
665 fn lints(&self) -> &LintStore {
669 fn lookup<S: Into<MultiSpan>>(
673 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
675 self.builder.struct_lint(lint, span.map(|s| s.into()), decorate)
679 impl<'tcx> LateContext<'tcx> {
680 /// Gets the type-checking results for the current body,
681 /// or `None` if outside a body.
682 pub fn maybe_typeck_results(&self) -> Option<&'tcx ty::TypeckResults<'tcx>> {
683 self.cached_typeck_results.get().or_else(|| {
684 self.enclosing_body.map(|body| {
685 let typeck_results = self.tcx.typeck_body(body);
686 self.cached_typeck_results.set(Some(typeck_results));
692 /// Gets the type-checking results for the current body.
693 /// As this will ICE if called outside bodies, only call when working with
694 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
696 pub fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
697 self.maybe_typeck_results().expect("`LateContext::typeck_results` called outside of body")
700 /// Returns the final resolution of a `QPath`, or `Res::Err` if unavailable.
701 /// Unlike `.typeck_results().qpath_res(qpath, id)`, this can be used even outside
702 /// bodies (e.g. for paths in `hir::Ty`), without any risk of ICE-ing.
703 pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
705 hir::QPath::Resolved(_, ref path) => path.res,
706 hir::QPath::TypeRelative(..) => self
707 .maybe_typeck_results()
708 .and_then(|typeck_results| typeck_results.type_dependent_def(id))
709 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
713 pub fn current_lint_root(&self) -> hir::HirId {
714 self.last_node_with_lint_attrs
717 /// Check if a `DefId`'s path matches the given absolute type path usage.
719 /// Anonymous scopes such as `extern` imports are matched with `kw::Invalid`;
720 /// inherent `impl` blocks are matched with the name of the type.
724 /// ```rust,ignore (no context or def id available)
725 /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
726 /// // The given `def_id` is that of an `Option` type
729 pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
730 let names = self.get_def_path(def_id);
732 names.len() == path.len() && names.into_iter().zip(path.iter()).all(|(a, &b)| a == b)
735 /// Gets the absolute path of `def_id` as a vector of `Symbol`.
739 /// ```rust,ignore (no context or def id available)
740 /// let def_path = cx.get_def_path(def_id);
741 /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
742 /// // The given `def_id` is that of an `Option` type
745 pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
746 pub struct AbsolutePathPrinter<'tcx> {
747 pub tcx: TyCtxt<'tcx>,
750 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
753 type Path = Vec<Symbol>;
756 type DynExistential = ();
759 fn tcx(&self) -> TyCtxt<'tcx> {
763 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
767 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
771 fn print_dyn_existential(
773 _predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
774 ) -> Result<Self::DynExistential, Self::Error> {
778 fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
782 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
783 Ok(vec![self.tcx.original_crate_name(cnum)])
789 trait_ref: Option<ty::TraitRef<'tcx>>,
790 ) -> Result<Self::Path, Self::Error> {
791 if trait_ref.is_none() {
792 if let ty::Adt(def, substs) = self_ty.kind {
793 return self.print_def_path(def.did, substs);
797 // This shouldn't ever be needed, but just in case:
798 Ok(vec![match trait_ref {
799 Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
800 None => Symbol::intern(&format!("<{}>", self_ty)),
806 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
807 _disambiguated_data: &DisambiguatedDefPathData,
809 trait_ref: Option<ty::TraitRef<'tcx>>,
810 ) -> Result<Self::Path, Self::Error> {
811 let mut path = print_prefix(self)?;
813 // This shouldn't ever be needed, but just in case:
814 path.push(match trait_ref {
815 Some(trait_ref) => Symbol::intern(&format!(
817 trait_ref.print_only_trait_path(),
820 None => Symbol::intern(&format!("<impl {}>", self_ty)),
828 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
829 disambiguated_data: &DisambiguatedDefPathData,
830 ) -> Result<Self::Path, Self::Error> {
831 let mut path = print_prefix(self)?;
833 // Skip `::{{constructor}}` on tuple/unit structs.
834 if let DefPathData::Ctor = disambiguated_data.data {
838 path.push(disambiguated_data.data.as_symbol());
842 fn path_generic_args(
844 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
845 _args: &[GenericArg<'tcx>],
846 ) -> Result<Self::Path, Self::Error> {
851 AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
855 impl<'tcx> LayoutOf for LateContext<'tcx> {
857 type TyAndLayout = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
859 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
860 self.tcx.layout_of(self.param_env.and(ty))