Skip to content

Commit

Permalink
Use Symbol more in lint APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
oli-obk committed May 14, 2019
1 parent 80e7cde commit 1107158
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 28 deletions.
36 changes: 18 additions & 18 deletions src/librustc/lint/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -759,35 +759,35 @@ impl<'a, 'tcx> LateContext<'a, 'tcx> {
/// # Examples
///
/// ```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
/// }
/// ```
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);

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
///
/// ```rust,ignore (no context or def id available)
/// 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
/// }
/// ```
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 tcx: TyCtxt<'a, 'tcx, 'tcx>,
}

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

type Path = Vec<LocalInternedString>;
type Path = Vec<Symbol>;
type Region = ();
type Type = ();
type DynExistential = ();
Expand All @@ -807,19 +807,19 @@ impl<'a, 'tcx> LateContext<'a, 'tcx> {
fn print_dyn_existential(
self,
_predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
) -> Result<Self::DynExistential, Self::Error> {
) -> Result<Self::DynExistential, Self::Error> {
Ok(())
}

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(
self,
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<Self::Path, Self::Error> {
) -> Result<Self::Path, Self::Error> {
if trait_ref.is_none() {
if let ty::Adt(def, substs) = self_ty.sty {
return self.print_def_path(def.did, substs);
Expand All @@ -828,8 +828,8 @@ impl<'a, 'tcx> LateContext<'a, 'tcx> {

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

Expand All @@ -839,15 +839,15 @@ impl<'a, 'tcx> LateContext<'a, 'tcx> {
_disambiguated_data: &DisambiguatedDefPathData,
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<Self::Path, Self::Error> {
) -> 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, self_ty)).as_str()
Symbol::intern(&format!("<impl {} for {}>", trait_ref, self_ty))
},
None => Symbol::intern(&format!("<impl {}>", self_ty)).as_str(),
None => Symbol::intern(&format!("<impl {}>", self_ty)),
});

Ok(path)
Expand All @@ -857,7 +857,7 @@ impl<'a, 'tcx> LateContext<'a, 'tcx> {
self,
print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
disambiguated_data: &DisambiguatedDefPathData,
) -> Result<Self::Path, Self::Error> {
) -> Result<Self::Path, Self::Error> {
let mut path = print_prefix(self)?;

// Skip `::{{constructor}}` on tuple/unit structs.
Expand All @@ -866,15 +866,15 @@ impl<'a, 'tcx> LateContext<'a, 'tcx> {
_ => {}
}

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

fn path_generic_args(
self,
print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
_args: &[Kind<'tcx>],
) -> Result<Self::Path, Self::Error> {
) -> Result<Self::Path, Self::Error> {
print_prefix(self)
}
}
Expand Down
26 changes: 16 additions & 10 deletions src/librustc/lint/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::lint::{
use errors::Applicability;
use rustc_data_structures::fx::FxHashMap;
use syntax::ast::Ident;
use syntax::symbol::{sym, Symbol};

declare_lint! {
pub DEFAULT_HASH_TYPES,
Expand All @@ -16,14 +17,16 @@ declare_lint! {
}

pub struct DefaultHashTypes {
map: FxHashMap<String, String>,
map: FxHashMap<Symbol, Symbol>,
}

impl DefaultHashTypes {
// we are allowed to use `HashMap` and `HashSet` as identifiers for implementing the lint itself
#[allow(internal)]
pub fn new() -> Self {
let mut map = FxHashMap::default();
map.insert("HashMap".to_string(), "FxHashMap".to_string());
map.insert("HashSet".to_string(), "FxHashSet".to_string());
map.insert(sym::HashMap, sym::FxHashMap);
map.insert(sym::HashSet, sym::FxHashSet);
Self { map }
}
}
Expand All @@ -32,11 +35,10 @@ impl_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);

impl EarlyLintPass for DefaultHashTypes {
fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) {
let ident_string = ident.to_string();
if let Some(replace) = self.map.get(&ident_string) {
if let Some(replace) = self.map.get(&ident.name) {
let msg = format!(
"Prefer {} over {}, it has better performance",
replace, ident_string
replace, ident
);
let mut db = cx.struct_span_lint(DEFAULT_HASH_TYPES, ident.span, &msg);
db.span_suggestion(
Expand Down Expand Up @@ -169,25 +171,29 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TyTyKind {
}

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(did) = res.opt_def_id() {
return cx.match_def_path(did, &["rustc", "ty", "sty", "TyKind"]);
return cx.match_def_path(did, TYKIND_PATH);
}
}
}

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> {
match &ty.node {
TyKind::Path(qpath) => {
if let QPath::Resolved(_, path) = qpath {
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())));
} 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())));
}
}
Expand Down
10 changes: 10 additions & 0 deletions src/libsyntax_pos/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ symbols! {
const_raw_ptr_to_usize_cast,
const_transmute,
contents,
context,
convert,
copy_closures,
core,
Expand Down Expand Up @@ -253,12 +254,16 @@ symbols! {
fundamental,
future,
Future,
FxHashSet,
FxHashMap,
generators,
generic_associated_types,
generic_param_attrs,
global_allocator,
global_asm,
globs,
HashSet,
HashMap,
hexagon_target_feature,
hidden,
homogeneous_aggregate,
Expand Down Expand Up @@ -454,6 +459,7 @@ symbols! {
rust_2015_preview,
rust_2018_preview,
rust_begin_unwind,
rustc,
rustc_allocator_nounwind,
rustc_allow_const_fn_ptr,
rustc_args_required_const,
Expand Down Expand Up @@ -536,6 +542,7 @@ symbols! {
struct_inherit,
structural_match,
struct_variant,
sty,
suggestion,
target_feature,
target_has_atomic,
Expand All @@ -560,7 +567,10 @@ symbols! {
Try,
try_blocks,
tuple_indexing,
Ty,
ty,
TyCtxt,
TyKind,
type_alias_enum_variants,
type_ascription,
type_length_limit,
Expand Down

0 comments on commit 1107158

Please sign in to comment.