Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move linting mechanisms to librustc_lint. #67737

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3636,6 +3636,7 @@ dependencies = [
"rustc",
"rustc_data_structures",
"rustc_error_codes",
"rustc_errors",
"rustc_feature",
"rustc_index",
"rustc_session",
Expand Down
69 changes: 1 addition & 68 deletions src/librustc/lint/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//! compiler code, rather than using their own custom pass. Those
//! lints are all available in `rustc_lint::builtin`.

use crate::lint::{FutureIncompatibleInfo, LateLintPass, LintArray, LintPass};
use crate::lint::FutureIncompatibleInfo;
use crate::middle::stability;
use crate::session::Session;
use errors::{pluralize, Applicability, DiagnosticBuilder};
Expand All @@ -13,7 +13,6 @@ use rustc_span::edition::Edition;
use rustc_span::source_map::Span;
use rustc_span::symbol::Symbol;
use syntax::ast;
use syntax::early_buffered_lints::{ILL_FORMED_ATTRIBUTE_INPUT, META_VARIABLE_MISUSE};

declare_lint! {
pub EXCEEDING_BITSHIFTS,
Expand Down Expand Up @@ -443,70 +442,6 @@ declare_lint! {
};
}

declare_lint_pass! {
/// Does nothing as a lint pass, but registers some `Lint`s
/// that are used by other parts of the compiler.
HardwiredLints => [
ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
EXCEEDING_BITSHIFTS,
UNUSED_IMPORTS,
UNUSED_EXTERN_CRATES,
UNUSED_QUALIFICATIONS,
UNKNOWN_LINTS,
UNUSED_VARIABLES,
UNUSED_ASSIGNMENTS,
DEAD_CODE,
UNREACHABLE_CODE,
UNREACHABLE_PATTERNS,
OVERLAPPING_PATTERNS,
UNUSED_MACROS,
WARNINGS,
UNUSED_FEATURES,
STABLE_FEATURES,
UNKNOWN_CRATE_TYPES,
TRIVIAL_CASTS,
TRIVIAL_NUMERIC_CASTS,
PRIVATE_IN_PUBLIC,
EXPORTED_PRIVATE_DEPENDENCIES,
PUB_USE_OF_PRIVATE_EXTERN_CRATE,
INVALID_TYPE_PARAM_DEFAULT,
CONST_ERR,
RENAMED_AND_REMOVED_LINTS,
SAFE_PACKED_BORROWS,
PATTERNS_IN_FNS_WITHOUT_BODY,
MISSING_FRAGMENT_SPECIFIER,
LATE_BOUND_LIFETIME_ARGUMENTS,
ORDER_DEPENDENT_TRAIT_OBJECTS,
DEPRECATED,
UNUSED_UNSAFE,
UNUSED_MUT,
UNCONDITIONAL_RECURSION,
SINGLE_USE_LIFETIMES,
UNUSED_LIFETIMES,
UNUSED_LABELS,
TYVAR_BEHIND_RAW_POINTER,
ELIDED_LIFETIMES_IN_PATHS,
BARE_TRAIT_OBJECTS,
ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
UNSTABLE_NAME_COLLISIONS,
IRREFUTABLE_LET_PATTERNS,
INTRA_DOC_LINK_RESOLUTION_FAILURE,
MISSING_DOC_CODE_EXAMPLES,
PRIVATE_DOC_TESTS,
WHERE_CLAUSES_OBJECT_SAFETY,
PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
MACRO_USE_EXTERN_CRATE,
MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
ILL_FORMED_ATTRIBUTE_INPUT,
META_VARIABLE_MISUSE,
DEPRECATED_IN_FUTURE,
AMBIGUOUS_ASSOCIATED_ITEMS,
MUTABLE_BORROW_RESERVATION_CONFLICT,
INDIRECT_STRUCTURAL_MATCH,
SOFT_UNSTABLE,
]
}

// this could be a closure, but then implementing derive traits
// becomes hacky (and it gets allocated)
#[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
Expand Down Expand Up @@ -646,5 +581,3 @@ impl BuiltinLintDiagnostics {
}
}
}

impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HardwiredLints {}
148 changes: 1 addition & 147 deletions src/librustc/lint/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,14 @@
use self::TargetLint::*;

use crate::hir;
use crate::hir::def_id::{CrateNum, DefId};
use crate::hir::map::{definitions::DisambiguatedDefPathData, DefPathData};
use crate::lint::builtin::BuiltinLintDiagnostics;
use crate::lint::levels::{LintLevelSets, LintLevelsBuilder};
use crate::lint::{EarlyLintPassObject, LateLintPassObject};
use crate::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId};
use crate::middle::privacy::AccessLevels;
use crate::session::Session;
use crate::ty::layout::{LayoutError, LayoutOf, TyLayout};
use crate::ty::{self, print::Printer, subst::GenericArg, Ty, TyCtxt};
use crate::ty::{self, Ty, TyCtxt};
use crate::util::nodemap::FxHashMap;

use errors::DiagnosticBuilder;
Expand Down Expand Up @@ -619,150 +617,6 @@ impl LintContext for EarlyContext<'_> {
}
}

impl<'a, 'tcx> LateContext<'a, 'tcx> {
pub fn current_lint_root(&self) -> hir::HirId {
self.last_node_with_lint_attrs
}

/// Check if a `DefId`'s path matches the given absolute type path usage.
///
/// Anonymous scopes such as `extern` imports are matched with `kw::Invalid`;
/// inherent `impl` blocks are matched with the name of the type.
///
/// # Examples
///
/// ```rust,ignore (no context or def id available)
/// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
/// // The given `def_id` is that of an `Option` type
/// }
/// ```
pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
let names = self.get_def_path(def_id);

names.len() == path.len() && names.into_iter().zip(path.iter()).all(|(a, &b)| a == b)
}

/// Gets the absolute path of `def_id` as a vector of `Symbol`.
///
/// # Examples
///
/// ```rust,ignore (no context or def id available)
/// let def_path = cx.get_def_path(def_id);
/// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
/// // The given `def_id` is that of an `Option` type
/// }
/// ```
pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
pub struct AbsolutePathPrinter<'tcx> {
pub tcx: TyCtxt<'tcx>,
}

impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
type Error = !;

type Path = Vec<Symbol>;
type Region = ();
type Type = ();
type DynExistential = ();
type Const = ();

fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx
}

fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
Ok(())
}

fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
Ok(())
}

fn print_dyn_existential(
self,
_predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
) -> Result<Self::DynExistential, Self::Error> {
Ok(())
}

fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
Ok(())
}

fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
Ok(vec![self.tcx.original_crate_name(cnum)])
}

fn path_qualified(
self,
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<Self::Path, Self::Error> {
if trait_ref.is_none() {
if let ty::Adt(def, substs) = self_ty.kind {
return self.print_def_path(def.did, substs);
}
}

// This shouldn't ever be needed, but just in case:
Ok(vec![match trait_ref {
Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
None => Symbol::intern(&format!("<{}>", self_ty)),
}])
}

fn path_append_impl(
self,
print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
_disambiguated_data: &DisambiguatedDefPathData,
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<Self::Path, Self::Error> {
let mut path = print_prefix(self)?;

// This shouldn't ever be needed, but just in case:
path.push(match trait_ref {
Some(trait_ref) => Symbol::intern(&format!(
"<impl {} for {}>",
trait_ref.print_only_trait_path(),
self_ty
)),
None => Symbol::intern(&format!("<impl {}>", self_ty)),
});

Ok(path)
}

fn path_append(
self,
print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
disambiguated_data: &DisambiguatedDefPathData,
) -> Result<Self::Path, Self::Error> {
let mut path = print_prefix(self)?;

// Skip `::{{constructor}}` on tuple/unit structs.
match disambiguated_data.data {
DefPathData::Ctor => return Ok(path),
_ => {}
}

path.push(disambiguated_data.data.as_symbol());
Ok(path)
}

fn path_generic_args(
self,
print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
_args: &[GenericArg<'tcx>],
) -> Result<Self::Path, Self::Error> {
print_prefix(self)
}
}

AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
}
}

impl<'a, 'tcx> LayoutOf for LateContext<'a, 'tcx> {
type Ty = Ty<'tcx>;
type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
Expand Down
101 changes: 0 additions & 101 deletions src/librustc/lint/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,56 +169,6 @@ macro_rules! declare_late_lint_pass {

late_lint_methods!(declare_late_lint_pass, [], ['tcx]);

#[macro_export]
macro_rules! expand_combined_late_lint_pass_method {
([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
$($self.$passes.$name $params;)*
})
}

#[macro_export]
macro_rules! expand_combined_late_lint_pass_methods {
($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
$(fn $name(&mut self, context: &LateContext<'a, 'tcx>, $($param: $arg),*) {
expand_combined_late_lint_pass_method!($passes, self, $name, (context, $($param),*));
})*
)
}

#[macro_export]
macro_rules! declare_combined_late_lint_pass {
([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], [$hir:tt], $methods:tt) => (
#[allow(non_snake_case)]
$v struct $name {
$($passes: $passes,)*
}

impl $name {
$v fn new() -> Self {
Self {
$($passes: $constructor,)*
}
}

$v fn get_lints() -> LintArray {
let mut lints = Vec::new();
$(lints.extend_from_slice(&$passes::get_lints());)*
lints
}
}

impl<'a, 'tcx> LateLintPass<'a, 'tcx> for $name {
expand_combined_late_lint_pass_methods!([$($passes),*], $methods);
}

impl LintPass for $name {
fn name(&self) -> &'static str {
panic!()
}
}
)
}

#[macro_export]
macro_rules! early_lint_methods {
($macro:path, $args:tt) => (
Expand Down Expand Up @@ -296,56 +246,6 @@ macro_rules! declare_early_lint_pass {

early_lint_methods!(declare_early_lint_pass, []);

#[macro_export]
macro_rules! expand_combined_early_lint_pass_method {
([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
$($self.$passes.$name $params;)*
})
}

#[macro_export]
macro_rules! expand_combined_early_lint_pass_methods {
($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
$(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
expand_combined_early_lint_pass_method!($passes, self, $name, (context, $($param),*));
})*
)
}

#[macro_export]
macro_rules! declare_combined_early_lint_pass {
([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], $methods:tt) => (
#[allow(non_snake_case)]
$v struct $name {
$($passes: $passes,)*
}

impl $name {
$v fn new() -> Self {
Self {
$($passes: $constructor,)*
}
}

$v fn get_lints() -> LintArray {
let mut lints = Vec::new();
$(lints.extend_from_slice(&$passes::get_lints());)*
lints
}
}

impl EarlyLintPass for $name {
expand_combined_early_lint_pass_methods!([$($passes),*], $methods);
}

impl LintPass for $name {
fn name(&self) -> &'static str {
panic!()
}
}
)
}

/// A lint pass boxed up as a trait object.
pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
pub type LateLintPassObject =
Expand All @@ -369,7 +269,6 @@ pub type LevelSource = (Level, LintSource);

pub mod builtin;
mod context;
pub mod internal;
mod levels;

pub use self::levels::{LintLevelMap, LintLevelSets, LintLevelsBuilder};
Expand Down
1 change: 1 addition & 0 deletions src/librustc_lint/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@ rustc_span = { path = "../librustc_span" }
rustc_data_structures = { path = "../librustc_data_structures" }
rustc_feature = { path = "../librustc_feature" }
rustc_index = { path = "../librustc_index" }
rustc_errors = { path = "../librustc_errors" }
rustc_error_codes = { path = "../librustc_error_codes" }
rustc_session = { path = "../librustc_session" }
Loading