2014-06-06 15:49:48 -07:00
//! Implementation of lint checking.
//!
2018-05-08 16:10:16 +03:00
//! The lint checking is mostly consolidated into one pass which runs
//! after all other analyses. Throughout compilation, lint warnings
2014-06-06 15:49:48 -07:00
//! can be added via the `add_lint` method on the Session structure. This
2019-02-08 14:53:55 +01:00
//! requires a span and an ID of the node that the lint is being added to. The
2014-06-06 15:49:48 -07:00
//! lint isn't actually emitted at that time because it is unknown what the
//! actual lint level at that location is.
//!
2018-05-08 16:10:16 +03:00
//! To actually emit lint warnings/errors, a separate pass is used.
//! A context keeps track of the current state of all lint levels.
2014-06-06 15:49:48 -07:00
//! Upon entering a node of the ast which can modify the lint settings, the
//! previous lint state is pushed onto a stack and the ast is then recursed
2019-02-08 14:53:55 +01:00
//! upon. As the ast is traversed, this keeps track of the current lint level
2014-06-06 15:49:48 -07:00
//! for all lint attributes.
2017-07-26 21:51:09 -07:00
2014-11-06 00:05:53 -08:00
use self ::TargetLint ::* ;
2014-06-06 15:49:48 -07:00
2021-09-29 01:17:54 +03:00
use crate ::levels ::LintLevelsBuilder ;
2020-01-09 07:52:01 +01:00
use crate ::passes ::{ EarlyLintPassObject , LateLintPassObject } ;
2021-09-29 01:17:54 +03:00
use rustc_ast ::util ::unicode ::TEXT_FLOW_CONTROL_CHARS ;
2019-12-24 05:02:53 +01:00
use rustc_data_structures ::fx ::FxHashMap ;
2019-12-30 14:22:46 +01:00
use rustc_data_structures ::sync ;
2022-09-16 11:01:02 +04:00
use rustc_errors ::{ add_elided_lifetime_in_path_suggestion , DiagnosticBuilder , DiagnosticMessage } ;
use rustc_errors ::{ Applicability , DecorateLint , MultiSpan , SuggestionStyle } ;
2023-08-09 20:28:00 +08:00
use rustc_feature ::Features ;
2020-01-05 02:37:57 +01:00
use rustc_hir as hir ;
2020-06-26 05:55:23 +03:00
use rustc_hir ::def ::Res ;
2020-01-05 02:37:57 +01:00
use rustc_hir ::def_id ::{ CrateNum , DefId } ;
2020-09-01 13:11:28 +01:00
use rustc_hir ::definitions ::{ DefPathData , DisambiguatedDefPathData } ;
2022-09-22 16:19:53 +03:00
use rustc_middle ::middle ::privacy ::EffectiveVisibilities ;
2020-03-29 16:41:09 +02:00
use rustc_middle ::middle ::stability ;
2021-08-30 20:37:36 +03:00
use rustc_middle ::ty ::layout ::{ LayoutError , LayoutOfHelpers , TyAndLayout } ;
2023-10-16 20:46:24 +02:00
use rustc_middle ::ty ::print ::{ with_no_trimmed_paths , PrintError } ;
2023-07-11 22:35:29 +01:00
use rustc_middle ::ty ::{ self , print ::Printer , GenericArg , RegisteredTools , Ty , TyCtxt } ;
2023-04-30 19:09:15 +02:00
use rustc_session ::config ::ExpectedValues ;
2022-06-16 13:20:57 +02:00
use rustc_session ::lint ::{ BuiltinLintDiagnostics , LintExpectationId } ;
2020-01-05 09:40:16 +01:00
use rustc_session ::lint ::{ FutureIncompatibleInfo , Level , Lint , LintBuffer , LintId } ;
2023-11-17 15:24:55 -05:00
use rustc_session ::{ LintStoreMarker , Session } ;
2023-02-19 04:03:56 +00:00
use rustc_span ::edit_distance ::find_best_match_for_name ;
2021-09-29 01:17:54 +03:00
use rustc_span ::symbol ::{ sym , Ident , Symbol } ;
2022-08-20 15:48:03 -04:00
use rustc_span ::{ BytePos , Span } ;
2021-08-30 17:38:27 +03:00
use rustc_target ::abi ;
2014-06-06 15:49:48 -07:00
2020-06-26 02:56:23 +03:00
use std ::cell ::Cell ;
2021-03-08 15:32:41 -08:00
use std ::iter ;
2019-12-31 21:25:16 +01:00
use std ::slice ;
2019-11-11 22:46:56 +01:00
2023-03-03 10:14:57 +08:00
type EarlyLintPassFactory = dyn Fn ( ) -> EarlyLintPassObject + sync ::DynSend + sync ::DynSync ;
2022-09-06 14:23:03 -04:00
type LateLintPassFactory =
2023-03-03 10:14:57 +08:00
dyn for < ' tcx > Fn ( TyCtxt < ' tcx > ) -> LateLintPassObject < ' tcx > + sync ::DynSend + sync ::DynSync ;
2022-09-06 14:23:03 -04:00
2014-06-06 15:49:48 -07:00
/// Information about the registered lints.
///
/// This is basically the subset of `Context` that we can
/// build early in the compile pipeline.
pub struct LintStore {
2019-11-30 11:31:25 +03:00
/// Registered lints.
2019-10-07 16:52:53 -04:00
lints : Vec < & 'static Lint > ,
2014-06-06 15:49:48 -07:00
2019-10-07 18:23:16 -04:00
/// Constructor functions for each variety of lint pass.
///
/// These should only be called once, but since we want to avoid locks or
/// interior mutability, we don't enforce this (and lints should, in theory,
/// be compatible with being constructed more than once, though not
/// necessarily in a sane manner. This is safe though.)
2022-09-06 14:23:03 -04:00
pub pre_expansion_passes : Vec < Box < EarlyLintPassFactory > > ,
pub early_passes : Vec < Box < EarlyLintPassFactory > > ,
pub late_passes : Vec < Box < LateLintPassFactory > > ,
2019-10-07 18:23:16 -04:00
/// This is unique in that we construct them per-module, so not once.
2022-09-06 14:23:03 -04:00
pub late_module_passes : Vec < Box < LateLintPassFactory > > ,
2014-06-06 15:49:48 -07:00
/// Lints indexed by name.
2016-11-08 14:02:55 +11:00
by_name : FxHashMap < String , TargetLint > ,
2014-06-06 15:49:48 -07:00
2018-09-15 17:32:24 +01:00
/// Map of registered lint groups to what lints they expand to.
lint_groups : FxHashMap < & 'static str , LintGroup > ,
2017-05-16 03:16:18 +08:00
}
2023-11-17 15:24:55 -05:00
impl LintStoreMarker for LintStore { }
2017-08-15 21:45:21 +02:00
/// The target of the `by_name` map, which accounts for renaming/deprecation.
2020-12-29 23:16:16 -05:00
#[ derive(Debug) ]
2014-10-14 11:32:31 -07:00
enum TargetLint {
/// A direct lint target
Id ( LintId ) ,
/// Temporary renaming, used for easing migration pain; see #16545
Renamed ( String , LintId ) ,
2015-07-15 20:12:30 +03:00
/// Lint with this name existed previously, but has been removed/deprecated.
/// The string argument is the reason for removal.
Removed ( String ) ,
2021-03-16 11:59:05 -04:00
/// A lint name that should give no warnings and have no effect.
///
/// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers them as tool lints.
Ignored ,
2015-07-15 20:12:30 +03:00
}
2017-07-26 21:51:09 -07:00
pub enum FindLintError {
2015-07-15 20:12:30 +03:00
NotFound ,
2017-03-13 02:12:13 +02:00
Removed ,
2014-10-14 11:32:31 -07:00
}
2018-09-15 17:32:24 +01:00
struct LintAlias {
name : & 'static str ,
/// Whether deprecation warnings should be suppressed for this alias.
silent : bool ,
}
struct LintGroup {
lint_ids : Vec < LintId > ,
2023-10-03 13:54:17 +11:00
is_loaded : bool ,
2018-09-15 17:32:24 +01:00
depr : Option < LintAlias > ,
}
2021-08-06 23:18:16 +02:00
#[ derive(Debug) ]
2017-07-26 21:51:09 -07:00
pub enum CheckLintNameResult < ' a > {
Ok ( & ' a [ LintId ] ) ,
2018-12-19 13:51:52 -05:00
/// Lint doesn't exist. Potentially contains a suggestion for a correct lint name.
NoLint ( Option < Symbol > ) ,
2021-07-06 17:19:20 -07:00
/// The lint refers to a tool that has not been registered.
NoTool ,
2023-08-23 23:53:37 +01:00
/// The lint has been renamed to a new name.
Renamed ( String ) ,
/// The lint has been removed due to the given reason.
Removed ( String ) ,
2018-07-30 11:29:23 +02:00
/// The lint is from a tool. If the Option is None, then either
/// the lint does not exist in the tool or the code was not
/// compiled with the tool and therefore the lint was never
/// added to the `LintStore`. Otherwise the `LintId` will be
/// returned as if it where a rustc lint.
2018-08-27 23:25:31 +02:00
Tool ( Result < & ' a [ LintId ] , ( Option < & ' a [ LintId ] > , String ) > ) ,
2017-07-26 21:51:09 -07:00
}
2014-06-06 15:49:48 -07:00
impl LintStore {
pub fn new ( ) -> LintStore {
LintStore {
2016-10-29 22:54:04 +01:00
lints : vec ! [ ] ,
2019-10-07 18:23:16 -04:00
pre_expansion_passes : vec ! [ ] ,
early_passes : vec ! [ ] ,
late_passes : vec ! [ ] ,
2019-01-31 04:36:37 +01:00
late_module_passes : vec ! [ ] ,
2018-10-16 16:57:53 +02:00
by_name : Default ::default ( ) ,
lint_groups : Default ::default ( ) ,
2014-06-06 15:49:48 -07:00
}
}
2019-10-07 16:52:53 -04:00
pub fn get_lints < ' t > ( & ' t self ) -> & ' t [ & 'static Lint ] {
2015-02-20 14:08:14 -05:00
& self . lints
2014-06-06 15:49:48 -07:00
}
2022-01-05 13:02:16 +01:00
pub fn get_lint_groups < ' t > (
& ' t self ,
) -> impl Iterator < Item = ( & 'static str , Vec < LintId > , bool ) > + ' t {
// This function is not used in a way which observes the order of lints.
2022-02-23 08:06:22 -05:00
#[ allow(rustc::potential_query_instability) ]
2018-09-15 15:26:45 +01:00
self . lint_groups
. iter ( )
2018-09-15 17:32:24 +01:00
. filter ( | ( _ , LintGroup { depr , .. } ) | {
// Don't display deprecated lint groups.
depr . is_none ( )
} )
2023-10-03 13:54:17 +11:00
. map ( | ( k , LintGroup { lint_ids , is_loaded , .. } ) | ( * k , lint_ids . clone ( ) , * is_loaded ) )
2014-07-21 15:27:59 +12:00
}
2019-10-22 16:53:28 -04:00
pub fn register_early_pass (
& mut self ,
2023-03-03 10:14:57 +08:00
pass : impl Fn ( ) -> EarlyLintPassObject + 'static + sync ::DynSend + sync ::DynSync ,
2019-10-22 16:53:28 -04:00
) {
2019-10-10 19:33:00 -04:00
self . early_passes . push ( Box ::new ( pass ) ) ;
2015-09-15 11:35:25 +12:00
}
2022-02-26 11:32:07 +01:00
/// This lint pass is softly deprecated. It misses expanded code and has caused a few
/// errors in the past. Currently, it is only used in Clippy. New implementations
/// should avoid using this interface, as it might be removed in the future.
///
/// * See [rust#69838](https://github.com/rust-lang/rust/pull/69838)
/// * See [rust-clippy#5518](https://github.com/rust-lang/rust-clippy/pull/5518)
2019-10-22 16:53:28 -04:00
pub fn register_pre_expansion_pass (
& mut self ,
2023-03-03 10:14:57 +08:00
pass : impl Fn ( ) -> EarlyLintPassObject + 'static + sync ::DynSend + sync ::DynSync ,
2019-10-22 16:53:28 -04:00
) {
2019-10-10 19:33:00 -04:00
self . pre_expansion_passes . push ( Box ::new ( pass ) ) ;
2018-07-14 16:40:17 +02:00
}
2019-10-22 16:53:28 -04:00
pub fn register_late_pass (
& mut self ,
2022-09-06 14:23:03 -04:00
pass : impl for < ' tcx > Fn ( TyCtxt < ' tcx > ) -> LateLintPassObject < ' tcx >
+ 'static
2023-03-03 10:14:57 +08:00
+ sync ::DynSend
+ sync ::DynSync ,
2019-10-22 16:53:28 -04:00
) {
2019-10-10 19:33:00 -04:00
self . late_passes . push ( Box ::new ( pass ) ) ;
2019-10-07 16:59:12 -04:00
}
2019-10-22 16:53:28 -04:00
pub fn register_late_mod_pass (
& mut self ,
2022-09-06 14:23:03 -04:00
pass : impl for < ' tcx > Fn ( TyCtxt < ' tcx > ) -> LateLintPassObject < ' tcx >
+ 'static
2023-03-03 10:14:57 +08:00
+ sync ::DynSend
+ sync ::DynSync ,
2019-10-22 16:53:28 -04:00
) {
2019-10-10 19:33:00 -04:00
self . late_module_passes . push ( Box ::new ( pass ) ) ;
2015-09-15 11:35:25 +12:00
}
2022-11-27 11:15:06 +00:00
/// Helper method for register_early/late_pass
2019-10-07 17:21:50 -04:00
pub fn register_lints ( & mut self , lints : & [ & 'static Lint ] ) {
2019-09-24 18:24:45 -04:00
for lint in lints {
2019-10-07 16:52:53 -04:00
self . lints . push ( lint ) ;
2014-06-06 15:49:48 -07:00
2018-06-21 09:04:50 +02:00
let id = LintId ::of ( lint ) ;
2014-11-06 12:25:16 -05:00
if self . by_name . insert ( lint . name_lower ( ) , Id ( id ) ) . is_some ( ) {
2019-09-23 20:13:02 -04:00
bug! ( " duplicate specification of lint {} " , lint . name_lower ( ) )
2014-06-06 15:49:48 -07:00
}
2021-06-15 17:16:21 +02:00
if let Some ( FutureIncompatibleInfo { reason , .. } ) = lint . future_incompatible {
if let Some ( edition ) = reason . edition ( ) {
2019-10-08 21:49:21 -04:00
self . lint_groups
. entry ( edition . lint_name ( ) )
. or_insert ( LintGroup {
lint_ids : vec ! [ ] ,
2023-10-03 13:54:17 +11:00
is_loaded : lint . is_loaded ,
2019-10-08 21:49:21 -04:00
depr : None ,
} )
. lint_ids
. push ( id ) ;
2021-06-24 16:29:03 +02:00
} else {
2021-06-28 17:42:27 +02:00
// Lints belonging to the `future_incompatible` lint group are lints where a
// future version of rustc will cause existing code to stop compiling.
// Lints tied to an edition don't count because they are opt-in.
2021-06-24 16:29:03 +02:00
self . lint_groups
. entry ( " future_incompatible " )
. or_insert ( LintGroup {
lint_ids : vec ! [ ] ,
2023-10-03 13:54:17 +11:00
is_loaded : lint . is_loaded ,
2021-06-24 16:29:03 +02:00
depr : None ,
} )
. lint_ids
. push ( id ) ;
2019-10-08 21:49:21 -04:00
}
2018-02-22 16:51:42 -08:00
}
}
2016-01-08 17:53:44 -05:00
}
2018-09-15 15:26:45 +01:00
pub fn register_group_alias ( & mut self , lint_name : & 'static str , alias : & 'static str ) {
2018-09-15 17:32:24 +01:00
self . lint_groups . insert (
alias ,
LintGroup {
lint_ids : vec ! [ ] ,
2023-10-03 13:54:17 +11:00
is_loaded : false ,
2018-09-15 17:32:24 +01:00
depr : Some ( LintAlias { name : lint_name , silent : true } ) ,
} ,
) ;
2018-09-15 15:26:45 +01:00
}
2018-08-27 23:24:42 +02:00
pub fn register_group (
& mut self ,
2023-10-03 13:54:17 +11:00
is_loaded : bool ,
2018-08-27 23:24:42 +02:00
name : & 'static str ,
deprecated_name : Option < & 'static str > ,
to : Vec < LintId > ,
) {
let new = self
. lint_groups
2023-10-03 13:54:17 +11:00
. insert ( name , LintGroup { lint_ids : to , is_loaded , depr : None } )
2018-08-27 23:24:42 +02:00
. is_none ( ) ;
if let Some ( deprecated ) = deprecated_name {
2018-09-15 17:32:24 +01:00
self . lint_groups . insert (
deprecated ,
LintGroup {
lint_ids : vec ! [ ] ,
2023-10-03 13:54:17 +11:00
is_loaded ,
2018-09-15 17:32:24 +01:00
depr : Some ( LintAlias { name , silent : false } ) ,
} ,
) ;
2018-08-27 23:24:42 +02:00
}
2014-07-21 15:27:59 +12:00
if ! new {
2019-09-23 20:13:02 -04:00
bug! ( " duplicate specification of lint group {} " , name ) ;
2014-07-21 15:27:59 +12:00
}
}
2021-03-16 11:59:05 -04:00
/// This lint should give no warning and have no effect.
///
/// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers them as tool lints.
#[ track_caller ]
pub fn register_ignored ( & mut self , name : & str ) {
if self . by_name . insert ( name . to_string ( ) , Ignored ) . is_some ( ) {
bug! ( " duplicate specification of lint {} " , name ) ;
}
}
/// This lint has been renamed; warn about using the new name and apply the lint.
2020-12-29 23:16:40 -05:00
#[ track_caller ]
2015-02-25 22:44:44 +11:00
pub fn register_renamed ( & mut self , old_name : & str , new_name : & str ) {
2022-02-19 00:48:49 +01:00
let Some ( & Id ( target ) ) = self . by_name . get ( new_name ) else {
bug! ( " invalid lint renaming of {} to {} " , old_name , new_name ) ;
2014-10-14 11:32:31 -07:00
} ;
self . by_name . insert ( old_name . to_string ( ) , Renamed ( new_name . to_string ( ) , target ) ) ;
}
2015-07-15 20:12:30 +03:00
pub fn register_removed ( & mut self , name : & str , reason : & str ) {
self . by_name . insert ( name . into ( ) , Removed ( reason . into ( ) ) ) ;
}
2018-09-15 17:05:52 +01:00
pub fn find_lints ( & self , mut lint_name : & str ) -> Result < Vec < LintId > , FindLintError > {
2014-11-12 15:51:51 -08:00
match self . by_name . get ( lint_name ) {
2017-07-26 21:51:09 -07:00
Some ( & Id ( lint_id ) ) = > Ok ( vec! [ lint_id ] ) ,
2016-01-13 18:54:06 +00:00
Some ( & Renamed ( _ , lint_id ) ) = > Ok ( vec! [ lint_id ] ) ,
2015-07-15 20:12:30 +03:00
Some ( & Removed ( _ ) ) = > Err ( FindLintError ::Removed ) ,
2021-03-16 11:59:05 -04:00
Some ( & Ignored ) = > Ok ( vec! [ ] ) ,
2017-07-26 21:51:09 -07:00
None = > loop {
2018-09-15 17:05:52 +01:00
return match self . lint_groups . get ( lint_name ) {
2018-09-15 17:32:24 +01:00
Some ( LintGroup { lint_ids , depr , .. } ) = > {
if let Some ( LintAlias { name , .. } ) = depr {
2018-09-15 17:05:52 +01:00
lint_name = name ;
continue ;
}
Ok ( lint_ids . clone ( ) )
2019-12-22 17:42:04 -05:00
}
2018-09-15 17:05:52 +01:00
None = > Err ( FindLintError ::Removed ) ,
} ;
2014-06-06 15:49:48 -07:00
} ,
}
2017-05-16 03:16:18 +08:00
}
2021-01-29 19:06:00 -05:00
/// True if this symbol represents a lint group name.
pub fn is_lint_group ( & self , lint_name : Symbol ) -> bool {
debug! (
" is_lint_group(lint_name={:?}, lint_groups={:?}) " ,
lint_name ,
self . lint_groups . keys ( ) . collect ::< Vec < _ > > ( )
) ;
2021-12-15 14:39:23 +11:00
let lint_name_str = lint_name . as_str ( ) ;
self . lint_groups . contains_key ( lint_name_str ) | | {
2021-01-29 19:06:00 -05:00
let warnings_name_str = crate ::WARNINGS . name_lower ( ) ;
2021-12-15 14:39:23 +11:00
lint_name_str = = warnings_name_str
2021-01-29 19:06:00 -05:00
}
2017-05-16 03:16:18 +08:00
}
2017-07-26 21:51:09 -07:00
/// Checks the name of a lint for its existence, and whether it was
/// renamed or removed. Generates a DiagnosticBuilder containing a
/// warning for renamed and removed lints. This is over both lint
/// names from attributes and those passed on the command line. Since
/// it emits non-fatal warnings and there are *two* lint passes that
/// inspect attributes, this is only run from the late pass to avoid
/// printing duplicate warnings.
2018-07-30 11:29:23 +02:00
pub fn check_lint_name (
& self ,
lint_name : & str ,
2019-09-03 16:02:32 +10:00
tool_name : Option < Symbol > ,
2021-09-29 01:17:54 +03:00
registered_tools : & RegisteredTools ,
2018-08-29 22:02:42 -07:00
) -> CheckLintNameResult < '_ > {
2021-07-07 10:50:50 -07:00
if let Some ( tool_name ) = tool_name {
2021-09-29 01:17:54 +03:00
// FIXME: rustc and rustdoc are considered tools for lints, but not for attributes.
if tool_name ! = sym ::rustc
& & tool_name ! = sym ::rustdoc
& & ! registered_tools . contains ( & Ident ::with_dummy_span ( tool_name ) )
{
2021-07-07 10:50:50 -07:00
return CheckLintNameResult ::NoTool ;
}
}
2018-07-30 11:29:23 +02:00
let complete_name = if let Some ( tool_name ) = tool_name {
2023-07-25 23:17:39 +02:00
format! ( " {tool_name} :: {lint_name} " )
2018-07-30 11:29:23 +02:00
} else {
lint_name . to_string ( )
} ;
2018-08-27 23:25:31 +02:00
// If the lint was scoped with `tool::` check if the tool lint exists
2020-12-30 13:49:28 -05:00
if let Some ( tool_name ) = tool_name {
2018-07-30 11:29:23 +02:00
match self . by_name . get ( & complete_name ) {
None = > match self . lint_groups . get ( & * complete_name ) {
2020-12-30 13:49:28 -05:00
// If the lint isn't registered, there are two possibilities:
None = > {
// 1. The tool is currently running, so this lint really doesn't exist.
// FIXME: should this handle tools that never register a lint, like rustfmt?
2022-08-31 13:09:26 +00:00
debug! ( " lints={:?} " , self . by_name . keys ( ) . collect ::< Vec < _ > > ( ) ) ;
2023-07-25 23:17:39 +02:00
let tool_prefix = format! ( " {tool_name} :: " ) ;
2020-12-30 13:49:28 -05:00
return if self . by_name . keys ( ) . any ( | lint | lint . starts_with ( & tool_prefix ) ) {
self . no_lint_suggestion ( & complete_name )
} else {
// 2. The tool isn't currently running, so no lints will be registered.
// To avoid giving a false positive, ignore all unknown lints.
CheckLintNameResult ::Tool ( Err ( ( None , String ::new ( ) ) ) )
} ;
}
2018-09-15 17:32:24 +01:00
Some ( LintGroup { lint_ids , .. } ) = > {
2023-11-21 20:07:32 +01:00
return CheckLintNameResult ::Tool ( Ok ( lint_ids ) ) ;
2018-09-15 17:32:24 +01:00
}
2018-07-30 11:29:23 +02:00
} ,
2022-12-18 17:01:58 +01:00
Some ( Id ( id ) ) = > return CheckLintNameResult ::Tool ( Ok ( slice ::from_ref ( id ) ) ) ,
2018-07-30 11:29:23 +02:00
// If the lint was registered as removed or renamed by the lint tool, we don't need
// to treat tool_lints and rustc lints different and can use the code below.
_ = > { }
2015-07-23 22:19:12 -07:00
}
2018-07-30 11:29:23 +02:00
}
match self . by_name . get ( & complete_name ) {
2023-08-23 23:53:37 +01:00
Some ( Renamed ( new_name , _ ) ) = > CheckLintNameResult ::Renamed ( new_name . to_string ( ) ) ,
Some ( Removed ( reason ) ) = > CheckLintNameResult ::Removed ( reason . to_string ( ) ) ,
2018-07-30 11:29:23 +02:00
None = > match self . lint_groups . get ( & * complete_name ) {
2018-08-27 23:25:31 +02:00
// If neither the lint, nor the lint group exists check if there is a `clippy::`
// variant of this lint
None = > self . check_tool_name_for_backwards_compat ( & complete_name , " clippy " ) ,
2018-09-15 17:32:24 +01:00
Some ( LintGroup { lint_ids , depr , .. } ) = > {
2018-08-27 23:25:31 +02:00
// Check if the lint group name is deprecated
2018-09-15 17:32:24 +01:00
if let Some ( LintAlias { name , silent } ) = depr {
let LintGroup { lint_ids , .. } = self . lint_groups . get ( name ) . unwrap ( ) ;
return if * silent {
2023-11-21 20:07:32 +01:00
CheckLintNameResult ::Ok ( lint_ids )
2018-09-15 15:26:45 +01:00
} else {
2023-11-21 20:07:32 +01:00
CheckLintNameResult ::Tool ( Err ( ( Some ( lint_ids ) , ( * name ) . to_string ( ) ) ) )
2018-09-15 15:26:45 +01:00
} ;
2018-08-27 23:25:31 +02:00
}
2023-11-21 20:07:32 +01:00
CheckLintNameResult ::Ok ( lint_ids )
2018-08-27 23:25:31 +02:00
}
2018-07-30 11:29:23 +02:00
} ,
2022-12-18 17:01:58 +01:00
Some ( Id ( id ) ) = > CheckLintNameResult ::Ok ( slice ::from_ref ( id ) ) ,
2021-03-16 11:59:05 -04:00
Some ( & Ignored ) = > CheckLintNameResult ::Ok ( & [ ] ) ,
2015-07-23 22:19:12 -07:00
}
2014-06-06 15:49:48 -07:00
}
2018-08-27 23:25:31 +02:00
2020-12-30 13:49:28 -05:00
fn no_lint_suggestion ( & self , lint_name : & str ) -> CheckLintNameResult < '_ > {
2021-01-16 17:11:26 +01:00
let name_lower = lint_name . to_lowercase ( ) ;
2020-12-30 13:49:28 -05:00
2021-01-16 17:11:26 +01:00
if lint_name . chars ( ) . any ( char ::is_uppercase ) & & self . find_lints ( & name_lower ) . is_ok ( ) {
// First check if the lint name is (partly) in upper case instead of lower case...
2021-05-05 10:33:14 -05:00
return CheckLintNameResult ::NoLint ( Some ( Symbol ::intern ( & name_lower ) ) ) ;
2021-01-16 17:11:26 +01:00
}
2021-05-05 10:33:14 -05:00
// ...if not, search for lints with a similar name
2022-12-21 17:27:45 +01:00
// Note: find_best_match_for_name depends on the sort order of its input vector.
// To ensure deterministic output, sort elements of the lint_groups hash map.
// Also, never suggest deprecated lint groups.
let mut groups : Vec < _ > = self
. lint_groups
. iter ( )
2023-02-15 17:39:43 +00:00
. filter_map ( | ( k , LintGroup { depr , .. } ) | depr . is_none ( ) . then_some ( k ) )
2022-12-21 17:27:45 +01:00
. collect ( ) ;
groups . sort ( ) ;
let groups = groups . iter ( ) . map ( | k | Symbol ::intern ( k ) ) ;
2021-05-05 10:33:14 -05:00
let lints = self . lints . iter ( ) . map ( | l | Symbol ::intern ( & l . name_lower ( ) ) ) ;
let names : Vec < Symbol > = groups . chain ( lints ) . collect ( ) ;
let suggestion = find_best_match_for_name ( & names , Symbol ::intern ( & name_lower ) , None ) ;
CheckLintNameResult ::NoLint ( suggestion )
2020-12-30 13:49:28 -05:00
}
2018-08-27 23:25:31 +02:00
fn check_tool_name_for_backwards_compat (
& self ,
lint_name : & str ,
tool_name : & str ,
2018-08-29 22:02:42 -07:00
) -> CheckLintNameResult < '_ > {
2023-07-25 23:17:39 +02:00
let complete_name = format! ( " {tool_name} :: {lint_name} " ) ;
2018-08-27 23:25:31 +02:00
match self . by_name . get ( & complete_name ) {
None = > match self . lint_groups . get ( & * complete_name ) {
// Now we are sure, that this lint exists nowhere
2020-12-30 13:49:28 -05:00
None = > self . no_lint_suggestion ( lint_name ) ,
2018-09-15 17:32:24 +01:00
Some ( LintGroup { lint_ids , depr , .. } ) = > {
2018-09-15 15:26:45 +01:00
// Reaching this would be weird, but let's cover this case anyway
2018-09-15 17:32:24 +01:00
if let Some ( LintAlias { name , silent } ) = depr {
let LintGroup { lint_ids , .. } = self . lint_groups . get ( name ) . unwrap ( ) ;
return if * silent {
2023-11-21 20:07:32 +01:00
CheckLintNameResult ::Tool ( Err ( ( Some ( lint_ids ) , complete_name ) ) )
2018-09-15 15:26:45 +01:00
} else {
2023-11-21 20:07:32 +01:00
CheckLintNameResult ::Tool ( Err ( ( Some ( lint_ids ) , ( * name ) . to_string ( ) ) ) )
2018-09-15 15:26:45 +01:00
} ;
2018-08-27 23:25:31 +02:00
}
2023-11-21 20:07:32 +01:00
CheckLintNameResult ::Tool ( Err ( ( Some ( lint_ids ) , complete_name ) ) )
2018-08-27 23:25:31 +02:00
}
} ,
2022-12-18 17:01:58 +01:00
Some ( Id ( id ) ) = > {
2018-08-27 23:25:31 +02:00
CheckLintNameResult ::Tool ( Err ( ( Some ( slice ::from_ref ( id ) ) , complete_name ) ) )
}
2020-12-29 23:16:16 -05:00
Some ( other ) = > {
2022-08-31 13:09:26 +00:00
debug! ( " got renamed lint {:?} " , other ) ;
2020-12-29 23:16:16 -05:00
CheckLintNameResult ::NoLint ( None )
}
2018-08-27 23:25:31 +02:00
}
}
2014-06-06 15:49:48 -07:00
}
2021-10-25 15:43:07 -05:00
/// Context for lint checking outside of type inference.
2020-06-25 23:41:36 +03:00
pub struct LateContext < ' tcx > {
2014-06-06 15:49:48 -07:00
/// Type context we're checking in.
2019-06-14 00:48:52 +03:00
pub tcx : TyCtxt < ' tcx > ,
2014-06-06 15:49:48 -07:00
2020-06-26 02:56:23 +03:00
/// Current body, or `None` if outside a body.
pub enclosing_body : Option < hir ::BodyId > ,
2020-07-17 08:47:04 +00:00
/// Type-checking results for the current body. Access using the `typeck_results`
/// and `maybe_typeck_results` methods, which handle querying the typeck results on demand.
2020-06-26 02:56:23 +03:00
// FIXME(eddyb) move all the code accessing internal fields like this,
// to this module, to avoid exposing it to lint logic.
2020-07-17 08:47:04 +00:00
pub ( super ) cached_typeck_results : Cell < Option < & ' tcx ty ::TypeckResults < ' tcx > > > ,
2020-06-26 02:56:23 +03:00
2017-06-07 15:21:55 +03:00
/// Parameter environment for the item we are in.
pub param_env : ty ::ParamEnv < ' tcx > ,
2015-11-19 14:16:35 +03:00
/// Items accessible from the crate being checked.
2022-09-22 16:19:53 +03:00
pub effective_visibilities : & ' tcx EffectiveVisibilities ,
2014-06-17 16:55:34 -07:00
2019-12-30 14:22:46 +01:00
pub last_node_with_lint_attrs : hir ::HirId ,
2017-10-28 17:19:07 -04:00
/// Generic type parameters in scope for the item we are in.
2019-11-30 17:46:46 +01:00
pub generics : Option < & ' tcx hir ::Generics < ' tcx > > ,
2018-06-11 08:48:15 +02:00
/// We are only looking at one module
2019-12-30 14:11:49 +01:00
pub only_module : bool ,
2014-06-06 15:49:48 -07:00
}
2021-09-28 00:28:49 +03:00
/// Context for lint checking of the AST, after expansion, before lowering to HIR.
2015-09-10 16:40:59 +12:00
pub struct EarlyContext < ' a > {
2022-07-22 16:48:36 +00:00
pub builder : LintLevelsBuilder < ' a , crate ::levels ::TopDown > ,
2019-12-30 14:11:49 +01:00
pub buffered : LintBuffer ,
2019-01-18 07:40:55 +01:00
}
2023-11-06 15:56:41 +11:00
pub trait LintContext {
2015-09-10 16:40:59 +12:00
fn sess ( & self ) -> & Session ;
2014-06-06 15:49:48 -07:00
2023-11-06 15:56:41 +11:00
/// Emit a lint at the appropriate level, with an optional associated span and an existing
/// diagnostic.
2022-10-12 14:16:24 +00:00
///
/// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
2022-11-07 19:23:29 -05:00
#[ rustc_lint_diagnostics ]
2020-02-06 01:28:23 +10:00
fn lookup_with_diagnostics (
2018-02-22 22:34:06 -08:00
& self ,
lint : & 'static Lint ,
2020-02-06 01:28:23 +10:00
span : Option < impl Into < MultiSpan > > ,
2022-09-16 11:01:02 +04:00
msg : impl Into < DiagnosticMessage > ,
2023-12-08 01:52:56 +00:00
decorate : impl for < ' a , ' b > FnOnce ( & ' b mut DiagnosticBuilder < ' a , ( ) > ) ,
2018-02-22 22:34:06 -08:00
diagnostic : BuiltinLintDiagnostics ,
) {
2022-09-16 11:01:02 +04:00
// We first generate a blank diagnostic.
self . lookup ( lint , span , msg , | db | {
2020-02-02 19:41:14 +10:00
// Now, set up surrounding context.
2020-01-31 22:24:57 +10:00
let sess = self . sess ( ) ;
match diagnostic {
2021-08-19 11:40:00 -07:00
BuiltinLintDiagnostics ::UnicodeTextFlow ( span , content ) = > {
let spans : Vec < _ > = content
. char_indices ( )
. filter_map ( | ( i , c ) | {
2021-11-04 23:31:42 +01:00
TEXT_FLOW_CONTROL_CHARS . contains ( & c ) . then ( | | {
2021-08-19 11:40:00 -07:00
let lo = span . lo ( ) + BytePos ( 2 + i as u32 ) ;
( c , span . with_lo ( lo ) . with_hi ( lo + BytePos ( c . len_utf8 ( ) as u32 ) ) )
} )
} )
. collect ( ) ;
let ( an , s ) = match spans . len ( ) {
1 = > ( " an " , " " ) ,
_ = > ( " " , " s " ) ,
} ;
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
db . span_label ( span , format! (
2023-07-25 23:17:39 +02:00
" this comment contains {an}invisible unicode text flow control codepoint{s} " ,
2021-08-19 11:40:00 -07:00
) ) ;
for ( c , span ) in & spans {
2023-07-25 23:17:39 +02:00
db . span_label ( * span , format! ( " {c:?} " ) ) ;
2021-08-19 11:40:00 -07:00
}
db . note (
" these kind of unicode codepoints change the way text flows on \
applications that support them , but can cause confusion because they \
change the order of characters on the screen " ,
) ;
if ! spans . is_empty ( ) {
db . multipart_suggestion_with_style (
" if their presence wasn't intentional, you can remove them " ,
spans . into_iter ( ) . map ( | ( _ , span ) | ( span , " " . to_string ( ) ) ) . collect ( ) ,
Applicability ::MachineApplicable ,
SuggestionStyle ::HideCodeAlways ,
) ;
}
} ,
2020-01-31 22:24:57 +10:00
BuiltinLintDiagnostics ::Normal = > ( ) ,
BuiltinLintDiagnostics ::AbsPathWithModule ( span ) = > {
let ( sugg , app ) = match sess . source_map ( ) . span_to_snippet ( span ) {
Ok ( ref s ) = > {
// FIXME(Manishearth) ideally the emitting code
// can tell us whether or not this is global
2020-02-02 09:47:58 +10:00
let opt_colon =
if s . trim_start ( ) . starts_with ( " :: " ) { " " } else { " :: " } ;
2020-01-31 22:24:57 +10:00
2023-07-25 23:17:39 +02:00
( format! ( " crate {opt_colon} {s} " ) , Applicability ::MachineApplicable )
2020-01-31 22:24:57 +10:00
}
Err ( _ ) = > ( " crate::<path> " . to_string ( ) , Applicability ::HasPlaceholders ) ,
} ;
db . span_suggestion ( span , " use `crate` " , sugg , app ) ;
}
BuiltinLintDiagnostics ::ProcMacroDeriveResolutionFallback ( span ) = > {
db . span_label (
span ,
" names from parent modules are not accessible without an explicit import " ,
) ;
}
2020-02-02 09:47:58 +10:00
BuiltinLintDiagnostics ::MacroExpandedMacroExportsAccessedByAbsolutePaths (
span_def ,
) = > {
2020-01-31 22:24:57 +10:00
db . span_note ( span_def , " the macro is defined here " ) ;
}
2022-03-10 23:12:35 +01:00
BuiltinLintDiagnostics ::ElidedLifetimesInPaths (
n ,
path_span ,
incl_angl_brckt ,
insertion_span ,
) = > {
add_elided_lifetime_in_path_suggestion (
sess . source_map ( ) ,
2022-09-16 11:01:02 +04:00
db ,
2022-03-10 23:12:35 +01:00
n ,
path_span ,
incl_angl_brckt ,
insertion_span ,
) ;
}
2020-01-31 22:24:57 +10:00
BuiltinLintDiagnostics ::UnknownCrateTypes ( span , note , sugg ) = > {
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
db . span_suggestion ( span , note , sugg , Applicability ::MaybeIncorrect ) ;
2020-01-31 22:24:57 +10:00
}
2021-10-23 18:55:02 +09:00
BuiltinLintDiagnostics ::UnusedImports ( message , replaces , in_test_module ) = > {
2020-01-31 22:24:57 +10:00
if ! replaces . is_empty ( ) {
db . tool_only_multipart_suggestion (
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
message ,
2020-01-31 22:24:57 +10:00
replaces ,
Applicability ::MachineApplicable ,
) ;
}
2021-10-23 18:55:02 +09:00
if let Some ( span ) = in_test_module {
db . span_help (
2022-07-08 02:10:15 +00:00
self . sess ( ) . source_map ( ) . guess_head_span ( span ) ,
2021-10-23 18:55:02 +09:00
" consider adding a `#[cfg(test)]` to the containing module " ,
) ;
}
2020-01-31 22:24:57 +10:00
}
BuiltinLintDiagnostics ::RedundantImport ( spans , ident ) = > {
for ( span , is_imported ) in spans {
let introduced = if is_imported { " imported " } else { " defined " } ;
db . span_label (
span ,
2023-07-25 23:17:39 +02:00
format! ( " the item ` {ident} ` is already {introduced} here " ) ,
2020-01-31 22:24:57 +10:00
) ;
}
}
BuiltinLintDiagnostics ::DeprecatedMacro ( suggestion , span ) = > {
2022-09-16 11:01:02 +04:00
stability ::deprecation_suggestion ( db , " macro " , suggestion , span )
2020-01-05 10:07:26 +01:00
}
2020-02-21 16:01:48 -08:00
BuiltinLintDiagnostics ::UnusedDocComment ( span ) = > {
2020-04-21 21:09:24 -07:00
db . span_label ( span , " rustdoc does not generate documentation for macro invocations " ) ;
2020-02-21 16:01:48 -08:00
db . help ( " to document an item produced by a macro, \
the macro must produce the documentation as part of its expansion " );
}
2020-11-30 23:24:08 +09:00
BuiltinLintDiagnostics ::PatternsInFnsWithoutBody ( span , ident ) = > {
2022-06-13 15:48:40 +09:00
db . span_suggestion ( span , " remove `mut` from the parameter " , ident , Applicability ::MachineApplicable ) ;
2020-11-30 23:24:08 +09:00
}
2020-09-01 17:12:38 -04:00
BuiltinLintDiagnostics ::MissingAbi ( span , default_abi ) = > {
db . span_label ( span , " ABI should be specified here " ) ;
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
db . help ( format! ( " the default ABI is {} " , default_abi . name ( ) ) ) ;
2020-09-01 17:12:38 -04:00
}
2020-11-14 14:47:14 +03:00
BuiltinLintDiagnostics ::LegacyDeriveHelpers ( span ) = > {
db . span_label ( span , " the attribute is introduced here " ) ;
}
2021-03-14 16:55:59 -04:00
BuiltinLintDiagnostics ::ProcMacroBackCompat ( note ) = > {
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
db . note ( note ) ;
2021-03-14 16:55:59 -04:00
}
2021-03-25 21:42:21 +08:00
BuiltinLintDiagnostics ::OrPatternsBackCompat ( span , suggestion ) = > {
2021-04-14 20:34:51 -05:00
db . span_suggestion ( span , " use pat_param to preserve semantics " , suggestion , Applicability ::MachineApplicable ) ;
2021-03-25 21:42:21 +08:00
}
2021-06-14 12:56:49 +00:00
BuiltinLintDiagnostics ::ReservedPrefix ( span ) = > {
db . span_label ( span , " unknown prefix " ) ;
db . span_suggestion_verbose (
span . shrink_to_hi ( ) ,
" insert whitespace here to avoid this being parsed as a prefix in Rust 2021 " ,
2022-04-26 06:17:33 +01:00
" " ,
2021-06-14 12:56:49 +00:00
Applicability ::MachineApplicable ,
) ;
}
2021-07-14 19:51:45 -05:00
BuiltinLintDiagnostics ::UnusedBuiltinAttribute {
attr_name ,
macro_name ,
invoc_span
} = > {
db . span_note (
invoc_span ,
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
format! ( " the built-in attribute ` {attr_name} ` will be ignored, since it's applied to the macro invocation ` {macro_name} ` " )
2021-07-14 19:51:45 -05:00
) ;
}
Display an extra note for trailing semicolon lint with trailing macro
Currently, we parse macros at the end of a block
(e.g. `fn foo() { my_macro!() }`) as expressions, rather than
statements. This means that a macro invoked in this position
cannot expand to items or semicolon-terminated expressions.
In the future, we might want to start parsing these kinds of macros
as statements. This would make expansion more 'token-based'
(i.e. macro expansion behaves (almost) as if you just textually
replaced the macro invocation with its output). However,
this is a breaking change (see PR #78991), so it will require
further discussion.
Since the current behavior will not be changing any time soon,
we need to address the interaction with the
`SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` lint. Since we are parsing
the result of macro expansion as an expression, we will emit a lint
if there's a trailing semicolon in the macro output. However, this
results in a somewhat confusing message for users, since it visually
looks like there should be no problem with having a semicolon
at the end of a block
(e.g. `fn foo() { my_macro!() }` => `fn foo() { produced_expr; }`)
To help reduce confusion, this commit adds a note explaining
that the macro is being interpreted as an expression. Additionally,
we suggest adding a semicolon after the macro *invocation* - this
will cause us to parse the macro call as a statement. We do *not*
use a structured suggestion for this, since the user may actually
want to remove the semicolon from the macro definition (allowing
the block to evaluate to the expression produced by the macro).
2021-07-22 11:24:42 -05:00
BuiltinLintDiagnostics ::TrailingMacro ( is_trailing , name ) = > {
if is_trailing {
db . note ( " macro invocations at the end of a block are treated as expressions " ) ;
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
db . note ( format! ( " to ignore the value produced by the macro, add a semicolon after the invocation of ` {name} ` " ) ) ;
Display an extra note for trailing semicolon lint with trailing macro
Currently, we parse macros at the end of a block
(e.g. `fn foo() { my_macro!() }`) as expressions, rather than
statements. This means that a macro invoked in this position
cannot expand to items or semicolon-terminated expressions.
In the future, we might want to start parsing these kinds of macros
as statements. This would make expansion more 'token-based'
(i.e. macro expansion behaves (almost) as if you just textually
replaced the macro invocation with its output). However,
this is a breaking change (see PR #78991), so it will require
further discussion.
Since the current behavior will not be changing any time soon,
we need to address the interaction with the
`SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` lint. Since we are parsing
the result of macro expansion as an expression, we will emit a lint
if there's a trailing semicolon in the macro output. However, this
results in a somewhat confusing message for users, since it visually
looks like there should be no problem with having a semicolon
at the end of a block
(e.g. `fn foo() { my_macro!() }` => `fn foo() { produced_expr; }`)
To help reduce confusion, this commit adds a note explaining
that the macro is being interpreted as an expression. Additionally,
we suggest adding a semicolon after the macro *invocation* - this
will cause us to parse the macro call as a statement. We do *not*
use a structured suggestion for this, since the user may actually
want to remove the semicolon from the macro definition (allowing
the block to evaluate to the expression produced by the macro).
2021-07-22 11:24:42 -05:00
}
}
2021-07-10 16:38:55 +02:00
BuiltinLintDiagnostics ::BreakWithLabelAndLoop ( span ) = > {
2021-08-03 21:23:29 +02:00
db . multipart_suggestion (
" wrap this expression in parentheses " ,
vec! [ ( span . shrink_to_lo ( ) , " ( " . to_string ( ) ) ,
( span . shrink_to_hi ( ) , " ) " . to_string ( ) ) ] ,
Applicability ::MachineApplicable
) ;
2021-07-10 16:38:55 +02:00
}
2021-07-20 16:35:26 -04:00
BuiltinLintDiagnostics ::NamedAsmLabel ( help ) = > {
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
db . help ( help ) ;
2022-01-06 14:39:42 +01:00
db . note ( " see the asm section of Rust By Example <https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels> for more information " ) ;
2022-02-20 00:48:10 +01:00
} ,
2023-04-30 19:09:15 +02:00
BuiltinLintDiagnostics ::UnexpectedCfgName ( ( name , name_span ) , value ) = > {
2023-11-03 17:18:19 +01:00
let possibilities : Vec < Symbol > = sess . parse_sess . check_config . expecteds . keys ( ) . copied ( ) . collect ( ) ;
2023-11-22 16:50:24 +01:00
let is_from_cargo = std ::env ::var_os ( " CARGO " ) . is_some ( ) ;
let mut is_feature_cfg = name = = sym ::feature ;
2022-03-03 15:56:19 +01:00
2023-11-22 16:50:24 +01:00
if is_feature_cfg & & is_from_cargo {
db . help ( " consider defining some features in `Cargo.toml` " ) ;
2022-03-03 15:56:19 +01:00
// Suggest the most probable if we found one
2023-11-22 16:50:24 +01:00
} else if let Some ( best_match ) = find_best_match_for_name ( & possibilities , name , None ) {
2023-04-30 19:09:15 +02:00
if let Some ( ExpectedValues ::Some ( best_match_values ) ) =
sess . parse_sess . check_config . expecteds . get ( & best_match ) {
let mut possibilities = best_match_values . iter ( )
. flatten ( )
. map ( Symbol ::as_str )
. collect ::< Vec < _ > > ( ) ;
possibilities . sort ( ) ;
2023-10-12 16:46:27 +02:00
let mut should_print_possibilities = true ;
2023-04-30 19:09:15 +02:00
if let Some ( ( value , value_span ) ) = value {
if best_match_values . contains ( & Some ( value ) ) {
db . span_suggestion ( name_span , " there is a config with a similar name and value " , best_match , Applicability ::MaybeIncorrect ) ;
2023-10-12 16:46:27 +02:00
should_print_possibilities = false ;
2023-04-30 19:09:15 +02:00
} else if best_match_values . contains ( & None ) {
db . span_suggestion ( name_span . to ( value_span ) , " there is a config with a similar name and no value " , best_match , Applicability ::MaybeIncorrect ) ;
2023-10-12 16:46:27 +02:00
should_print_possibilities = false ;
2023-04-30 19:09:15 +02:00
} else if let Some ( first_value ) = possibilities . first ( ) {
db . span_suggestion ( name_span . to ( value_span ) , " there is a config with a similar name and different values " , format! ( " {best_match} = \" {first_value} \" " ) , Applicability ::MaybeIncorrect ) ;
} else {
db . span_suggestion ( name_span . to ( value_span ) , " there is a config with a similar name and different values " , best_match , Applicability ::MaybeIncorrect ) ;
} ;
} else {
db . span_suggestion ( name_span , " there is a config with a similar name " , best_match , Applicability ::MaybeIncorrect ) ;
}
2023-10-12 16:46:27 +02:00
if ! possibilities . is_empty ( ) & & should_print_possibilities {
2023-04-30 19:09:15 +02:00
let possibilities = possibilities . join ( " `, ` " ) ;
db . help ( format! ( " expected values for ` {best_match} ` are: ` {possibilities} ` " ) ) ;
}
} else {
db . span_suggestion ( name_span , " there is a config with a similar name " , best_match , Applicability ::MaybeIncorrect ) ;
}
2023-11-22 16:50:24 +01:00
is_feature_cfg | = best_match = = sym ::feature ;
2023-10-12 16:46:27 +02:00
} else if ! possibilities . is_empty ( ) {
let mut possibilities = possibilities . iter ( )
. map ( Symbol ::as_str )
. collect ::< Vec < _ > > ( ) ;
possibilities . sort ( ) ;
let possibilities = possibilities . join ( " `, ` " ) ;
2023-10-12 17:01:55 +02:00
// The list of expected names can be long (even by default) and
// so the diagnostic produced can take a lot of space. To avoid
// cloging the user output we only want to print that diagnostic
// once.
db . help_once ( format! ( " expected names are: ` {possibilities} ` " ) ) ;
2022-03-03 15:56:19 +01:00
}
2023-11-22 16:50:24 +01:00
let inst = if let Some ( ( value , _value_span ) ) = value {
let pre = if is_from_cargo { " \\ " } else { " " } ;
format! ( " cfg( {name} , values( {pre} \" {value} {pre} \" )) " )
} else {
format! ( " cfg( {name} ) " )
} ;
if is_from_cargo {
if ! is_feature_cfg {
db . help ( format! ( " consider using a Cargo feature instead or adding `println!( \" cargo:rustc-check-cfg= {inst} \" );` to the top of a `build.rs` " ) ) ;
}
db . note ( " see <https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#check-cfg> for more information about checking conditional configuration " ) ;
} else {
db . help ( format! ( " to expect this configuration use `--check-cfg= {inst} ` " ) ) ;
db . note ( " see <https://doc.rust-lang.org/nightly/unstable-book/compiler-flags/check-cfg.html> for more information about checking conditional configuration " ) ;
}
2022-03-03 15:56:19 +01:00
} ,
2023-04-30 19:09:15 +02:00
BuiltinLintDiagnostics ::UnexpectedCfgValue ( ( name , name_span ) , value ) = > {
let Some ( ExpectedValues ::Some ( values ) ) = & sess . parse_sess . check_config . expecteds . get ( & name ) else {
2022-03-03 15:56:19 +01:00
bug! ( " it shouldn't be possible to have a diagnostic on a value whose name is not in values " ) ;
2022-02-20 00:48:10 +01:00
} ;
2023-04-30 14:43:59 +02:00
let mut have_none_possibility = false ;
let possibilities : Vec < Symbol > = values . iter ( )
. inspect ( | a | have_none_possibility | = a . is_none ( ) )
. copied ( )
2023-04-30 19:09:15 +02:00
. flatten ( )
2023-04-30 14:43:59 +02:00
. collect ( ) ;
2023-11-22 16:50:24 +01:00
let is_from_cargo = std ::env ::var_os ( " CARGO " ) . is_some ( ) ;
2022-02-20 00:48:10 +01:00
// Show the full list if all possible values for a given name, but don't do it
// for names as the possibilities could be very long
2022-03-03 15:56:19 +01:00
if ! possibilities . is_empty ( ) {
{
2022-02-20 01:26:52 +01:00
let mut possibilities = possibilities . iter ( ) . map ( Symbol ::as_str ) . collect ::< Vec < _ > > ( ) ;
possibilities . sort ( ) ;
2022-02-20 00:48:10 +01:00
2023-04-30 15:52:44 +02:00
let possibilities = possibilities . join ( " `, ` " ) ;
let none = if have_none_possibility { " (none), " } else { " " } ;
db . note ( format! ( " expected values for ` {name} ` are: {none} ` {possibilities} ` " ) ) ;
2022-02-20 01:26:52 +01:00
}
2022-02-20 00:48:10 +01:00
2023-04-30 19:09:15 +02:00
if let Some ( ( value , value_span ) ) = value {
// Suggest the most probable if we found one
if let Some ( best_match ) = find_best_match_for_name ( & possibilities , value , None ) {
db . span_suggestion ( value_span , " there is a expected value with a similar name " , format! ( " \" {best_match} \" " ) , Applicability ::MaybeIncorrect ) ;
}
2023-11-22 16:50:24 +01:00
} else if name = = sym ::feature & & is_from_cargo {
db . help ( format! ( " consider defining ` {name} ` as feature in `Cargo.toml` " ) ) ;
2023-04-30 19:09:15 +02:00
} else if let & [ first_possibility ] = & possibilities [ .. ] {
db . span_suggestion ( name_span . shrink_to_hi ( ) , " specify a config value " , format! ( " = \" {first_possibility} \" " ) , Applicability ::MaybeIncorrect ) ;
2022-03-03 15:56:19 +01:00
}
2023-04-30 15:52:44 +02:00
} else if have_none_possibility {
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
db . note ( format! ( " no expected value for ` {name} ` " ) ) ;
2023-04-30 19:09:15 +02:00
if let Some ( ( _value , value_span ) ) = value {
db . span_suggestion ( name_span . shrink_to_hi ( ) . to ( value_span ) , " remove the value " , " " , Applicability ::MaybeIncorrect ) ;
}
2022-02-20 00:48:10 +01:00
}
2023-11-22 16:50:24 +01:00
let inst = if let Some ( ( value , _value_span ) ) = value {
let pre = if is_from_cargo { " \\ " } else { " " } ;
format! ( " cfg( {name} , values( {pre} \" {value} {pre} \" )) " )
} else {
format! ( " cfg( {name} ) " )
} ;
if is_from_cargo {
if name = = sym ::feature {
if let Some ( ( value , _value_span ) ) = value {
db . help ( format! ( " consider adding ` {value} ` as a feature in `Cargo.toml` " ) ) ;
}
} else {
db . help ( format! ( " consider using a Cargo feature instead or adding `println!( \" cargo:rustc-check-cfg= {inst} \" );` to the top of a `build.rs` " ) ) ;
}
db . note ( " see <https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#check-cfg> for more information about checking conditional configuration " ) ;
} else {
db . help ( format! ( " to expect this configuration use `--check-cfg= {inst} ` " ) ) ;
db . note ( " see <https://doc.rust-lang.org/nightly/unstable-book/compiler-flags/check-cfg.html> for more information about checking conditional configuration " ) ;
}
2022-02-20 00:48:10 +01:00
} ,
2022-02-07 01:23:37 -05:00
BuiltinLintDiagnostics ::DeprecatedWhereclauseLocation ( new_span , suggestion ) = > {
2022-02-14 13:00:10 -05:00
db . multipart_suggestion (
" move it to the end of the type declaration " ,
vec! [ ( db . span . primary_span ( ) . unwrap ( ) , " " . to_string ( ) ) , ( new_span , suggestion ) ] ,
2022-02-07 01:23:37 -05:00
Applicability ::MachineApplicable ,
) ;
2022-02-14 13:00:10 -05:00
db . note (
" see issue #89122 <https://github.com/rust-lang/rust/issues/89122> for more information " ,
) ;
2022-02-07 01:23:37 -05:00
} ,
2022-05-10 21:15:30 +02:00
BuiltinLintDiagnostics ::SingleUseLifetime {
param_span ,
use_span : Some ( ( use_span , elide ) ) ,
deletion_span ,
} = > {
debug! ( ? param_span , ? use_span , ? deletion_span ) ;
db . span_label ( param_span , " this lifetime... " ) ;
db . span_label ( use_span , " ...is used only here " ) ;
2023-01-16 21:06:34 +09:00
if let Some ( deletion_span ) = deletion_span {
let msg = " elide the single-use lifetime " ;
let ( use_span , replace_lt ) = if elide {
let use_span = sess . source_map ( ) . span_extend_while (
use_span ,
char ::is_whitespace ,
) . unwrap_or ( use_span ) ;
( use_span , String ::new ( ) )
} else {
( use_span , " '_ " . to_owned ( ) )
} ;
debug! ( ? deletion_span , ? use_span ) ;
2023-02-13 17:20:38 +00:00
// issue 107998 for the case such as a wrong function pointer type
// `deletion_span` is empty and there is no need to report lifetime uses here
let suggestions = if deletion_span . is_empty ( ) {
vec! [ ( use_span , replace_lt ) ]
} else {
vec! [ ( deletion_span , String ::new ( ) ) , ( use_span , replace_lt ) ]
} ;
2023-01-16 21:06:34 +09:00
db . multipart_suggestion (
msg ,
2023-02-13 17:20:38 +00:00
suggestions ,
2023-01-16 21:06:34 +09:00
Applicability ::MachineApplicable ,
) ;
}
2022-05-10 21:15:30 +02:00
} ,
BuiltinLintDiagnostics ::SingleUseLifetime {
param_span : _ ,
use_span : None ,
deletion_span ,
} = > {
debug! ( ? deletion_span ) ;
2023-01-16 21:06:34 +09:00
if let Some ( deletion_span ) = deletion_span {
db . span_suggestion (
deletion_span ,
" elide the unused lifetime " ,
" " ,
Applicability ::MachineApplicable ,
) ;
}
2022-05-10 21:15:30 +02:00
} ,
2022-07-29 22:52:46 -06:00
BuiltinLintDiagnostics ::NamedArgumentUsedPositionally { position_sp_to_replace , position_sp_for_msg , named_arg_sp , named_arg_name , is_formatting_arg } = > {
db . span_label ( named_arg_sp , " this named argument is referred to by position in formatting string " ) ;
if let Some ( positional_arg_for_msg ) = position_sp_for_msg {
2023-07-25 23:17:39 +02:00
let msg = format! ( " this formatting argument uses named argument ` {named_arg_name} ` by position " ) ;
2022-07-29 22:52:46 -06:00
db . span_label ( positional_arg_for_msg , msg ) ;
}
if let Some ( positional_arg_to_replace ) = position_sp_to_replace {
let name = if is_formatting_arg { named_arg_name + " $ " } else { named_arg_name } ;
2022-08-20 23:29:38 +00:00
let span_to_replace = if let Ok ( positional_arg_content ) =
2022-09-03 22:57:22 +02:00
self . sess ( ) . source_map ( ) . span_to_snippet ( positional_arg_to_replace ) & & positional_arg_content . starts_with ( ':' ) {
2022-08-20 23:29:38 +00:00
positional_arg_to_replace . shrink_to_lo ( )
} else {
positional_arg_to_replace
} ;
2022-07-16 15:13:14 -06:00
db . span_suggestion_verbose (
2022-08-20 23:29:38 +00:00
span_to_replace ,
2022-07-15 17:32:15 +00:00
" use the named argument by name to avoid ambiguity " ,
2022-07-16 15:13:14 -06:00
name ,
2022-07-15 17:32:15 +00:00
Applicability ::MaybeIncorrect ,
) ;
}
2022-06-24 23:52:13 -06:00
}
Allow more deriving on packed structs.
Currently, deriving on packed structs has some non-trivial limitations,
related to the fact that taking references on unaligned fields is UB.
The current approach to field accesses in derived code:
- Normal case: `&self.0`
- In a packed struct that derives `Copy`: `&{self.0}`
- In a packed struct that doesn't derive `Copy`: `&self.0`
Plus, we disallow deriving any builtin traits other than `Default` for any
packed generic type, because it's possible that there might be
misaligned fields. This is a fairly broad restriction.
Plus, we disallow deriving any builtin traits other than `Default` for most
packed types that don't derive `Copy`. (The exceptions are those where the
alignments inherently satisfy the packing, e.g. in a type with
`repr(packed(N))` where all the fields have alignments of `N` or less
anyway. Such types are pretty strange, because the `packed` attribute is
not having any effect.)
This commit introduces a new, simpler approach to field accesses:
- Normal case: `&self.0`
- In a packed struct: `&{self.0}`
In the latter case, this requires that all fields impl `Copy`, which is
a new restriction. This means that the following example compiles under
the old approach and doesn't compile under the new approach.
```
#[derive(Debug)]
struct NonCopy(u8);
#[derive(Debug)
#[repr(packed)]
struct MyType(NonCopy);
```
(Note that the old approach's support for cases like this was brittle.
Changing the `u8` to a `u16` would be enough to stop it working. So not
much capability is lost here.)
However, the other constraints from the old rules are removed. We can now
derive builtin traits for packed generic structs like this:
```
trait Trait { type A; }
#[derive(Hash)]
#[repr(packed)]
pub struct Foo<T: Trait>(T, T::A);
```
To allow this, we add a `T: Copy` bound in the derived impl and a `T::A:
Copy` bound in where clauses. So `T` and `T::A` must impl `Copy`.
We can now also derive builtin traits for packed structs that don't derive
`Copy`, so long as the fields impl `Copy`:
```
#[derive(Hash)]
#[repr(packed)]
pub struct Foo(u32);
```
This includes types that hand-impl `Copy` rather than deriving it, such as the
following, that show up in winapi-0.2:
```
#[derive(Clone)]
#[repr(packed)]
struct MyType(i32);
impl Copy for MyType {}
```
The new approach is simpler to understand and implement, and it avoids
the need for the `unsafe_derive_on_repr_packed` check.
One exception is required for backwards-compatibility: we allow `[u8]`
fields for now. There is a new lint for this,
`byte_slice_in_packed_struct_with_derive`.
2022-11-21 14:40:32 +11:00
BuiltinLintDiagnostics ::ByteSliceInPackedStructWithDerive = > {
db . help ( " consider implementing the trait by hand, or remove the `packed` attribute " ) ;
}
2023-02-22 20:25:10 +00:00
BuiltinLintDiagnostics ::UnusedExternCrate { removal_span } = > {
db . span_suggestion (
removal_span ,
" remove it " ,
" " ,
Applicability ::MachineApplicable ,
) ;
}
BuiltinLintDiagnostics ::ExternCrateNotIdiomatic { vis_span , ident_span } = > {
let suggestion_span = vis_span . between ( ident_span ) ;
db . span_suggestion_verbose (
suggestion_span ,
" convert it to a `use` " ,
if vis_span . is_empty ( ) { " use " } else { " use " } ,
Applicability ::MachineApplicable ,
) ;
}
2023-07-26 22:46:49 +08:00
BuiltinLintDiagnostics ::AmbiguousGlobImports { diag } = > {
rustc_errors ::report_ambiguity_error ( db , diag ) ;
}
2023-03-20 03:11:28 +08:00
BuiltinLintDiagnostics ::AmbiguousGlobReexports { name , namespace , first_reexport_span , duplicate_reexport_span } = > {
2023-07-25 23:17:39 +02:00
db . span_label ( first_reexport_span , format! ( " the name ` {name} ` in the {namespace} namespace is first re-exported here " ) ) ;
db . span_label ( duplicate_reexport_span , format! ( " but the name ` {name} ` in the {namespace} namespace is also re-exported here " ) ) ;
2023-03-20 03:11:28 +08:00
}
2023-05-09 07:15:46 +08:00
BuiltinLintDiagnostics ::HiddenGlobReexports { name , namespace , glob_reexport_span , private_item_span } = > {
2023-07-25 23:17:39 +02:00
db . span_note ( glob_reexport_span , format! ( " the name ` {name} ` in the {namespace} namespace is supposed to be publicly re-exported here " ) ) ;
2023-06-08 15:03:21 +08:00
db . span_note ( private_item_span , " but the private item here shadows it " . to_owned ( ) ) ;
2023-05-09 07:15:46 +08:00
}
2023-07-18 09:10:45 +08:00
BuiltinLintDiagnostics ::UnusedQualifications { removal_span } = > {
2023-06-17 15:06:48 +08:00
db . span_suggestion_verbose (
2023-07-18 09:10:45 +08:00
removal_span ,
" remove the unnecessary path segments " ,
" " ,
2023-06-17 15:06:48 +08:00
Applicability ::MachineApplicable
) ;
}
2023-08-19 23:27:50 +00:00
BuiltinLintDiagnostics ::AssociatedConstElidedLifetime { elided , span } = > {
db . span_suggestion_verbose (
if elided { span . shrink_to_hi ( ) } else { span } ,
" use the `'static` lifetime " ,
if elided { " 'static " } else { " 'static " } ,
Applicability ::MachineApplicable
) ;
2023-12-01 10:25:40 +08:00
} ,
BuiltinLintDiagnostics ::RedundantImportVisibility { max_vis , span } = > {
db . span_note ( span , format! ( " the most public imported item is ` {max_vis} ` " ) ) ;
db . help ( " reduce the glob import's visibility or increase visibility of imported items " ) ;
2023-08-19 23:27:50 +00:00
}
2020-01-05 10:07:26 +01:00
}
2020-02-02 19:41:14 +10:00
// Rewrap `db`, and pass control to the user.
2022-09-16 11:01:02 +04:00
decorate ( db )
2020-01-31 22:24:57 +10:00
} ) ;
2018-02-22 22:34:06 -08:00
}
2020-02-06 03:18:40 +10:00
// FIXME: These methods should not take an Into<MultiSpan> -- instead, callers should need to
// set the span in their `decorate` function (preferably using set_span).
2022-10-12 14:16:24 +00:00
/// Emit a lint at the appropriate level, with an optional associated span.
///
/// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
2022-11-07 19:23:29 -05:00
#[ rustc_lint_diagnostics ]
2016-10-12 17:00:30 -04:00
fn lookup < S : Into < MultiSpan > > (
& self ,
lint : & 'static Lint ,
span : Option < S > ,
2022-09-16 11:01:02 +04:00
msg : impl Into < DiagnosticMessage > ,
2023-12-08 01:52:56 +00:00
decorate : impl for < ' a , ' b > FnOnce ( & ' b mut DiagnosticBuilder < ' a , ( ) > ) ,
2020-01-31 22:24:57 +10:00
) ;
2015-12-21 10:00:43 +13:00
2022-06-29 16:07:46 +01:00
/// Emit a lint at `span` from a lint struct (some type that implements `DecorateLint`,
/// typically generated by `#[derive(LintDiagnostic)]`).
fn emit_spanned_lint < S : Into < MultiSpan > > (
& self ,
lint : & 'static Lint ,
span : S ,
decorator : impl for < ' a > DecorateLint < ' a , ( ) > ,
) {
2023-12-08 01:52:56 +00:00
self . lookup ( lint , Some ( span ) , decorator . msg ( ) , | diag | {
decorator . decorate_lint ( diag ) ;
} ) ;
2022-06-29 16:07:46 +01:00
}
2022-10-12 14:16:24 +00:00
/// Emit a lint at the appropriate level, with an associated span.
///
/// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
2022-11-07 19:23:29 -05:00
#[ rustc_lint_diagnostics ]
2016-10-12 17:00:30 -04:00
fn struct_span_lint < S : Into < MultiSpan > > (
& self ,
lint : & 'static Lint ,
span : S ,
2022-09-16 11:01:02 +04:00
msg : impl Into < DiagnosticMessage > ,
2023-12-08 01:52:56 +00:00
decorate : impl for < ' a , ' b > FnOnce ( & ' b mut DiagnosticBuilder < ' a , ( ) > ) ,
2020-01-31 22:24:57 +10:00
) {
2022-09-16 11:01:02 +04:00
self . lookup ( lint , Some ( span ) , msg , decorate ) ;
2015-12-21 10:00:43 +13:00
}
2022-06-29 16:07:46 +01:00
/// Emit a lint from a lint struct (some type that implements `DecorateLint`, typically
/// generated by `#[derive(LintDiagnostic)]`).
fn emit_lint ( & self , lint : & 'static Lint , decorator : impl for < ' a > DecorateLint < ' a , ( ) > ) {
2022-09-16 11:01:02 +04:00
self . lookup ( lint , None as Option < Span > , decorator . msg ( ) , | diag | {
2023-12-08 01:52:56 +00:00
decorator . decorate_lint ( diag ) ;
2022-09-16 11:01:02 +04:00
} ) ;
2022-06-29 16:07:46 +01:00
}
2015-09-10 16:40:59 +12:00
/// Emit a lint at the appropriate level, with no associated span.
2022-10-12 14:16:24 +00:00
///
/// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
2022-11-07 19:23:29 -05:00
#[ rustc_lint_diagnostics ]
2022-01-22 18:49:12 -06:00
fn lint (
& self ,
lint : & 'static Lint ,
2022-09-22 18:25:05 +04:00
msg : impl Into < DiagnosticMessage > ,
2023-12-08 01:52:56 +00:00
decorate : impl for < ' a , ' b > FnOnce ( & ' b mut DiagnosticBuilder < ' a , ( ) > ) ,
2022-01-22 18:49:12 -06:00
) {
2022-09-16 11:01:02 +04:00
self . lookup ( lint , None as Option < Span > , msg , decorate ) ;
2015-09-10 16:40:59 +12:00
}
2022-06-16 13:20:57 +02:00
/// This returns the lint level for the given lint at the current location.
fn get_lint_level ( & self , lint : & 'static Lint ) -> Level ;
/// This function can be used to manually fulfill an expectation. This can
/// be used for lints which contain several spans, and should be suppressed,
/// if either location was marked with an expectation.
///
/// Note that this function should only be called for [`LintExpectationId`]s
/// retrieved from the current lint pass. Buffered or manually created ids can
/// cause ICEs.
2022-11-10 21:01:45 -05:00
#[ rustc_lint_diagnostics ]
2022-06-16 13:20:57 +02:00
fn fulfill_expectation ( & self , expectation : LintExpectationId ) {
// We need to make sure that submitted expectation ids are correctly fulfilled suppressed
// and stored between compilation sessions. To not manually do these steps, we simply create
// a dummy diagnostic and emit is as usual, which will be suppressed and stored like a normal
// expected lint diagnostic.
self . sess ( )
2023-12-18 22:21:37 +11:00
. dcx ( )
2022-06-16 13:20:57 +02:00
. struct_expect (
" this is a dummy diagnostic, to submit and store an expectation " ,
expectation ,
)
. emit ( ) ;
}
2015-09-10 16:40:59 +12:00
}
impl < ' a > EarlyContext < ' a > {
2021-09-28 00:28:49 +03:00
pub ( crate ) fn new (
2018-07-14 16:40:17 +02:00
sess : & ' a Session ,
2023-08-09 20:28:00 +08:00
features : & ' a Features ,
2021-09-28 00:28:49 +03:00
warn_about_weird_lints : bool ,
2019-10-09 08:46:11 -04:00
lint_store : & ' a LintStore ,
2021-09-29 01:17:54 +03:00
registered_tools : & ' a RegisteredTools ,
2018-07-14 16:40:17 +02:00
buffered : LintBuffer ,
) -> EarlyContext < ' a > {
2015-09-10 16:40:59 +12:00
EarlyContext {
2021-09-29 01:17:54 +03:00
builder : LintLevelsBuilder ::new (
sess ,
2023-08-09 20:28:00 +08:00
features ,
2021-09-29 01:17:54 +03:00
warn_about_weird_lints ,
lint_store ,
registered_tools ,
) ,
2018-07-14 16:40:17 +02:00
buffered ,
2017-07-26 21:51:09 -07:00
}
}
2019-01-18 07:40:55 +01:00
}
2017-07-26 21:51:09 -07:00
2022-09-06 14:23:03 -04:00
impl < ' tcx > LintContext for LateContext < ' tcx > {
2019-02-08 14:53:55 +01:00
/// Gets the overall compiler `Session` object.
2015-09-10 16:40:59 +12:00
fn sess ( & self ) -> & Session {
2023-11-21 20:07:32 +01:00
self . tcx . sess
2015-09-10 16:40:59 +12:00
}
2022-11-10 21:01:45 -05:00
#[ rustc_lint_diagnostics ]
2017-07-26 21:51:09 -07:00
fn lookup < S : Into < MultiSpan > > (
& self ,
lint : & 'static Lint ,
span : Option < S > ,
2022-09-16 11:01:02 +04:00
msg : impl Into < DiagnosticMessage > ,
2023-12-08 01:52:56 +00:00
decorate : impl for < ' a , ' b > FnOnce ( & ' b mut DiagnosticBuilder < ' a , ( ) > ) ,
2020-01-31 22:24:57 +10:00
) {
2019-02-06 14:16:11 +01:00
let hir_id = self . last_node_with_lint_attrs ;
2017-07-26 21:51:09 -07:00
match span {
2022-09-16 11:01:02 +04:00
Some ( s ) = > self . tcx . struct_span_lint_hir ( lint , hir_id , s , msg , decorate ) ,
None = > self . tcx . struct_lint_node ( lint , hir_id , msg , decorate ) ,
2017-07-26 21:51:09 -07:00
}
}
2022-06-16 13:20:57 +02:00
fn get_lint_level ( & self , lint : & 'static Lint ) -> Level {
self . tcx . lint_level_at_node ( lint , self . last_node_with_lint_attrs ) . 0
}
2015-09-10 16:40:59 +12:00
}
2019-06-11 12:21:38 +03:00
impl LintContext for EarlyContext < '_ > {
2019-02-08 14:53:55 +01:00
/// Gets the overall compiler `Session` object.
2015-09-10 16:40:59 +12:00
fn sess ( & self ) -> & Session {
2023-11-21 20:07:32 +01:00
self . builder . sess ( )
2015-09-10 16:40:59 +12:00
}
2022-11-10 21:01:45 -05:00
#[ rustc_lint_diagnostics ]
2017-07-26 21:51:09 -07:00
fn lookup < S : Into < MultiSpan > > (
& self ,
lint : & 'static Lint ,
span : Option < S > ,
2022-09-16 11:01:02 +04:00
msg : impl Into < DiagnosticMessage > ,
2023-12-08 01:52:56 +00:00
decorate : impl for < ' a , ' b > FnOnce ( & ' b mut DiagnosticBuilder < ' a , ( ) > ) ,
2020-01-31 22:24:57 +10:00
) {
2022-09-16 11:01:02 +04:00
self . builder . struct_lint ( lint , span . map ( | s | s . into ( ) ) , msg , decorate )
2017-07-26 21:51:09 -07:00
}
2022-06-16 13:20:57 +02:00
fn get_lint_level ( & self , lint : & 'static Lint ) -> Level {
self . builder . lint_level ( lint ) . 0
}
2019-01-18 07:40:55 +01:00
}
2017-07-26 21:51:09 -07:00
2020-06-25 23:41:36 +03:00
impl < ' tcx > LateContext < ' tcx > {
2020-07-17 08:47:04 +00:00
/// Gets the type-checking results for the current body,
2020-06-26 05:55:23 +03:00
/// or `None` if outside a body.
2020-07-17 08:47:04 +00:00
pub fn maybe_typeck_results ( & self ) -> Option < & ' tcx ty ::TypeckResults < ' tcx > > {
self . cached_typeck_results . get ( ) . or_else ( | | {
2020-06-26 05:55:23 +03:00
self . enclosing_body . map ( | body | {
2020-07-17 08:47:04 +00:00
let typeck_results = self . tcx . typeck_body ( body ) ;
self . cached_typeck_results . set ( Some ( typeck_results ) ) ;
typeck_results
2020-06-26 02:56:23 +03:00
} )
2020-06-26 05:55:23 +03:00
} )
}
2020-07-17 08:47:04 +00:00
/// Gets the type-checking results for the current body.
2020-06-26 05:55:23 +03:00
/// As this will ICE if called outside bodies, only call when working with
/// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
#[ track_caller ]
2020-07-17 08:47:04 +00:00
pub fn typeck_results ( & self ) -> & ' tcx ty ::TypeckResults < ' tcx > {
self . maybe_typeck_results ( ) . expect ( " `LateContext::typeck_results` called outside of body " )
2020-06-26 05:55:23 +03:00
}
/// Returns the final resolution of a `QPath`, or `Res::Err` if unavailable.
2020-07-17 08:47:04 +00:00
/// Unlike `.typeck_results().qpath_res(qpath, id)`, this can be used even outside
2020-06-26 05:55:23 +03:00
/// bodies (e.g. for paths in `hir::Ty`), without any risk of ICE-ing.
pub fn qpath_res ( & self , qpath : & hir ::QPath < '_ > , id : hir ::HirId ) -> Res {
match * qpath {
2023-11-21 20:07:32 +01:00
hir ::QPath ::Resolved ( _ , path ) = > path . res ,
2020-08-04 14:34:24 +01:00
hir ::QPath ::TypeRelative ( .. ) | hir ::QPath ::LangItem ( .. ) = > self
2020-07-17 08:47:04 +00:00
. maybe_typeck_results ( )
2021-01-18 13:29:37 -06:00
. filter ( | typeck_results | typeck_results . hir_owner = = id . owner )
. or_else ( | | {
2023-02-15 11:43:41 +00:00
self . tcx
. has_typeck_results ( id . owner . to_def_id ( ) )
. then ( | | self . tcx . typeck ( id . owner . def_id ) )
2021-01-18 13:29:37 -06:00
} )
2020-07-17 08:47:04 +00:00
. and_then ( | typeck_results | typeck_results . type_dependent_def ( id ) )
2020-06-26 05:55:23 +03:00
. map_or ( Res ::Err , | ( kind , def_id ) | Res ::Def ( kind , def_id ) ) ,
2020-06-26 02:56:23 +03:00
}
}
2019-04-05 23:04:56 +02:00
/// Check if a `DefId`'s path matches the given absolute type path usage.
2019-04-07 19:47:54 +02:00
///
2020-12-29 20:28:08 -05:00
/// Anonymous scopes such as `extern` imports are matched with `kw::Empty`;
2019-11-02 16:12:33 +01:00
/// inherent `impl` blocks are matched with the name of the type.
///
2020-09-19 11:32:55 +02:00
/// Instead of using this method, it is often preferable to instead use
2020-09-19 15:36:53 +02:00
/// `rustc_diagnostic_item` or a `lang_item`. This is less prone to errors
/// as paths get invalidated if the target definition moves.
2020-09-19 10:57:13 +02:00
///
2019-04-07 19:47:54 +02:00
/// # Examples
2019-05-02 12:33:59 -04:00
///
/// ```rust,ignore (no context or def id available)
2019-05-14 15:58:22 +02:00
/// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
2019-04-07 19:47:54 +02:00
/// // The given `def_id` is that of an `Option` type
/// }
/// ```
2021-03-16 01:50:34 -04:00
///
/// Used by clippy, but should be replaced by diagnostic items eventually.
2019-05-14 15:58:22 +02:00
pub fn match_def_path ( & self , def_id : DefId , path : & [ Symbol ] ) -> bool {
2019-04-07 19:47:54 +02:00
let names = self . get_def_path ( def_id ) ;
2021-03-08 15:32:41 -08:00
names . len ( ) = = path . len ( ) & & iter ::zip ( names , path ) . all ( | ( a , & b ) | a = = b )
2019-04-07 19:47:54 +02:00
}
2019-05-14 15:58:22 +02:00
/// Gets the absolute path of `def_id` as a vector of `Symbol`.
2019-04-07 19:47:54 +02:00
///
/// # Examples
2019-05-02 12:33:59 -04:00
///
/// ```rust,ignore (no context or def id available)
2019-04-07 19:47:54 +02:00
/// let def_path = cx.get_def_path(def_id);
2019-05-14 15:58:22 +02:00
/// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
2019-04-07 19:47:54 +02:00
/// // The given `def_id` is that of an `Option` type
/// }
/// ```
2019-05-14 15:58:22 +02:00
pub fn get_def_path ( & self , def_id : DefId ) -> Vec < Symbol > {
2023-10-16 20:26:12 +02:00
struct AbsolutePathPrinter < ' tcx > {
tcx : TyCtxt < ' tcx > ,
path : Vec < Symbol > ,
2019-04-05 23:04:56 +02:00
}
2019-06-14 00:48:52 +03:00
impl < ' tcx > Printer < ' tcx > for AbsolutePathPrinter < ' tcx > {
fn tcx ( & self ) -> TyCtxt < ' tcx > {
2019-04-05 23:04:56 +02:00
self . tcx
}
2023-10-17 19:46:14 +02:00
fn print_region ( & mut self , _region : ty ::Region < '_ > ) -> Result < ( ) , PrintError > {
Ok ( ( ) )
2019-04-05 23:04:56 +02:00
}
2023-10-17 19:46:14 +02:00
fn print_type ( & mut self , _ty : Ty < ' tcx > ) -> Result < ( ) , PrintError > {
Ok ( ( ) )
2019-04-05 23:04:56 +02:00
}
fn print_dyn_existential (
2023-10-17 19:46:14 +02:00
& mut self ,
2022-11-19 03:28:56 +00:00
_predicates : & ' tcx ty ::List < ty ::PolyExistentialPredicate < ' tcx > > ,
2023-10-17 19:46:14 +02:00
) -> Result < ( ) , PrintError > {
Ok ( ( ) )
2019-03-18 12:50:57 +02:00
}
2023-10-17 19:46:14 +02:00
fn print_const ( & mut self , _ct : ty ::Const < ' tcx > ) -> Result < ( ) , PrintError > {
Ok ( ( ) )
2019-04-05 23:04:56 +02:00
}
2023-10-17 19:46:14 +02:00
fn path_crate ( & mut self , cnum : CrateNum ) -> Result < ( ) , PrintError > {
2023-10-16 20:26:12 +02:00
self . path = vec! [ self . tcx . crate_name ( cnum ) ] ;
2023-10-17 19:46:14 +02:00
Ok ( ( ) )
2019-04-05 23:04:56 +02:00
}
fn path_qualified (
2023-10-17 19:46:14 +02:00
& mut self ,
2019-04-05 23:04:56 +02:00
self_ty : Ty < ' tcx > ,
trait_ref : Option < ty ::TraitRef < ' tcx > > ,
2023-10-17 19:46:14 +02:00
) -> Result < ( ) , PrintError > {
2019-04-05 23:04:56 +02:00
if trait_ref . is_none ( ) {
2023-07-11 22:35:29 +01:00
if let ty ::Adt ( def , args ) = self_ty . kind ( ) {
return self . print_def_path ( def . did ( ) , args ) ;
2019-04-05 23:04:56 +02:00
}
}
// This shouldn't ever be needed, but just in case:
2022-02-16 13:04:48 -05:00
with_no_trimmed_paths! ( {
2023-10-16 20:26:12 +02:00
self . path = vec! [ match trait_ref {
2023-07-25 23:17:39 +02:00
Some ( trait_ref ) = > Symbol ::intern ( & format! ( " {trait_ref:?} " ) ) ,
None = > Symbol ::intern ( & format! ( " < {self_ty} > " ) ) ,
2023-10-16 20:26:12 +02:00
} ] ;
2023-10-17 19:46:14 +02:00
Ok ( ( ) )
2020-09-02 10:40:56 +03:00
} )
2019-04-05 23:04:56 +02:00
}
fn path_append_impl (
2023-10-17 19:46:14 +02:00
& mut self ,
print_prefix : impl FnOnce ( & mut Self ) -> Result < ( ) , PrintError > ,
2019-04-05 23:04:56 +02:00
_disambiguated_data : & DisambiguatedDefPathData ,
self_ty : Ty < ' tcx > ,
trait_ref : Option < ty ::TraitRef < ' tcx > > ,
2023-10-17 19:46:14 +02:00
) -> Result < ( ) , PrintError > {
print_prefix ( self ) ? ;
2019-04-05 23:04:56 +02:00
// This shouldn't ever be needed, but just in case:
2023-10-17 19:46:14 +02:00
self . path . push ( match trait_ref {
2022-02-16 13:04:48 -05:00
Some ( trait_ref ) = > {
with_no_trimmed_paths! ( Symbol ::intern ( & format! (
2020-09-02 10:40:56 +03:00
" <impl {} for {}> " ,
trait_ref . print_only_trait_path ( ) ,
self_ty
2022-02-16 13:04:48 -05:00
) ) )
}
2020-09-02 10:40:56 +03:00
None = > {
2023-07-25 23:17:39 +02:00
with_no_trimmed_paths! ( Symbol ::intern ( & format! ( " <impl {self_ty} > " ) ) )
2020-09-02 10:40:56 +03:00
}
2019-04-05 23:04:56 +02:00
} ) ;
2023-10-17 19:46:14 +02:00
Ok ( ( ) )
2019-04-05 23:04:56 +02:00
}
fn path_append (
2023-10-17 19:46:14 +02:00
& mut self ,
print_prefix : impl FnOnce ( & mut Self ) -> Result < ( ) , PrintError > ,
2019-04-05 23:04:56 +02:00
disambiguated_data : & DisambiguatedDefPathData ,
2023-10-17 19:46:14 +02:00
) -> Result < ( ) , PrintError > {
print_prefix ( self ) ? ;
2019-04-05 23:04:56 +02:00
2021-12-17 16:45:15 +08:00
// Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
if let DefPathData ::ForeignMod | DefPathData ::Ctor = disambiguated_data . data {
2023-10-17 19:46:14 +02:00
return Ok ( ( ) ) ;
2019-04-05 23:04:56 +02:00
}
2023-10-17 19:46:14 +02:00
self . path . push ( Symbol ::intern ( & disambiguated_data . data . to_string ( ) ) ) ;
Ok ( ( ) )
2019-04-05 23:04:56 +02:00
}
fn path_generic_args (
2023-10-17 19:46:14 +02:00
& mut self ,
print_prefix : impl FnOnce ( & mut Self ) -> Result < ( ) , PrintError > ,
2019-09-25 16:39:44 +01:00
_args : & [ GenericArg < ' tcx > ] ,
2023-10-17 19:46:14 +02:00
) -> Result < ( ) , PrintError > {
2019-04-05 23:04:56 +02:00
print_prefix ( self )
}
}
2023-10-17 19:46:14 +02:00
let mut printer = AbsolutePathPrinter { tcx : self . tcx , path : vec ! [ ] } ;
printer . print_def_path ( def_id , & [ ] ) . unwrap ( ) ;
printer . path
2019-04-05 23:04:56 +02:00
}
2022-11-22 19:52:46 +00:00
/// Returns the associated type `name` for `self_ty` as an implementation of `trait_id`.
/// Do not invoke without first verifying that the type implements the trait.
pub fn get_associated_type (
& self ,
self_ty : Ty < ' tcx > ,
trait_id : DefId ,
name : & str ,
) -> Option < Ty < ' tcx > > {
let tcx = self . tcx ;
tcx . associated_items ( trait_id )
. find_by_name_and_kind ( tcx , Ident ::from_str ( name ) , ty ::AssocKind ::Type , trait_id )
. and_then ( | assoc | {
2023-07-05 20:13:26 +01:00
let proj = Ty ::new_projection ( tcx , assoc . def_id , [ self_ty ] ) ;
2022-11-22 19:52:46 +00:00
tcx . try_normalize_erasing_regions ( self . param_env , proj ) . ok ( )
} )
}
2023-09-05 15:14:53 +02:00
2023-09-27 17:14:01 +02:00
/// If the given expression is a local binding, find the initializer expression.
/// If that initializer expression is another local binding, find its initializer again.
///
/// This process repeats as long as possible (but usually no more than once).
/// Type-check adjustments are not taken in account in this function.
///
/// Examples:
/// ```
/// let abc = 1;
/// let def = abc + 2;
/// // ^^^^^^^ output
/// let def = def;
/// dbg!(def);
/// // ^^^ input
/// ```
pub fn expr_or_init < ' a > ( & self , mut expr : & ' a hir ::Expr < ' tcx > ) -> & ' a hir ::Expr < ' tcx > {
expr = expr . peel_blocks ( ) ;
while let hir ::ExprKind ::Path ( ref qpath ) = expr . kind
& & let Some ( parent_node ) = match self . qpath_res ( qpath , expr . hir_id ) {
Res ::Local ( hir_id ) = > self . tcx . hir ( ) . find_parent ( hir_id ) ,
_ = > None ,
}
& & let Some ( init ) = match parent_node {
hir ::Node ::Expr ( expr ) = > Some ( expr ) ,
hir ::Node ::Local ( hir ::Local { init , .. } ) = > * init ,
_ = > None ,
}
{
expr = init . peel_blocks ( ) ;
}
expr
}
2023-09-05 15:14:53 +02:00
/// If the given expression is a local binding, find the initializer expression.
/// If that initializer expression is another local or **outside** (`const`/`static`)
/// binding, find its initializer again.
///
/// This process repeats as long as possible (but usually no more than once).
/// Type-check adjustments are not taken in account in this function.
///
/// Examples:
/// ```
/// const ABC: i32 = 1;
/// // ^ output
/// let def = ABC;
/// dbg!(def);
/// // ^^^ input
///
/// // or...
/// let abc = 1;
/// let def = abc + 2;
/// // ^^^^^^^ output
/// dbg!(def);
/// // ^^^ input
/// ```
2023-09-27 17:14:01 +02:00
pub fn expr_or_init_with_outside_body < ' a > (
& self ,
mut expr : & ' a hir ::Expr < ' tcx > ,
) -> & ' a hir ::Expr < ' tcx > {
2023-09-05 15:14:53 +02:00
expr = expr . peel_blocks ( ) ;
while let hir ::ExprKind ::Path ( ref qpath ) = expr . kind
& & let Some ( parent_node ) = match self . qpath_res ( qpath , expr . hir_id ) {
Res ::Local ( hir_id ) = > self . tcx . hir ( ) . find_parent ( hir_id ) ,
Res ::Def ( _ , def_id ) = > self . tcx . hir ( ) . get_if_local ( def_id ) ,
_ = > None ,
}
& & let Some ( init ) = match parent_node {
hir ::Node ::Expr ( expr ) = > Some ( expr ) ,
hir ::Node ::Local ( hir ::Local { init , .. } ) = > * init ,
hir ::Node ::Item ( item ) = > match item . kind {
hir ::ItemKind ::Const ( .. , body_id ) | hir ::ItemKind ::Static ( .. , body_id ) = > {
Some ( self . tcx . hir ( ) . body ( body_id ) . value )
}
_ = > None ,
} ,
_ = > None ,
}
{
expr = init . peel_blocks ( ) ;
}
expr
}
2019-01-31 01:36:11 +01:00
}
2021-08-25 16:40:39 +03:00
impl < ' tcx > abi ::HasDataLayout for LateContext < ' tcx > {
#[ inline ]
fn data_layout ( & self ) -> & abi ::TargetDataLayout {
& self . tcx . data_layout
}
}
impl < ' tcx > ty ::layout ::HasTyCtxt < ' tcx > for LateContext < ' tcx > {
#[ inline ]
fn tcx ( & self ) -> TyCtxt < ' tcx > {
self . tcx
}
}
impl < ' tcx > ty ::layout ::HasParamEnv < ' tcx > for LateContext < ' tcx > {
#[ inline ]
fn param_env ( & self ) -> ty ::ParamEnv < ' tcx > {
self . param_env
}
}
2021-08-30 20:37:36 +03:00
impl < ' tcx > LayoutOfHelpers < ' tcx > for LateContext < ' tcx > {
2021-08-30 17:38:27 +03:00
type LayoutOfResult = Result < TyAndLayout < ' tcx > , LayoutError < ' tcx > > ;
2019-01-31 01:36:11 +01:00
2021-08-30 18:01:58 +03:00
#[ inline ]
fn handle_layout_err ( & self , err : LayoutError < ' tcx > , _ : Span , _ : Ty < ' tcx > ) -> LayoutError < ' tcx > {
err
2019-01-31 01:36:11 +01:00
}
}