Auto merge of #60827 - oli-obk:late_symbol, r=nnethercote

Use `Symbol` more in lint APIs

r? @nnethercote

This will cause clippy breakage, but super trivial to fix since we can then remove the hacky `match_def_path` function that I added and go back to calling rustc's `match_def_path` method.
This commit is contained in:
bors 2019-05-27 15:36:32 +00:00
commit fa40a111ff
3 changed files with 43 additions and 27 deletions

View File

@ -759,27 +759,27 @@ pub fn current_lint_root(&self) -> hir::HirId {
/// # Examples /// # Examples
/// ///
/// ```rust,ignore (no context or def id available) /// ```rust,ignore (no context or def id available)
/// if cx.match_def_path(def_id, &["core", "option", "Option"]) { /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
/// // The given `def_id` is that of an `Option` type /// // The given `def_id` is that of an `Option` type
/// } /// }
/// ``` /// ```
pub fn match_def_path(&self, def_id: DefId, path: &[&str]) -> bool { pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
let names = self.get_def_path(def_id); let names = self.get_def_path(def_id);
names.len() == path.len() && names.into_iter().zip(path.iter()).all(|(a, &b)| *a == *b) 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 `&str`. /// Gets the absolute path of `def_id` as a vector of `Symbol`.
/// ///
/// # Examples /// # Examples
/// ///
/// ```rust,ignore (no context or def id available) /// ```rust,ignore (no context or def id available)
/// let def_path = cx.get_def_path(def_id); /// let def_path = cx.get_def_path(def_id);
/// if let &["core", "option", "Option"] = &def_path[..] { /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
/// // The given `def_id` is that of an `Option` type /// // The given `def_id` is that of an `Option` type
/// } /// }
/// ``` /// ```
pub fn get_def_path(&self, def_id: DefId) -> Vec<LocalInternedString> { pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
pub struct AbsolutePathPrinter<'a, 'tcx> { pub struct AbsolutePathPrinter<'a, 'tcx> {
pub tcx: TyCtxt<'a, 'tcx, 'tcx>, pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
} }
@ -787,7 +787,7 @@ pub struct AbsolutePathPrinter<'a, 'tcx> {
impl<'tcx> Printer<'tcx, 'tcx> for AbsolutePathPrinter<'_, 'tcx> { impl<'tcx> Printer<'tcx, 'tcx> for AbsolutePathPrinter<'_, 'tcx> {
type Error = !; type Error = !;
type Path = Vec<LocalInternedString>; type Path = Vec<Symbol>;
type Region = (); type Region = ();
type Type = (); type Type = ();
type DynExistential = (); type DynExistential = ();
@ -820,7 +820,7 @@ fn print_const(
} }
fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> { fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
Ok(vec![self.tcx.original_crate_name(cnum).as_str()]) Ok(vec![self.tcx.original_crate_name(cnum)])
} }
fn path_qualified( fn path_qualified(
@ -836,8 +836,8 @@ fn path_qualified(
// This shouldn't ever be needed, but just in case: // This shouldn't ever be needed, but just in case:
Ok(vec![match trait_ref { Ok(vec![match trait_ref {
Some(trait_ref) => LocalInternedString::intern(&format!("{:?}", trait_ref)), Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
None => LocalInternedString::intern(&format!("<{}>", self_ty)), None => Symbol::intern(&format!("<{}>", self_ty)),
}]) }])
} }
@ -853,10 +853,10 @@ fn path_append_impl(
// This shouldn't ever be needed, but just in case: // This shouldn't ever be needed, but just in case:
path.push(match trait_ref { path.push(match trait_ref {
Some(trait_ref) => { Some(trait_ref) => {
LocalInternedString::intern(&format!("<impl {} for {}>", trait_ref, Symbol::intern(&format!("<impl {} for {}>", trait_ref,
self_ty)) self_ty))
}, },
None => LocalInternedString::intern(&format!("<impl {}>", self_ty)), None => Symbol::intern(&format!("<impl {}>", self_ty)),
}); });
Ok(path) Ok(path)
@ -875,7 +875,7 @@ fn path_append(
_ => {} _ => {}
} }
path.push(disambiguated_data.data.as_interned_str().as_str()); path.push(disambiguated_data.data.as_interned_str().as_symbol());
Ok(path) Ok(path)
} }

View File

@ -8,6 +8,7 @@
use errors::Applicability; use errors::Applicability;
use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::fx::FxHashMap;
use syntax::ast::Ident; use syntax::ast::Ident;
use syntax::symbol::{sym, Symbol};
declare_lint! { declare_lint! {
pub DEFAULT_HASH_TYPES, pub DEFAULT_HASH_TYPES,
@ -16,14 +17,16 @@
} }
pub struct DefaultHashTypes { pub struct DefaultHashTypes {
map: FxHashMap<String, String>, map: FxHashMap<Symbol, Symbol>,
} }
impl DefaultHashTypes { impl DefaultHashTypes {
// we are allowed to use `HashMap` and `HashSet` as identifiers for implementing the lint itself
#[allow(internal)]
pub fn new() -> Self { pub fn new() -> Self {
let mut map = FxHashMap::default(); let mut map = FxHashMap::default();
map.insert("HashMap".to_string(), "FxHashMap".to_string()); map.insert(sym::HashMap, sym::FxHashMap);
map.insert("HashSet".to_string(), "FxHashSet".to_string()); map.insert(sym::HashSet, sym::FxHashSet);
Self { map } Self { map }
} }
} }
@ -32,11 +35,10 @@ pub fn new() -> Self {
impl EarlyLintPass for DefaultHashTypes { impl EarlyLintPass for DefaultHashTypes {
fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) { fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) {
let ident_string = ident.to_string(); if let Some(replace) = self.map.get(&ident.name) {
if let Some(replace) = self.map.get(&ident_string) {
let msg = format!( let msg = format!(
"Prefer {} over {}, it has better performance", "Prefer {} over {}, it has better performance",
replace, ident_string replace, ident
); );
let mut db = cx.struct_span_lint(DEFAULT_HASH_TYPES, ident.span, &msg); let mut db = cx.struct_span_lint(DEFAULT_HASH_TYPES, ident.span, &msg);
db.span_suggestion( db.span_suggestion(
@ -169,10 +171,10 @@ fn check_ty(&mut self, cx: &LateContext<'_, '_>, ty: &'tcx Ty) {
} }
fn lint_ty_kind_usage(cx: &LateContext<'_, '_>, segment: &PathSegment) -> bool { fn lint_ty_kind_usage(cx: &LateContext<'_, '_>, segment: &PathSegment) -> bool {
if segment.ident.as_str() == "TyKind" { if segment.ident.name == sym::TyKind {
if let Some(res) = segment.res { if let Some(res) = segment.res {
if let Some(did) = res.opt_def_id() { if let Some(did) = res.opt_def_id() {
return cx.match_def_path(did, &["rustc", "ty", "sty", "TyKind"]); return cx.match_def_path(did, TYKIND_PATH);
} }
} }
} }
@ -180,14 +182,18 @@ fn lint_ty_kind_usage(cx: &LateContext<'_, '_>, segment: &PathSegment) -> bool {
false false
} }
const TYKIND_PATH: &[Symbol] = &[sym::rustc, sym::ty, sym::sty, sym::TyKind];
const TY_PATH: &[Symbol] = &[sym::rustc, sym::ty, sym::Ty];
const TYCTXT_PATH: &[Symbol] = &[sym::rustc, sym::ty, sym::context, sym::TyCtxt];
fn is_ty_or_ty_ctxt(cx: &LateContext<'_, '_>, ty: &Ty) -> Option<String> { fn is_ty_or_ty_ctxt(cx: &LateContext<'_, '_>, ty: &Ty) -> Option<String> {
match &ty.node { match &ty.node {
TyKind::Path(qpath) => { TyKind::Path(qpath) => {
if let QPath::Resolved(_, path) = qpath { if let QPath::Resolved(_, path) = qpath {
let did = path.res.opt_def_id()?; let did = path.res.opt_def_id()?;
if cx.match_def_path(did, &["rustc", "ty", "Ty"]) { if cx.match_def_path(did, TY_PATH) {
return Some(format!("Ty{}", gen_args(path.segments.last().unwrap()))); return Some(format!("Ty{}", gen_args(path.segments.last().unwrap())));
} else if cx.match_def_path(did, &["rustc", "ty", "context", "TyCtxt"]) { } else if cx.match_def_path(did, TYCTXT_PATH) {
return Some(format!("TyCtxt{}", gen_args(path.segments.last().unwrap()))); return Some(format!("TyCtxt{}", gen_args(path.segments.last().unwrap())));
} }
} }

View File

@ -194,6 +194,7 @@
const_raw_ptr_to_usize_cast, const_raw_ptr_to_usize_cast,
const_transmute, const_transmute,
contents, contents,
context,
convert, convert,
copy_closures, copy_closures,
core, core,
@ -282,6 +283,8 @@
fundamental, fundamental,
future, future,
Future, Future,
FxHashSet,
FxHashMap,
gen_future, gen_future,
generators, generators,
generic_associated_types, generic_associated_types,
@ -291,6 +294,8 @@
globs, globs,
hash, hash,
Hash, Hash,
HashSet,
HashMap,
hexagon_target_feature, hexagon_target_feature,
hidden, hidden,
homogeneous_aggregate, homogeneous_aggregate,
@ -505,6 +510,7 @@
rust_2015_preview, rust_2015_preview,
rust_2018_preview, rust_2018_preview,
rust_begin_unwind, rust_begin_unwind,
rustc,
rustc_allocator_nounwind, rustc_allocator_nounwind,
rustc_allow_const_fn_ptr, rustc_allow_const_fn_ptr,
rustc_args_required_const, rustc_args_required_const,
@ -590,6 +596,7 @@
struct_inherit, struct_inherit,
structural_match, structural_match,
struct_variant, struct_variant,
sty,
suggestion, suggestion,
target_feature, target_feature,
target_has_atomic, target_has_atomic,
@ -618,7 +625,10 @@
try_trait, try_trait,
tt, tt,
tuple_indexing, tuple_indexing,
Ty,
ty, ty,
TyCtxt,
TyKind,
type_alias_enum_variants, type_alias_enum_variants,
type_ascription, type_ascription,
type_length_limit, type_length_limit,