Remove the equality operation between Symbol and strings.

And also the equality between `Path` and strings, because `Path` is made
up of `Symbol`s.
This commit is contained in:
Nicholas Nethercote 2019-05-07 16:03:44 +10:00
parent fb084a48e2
commit 999c1fc281
49 changed files with 182 additions and 173 deletions

View File

@ -73,7 +73,7 @@ use syntax_pos::Span;
const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF; const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF;
pub struct LoweringContext<'a> { pub struct LoweringContext<'a> {
crate_root: Option<&'static str>, crate_root: Option<Symbol>,
/// Used to assign ids to HIR nodes that do not directly correspond to an AST node. /// Used to assign ids to HIR nodes that do not directly correspond to an AST node.
sess: &'a Session, sess: &'a Session,
@ -164,8 +164,8 @@ pub trait Resolver {
fn resolve_str_path( fn resolve_str_path(
&mut self, &mut self,
span: Span, span: Span,
crate_root: Option<&str>, crate_root: Option<Symbol>,
components: &[&str], components: &[Symbol],
is_value: bool, is_value: bool,
) -> hir::Path; ) -> hir::Path;
} }
@ -228,7 +228,7 @@ pub fn lower_crate(
dep_graph.assert_ignored(); dep_graph.assert_ignored();
LoweringContext { LoweringContext {
crate_root: std_inject::injected_crate_name(), crate_root: std_inject::injected_crate_name().map(Symbol::intern),
sess, sess,
cstore, cstore,
resolver, resolver,
@ -1149,7 +1149,7 @@ impl<'a> LoweringContext<'a> {
].into()), ].into()),
); );
let gen_future = self.expr_std_path( let gen_future = self.expr_std_path(
unstable_span, &["future", "from_generator"], None, ThinVec::new()); unstable_span, &[sym::future, sym::from_generator], None, ThinVec::new());
hir::ExprKind::Call(P(gen_future), hir_vec![generator]) hir::ExprKind::Call(P(gen_future), hir_vec![generator])
} }
@ -2548,7 +2548,7 @@ impl<'a> LoweringContext<'a> {
// ::std::future::Future<future_params> // ::std::future::Future<future_params>
let future_path = let future_path =
self.std_path(span, &["future", "Future"], Some(future_params), false); self.std_path(span, &[sym::future, sym::Future], Some(future_params), false);
hir::GenericBound::Trait( hir::GenericBound::Trait(
hir::PolyTraitRef { hir::PolyTraitRef {
@ -4194,7 +4194,7 @@ impl<'a> LoweringContext<'a> {
|x: P<hir::Expr>| x.into_inner(), |x: P<hir::Expr>| x.into_inner(),
); );
block.expr = Some(this.wrap_in_try_constructor( block.expr = Some(this.wrap_in_try_constructor(
"from_ok", tail, unstable_span)); sym::from_ok, tail, unstable_span));
hir::ExprKind::Block(P(block), None) hir::ExprKind::Block(P(block), None)
}) })
} }
@ -4336,7 +4336,7 @@ impl<'a> LoweringContext<'a> {
self.expr_call_std_assoc_fn( self.expr_call_std_assoc_fn(
id, id,
e.span, e.span,
&["ops", "RangeInclusive"], &[sym::ops, sym::RangeInclusive],
"new", "new",
hir_vec![e1, e2], hir_vec![e1, e2],
) )
@ -4345,11 +4345,11 @@ impl<'a> LoweringContext<'a> {
use syntax::ast::RangeLimits::*; use syntax::ast::RangeLimits::*;
let path = match (e1, e2, lims) { let path = match (e1, e2, lims) {
(&None, &None, HalfOpen) => "RangeFull", (&None, &None, HalfOpen) => sym::RangeFull,
(&Some(..), &None, HalfOpen) => "RangeFrom", (&Some(..), &None, HalfOpen) => sym::RangeFrom,
(&None, &Some(..), HalfOpen) => "RangeTo", (&None, &Some(..), HalfOpen) => sym::RangeTo,
(&Some(..), &Some(..), HalfOpen) => "Range", (&Some(..), &Some(..), HalfOpen) => sym::Range,
(&None, &Some(..), Closed) => "RangeToInclusive", (&None, &Some(..), Closed) => sym::RangeToInclusive,
(&Some(..), &Some(..), Closed) => unreachable!(), (&Some(..), &Some(..), Closed) => unreachable!(),
(_, &None, Closed) => self.diagnostic() (_, &None, Closed) => self.diagnostic()
.span_fatal(e.span, "inclusive range with no end") .span_fatal(e.span, "inclusive range with no end")
@ -4367,7 +4367,7 @@ impl<'a> LoweringContext<'a> {
.collect::<P<[hir::Field]>>(); .collect::<P<[hir::Field]>>();
let is_unit = fields.is_empty(); let is_unit = fields.is_empty();
let struct_path = ["ops", path]; let struct_path = [sym::ops, path];
let struct_path = self.std_path(e.span, &struct_path, None, is_unit); let struct_path = self.std_path(e.span, &struct_path, None, is_unit);
let struct_path = hir::QPath::Resolved(None, P(struct_path)); let struct_path = hir::QPath::Resolved(None, P(struct_path));
@ -4656,7 +4656,7 @@ impl<'a> LoweringContext<'a> {
let match_expr = { let match_expr = {
let iter = P(self.expr_ident(head_sp, iter, iter_pat_nid)); let iter = P(self.expr_ident(head_sp, iter, iter_pat_nid));
let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter); let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
let next_path = &["iter", "Iterator", "next"]; let next_path = &[sym::iter, sym::Iterator, sym::next];
let next_expr = P(self.expr_call_std_path( let next_expr = P(self.expr_call_std_path(
head_sp, head_sp,
next_path, next_path,
@ -4723,7 +4723,8 @@ impl<'a> LoweringContext<'a> {
// `match ::std::iter::IntoIterator::into_iter(<head>) { ... }` // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
let into_iter_expr = { let into_iter_expr = {
let into_iter_path = &["iter", "IntoIterator", "into_iter"]; let into_iter_path =
&[sym::iter, sym::IntoIterator, sym::into_iter];
P(self.expr_call_std_path( P(self.expr_call_std_path(
head_sp, head_sp,
into_iter_path, into_iter_path,
@ -4780,7 +4781,7 @@ impl<'a> LoweringContext<'a> {
// expand <expr> // expand <expr>
let sub_expr = self.lower_expr(sub_expr); let sub_expr = self.lower_expr(sub_expr);
let path = &["ops", "Try", "into_result"]; let path = &[sym::ops, sym::Try, sym::into_result];
P(self.expr_call_std_path( P(self.expr_call_std_path(
unstable_span, unstable_span,
path, path,
@ -4822,12 +4823,12 @@ impl<'a> LoweringContext<'a> {
let err_ident = self.str_to_ident("err"); let err_ident = self.str_to_ident("err");
let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident); let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
let from_expr = { let from_expr = {
let from_path = &["convert", "From", "from"]; let from_path = &[sym::convert, sym::From, sym::from];
let err_expr = self.expr_ident(try_span, err_ident, err_local_nid); let err_expr = self.expr_ident(try_span, err_ident, err_local_nid);
self.expr_call_std_path(try_span, from_path, hir_vec![err_expr]) self.expr_call_std_path(try_span, from_path, hir_vec![err_expr])
}; };
let from_err_expr = let from_err_expr =
self.wrap_in_try_constructor("from_error", from_expr, unstable_span); self.wrap_in_try_constructor(sym::from_error, from_expr, unstable_span);
let thin_attrs = ThinVec::from(attrs); let thin_attrs = ThinVec::from(attrs);
let catch_scope = self.catch_scopes.last().map(|x| *x); let catch_scope = self.catch_scopes.last().map(|x| *x);
let ret_expr = if let Some(catch_node) = catch_scope { let ret_expr = if let Some(catch_node) = catch_scope {
@ -5057,7 +5058,7 @@ impl<'a> LoweringContext<'a> {
fn expr_call_std_path( fn expr_call_std_path(
&mut self, &mut self,
span: Span, span: Span,
path_components: &[&str], path_components: &[Symbol],
args: hir::HirVec<hir::Expr>, args: hir::HirVec<hir::Expr>,
) -> hir::Expr { ) -> hir::Expr {
let path = P(self.expr_std_path(span, path_components, None, ThinVec::new())); let path = P(self.expr_std_path(span, path_components, None, ThinVec::new()));
@ -5077,7 +5078,7 @@ impl<'a> LoweringContext<'a> {
&mut self, &mut self,
ty_path_id: hir::HirId, ty_path_id: hir::HirId,
span: Span, span: Span,
ty_path_components: &[&str], ty_path_components: &[Symbol],
assoc_fn_name: &str, assoc_fn_name: &str,
args: hir::HirVec<hir::Expr>, args: hir::HirVec<hir::Expr>,
) -> hir::ExprKind { ) -> hir::ExprKind {
@ -5119,7 +5120,7 @@ impl<'a> LoweringContext<'a> {
fn expr_std_path( fn expr_std_path(
&mut self, &mut self,
span: Span, span: Span,
components: &[&str], components: &[Symbol],
params: Option<P<hir::GenericArgs>>, params: Option<P<hir::GenericArgs>>,
attrs: ThinVec<Attribute>, attrs: ThinVec<Attribute>,
) -> hir::Expr { ) -> hir::Expr {
@ -5250,25 +5251,25 @@ impl<'a> LoweringContext<'a> {
} }
fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> { fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat]) self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![pat])
} }
fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> { fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat]) self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![pat])
} }
fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> { fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat]) self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![pat])
} }
fn pat_none(&mut self, span: Span) -> P<hir::Pat> { fn pat_none(&mut self, span: Span) -> P<hir::Pat> {
self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![]) self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], hir_vec![])
} }
fn pat_std_enum( fn pat_std_enum(
&mut self, &mut self,
span: Span, span: Span,
components: &[&str], components: &[Symbol],
subpats: hir::HirVec<P<hir::Pat>>, subpats: hir::HirVec<P<hir::Pat>>,
) -> P<hir::Pat> { ) -> P<hir::Pat> {
let path = self.std_path(span, components, None, true); let path = self.std_path(span, components, None, true);
@ -5321,7 +5322,7 @@ impl<'a> LoweringContext<'a> {
fn std_path( fn std_path(
&mut self, &mut self,
span: Span, span: Span,
components: &[&str], components: &[Symbol],
params: Option<P<hir::GenericArgs>>, params: Option<P<hir::GenericArgs>>,
is_value: bool, is_value: bool,
) -> hir::Path { ) -> hir::Path {
@ -5520,11 +5521,11 @@ impl<'a> LoweringContext<'a> {
fn wrap_in_try_constructor( fn wrap_in_try_constructor(
&mut self, &mut self,
method: &'static str, method: Symbol,
e: hir::Expr, e: hir::Expr,
unstable_span: Span, unstable_span: Span,
) -> P<hir::Expr> { ) -> P<hir::Expr> {
let path = &["ops", "Try", method]; let path = &[sym::ops, sym::Try, method];
let from_err = P(self.expr_std_path(unstable_span, path, None, let from_err = P(self.expr_std_path(unstable_span, path, None,
ThinVec::new())); ThinVec::new()));
P(self.expr_call(e.span, from_err, hir_vec![e])) P(self.expr_call(e.span, from_err, hir_vec![e]))
@ -5594,7 +5595,7 @@ impl<'a> LoweringContext<'a> {
let new_unchecked_expr_kind = self.expr_call_std_assoc_fn( let new_unchecked_expr_kind = self.expr_call_std_assoc_fn(
pin_ty_id, pin_ty_id,
span, span,
&["pin", "Pin"], &[sym::pin, sym::Pin],
"new_unchecked", "new_unchecked",
hir_vec![ref_mut_pinned], hir_vec![ref_mut_pinned],
); );
@ -5602,7 +5603,7 @@ impl<'a> LoweringContext<'a> {
let unsafe_expr = self.expr_unsafe(new_unchecked); let unsafe_expr = self.expr_unsafe(new_unchecked);
P(self.expr_call_std_path( P(self.expr_call_std_path(
gen_future_span, gen_future_span,
&["future", "poll_with_tls_context"], &[sym::future, sym::poll_with_tls_context],
hir_vec![unsafe_expr], hir_vec![unsafe_expr],
)) ))
}; };
@ -5616,7 +5617,7 @@ impl<'a> LoweringContext<'a> {
let x_expr = P(self.expr_ident(span, x_ident, x_pat_hid)); let x_expr = P(self.expr_ident(span, x_ident, x_pat_hid));
let ready_pat = self.pat_std_enum( let ready_pat = self.pat_std_enum(
span, span,
&["task", "Poll", "Ready"], &[sym::task, sym::Poll, sym::Ready],
hir_vec![x_pat], hir_vec![x_pat],
); );
let break_x = self.with_loop_scope(loop_node_id, |this| { let break_x = self.with_loop_scope(loop_node_id, |this| {
@ -5633,7 +5634,7 @@ impl<'a> LoweringContext<'a> {
let pending_arm = { let pending_arm = {
let pending_pat = self.pat_std_enum( let pending_pat = self.pat_std_enum(
span, span,
&["task", "Poll", "Pending"], &[sym::task, sym::Poll, sym::Pending],
hir_vec![], hir_vec![],
); );
let empty_block = P(self.expr_block_empty(span)); let empty_block = P(self.expr_block_empty(span));

View File

@ -1146,7 +1146,7 @@ impl<'a> NodesMatchingSuffix<'a> {
None => return false, None => return false,
Some((node_id, name)) => (node_id, name), Some((node_id, name)) => (node_id, name),
}; };
if mod_name != &**part { if mod_name.as_str() != *part {
return false; return false;
} }
cursor = self.map.get_parent_item(mod_id); cursor = self.map.get_parent_item(mod_id);
@ -1183,7 +1183,7 @@ impl<'a> NodesMatchingSuffix<'a> {
// We are looking at some node `n` with a given name and parent // We are looking at some node `n` with a given name and parent
// id; do their names match what I am seeking? // id; do their names match what I am seeking?
fn matches_names(&self, parent_of_n: HirId, name: Name) -> bool { fn matches_names(&self, parent_of_n: HirId, name: Name) -> bool {
name == &**self.item_name && self.suffix_matches(parent_of_n) name.as_str() == *self.item_name && self.suffix_matches(parent_of_n)
} }
fn matches_suffix(&self, hir: HirId) -> bool { fn matches_suffix(&self, hir: HirId) -> bool {

View File

@ -221,7 +221,7 @@ impl<'a> LintLevelsBuilder<'a> {
match item.node { match item.node {
ast::MetaItemKind::Word => {} // actual lint names handled later ast::MetaItemKind::Word => {} // actual lint names handled later
ast::MetaItemKind::NameValue(ref name_value) => { ast::MetaItemKind::NameValue(ref name_value) => {
if item.path == "reason" { if item.path == sym::reason {
// found reason, reslice meta list to exclude it // found reason, reslice meta list to exclude it
metas = &metas[0..metas.len()-1]; metas = &metas[0..metas.len()-1];
// FIXME (#55112): issue unused-attributes lint if we thereby // FIXME (#55112): issue unused-attributes lint if we thereby
@ -261,7 +261,7 @@ impl<'a> LintLevelsBuilder<'a> {
let mut err = bad_attr(li.span()); let mut err = bad_attr(li.span());
if let Some(item) = li.meta_item() { if let Some(item) = li.meta_item() {
if let ast::MetaItemKind::NameValue(_) = item.node { if let ast::MetaItemKind::NameValue(_) = item.node {
if item.path == "reason" { if item.path == sym::reason {
err.help("reason in lint attribute must come last"); err.help("reason in lint attribute must come last");
} }
} }

View File

@ -86,7 +86,7 @@ fn entry_point_type(item: &Item, at_root: bool) -> EntryPointType {
EntryPointType::Start EntryPointType::Start
} else if attr::contains_name(&item.attrs, sym::main) { } else if attr::contains_name(&item.attrs, sym::main) {
EntryPointType::MainAttr EntryPointType::MainAttr
} else if item.ident.name == "main" { } else if item.ident.name == sym::main {
if at_root { if at_root {
// This is a top-level function so can be 'main'. // This is a top-level function so can be 'main'.
EntryPointType::MainNamed EntryPointType::MainNamed

View File

@ -76,7 +76,7 @@ impl<'a, 'tcx> LibFeatureCollector<'a, 'tcx> {
// This additional check for stability is to make sure we // This additional check for stability is to make sure we
// don't emit additional, irrelevant errors for malformed // don't emit additional, irrelevant errors for malformed
// attributes. // attributes.
if *stab_attr != "stable" || since.is_some() { if *stab_attr != sym::stable || since.is_some() {
return Some((feature, since, attr.span)); return Some((feature, since, attr.span));
} }
} }

View File

@ -686,7 +686,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
// the `-Z force-unstable-if-unmarked` flag present (we're // the `-Z force-unstable-if-unmarked` flag present (we're
// compiling a compiler crate), then let this missing feature // compiling a compiler crate), then let this missing feature
// annotation slide. // annotation slide.
if feature == "rustc_private" && issue == 27812 { if feature == sym::rustc_private && issue == 27812 {
if self.sess.opts.debugging_opts.force_unstable_if_unmarked { if self.sess.opts.debugging_opts.force_unstable_if_unmarked {
return EvalResult::Allow; return EvalResult::Allow;
} }

View File

@ -6,7 +6,7 @@ use crate::middle::lang_items;
use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::fx::FxHashSet;
use rustc_target::spec::PanicStrategy; use rustc_target::spec::PanicStrategy;
use syntax::ast; use syntax::ast;
use syntax::symbol::Symbol; use syntax::symbol::{Symbol, sym};
use syntax_pos::Span; use syntax_pos::Span;
use crate::hir::def_id::DefId; use crate::hir::def_id::DefId;
use crate::hir::intravisit::{Visitor, NestedVisitorMap}; use crate::hir::intravisit::{Visitor, NestedVisitorMap};
@ -46,8 +46,8 @@ pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
pub fn link_name(attrs: &[ast::Attribute]) -> Option<Symbol> { pub fn link_name(attrs: &[ast::Attribute]) -> Option<Symbol> {
lang_items::extract(attrs).and_then(|(name, _)| { lang_items::extract(attrs).and_then(|(name, _)| {
$(if name == stringify!($name) { $(if name == sym::$name {
Some(Symbol::intern(stringify!($sym))) Some(sym::$sym)
} else)* { } else)* {
None None
} }

View File

@ -2753,6 +2753,7 @@ mod tests {
// another --cfg test // another --cfg test
#[test] #[test]
fn test_switch_implies_cfg_test_unless_cfg_test() { fn test_switch_implies_cfg_test_unless_cfg_test() {
use syntax::symbol::sym;
syntax::with_globals(|| { syntax::with_globals(|| {
let matches = &match optgroups().parse(&["--test".to_string(), let matches = &match optgroups().parse(&["--test".to_string(),
"--cfg=test".to_string()]) { "--cfg=test".to_string()]) {
@ -2763,7 +2764,7 @@ mod tests {
let (sessopts, cfg) = build_session_options_and_crate_config(matches); let (sessopts, cfg) = build_session_options_and_crate_config(matches);
let sess = build_session(sessopts, None, registry); let sess = build_session(sessopts, None, registry);
let cfg = build_configuration(&sess, to_crate_config(cfg)); let cfg = build_configuration(&sess, to_crate_config(cfg));
let mut test_items = cfg.iter().filter(|&&(name, _)| name == "test"); let mut test_items = cfg.iter().filter(|&&(name, _)| name == sym::test);
assert!(test_items.next().is_some()); assert!(test_items.next().is_some());
assert!(test_items.next().is_none()); assert!(test_items.next().is_none());
}); });

View File

@ -19,6 +19,7 @@ use crate::mir::interpret::{GlobalId, ConstValue};
use rustc_data_structures::snapshot_map::{Snapshot, SnapshotMap}; use rustc_data_structures::snapshot_map::{Snapshot, SnapshotMap};
use rustc_macros::HashStable; use rustc_macros::HashStable;
use syntax::ast::Ident; use syntax::ast::Ident;
use syntax::symbol::sym;
use crate::ty::subst::{Subst, InternalSubsts}; use crate::ty::subst::{Subst, InternalSubsts};
use crate::ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt}; use crate::ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt};
use crate::ty::fold::{TypeFoldable, TypeFolder}; use crate::ty::fold::{TypeFoldable, TypeFolder};
@ -1318,9 +1319,9 @@ fn confirm_generator_candidate<'cx, 'gcx, 'tcx>(
gen_sig) gen_sig)
.map_bound(|(trait_ref, yield_ty, return_ty)| { .map_bound(|(trait_ref, yield_ty, return_ty)| {
let name = tcx.associated_item(obligation.predicate.item_def_id).ident.name; let name = tcx.associated_item(obligation.predicate.item_def_id).ident.name;
let ty = if name == "Return" { let ty = if name == sym::Return {
return_ty return_ty
} else if name == "Yield" { } else if name == sym::Yield {
yield_ty yield_ty
} else { } else {
bug!() bug!()

View File

@ -386,7 +386,7 @@ pub fn start_async_codegen<B: ExtraBackendMethods>(
let subsystem = attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs, let subsystem = attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs,
sym::windows_subsystem); sym::windows_subsystem);
let windows_subsystem = subsystem.map(|subsystem| { let windows_subsystem = subsystem.map(|subsystem| {
if subsystem != "windows" && subsystem != "console" { if subsystem != sym::windows && subsystem != sym::console {
tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \ tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
`windows` and `console` are allowed", `windows` and `console` are allowed",
subsystem)); subsystem));

View File

@ -56,7 +56,7 @@ pub fn find_crate_name(sess: Option<&Session>,
if let Some(sess) = sess { if let Some(sess) = sess {
if let Some(ref s) = sess.opts.crate_name { if let Some(ref s) = sess.opts.crate_name {
if let Some((attr, name)) = attr_crate_name { if let Some((attr, name)) = attr_crate_name {
if name != &**s { if name.as_str() != *s {
let msg = format!("--crate-name and #[crate_name] are \ let msg = format!("--crate-name and #[crate_name] are \
required to match, but `{}` != `{}`", required to match, but `{}` != `{}`",
s, name); s, name);

View File

@ -63,6 +63,7 @@ use syntax::ast;
use syntax::source_map::FileLoader; use syntax::source_map::FileLoader;
use syntax::feature_gate::{GatedCfg, UnstableFeatures}; use syntax::feature_gate::{GatedCfg, UnstableFeatures};
use syntax::parse::{self, PResult}; use syntax::parse::{self, PResult};
use syntax::symbol::sym;
use syntax_pos::{DUMMY_SP, MultiSpan, FileName}; use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
pub mod pretty; pub mod pretty;
@ -669,7 +670,7 @@ impl RustcDefaultCalls {
// through to build scripts. // through to build scripts.
let value = value.as_ref().map(|s| s.as_str()); let value = value.as_ref().map(|s| s.as_str());
let value = value.as_ref().map(|s| s.as_ref()); let value = value.as_ref().map(|s| s.as_ref());
if name != "target_feature" || value != Some("crt-static") { if name != sym::target_feature || value != Some("crt-static") {
if !allow_unstable_cfg && gated_cfg.is_some() { if !allow_unstable_cfg && gated_cfg.is_some() {
return None return None
} }

View File

@ -497,22 +497,22 @@ pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<c
.filter_map(|a| { .filter_map(|a| {
if a.check_name(sym::crate_type) { if a.check_name(sym::crate_type) {
match a.value_str() { match a.value_str() {
Some(ref n) if *n == "rlib" => Some(config::CrateType::Rlib), Some(sym::rlib) => Some(config::CrateType::Rlib),
Some(ref n) if *n == "dylib" => Some(config::CrateType::Dylib), Some(sym::dylib) => Some(config::CrateType::Dylib),
Some(ref n) if *n == "cdylib" => Some(config::CrateType::Cdylib), Some(sym::cdylib) => Some(config::CrateType::Cdylib),
Some(ref n) if *n == "lib" => Some(config::default_lib_output()), Some(sym::lib) => Some(config::default_lib_output()),
Some(ref n) if *n == "staticlib" => Some(config::CrateType::Staticlib), Some(sym::staticlib) => Some(config::CrateType::Staticlib),
Some(ref n) if *n == "proc-macro" => Some(config::CrateType::ProcMacro), Some(sym::proc_dash_macro) => Some(config::CrateType::ProcMacro),
Some(ref n) if *n == "bin" => Some(config::CrateType::Executable), Some(sym::bin) => Some(config::CrateType::Executable),
Some(ref n) => { Some(n) => {
let crate_types = vec![ let crate_types = vec![
Symbol::intern("rlib"), sym::rlib,
Symbol::intern("dylib"), sym::dylib,
Symbol::intern("cdylib"), sym::cdylib,
Symbol::intern("lib"), sym::lib,
Symbol::intern("staticlib"), sym::staticlib,
Symbol::intern("proc-macro"), sym::proc_dash_macro,
Symbol::intern("bin") sym::bin
]; ];
if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().node { if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().node {

View File

@ -837,7 +837,7 @@ impl<'a> CrateLoader<'a> {
let mut uses_std = false; let mut uses_std = false;
self.cstore.iter_crate_data(|_, data| { self.cstore.iter_crate_data(|_, data| {
if data.name == "std" { if data.name == sym::std {
uses_std = true; uses_std = true;
} }
}); });

View File

@ -31,7 +31,7 @@ use syntax::source_map;
use syntax::edition::Edition; use syntax::edition::Edition;
use syntax::parse::source_file_to_stream; use syntax::parse::source_file_to_stream;
use syntax::parse::parser::emit_unclosed_delims; use syntax::parse::parser::emit_unclosed_delims;
use syntax::symbol::Symbol; use syntax::symbol::{Symbol, sym};
use syntax_pos::{Span, NO_EXPANSION, FileName}; use syntax_pos::{Span, NO_EXPANSION, FileName};
use rustc_data_structures::bit_set::BitSet; use rustc_data_structures::bit_set::BitSet;
@ -432,7 +432,7 @@ impl cstore::CStore {
let data = self.get_crate_data(id.krate); let data = self.get_crate_data(id.krate);
if let Some(ref proc_macros) = data.proc_macros { if let Some(ref proc_macros) = data.proc_macros {
return LoadedMacro::ProcMacro(proc_macros[id.index.to_proc_macro_index()].1.clone()); return LoadedMacro::ProcMacro(proc_macros[id.index.to_proc_macro_index()].1.clone());
} else if data.name == "proc_macro" && data.item_name(id.index) == "quote" { } else if data.name == sym::proc_macro && data.item_name(id.index) == "quote" {
use syntax::ext::base::SyntaxExtension; use syntax::ext::base::SyntaxExtension;
use syntax_ext::proc_macro_impl::BangProcMacro; use syntax_ext::proc_macro_impl::BangProcMacro;

View File

@ -11,7 +11,7 @@ pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Vec<String> {
tcx.hir().krate().visit_all_item_likes(&mut collector); tcx.hir().krate().visit_all_item_likes(&mut collector);
for attr in tcx.hir().krate().attrs.iter() { for attr in tcx.hir().krate().attrs.iter() {
if attr.path == "link_args" { if attr.path == sym::link_args {
if let Some(linkarg) = attr.value_str() { if let Some(linkarg) = attr.value_str() {
collector.add_link_args(&linkarg.as_str()); collector.add_link_args(&linkarg.as_str());
} }

View File

@ -225,7 +225,7 @@ use rustc::session::search_paths::PathKind;
use rustc::util::nodemap::FxHashMap; use rustc::util::nodemap::FxHashMap;
use errors::DiagnosticBuilder; use errors::DiagnosticBuilder;
use syntax::symbol::Symbol; use syntax::symbol::{Symbol, sym};
use syntax::struct_span_err; use syntax::struct_span_err;
use syntax_pos::Span; use syntax_pos::Span;
use rustc_target::spec::{Target, TargetTriple}; use rustc_target::spec::{Target, TargetTriple};
@ -408,7 +408,7 @@ impl<'a> Context<'a> {
self.ident, self.ident,
add); add);
if (self.ident == "std" || self.ident == "core") if (self.ident == sym::std || self.ident == sym::core)
&& self.triple != TargetTriple::from_triple(config::host_triple()) { && self.triple != TargetTriple::from_triple(config::host_triple()) {
err.note(&format!("the `{}` target may not be installed", self.triple)); err.note(&format!("the `{}` target may not be installed", self.triple));
} }

View File

@ -181,7 +181,7 @@ impl<'a, 'tcx> Collector<'a, 'tcx> {
let any_duplicate = self.libs let any_duplicate = self.libs
.iter() .iter()
.filter_map(|lib| lib.name.as_ref()) .filter_map(|lib| lib.name.as_ref())
.any(|n| n == name); .any(|n| n.as_str() == *name);
if new_name.is_empty() { if new_name.is_empty() {
self.tcx.sess.err( self.tcx.sess.err(
&format!("an empty renaming target was specified for library `{}`",name)); &format!("an empty renaming target was specified for library `{}`",name));
@ -212,7 +212,7 @@ impl<'a, 'tcx> Collector<'a, 'tcx> {
// can move them to the end of the list below. // can move them to the end of the list below.
let mut existing = self.libs.drain_filter(|lib| { let mut existing = self.libs.drain_filter(|lib| {
if let Some(lib_name) = lib.name { if let Some(lib_name) = lib.name {
if lib_name == name as &str { if lib_name.as_str() == *name {
if let Some(k) = kind { if let Some(k) = kind {
lib.kind = k; lib.kind = k;
} }

View File

@ -7,7 +7,7 @@ use rustc::util::nodemap::FxHashMap;
use syntax::ext::base::{SyntaxExtension, NamedSyntaxExtension, NormalTT, IdentTT}; use syntax::ext::base::{SyntaxExtension, NamedSyntaxExtension, NormalTT, IdentTT};
use syntax::ext::base::MacroExpanderFn; use syntax::ext::base::MacroExpanderFn;
use syntax::ext::hygiene; use syntax::ext::hygiene;
use syntax::symbol::Symbol; use syntax::symbol::{Symbol, sym};
use syntax::ast; use syntax::ast;
use syntax::feature_gate::AttributeType; use syntax::feature_gate::AttributeType;
use syntax_pos::Span; use syntax_pos::Span;
@ -86,7 +86,7 @@ impl<'a> Registry<'a> {
/// ///
/// This is the most general hook into `libsyntax`'s expansion behavior. /// This is the most general hook into `libsyntax`'s expansion behavior.
pub fn register_syntax_extension(&mut self, name: ast::Name, extension: SyntaxExtension) { pub fn register_syntax_extension(&mut self, name: ast::Name, extension: SyntaxExtension) {
if name == "macro_rules" { if name == sym::macro_rules {
panic!("user-defined macros may not be named `macro_rules`"); panic!("user-defined macros may not be named `macro_rules`");
} }
self.syntax_exts.push((name, match extension { self.syntax_exts.push((name, match extension {

View File

@ -369,7 +369,7 @@ impl<'a> Resolver<'a> {
}; };
self.populate_module_if_necessary(module); self.populate_module_if_necessary(module);
if injected_crate_name().map_or(false, |name| ident.name == name) { if injected_crate_name().map_or(false, |name| ident.name.as_str() == name) {
self.injected_crate = Some(module); self.injected_crate = Some(module);
} }

View File

@ -1812,8 +1812,8 @@ impl<'a> hir::lowering::Resolver for Resolver<'a> {
fn resolve_str_path( fn resolve_str_path(
&mut self, &mut self,
span: Span, span: Span,
crate_root: Option<&str>, crate_root: Option<Symbol>,
components: &[&str], components: &[Symbol],
is_value: bool is_value: bool
) -> hir::Path { ) -> hir::Path {
let root = if crate_root.is_some() { let root = if crate_root.is_some() {
@ -1825,7 +1825,7 @@ impl<'a> hir::lowering::Resolver for Resolver<'a> {
.chain( .chain(
crate_root.into_iter() crate_root.into_iter()
.chain(components.iter().cloned()) .chain(components.iter().cloned())
.map(Ident::from_str) .map(Ident::with_empty_ctxt)
).map(|i| self.new_ast_path_segment(i)).collect::<Vec<_>>(); ).map(|i| self.new_ast_path_segment(i)).collect::<Vec<_>>();

View File

@ -982,7 +982,7 @@ impl<'a> Resolver<'a> {
let msg = let msg =
format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang); format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
let mut err = self.session.struct_span_err(ident.span, &msg); let mut err = self.session.struct_span_err(ident.span, &msg);
self.suggest_macro_name(&ident.as_str(), kind, &mut err, ident.span); self.suggest_macro_name(ident.name, kind, &mut err, ident.span);
err.emit(); err.emit();
} }
} }
@ -1010,11 +1010,12 @@ impl<'a> Resolver<'a> {
} }
} }
fn suggest_macro_name(&mut self, name: &str, kind: MacroKind, fn suggest_macro_name(&mut self, name: Symbol, kind: MacroKind,
err: &mut DiagnosticBuilder<'a>, span: Span) { err: &mut DiagnosticBuilder<'a>, span: Span) {
// First check if this is a locally-defined bang macro. // First check if this is a locally-defined bang macro.
let suggestion = if let MacroKind::Bang = kind { let suggestion = if let MacroKind::Bang = kind {
find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, None) find_best_match_for_name(
self.macro_names.iter().map(|ident| &ident.name), &name.as_str(), None)
} else { } else {
None None
// Then check global macros. // Then check global macros.
@ -1023,7 +1024,7 @@ impl<'a> Resolver<'a> {
.filter_map(|(name, binding)| { .filter_map(|(name, binding)| {
if binding.macro_kind() == Some(kind) { Some(name) } else { None } if binding.macro_kind() == Some(kind) { Some(name) } else { None }
}); });
find_best_match_for_name(names, name, None) find_best_match_for_name(names, &name.as_str(), None)
// Then check modules. // Then check modules.
}).or_else(|| { }).or_else(|| {
let is_macro = |res| { let is_macro = |res| {
@ -1033,7 +1034,7 @@ impl<'a> Resolver<'a> {
false false
} }
}; };
let ident = Ident::new(Symbol::intern(name), span); let ident = Ident::new(name, span);
self.lookup_typo_candidate(&[Segment::from_ident(ident)], MacroNS, is_macro, span) self.lookup_typo_candidate(&[Segment::from_ident(ident)], MacroNS, is_macro, span)
.map(|suggestion| suggestion.candidate) .map(|suggestion| suggestion.candidate)
}); });
@ -1092,7 +1093,7 @@ impl<'a> Resolver<'a> {
current_legacy_scope: &mut LegacyScope<'a>) { current_legacy_scope: &mut LegacyScope<'a>) {
self.local_macro_def_scopes.insert(item.id, self.current_module); self.local_macro_def_scopes.insert(item.id, self.current_module);
let ident = item.ident; let ident = item.ident;
if ident.name == "macro_rules" { if ident.name == sym::macro_rules {
self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`"); self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
} }

View File

@ -29,7 +29,7 @@ use rustc::{bug, span_bug};
use syntax::ast::{self, Ident, Name, NodeId, CRATE_NODE_ID}; use syntax::ast::{self, Ident, Name, NodeId, CRATE_NODE_ID};
use syntax::ext::base::Determinacy::{self, Determined, Undetermined}; use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
use syntax::ext::hygiene::Mark; use syntax::ext::hygiene::Mark;
use syntax::symbol::keywords; use syntax::symbol::{keywords, sym};
use syntax::util::lev_distance::find_best_match_for_name; use syntax::util::lev_distance::find_best_match_for_name;
use syntax::{struct_span_err, unwrap_or}; use syntax::{struct_span_err, unwrap_or};
use syntax_pos::{MultiSpan, Span}; use syntax_pos::{MultiSpan, Span};
@ -496,7 +496,8 @@ impl<'a> Resolver<'a> {
// Reserve some names that are not quite covered by the general check // Reserve some names that are not quite covered by the general check
// performed on `Resolver::builtin_attrs`. // performed on `Resolver::builtin_attrs`.
if ns == MacroNS && if ns == MacroNS &&
(ident.name == "cfg" || ident.name == "cfg_attr" || ident.name == "derive") { (ident.name == sym::cfg || ident.name == sym::cfg_attr ||
ident.name == sym::derive) {
self.session.span_err(ident.span, self.session.span_err(ident.span,
&format!("name `{}` is reserved in macro namespace", ident)); &format!("name `{}` is reserved in macro namespace", ident));
} }
@ -706,7 +707,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> {
has_errors = true; has_errors = true;
if let SingleImport { source, ref source_bindings, .. } = import.subclass { if let SingleImport { source, ref source_bindings, .. } = import.subclass {
if source.name == "self" { if source.name == keywords::SelfLower.name() {
// Silence `unresolved import` error if E0429 is already emitted // Silence `unresolved import` error if E0429 is already emitted
if let Err(Determined) = source_bindings.value_ns.get() { if let Err(Determined) = source_bindings.value_ns.get() {
continue; continue;
@ -1041,7 +1042,8 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> {
let initial_res = source_bindings[ns].get().map(|initial_binding| { let initial_res = source_bindings[ns].get().map(|initial_binding| {
all_ns_err = false; all_ns_err = false;
if let Some(target_binding) = target_bindings[ns].get() { if let Some(target_binding) = target_bindings[ns].get() {
if target.name == "_" && // Note that as_str() de-gensyms the Symbol
if target.name.as_str() == "_" &&
initial_binding.is_extern_crate() && !initial_binding.is_import() { initial_binding.is_extern_crate() && !initial_binding.is_import() {
this.record_use(ident, ns, target_binding, this.record_use(ident, ns, target_binding,
directive.module_path.is_empty()); directive.module_path.is_empty());
@ -1392,7 +1394,8 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> {
// (e.g. implicitly injected `std`) cannot be properly encoded in metadata, // (e.g. implicitly injected `std`) cannot be properly encoded in metadata,
// so they can cause name conflict errors downstream. // so they can cause name conflict errors downstream.
let is_good_import = binding.is_import() && !binding.is_ambiguity() && let is_good_import = binding.is_import() && !binding.is_ambiguity() &&
!(ident.name.is_gensymed() && ident.name != "_"); // Note that as_str() de-gensyms the Symbol
!(ident.name.is_gensymed() && ident.name.as_str() != "_");
if is_good_import || binding.is_macro_def() { if is_good_import || binding.is_macro_def() {
let res = binding.res(); let res = binding.res();
if res != Res::Err { if res != Res::Err {

View File

@ -1197,7 +1197,7 @@ fn null_id() -> rls_data::Id {
fn lower_attributes(attrs: Vec<Attribute>, scx: &SaveContext<'_, '_>) -> Vec<rls_data::Attribute> { fn lower_attributes(attrs: Vec<Attribute>, scx: &SaveContext<'_, '_>) -> Vec<rls_data::Attribute> {
attrs.into_iter() attrs.into_iter()
// Only retain real attributes. Doc comments are lowered separately. // Only retain real attributes. Doc comments are lowered separately.
.filter(|attr| attr.path != "doc") .filter(|attr| attr.path != sym::doc)
.map(|mut attr| { .map(|mut attr| {
// Remove the surrounding '#[..]' or '#![..]' of the pretty printed // Remove the surrounding '#[..]' or '#![..]' of the pretty printed
// attribute. First normalize all inner attribute (#![..]) to outer // attribute. First normalize all inner attribute (#![..]) to outer

View File

@ -4197,7 +4197,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
// ... except when we try to 'break rust;'. // ... except when we try to 'break rust;'.
// ICE this expression in particular (see #43162). // ICE this expression in particular (see #43162).
if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.node { if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.node {
if path.segments.len() == 1 && path.segments[0].ident.name == "rust" { if path.segments.len() == 1 &&
path.segments[0].ident.name == sym::rust {
fatally_break_rust(self.tcx.sess); fatally_break_rust(self.tcx.sess);
} }
} }

View File

@ -2594,7 +2594,7 @@ fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> Codegen
} }
codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| { codegen_fn_attrs.inline = attrs.iter().fold(InlineAttr::None, |ia, attr| {
if attr.path != "inline" { if attr.path != sym::inline {
return ia; return ia;
} }
match attr.meta().map(|i| i.node) { match attr.meta().map(|i| i.node) {
@ -2634,7 +2634,7 @@ fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> Codegen
}); });
codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| { codegen_fn_attrs.optimize = attrs.iter().fold(OptimizeAttr::None, |ia, attr| {
if attr.path != "optimize" { if attr.path != sym::optimize {
return ia; return ia;
} }
let err = |sp, s| span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s); let err = |sp, s| span_err!(tcx.sess.diagnostic(), sp, E0722, "{}", s);

View File

@ -7,7 +7,7 @@ use std::mem;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use std::ops; use std::ops;
use syntax::symbol::Symbol; use syntax::symbol::{Symbol, sym};
use syntax::ast::{MetaItem, MetaItemKind, NestedMetaItem, LitKind}; use syntax::ast::{MetaItem, MetaItemKind, NestedMetaItem, LitKind};
use syntax::parse::ParseSess; use syntax::parse::ParseSess;
use syntax::feature_gate::Features; use syntax::feature_gate::Features;
@ -186,7 +186,7 @@ impl Cfg {
fn should_use_with_in_description(&self) -> bool { fn should_use_with_in_description(&self) -> bool {
match *self { match *self {
Cfg::Cfg(ref name, _) if name == &"target_feature" => true, Cfg::Cfg(name, _) if name == sym::target_feature => true,
_ => false, _ => false,
} }
} }

View File

@ -4383,7 +4383,7 @@ where
// Start of code copied from rust-clippy // Start of code copied from rust-clippy
pub fn path_to_def_local(tcx: TyCtxt<'_, '_, '_>, path: &[&str]) -> Option<DefId> { pub fn path_to_def_local(tcx: TyCtxt<'_, '_, '_>, path: &[Symbol]) -> Option<DefId> {
let krate = tcx.hir().krate(); let krate = tcx.hir().krate();
let mut items = krate.module.item_ids.clone(); let mut items = krate.module.item_ids.clone();
let mut path_it = path.iter().peekable(); let mut path_it = path.iter().peekable();
@ -4408,7 +4408,7 @@ pub fn path_to_def_local(tcx: TyCtxt<'_, '_, '_>, path: &[&str]) -> Option<DefId
} }
} }
pub fn path_to_def(tcx: TyCtxt<'_, '_, '_>, path: &[&str]) -> Option<DefId> { pub fn path_to_def(tcx: TyCtxt<'_, '_, '_>, path: &[Symbol]) -> Option<DefId> {
let crates = tcx.crates(); let crates = tcx.crates();
let krate = crates let krate = crates

View File

@ -368,9 +368,9 @@ pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOpt
}; };
let send_trait = if crate_name == Some("core".to_string()) { let send_trait = if crate_name == Some("core".to_string()) {
clean::path_to_def_local(tcx, &["marker", "Send"]) clean::path_to_def_local(tcx, &[sym::marker, sym::Send])
} else { } else {
clean::path_to_def(tcx, &["core", "marker", "Send"]) clean::path_to_def(tcx, &[sym::core, sym::marker, sym::Send])
}; };
let mut renderinfo = RenderInfo::default(); let mut renderinfo = RenderInfo::default();

View File

@ -99,7 +99,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
// Try looking for methods and associated items. // Try looking for methods and associated items.
let mut split = path_str.rsplitn(2, "::"); let mut split = path_str.rsplitn(2, "::");
let item_name = if let Some(first) = split.next() { let item_name = if let Some(first) = split.next() {
first Symbol::intern(first)
} else { } else {
return Err(()) return Err(())
}; };

View File

@ -81,12 +81,6 @@ impl PartialEq<Symbol> for Path {
} }
} }
impl<'a> PartialEq<&'a str> for Path {
fn eq(&self, string: &&'a str) -> bool {
self.segments.len() == 1 && self.segments[0].ident.name == *string
}
}
impl fmt::Debug for Path { impl fmt::Debug for Path {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "path({})", pprust::path_to_string(self)) write!(f, "path({})", pprust::path_to_string(self))

View File

@ -185,12 +185,12 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
'outer: for attr in attrs_iter { 'outer: for attr in attrs_iter {
if ![ if ![
"rustc_deprecated", sym::rustc_deprecated,
"rustc_const_unstable", sym::rustc_const_unstable,
"unstable", sym::unstable,
"stable", sym::stable,
"rustc_promotable", sym::rustc_promotable,
"rustc_allow_const_fn_ptr", sym::rustc_allow_const_fn_ptr,
].iter().any(|&s| attr.path == s) { ].iter().any(|&s| attr.path == s) {
continue // not a stability level continue // not a stability level
} }
@ -199,10 +199,10 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
let meta = attr.meta(); let meta = attr.meta();
if attr.path == "rustc_promotable" { if attr.path == sym::rustc_promotable {
promotable = true; promotable = true;
} }
if attr.path == "rustc_allow_const_fn_ptr" { if attr.path == sym::rustc_allow_const_fn_ptr {
allow_const_fn_ptr = true; allow_const_fn_ptr = true;
} }
// attributes with data // attributes with data
@ -721,7 +721,7 @@ pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
let mut acc = Vec::new(); let mut acc = Vec::new();
let diagnostic = &sess.span_diagnostic; let diagnostic = &sess.span_diagnostic;
if attr.path == "repr" { if attr.path == sym::repr {
if let Some(items) = attr.meta_item_list() { if let Some(items) = attr.meta_item_list() {
mark_used(attr); mark_used(attr);
for item in items { for item in items {
@ -770,14 +770,14 @@ pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
}; };
let mut literal_error = None; let mut literal_error = None;
if name == "align" { if name == sym::align {
recognised = true; recognised = true;
match parse_alignment(&value.node) { match parse_alignment(&value.node) {
Ok(literal) => acc.push(ReprAlign(literal)), Ok(literal) => acc.push(ReprAlign(literal)),
Err(message) => literal_error = Some(message) Err(message) => literal_error = Some(message)
}; };
} }
else if name == "packed" { else if name == sym::packed {
recognised = true; recognised = true;
match parse_alignment(&value.node) { match parse_alignment(&value.node) {
Ok(literal) => acc.push(ReprPacked(literal)), Ok(literal) => acc.push(ReprPacked(literal)),

View File

@ -19,7 +19,7 @@ pub fn entry_point_type(item: &Item, depth: usize) -> EntryPointType {
EntryPointType::Start EntryPointType::Start
} else if attr::contains_name(&item.attrs, sym::main) { } else if attr::contains_name(&item.attrs, sym::main) {
EntryPointType::MainAttr EntryPointType::MainAttr
} else if item.ident.name == "main" { } else if item.ident.name == sym::main {
if depth == 1 { if depth == 1 {
// This is a top-level function so can be 'main' // This is a top-level function so can be 'main'
EntryPointType::MainNamed EntryPointType::MainNamed

View File

@ -10,7 +10,7 @@ use crate::mut_visit::{self, MutVisitor};
use crate::parse::{self, parser, DirectoryOwnership}; use crate::parse::{self, parser, DirectoryOwnership};
use crate::parse::token; use crate::parse::token;
use crate::ptr::P; use crate::ptr::P;
use crate::symbol::{keywords, Ident, Symbol}; use crate::symbol::{keywords, Ident, Symbol, sym};
use crate::ThinVec; use crate::ThinVec;
use crate::tokenstream::{self, TokenStream}; use crate::tokenstream::{self, TokenStream};
@ -871,7 +871,7 @@ impl<'a> ExtCtxt<'a> {
let mut last_macro = None; let mut last_macro = None;
loop { loop {
if ctxt.outer().expn_info().map_or(None, |info| { if ctxt.outer().expn_info().map_or(None, |info| {
if info.format.name() == "include" { if info.format.name() == sym::include {
// Stop going up the backtrace once include! is encountered // Stop going up the backtrace once include! is encountered
return None; return None;
} }

View File

@ -4,7 +4,7 @@ use crate::source_map::{hygiene, ExpnInfo, ExpnFormat};
use crate::ext::base::ExtCtxt; use crate::ext::base::ExtCtxt;
use crate::ext::build::AstBuilder; use crate::ext::build::AstBuilder;
use crate::parse::parser::PathStyle; use crate::parse::parser::PathStyle;
use crate::symbol::Symbol; use crate::symbol::{Symbol, sym};
use syntax_pos::Span; use syntax_pos::Span;
@ -13,7 +13,7 @@ use rustc_data_structures::fx::FxHashSet;
pub fn collect_derives(cx: &mut ExtCtxt<'_>, attrs: &mut Vec<ast::Attribute>) -> Vec<ast::Path> { pub fn collect_derives(cx: &mut ExtCtxt<'_>, attrs: &mut Vec<ast::Attribute>) -> Vec<ast::Path> {
let mut result = Vec::new(); let mut result = Vec::new();
attrs.retain(|attr| { attrs.retain(|attr| {
if attr.path != "derive" { if attr.path != sym::derive {
return true; return true;
} }
if !attr.is_meta_item_list() { if !attr.is_meta_item_list() {

View File

@ -376,7 +376,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
} }
let mut item = self.fully_configure(item); let mut item = self.fully_configure(item);
item.visit_attrs(|attrs| attrs.retain(|a| a.path != "derive")); item.visit_attrs(|attrs| attrs.retain(|a| a.path != sym::derive));
let mut item_with_markers = item.clone(); let mut item_with_markers = item.clone();
add_derived_markers(&mut self.cx, item.span(), &traits, &mut item_with_markers); add_derived_markers(&mut self.cx, item.span(), &traits, &mut item_with_markers);
let derives = derives.entry(invoc.expansion_data.mark).or_default(); let derives = derives.entry(invoc.expansion_data.mark).or_default();
@ -1109,7 +1109,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
-> Option<ast::Attribute> { -> Option<ast::Attribute> {
let attr = attrs.iter() let attr = attrs.iter()
.position(|a| { .position(|a| {
if a.path == "derive" { if a.path == sym::derive {
*after_derive = true; *after_derive = true;
} }
!attr::is_known(a) && !is_builtin_attr(a) !attr::is_known(a) && !is_builtin_attr(a)
@ -1117,7 +1117,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
.map(|i| attrs.remove(i)); .map(|i| attrs.remove(i));
if let Some(attr) = &attr { if let Some(attr) = &attr {
if !self.cx.ecfg.enable_custom_inner_attributes() && if !self.cx.ecfg.enable_custom_inner_attributes() &&
attr.style == ast::AttrStyle::Inner && attr.path != "test" { attr.style == ast::AttrStyle::Inner && attr.path != sym::test {
emit_feature_err(&self.cx.parse_sess, sym::custom_inner_attributes, emit_feature_err(&self.cx.parse_sess, sym::custom_inner_attributes,
attr.span, GateIssue::Language, attr.span, GateIssue::Language,
"non-builtin inner attributes are unstable"); "non-builtin inner attributes are unstable");
@ -1167,7 +1167,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
self.check_attribute_inner(attr, features); self.check_attribute_inner(attr, features);
// macros are expanded before any lint passes so this warning has to be hardcoded // macros are expanded before any lint passes so this warning has to be hardcoded
if attr.path == "derive" { if attr.path == sym::derive {
self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations") self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
.note("this may become a hard error in a future release") .note("this may become a hard error in a future release")
.emit(); .emit();

View File

@ -13,7 +13,7 @@ use crate::parse::{Directory, ParseSess};
use crate::parse::parser::Parser; use crate::parse::parser::Parser;
use crate::parse::token::{self, NtTT}; use crate::parse::token::{self, NtTT};
use crate::parse::token::Token::*; use crate::parse::token::Token::*;
use crate::symbol::{Symbol, sym}; use crate::symbol::{Symbol, keywords, sym};
use crate::tokenstream::{DelimSpan, TokenStream, TokenTree}; use crate::tokenstream::{DelimSpan, TokenStream, TokenTree};
use errors::FatalError; use errors::FatalError;
@ -467,7 +467,7 @@ fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool {
TokenTree::Sequence(span, ref seq) => { TokenTree::Sequence(span, ref seq) => {
if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| { if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| {
match *seq_tt { match *seq_tt {
TokenTree::MetaVarDecl(_, _, id) => id.name == "vis", TokenTree::MetaVarDecl(_, _, id) => id.name == sym::vis,
TokenTree::Sequence(_, ref sub_seq) => TokenTree::Sequence(_, ref sub_seq) =>
sub_seq.op == quoted::KleeneOp::ZeroOrMore sub_seq.op == quoted::KleeneOp::ZeroOrMore
|| sub_seq.op == quoted::KleeneOp::ZeroOrOne, || sub_seq.op == quoted::KleeneOp::ZeroOrOne,
@ -1046,7 +1046,8 @@ fn is_in_follow(tok: &quoted::TokenTree, frag: &str) -> IsInFollow {
match *tok { match *tok {
TokenTree::Token(_, ref tok) => match *tok { TokenTree::Token(_, ref tok) => match *tok {
FatArrow | Comma | Eq | BinOp(token::Or) => IsInFollow::Yes, FatArrow | Comma | Eq | BinOp(token::Or) => IsInFollow::Yes,
Ident(i, false) if i.name == "if" || i.name == "in" => IsInFollow::Yes, Ident(i, false) if i.name == keywords::If.name() ||
i.name == keywords::In.name() => IsInFollow::Yes,
_ => IsInFollow::No(tokens), _ => IsInFollow::No(tokens),
}, },
_ => IsInFollow::No(tokens), _ => IsInFollow::No(tokens),
@ -1063,10 +1064,12 @@ fn is_in_follow(tok: &quoted::TokenTree, frag: &str) -> IsInFollow {
OpenDelim(token::DelimToken::Bracket) | OpenDelim(token::DelimToken::Bracket) |
Comma | FatArrow | Colon | Eq | Gt | BinOp(token::Shr) | Semi | Comma | FatArrow | Colon | Eq | Gt | BinOp(token::Shr) | Semi |
BinOp(token::Or) => IsInFollow::Yes, BinOp(token::Or) => IsInFollow::Yes,
Ident(i, false) if i.name == "as" || i.name == "where" => IsInFollow::Yes, Ident(i, false) if i.name == keywords::As.name() ||
i.name == keywords::Where.name() => IsInFollow::Yes,
_ => IsInFollow::No(tokens), _ => IsInFollow::No(tokens),
}, },
TokenTree::MetaVarDecl(_, _, frag) if frag.name == "block" => IsInFollow::Yes, TokenTree::MetaVarDecl(_, _, frag) if frag.name == sym::block =>
IsInFollow::Yes,
_ => IsInFollow::No(tokens), _ => IsInFollow::No(tokens),
} }
}, },
@ -1089,16 +1092,18 @@ fn is_in_follow(tok: &quoted::TokenTree, frag: &str) -> IsInFollow {
match *tok { match *tok {
TokenTree::Token(_, ref tok) => match *tok { TokenTree::Token(_, ref tok) => match *tok {
Comma => IsInFollow::Yes, Comma => IsInFollow::Yes,
Ident(i, is_raw) if is_raw || i.name != "priv" => IsInFollow::Yes, Ident(i, is_raw) if is_raw || i.name != keywords::Priv.name() =>
IsInFollow::Yes,
ref tok => if tok.can_begin_type() { ref tok => if tok.can_begin_type() {
IsInFollow::Yes IsInFollow::Yes
} else { } else {
IsInFollow::No(tokens) IsInFollow::No(tokens)
} }
}, },
TokenTree::MetaVarDecl(_, _, frag) if frag.name == "ident" TokenTree::MetaVarDecl(_, _, frag) if frag.name == sym::ident
|| frag.name == "ty" || frag.name == sym::ty
|| frag.name == "path" => IsInFollow::Yes, || frag.name == sym::path =>
IsInFollow::Yes,
_ => IsInFollow::No(tokens), _ => IsInFollow::No(tokens),
} }
}, },

View File

@ -22,13 +22,13 @@ use crate::source_map::Spanned;
use crate::edition::{ALL_EDITIONS, Edition}; use crate::edition::{ALL_EDITIONS, Edition};
use crate::visit::{self, FnKind, Visitor}; use crate::visit::{self, FnKind, Visitor};
use crate::parse::{token, ParseSess}; use crate::parse::{token, ParseSess};
use crate::symbol::Symbol; use crate::symbol::{Symbol, keywords, sym};
use crate::tokenstream::TokenTree; use crate::tokenstream::TokenTree;
use errors::{DiagnosticBuilder, Handler}; use errors::{DiagnosticBuilder, Handler};
use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::fx::FxHashMap;
use rustc_target::spec::abi::Abi; use rustc_target::spec::abi::Abi;
use syntax_pos::{Span, DUMMY_SP, sym}; use syntax_pos::{Span, DUMMY_SP};
use log::debug; use log::debug;
use lazy_static::lazy_static; use lazy_static::lazy_static;
@ -562,9 +562,9 @@ declare_features! (
// Some features are known to be incomplete and using them is likely to have // Some features are known to be incomplete and using them is likely to have
// unanticipated results, such as compiler crashes. We warn the user about these // unanticipated results, such as compiler crashes. We warn the user about these
// to alert them. // to alert them.
const INCOMPLETE_FEATURES: &[&str] = &[ const INCOMPLETE_FEATURES: &[Symbol] = &[
"generic_associated_types", sym::generic_associated_types,
"const_generics" sym::const_generics
]; ];
declare_features! ( declare_features! (
@ -1947,7 +1947,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
fn visit_item(&mut self, i: &'a ast::Item) { fn visit_item(&mut self, i: &'a ast::Item) {
match i.node { match i.node {
ast::ItemKind::Const(_,_) => { ast::ItemKind::Const(_,_) => {
if i.ident.name == "_" { if i.ident.name == keywords::Underscore.name() {
gate_feature_post!(&self, underscore_const_names, i.span, gate_feature_post!(&self, underscore_const_names, i.span,
"naming constants with `_` is unstable"); "naming constants with `_` is unstable");
} }
@ -2304,7 +2304,7 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
if edition <= crate_edition { if edition <= crate_edition {
// The `crate_edition` implies its respective umbrella feature-gate // The `crate_edition` implies its respective umbrella feature-gate
// (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX). // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
edition_enabled_features.insert(Symbol::intern(edition.feature_name()), edition); edition_enabled_features.insert(edition.feature_name(), edition);
} }
} }
@ -2335,7 +2335,7 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
} }
let name = mi.name_or_empty(); let name = mi.name_or_empty();
if INCOMPLETE_FEATURES.iter().any(|f| name == *f) { if INCOMPLETE_FEATURES.iter().any(|f| name == f.as_str()) {
span_handler.struct_span_warn( span_handler.struct_span_warn(
mi.span(), mi.span(),
&format!( &format!(
@ -2345,7 +2345,7 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
).emit(); ).emit();
} }
if let Some(edition) = ALL_EDITIONS.iter().find(|e| name == e.feature_name()) { if let Some(edition) = ALL_EDITIONS.iter().find(|e| name == e.feature_name().as_str()) {
if *edition <= crate_edition { if *edition <= crate_edition {
continue; continue;
} }

View File

@ -391,6 +391,8 @@ mod tests {
#[test] #[test]
fn string_to_tts_macro () { fn string_to_tts_macro () {
with_globals(|| { with_globals(|| {
use crate::symbol::sym;
let tts: Vec<_> = let tts: Vec<_> =
string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect(); string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
let tts: &[TokenTree] = &tts[..]; let tts: &[TokenTree] = &tts[..];
@ -403,8 +405,8 @@ mod tests {
Some(&TokenTree::Token(_, token::Ident(name_zip, false))), Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)), Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
) )
if name_macro_rules.name == "macro_rules" if name_macro_rules.name == sym::macro_rules
&& name_zip.name == "zip" => { && name_zip.name.as_str() == "zip" => {
let tts = &macro_tts.trees().collect::<Vec<_>>(); let tts = &macro_tts.trees().collect::<Vec<_>>();
match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) { match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
( (
@ -421,7 +423,7 @@ mod tests {
Some(&TokenTree::Token(_, token::Dollar)), Some(&TokenTree::Token(_, token::Dollar)),
Some(&TokenTree::Token(_, token::Ident(ident, false))), Some(&TokenTree::Token(_, token::Ident(ident, false))),
) )
if first_delim == token::Paren && ident.name == "a" => {}, if first_delim == token::Paren && ident.name.as_str() == "a" => {},
_ => panic!("value 3: {:?} {:?}", first_delim, first_tts), _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
} }
let tts = &second_tts.trees().collect::<Vec<_>>(); let tts = &second_tts.trees().collect::<Vec<_>>();
@ -431,7 +433,7 @@ mod tests {
Some(&TokenTree::Token(_, token::Dollar)), Some(&TokenTree::Token(_, token::Dollar)),
Some(&TokenTree::Token(_, token::Ident(ident, false))), Some(&TokenTree::Token(_, token::Ident(ident, false))),
) )
if second_delim == token::Paren && ident.name == "a" => {}, if second_delim == token::Paren && ident.name.as_str() == "a" => {},
_ => panic!("value 4: {:?} {:?}", second_delim, second_tts), _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
} }
}, },
@ -584,13 +586,13 @@ mod tests {
let item = parse_item_from_source_str(name_1, source, &sess) let item = parse_item_from_source_str(name_1, source, &sess)
.unwrap().unwrap(); .unwrap().unwrap();
let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap(); let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap();
assert_eq!(doc, "/// doc comment"); assert_eq!(doc.as_str(), "/// doc comment");
let name_2 = FileName::Custom("crlf_source_2".to_string()); let name_2 = FileName::Custom("crlf_source_2".to_string());
let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string(); let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
let item = parse_item_from_source_str(name_2, source, &sess) let item = parse_item_from_source_str(name_2, source, &sess)
.unwrap().unwrap(); .unwrap().unwrap();
let docs = item.attrs.iter().filter(|a| a.path == "doc") let docs = item.attrs.iter().filter(|a| a.path == sym::doc)
.map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>(); .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()]; let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
assert_eq!(&docs[..], b); assert_eq!(&docs[..], b);
@ -599,7 +601,7 @@ mod tests {
let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string(); let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap(); let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap(); let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap();
assert_eq!(doc, "/** doc comment\n * with CRLF */"); assert_eq!(doc.as_str(), "/** doc comment\n * with CRLF */");
}); });
} }

View File

@ -5099,7 +5099,7 @@ impl<'a> Parser<'a> {
(ident, ast::MacroDef { tokens: tokens.into(), legacy: false }) (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
} }
token::Ident(ident, _) if ident.name == "macro_rules" && token::Ident(ident, _) if ident.name == sym::macro_rules &&
self.look_ahead(1, |t| *t == token::Not) => { self.look_ahead(1, |t| *t == token::Not) => {
let prev_span = self.prev_span; let prev_span = self.prev_span;
self.complain_if_pub_macro(&vis.node, prev_span); self.complain_if_pub_macro(&vis.node, prev_span);

View File

@ -35,6 +35,9 @@ pub fn injected_crate_name() -> Option<&'static str> {
} }
thread_local! { thread_local! {
// A `Symbol` might make more sense here, but it doesn't work, probably for
// reasons relating to the use of thread-local storage for the Symbol
// interner.
static INJECTED_CRATE_NAME: Cell<Option<&'static str>> = Cell::new(None); static INJECTED_CRATE_NAME: Cell<Option<&'static str>> = Cell::new(None);
} }

View File

@ -272,7 +272,8 @@ fn generate_test_harness(sess: &ParseSess,
test_cases: Vec::new(), test_cases: Vec::new(),
reexport_test_harness_main, reexport_test_harness_main,
// N.B., doesn't consider the value of `--crate-name` passed on the command line. // N.B., doesn't consider the value of `--crate-name` passed on the command line.
is_libtest: attr::find_crate_name(&krate.attrs).map(|s| s == "test").unwrap_or(false), is_libtest: attr::find_crate_name(&krate.attrs)
.map(|s| s == sym::test).unwrap_or(false),
toplevel_reexport: None, toplevel_reexport: None,
ctxt: SyntaxContext::empty().apply_mark(mark), ctxt: SyntaxContext::empty().apply_mark(mark),
features, features,

View File

@ -39,7 +39,7 @@ impl State {
} }
} }
const OPTIONS: &[&str] = &["volatile", "alignstack", "intel"]; const OPTIONS: &[Symbol] = &[sym::volatile, sym::alignstack, sym::intel];
pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt<'_>, pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt<'_>,
sp: Span, sp: Span,
@ -233,13 +233,13 @@ fn parse_inline_asm<'a>(
Options => { Options => {
let (option, _) = p.parse_str()?; let (option, _) = p.parse_str()?;
if option == "volatile" { if option == sym::volatile {
// Indicates that the inline assembly has side effects // Indicates that the inline assembly has side effects
// and must not be optimized out along with its outputs. // and must not be optimized out along with its outputs.
volatile = true; volatile = true;
} else if option == "alignstack" { } else if option == sym::alignstack {
alignstack = true; alignstack = true;
} else if option == "intel" { } else if option == sym::intel {
dialect = AsmDialect::Intel; dialect = AsmDialect::Intel;
} else { } else {
cx.span_warn(p.prev_span, "unrecognized option"); cx.span_warn(p.prev_span, "unrecognized option");

View File

@ -6,7 +6,7 @@ use syntax::ext::base::{Annotatable, ExtCtxt, SyntaxExtension, Resolver};
use syntax::ext::build::AstBuilder; use syntax::ext::build::AstBuilder;
use syntax::ext::hygiene::{Mark, SyntaxContext}; use syntax::ext::hygiene::{Mark, SyntaxContext};
use syntax::ptr::P; use syntax::ptr::P;
use syntax::symbol::Symbol; use syntax::symbol::{Symbol, sym};
use syntax_pos::Span; use syntax_pos::Span;
macro path_local($x:ident) { macro path_local($x:ident) {
@ -139,7 +139,7 @@ fn call_intrinsic(cx: &ExtCtxt<'_>,
let intrinsic_allowed_via_allow_internal_unstable = cx let intrinsic_allowed_via_allow_internal_unstable = cx
.current_expansion.mark.expn_info().unwrap() .current_expansion.mark.expn_info().unwrap()
.allow_internal_unstable.map_or(false, |features| features.iter().any(|&s| .allow_internal_unstable.map_or(false, |features| features.iter().any(|&s|
s == "core_intrinsics" s == sym::core_intrinsics
)); ));
if intrinsic_allowed_via_allow_internal_unstable { if intrinsic_allowed_via_allow_internal_unstable {
span = span.with_ctxt(cx.backtrace()); span = span.with_ctxt(cx.backtrace());

View File

@ -1,3 +1,4 @@
use crate::symbol::{Symbol, sym};
use std::fmt; use std::fmt;
use std::str::FromStr; use std::str::FromStr;
@ -44,10 +45,10 @@ impl Edition {
} }
} }
pub fn feature_name(&self) -> &'static str { pub fn feature_name(&self) -> Symbol {
match *self { match *self {
Edition::Edition2015 => "rust_2015_preview", Edition::Edition2015 => sym::rust_2015_preview,
Edition::Edition2018 => "rust_2018_preview", Edition::Edition2018 => sym::rust_2018_preview,
} }
} }

View File

@ -393,7 +393,7 @@ impl Span {
Some(info) => info Some(info) => info
.allow_internal_unstable .allow_internal_unstable
.map_or(false, |features| features.iter().any(|&f| .map_or(false, |features| features.iter().any(|&f|
f == feature || f == "allow_internal_unstable_backcompat_hack" f == feature || f == sym::allow_internal_unstable_backcompat_hack
)), )),
None => false, None => false,
} }

View File

@ -822,12 +822,6 @@ impl Decodable for Symbol {
} }
} }
impl<T: std::ops::Deref<Target=str>> PartialEq<T> for Symbol {
fn eq(&self, other: &T) -> bool {
self.as_str() == other.deref()
}
}
// The `&'static str`s in this type actually point into the arena. // The `&'static str`s in this type actually point into the arena.
// //
// Note that normal symbols are indexed upward from 0, and gensyms are indexed // Note that normal symbols are indexed upward from 0, and gensyms are indexed

View File

@ -20,7 +20,7 @@ declare_lint_pass!(Pass => [TEST_LINT]);
impl EarlyLintPass for Pass { impl EarlyLintPass for Pass {
fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) { fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) {
if it.ident.name == "lintme" { if it.ident.name.as_str() == "lintme" {
cx.span_lint(TEST_LINT, it.span, "item is named 'lintme'"); cx.span_lint(TEST_LINT, it.span, "item is named 'lintme'");
} }
} }

View File

@ -23,10 +23,10 @@ declare_lint_pass!(Pass => [TEST_LINT, TEST_GROUP]);
impl EarlyLintPass for Pass { impl EarlyLintPass for Pass {
fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) { fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) {
if it.ident.name == "lintme" { if it.ident.name.as_str() == "lintme" {
cx.span_lint(TEST_LINT, it.span, "item is named 'lintme'"); cx.span_lint(TEST_LINT, it.span, "item is named 'lintme'");
} }
if it.ident.name == "lintmetoo" { if it.ident.name.as_str() == "lintmetoo" {
cx.span_lint(TEST_GROUP, it.span, "item is named 'lintmetoo'"); cx.span_lint(TEST_GROUP, it.span, "item is named 'lintmetoo'");
} }
} }