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;
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.
sess: &'a Session,
@ -164,8 +164,8 @@ pub trait Resolver {
fn resolve_str_path(
&mut self,
span: Span,
crate_root: Option<&str>,
components: &[&str],
crate_root: Option<Symbol>,
components: &[Symbol],
is_value: bool,
) -> hir::Path;
}
@ -228,7 +228,7 @@ pub fn lower_crate(
dep_graph.assert_ignored();
LoweringContext {
crate_root: std_inject::injected_crate_name(),
crate_root: std_inject::injected_crate_name().map(Symbol::intern),
sess,
cstore,
resolver,
@ -1149,7 +1149,7 @@ impl<'a> LoweringContext<'a> {
].into()),
);
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])
}
@ -2548,7 +2548,7 @@ impl<'a> LoweringContext<'a> {
// ::std::future::Future<future_params>
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::PolyTraitRef {
@ -4194,7 +4194,7 @@ impl<'a> LoweringContext<'a> {
|x: P<hir::Expr>| x.into_inner(),
);
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)
})
}
@ -4336,7 +4336,7 @@ impl<'a> LoweringContext<'a> {
self.expr_call_std_assoc_fn(
id,
e.span,
&["ops", "RangeInclusive"],
&[sym::ops, sym::RangeInclusive],
"new",
hir_vec![e1, e2],
)
@ -4345,11 +4345,11 @@ impl<'a> LoweringContext<'a> {
use syntax::ast::RangeLimits::*;
let path = match (e1, e2, lims) {
(&None, &None, HalfOpen) => "RangeFull",
(&Some(..), &None, HalfOpen) => "RangeFrom",
(&None, &Some(..), HalfOpen) => "RangeTo",
(&Some(..), &Some(..), HalfOpen) => "Range",
(&None, &Some(..), Closed) => "RangeToInclusive",
(&None, &None, HalfOpen) => sym::RangeFull,
(&Some(..), &None, HalfOpen) => sym::RangeFrom,
(&None, &Some(..), HalfOpen) => sym::RangeTo,
(&Some(..), &Some(..), HalfOpen) => sym::Range,
(&None, &Some(..), Closed) => sym::RangeToInclusive,
(&Some(..), &Some(..), Closed) => unreachable!(),
(_, &None, Closed) => self.diagnostic()
.span_fatal(e.span, "inclusive range with no end")
@ -4367,7 +4367,7 @@ impl<'a> LoweringContext<'a> {
.collect::<P<[hir::Field]>>();
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 = hir::QPath::Resolved(None, P(struct_path));
@ -4656,7 +4656,7 @@ impl<'a> LoweringContext<'a> {
let match_expr = {
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 next_path = &["iter", "Iterator", "next"];
let next_path = &[sym::iter, sym::Iterator, sym::next];
let next_expr = P(self.expr_call_std_path(
head_sp,
next_path,
@ -4723,7 +4723,8 @@ impl<'a> LoweringContext<'a> {
// `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
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(
head_sp,
into_iter_path,
@ -4780,7 +4781,7 @@ impl<'a> LoweringContext<'a> {
// expand <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(
unstable_span,
path,
@ -4822,12 +4823,12 @@ impl<'a> LoweringContext<'a> {
let err_ident = self.str_to_ident("err");
let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
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);
self.expr_call_std_path(try_span, from_path, hir_vec![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 catch_scope = self.catch_scopes.last().map(|x| *x);
let ret_expr = if let Some(catch_node) = catch_scope {
@ -5057,7 +5058,7 @@ impl<'a> LoweringContext<'a> {
fn expr_call_std_path(
&mut self,
span: Span,
path_components: &[&str],
path_components: &[Symbol],
args: hir::HirVec<hir::Expr>,
) -> hir::Expr {
let path = P(self.expr_std_path(span, path_components, None, ThinVec::new()));
@ -5077,7 +5078,7 @@ impl<'a> LoweringContext<'a> {
&mut self,
ty_path_id: hir::HirId,
span: Span,
ty_path_components: &[&str],
ty_path_components: &[Symbol],
assoc_fn_name: &str,
args: hir::HirVec<hir::Expr>,
) -> hir::ExprKind {
@ -5119,7 +5120,7 @@ impl<'a> LoweringContext<'a> {
fn expr_std_path(
&mut self,
span: Span,
components: &[&str],
components: &[Symbol],
params: Option<P<hir::GenericArgs>>,
attrs: ThinVec<Attribute>,
) -> hir::Expr {
@ -5250,25 +5251,25 @@ impl<'a> LoweringContext<'a> {
}
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> {
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> {
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> {
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(
&mut self,
span: Span,
components: &[&str],
components: &[Symbol],
subpats: hir::HirVec<P<hir::Pat>>,
) -> P<hir::Pat> {
let path = self.std_path(span, components, None, true);
@ -5321,7 +5322,7 @@ impl<'a> LoweringContext<'a> {
fn std_path(
&mut self,
span: Span,
components: &[&str],
components: &[Symbol],
params: Option<P<hir::GenericArgs>>,
is_value: bool,
) -> hir::Path {
@ -5520,11 +5521,11 @@ impl<'a> LoweringContext<'a> {
fn wrap_in_try_constructor(
&mut self,
method: &'static str,
method: Symbol,
e: hir::Expr,
unstable_span: Span,
) -> 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,
ThinVec::new()));
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(
pin_ty_id,
span,
&["pin", "Pin"],
&[sym::pin, sym::Pin],
"new_unchecked",
hir_vec![ref_mut_pinned],
);
@ -5602,7 +5603,7 @@ impl<'a> LoweringContext<'a> {
let unsafe_expr = self.expr_unsafe(new_unchecked);
P(self.expr_call_std_path(
gen_future_span,
&["future", "poll_with_tls_context"],
&[sym::future, sym::poll_with_tls_context],
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 ready_pat = self.pat_std_enum(
span,
&["task", "Poll", "Ready"],
&[sym::task, sym::Poll, sym::Ready],
hir_vec![x_pat],
);
let break_x = self.with_loop_scope(loop_node_id, |this| {
@ -5633,7 +5634,7 @@ impl<'a> LoweringContext<'a> {
let pending_arm = {
let pending_pat = self.pat_std_enum(
span,
&["task", "Poll", "Pending"],
&[sym::task, sym::Poll, sym::Pending],
hir_vec![],
);
let empty_block = P(self.expr_block_empty(span));

View File

@ -1146,7 +1146,7 @@ impl<'a> NodesMatchingSuffix<'a> {
None => return false,
Some((node_id, name)) => (node_id, name),
};
if mod_name != &**part {
if mod_name.as_str() != *part {
return false;
}
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
// id; do their names match what I am seeking?
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 {

View File

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

View File

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

View File

@ -76,7 +76,7 @@ impl<'a, 'tcx> LibFeatureCollector<'a, 'tcx> {
// This additional check for stability is to make sure we
// don't emit additional, irrelevant errors for malformed
// attributes.
if *stab_attr != "stable" || since.is_some() {
if *stab_attr != sym::stable || since.is_some() {
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
// compiling a compiler crate), then let this missing feature
// 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 {
return EvalResult::Allow;
}

View File

@ -6,7 +6,7 @@ use crate::middle::lang_items;
use rustc_data_structures::fx::FxHashSet;
use rustc_target::spec::PanicStrategy;
use syntax::ast;
use syntax::symbol::Symbol;
use syntax::symbol::{Symbol, sym};
use syntax_pos::Span;
use crate::hir::def_id::DefId;
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> {
lang_items::extract(attrs).and_then(|(name, _)| {
$(if name == stringify!($name) {
Some(Symbol::intern(stringify!($sym)))
$(if name == sym::$name {
Some(sym::$sym)
} else)* {
None
}

View File

@ -2753,6 +2753,7 @@ mod tests {
// another --cfg test
#[test]
fn test_switch_implies_cfg_test_unless_cfg_test() {
use syntax::symbol::sym;
syntax::with_globals(|| {
let matches = &match optgroups().parse(&["--test".to_string(),
"--cfg=test".to_string()]) {
@ -2763,7 +2764,7 @@ mod tests {
let (sessopts, cfg) = build_session_options_and_crate_config(matches);
let sess = build_session(sessopts, None, registry);
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_none());
});

View File

@ -19,6 +19,7 @@ use crate::mir::interpret::{GlobalId, ConstValue};
use rustc_data_structures::snapshot_map::{Snapshot, SnapshotMap};
use rustc_macros::HashStable;
use syntax::ast::Ident;
use syntax::symbol::sym;
use crate::ty::subst::{Subst, InternalSubsts};
use crate::ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt};
use crate::ty::fold::{TypeFoldable, TypeFolder};
@ -1318,9 +1319,9 @@ fn confirm_generator_candidate<'cx, 'gcx, 'tcx>(
gen_sig)
.map_bound(|(trait_ref, yield_ty, return_ty)| {
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
} else if name == "Yield" {
} else if name == sym::Yield {
yield_ty
} else {
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,
sym::windows_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 \
`windows` and `console` are allowed",
subsystem));

View File

@ -56,7 +56,7 @@ pub fn find_crate_name(sess: Option<&Session>,
if let Some(sess) = sess {
if let Some(ref s) = sess.opts.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 \
required to match, but `{}` != `{}`",
s, name);

View File

@ -63,6 +63,7 @@ use syntax::ast;
use syntax::source_map::FileLoader;
use syntax::feature_gate::{GatedCfg, UnstableFeatures};
use syntax::parse::{self, PResult};
use syntax::symbol::sym;
use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
pub mod pretty;
@ -669,7 +670,7 @@ impl RustcDefaultCalls {
// through to build scripts.
let value = value.as_ref().map(|s| s.as_str());
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() {
return None
}

View File

@ -497,22 +497,22 @@ pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<c
.filter_map(|a| {
if a.check_name(sym::crate_type) {
match a.value_str() {
Some(ref n) if *n == "rlib" => Some(config::CrateType::Rlib),
Some(ref n) if *n == "dylib" => Some(config::CrateType::Dylib),
Some(ref n) if *n == "cdylib" => Some(config::CrateType::Cdylib),
Some(ref n) if *n == "lib" => Some(config::default_lib_output()),
Some(ref n) if *n == "staticlib" => Some(config::CrateType::Staticlib),
Some(ref n) if *n == "proc-macro" => Some(config::CrateType::ProcMacro),
Some(ref n) if *n == "bin" => Some(config::CrateType::Executable),
Some(ref n) => {
Some(sym::rlib) => Some(config::CrateType::Rlib),
Some(sym::dylib) => Some(config::CrateType::Dylib),
Some(sym::cdylib) => Some(config::CrateType::Cdylib),
Some(sym::lib) => Some(config::default_lib_output()),
Some(sym::staticlib) => Some(config::CrateType::Staticlib),
Some(sym::proc_dash_macro) => Some(config::CrateType::ProcMacro),
Some(sym::bin) => Some(config::CrateType::Executable),
Some(n) => {
let crate_types = vec![
Symbol::intern("rlib"),
Symbol::intern("dylib"),
Symbol::intern("cdylib"),
Symbol::intern("lib"),
Symbol::intern("staticlib"),
Symbol::intern("proc-macro"),
Symbol::intern("bin")
sym::rlib,
sym::dylib,
sym::cdylib,
sym::lib,
sym::staticlib,
sym::proc_dash_macro,
sym::bin
];
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;
self.cstore.iter_crate_data(|_, data| {
if data.name == "std" {
if data.name == sym::std {
uses_std = true;
}
});

View File

@ -31,7 +31,7 @@ use syntax::source_map;
use syntax::edition::Edition;
use syntax::parse::source_file_to_stream;
use syntax::parse::parser::emit_unclosed_delims;
use syntax::symbol::Symbol;
use syntax::symbol::{Symbol, sym};
use syntax_pos::{Span, NO_EXPANSION, FileName};
use rustc_data_structures::bit_set::BitSet;
@ -432,7 +432,7 @@ impl cstore::CStore {
let data = self.get_crate_data(id.krate);
if let Some(ref proc_macros) = data.proc_macros {
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::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);
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() {
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 errors::DiagnosticBuilder;
use syntax::symbol::Symbol;
use syntax::symbol::{Symbol, sym};
use syntax::struct_span_err;
use syntax_pos::Span;
use rustc_target::spec::{Target, TargetTriple};
@ -408,7 +408,7 @@ impl<'a> Context<'a> {
self.ident,
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()) {
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
.iter()
.filter_map(|lib| lib.name.as_ref())
.any(|n| n == name);
.any(|n| n.as_str() == *name);
if new_name.is_empty() {
self.tcx.sess.err(
&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.
let mut existing = self.libs.drain_filter(|lib| {
if let Some(lib_name) = lib.name {
if lib_name == name as &str {
if lib_name.as_str() == *name {
if let Some(k) = kind {
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::MacroExpanderFn;
use syntax::ext::hygiene;
use syntax::symbol::Symbol;
use syntax::symbol::{Symbol, sym};
use syntax::ast;
use syntax::feature_gate::AttributeType;
use syntax_pos::Span;
@ -86,7 +86,7 @@ impl<'a> Registry<'a> {
///
/// This is the most general hook into `libsyntax`'s expansion behavior.
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`");
}
self.syntax_exts.push((name, match extension {

View File

@ -369,7 +369,7 @@ impl<'a> Resolver<'a> {
};
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);
}

View File

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

View File

@ -982,7 +982,7 @@ impl<'a> Resolver<'a> {
let msg =
format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
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();
}
}
@ -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) {
// First check if this is a locally-defined bang macro.
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 {
None
// Then check global macros.
@ -1023,7 +1024,7 @@ impl<'a> Resolver<'a> {
.filter_map(|(name, binding)| {
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.
}).or_else(|| {
let is_macro = |res| {
@ -1033,7 +1034,7 @@ impl<'a> Resolver<'a> {
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)
.map(|suggestion| suggestion.candidate)
});
@ -1092,7 +1093,7 @@ impl<'a> Resolver<'a> {
current_legacy_scope: &mut LegacyScope<'a>) {
self.local_macro_def_scopes.insert(item.id, self.current_module);
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`");
}

View File

@ -29,7 +29,7 @@ use rustc::{bug, span_bug};
use syntax::ast::{self, Ident, Name, NodeId, CRATE_NODE_ID};
use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
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::{struct_span_err, unwrap_or};
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
// performed on `Resolver::builtin_attrs`.
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,
&format!("name `{}` is reserved in macro namespace", ident));
}
@ -706,7 +707,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> {
has_errors = true;
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
if let Err(Determined) = source_bindings.value_ns.get() {
continue;
@ -1041,7 +1042,8 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> {
let initial_res = source_bindings[ns].get().map(|initial_binding| {
all_ns_err = false;
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() {
this.record_use(ident, ns, target_binding,
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,
// so they can cause name conflict errors downstream.
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() {
let res = binding.res();
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> {
attrs.into_iter()
// Only retain real attributes. Doc comments are lowered separately.
.filter(|attr| attr.path != "doc")
.filter(|attr| attr.path != sym::doc)
.map(|mut attr| {
// Remove the surrounding '#[..]' or '#![..]' of the pretty printed
// 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;'.
// ICE this expression in particular (see #43162).
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);
}
}

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| {
if attr.path != "inline" {
if attr.path != sym::inline {
return ia;
}
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| {
if attr.path != "optimize" {
if attr.path != sym::optimize {
return ia;
}
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::ops;
use syntax::symbol::Symbol;
use syntax::symbol::{Symbol, sym};
use syntax::ast::{MetaItem, MetaItemKind, NestedMetaItem, LitKind};
use syntax::parse::ParseSess;
use syntax::feature_gate::Features;
@ -186,7 +186,7 @@ impl Cfg {
fn should_use_with_in_description(&self) -> bool {
match *self {
Cfg::Cfg(ref name, _) if name == &"target_feature" => true,
Cfg::Cfg(name, _) if name == sym::target_feature => true,
_ => false,
}
}

View File

@ -4383,7 +4383,7 @@ where
// 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 mut items = krate.module.item_ids.clone();
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 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()) {
clean::path_to_def_local(tcx, &["marker", "Send"])
clean::path_to_def_local(tcx, &[sym::marker, sym::Send])
} 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();

View File

@ -99,7 +99,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
// Try looking for methods and associated items.
let mut split = path_str.rsplitn(2, "::");
let item_name = if let Some(first) = split.next() {
first
Symbol::intern(first)
} else {
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 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
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 {
if ![
"rustc_deprecated",
"rustc_const_unstable",
"unstable",
"stable",
"rustc_promotable",
"rustc_allow_const_fn_ptr",
sym::rustc_deprecated,
sym::rustc_const_unstable,
sym::unstable,
sym::stable,
sym::rustc_promotable,
sym::rustc_allow_const_fn_ptr,
].iter().any(|&s| attr.path == s) {
continue // not a stability level
}
@ -199,10 +199,10 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
let meta = attr.meta();
if attr.path == "rustc_promotable" {
if attr.path == sym::rustc_promotable {
promotable = true;
}
if attr.path == "rustc_allow_const_fn_ptr" {
if attr.path == sym::rustc_allow_const_fn_ptr {
allow_const_fn_ptr = true;
}
// attributes with data
@ -721,7 +721,7 @@ pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
let mut acc = Vec::new();
let diagnostic = &sess.span_diagnostic;
if attr.path == "repr" {
if attr.path == sym::repr {
if let Some(items) = attr.meta_item_list() {
mark_used(attr);
for item in items {
@ -770,14 +770,14 @@ pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
};
let mut literal_error = None;
if name == "align" {
if name == sym::align {
recognised = true;
match parse_alignment(&value.node) {
Ok(literal) => acc.push(ReprAlign(literal)),
Err(message) => literal_error = Some(message)
};
}
else if name == "packed" {
else if name == sym::packed {
recognised = true;
match parse_alignment(&value.node) {
Ok(literal) => acc.push(ReprPacked(literal)),

View File

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

View File

@ -10,7 +10,7 @@ use crate::mut_visit::{self, MutVisitor};
use crate::parse::{self, parser, DirectoryOwnership};
use crate::parse::token;
use crate::ptr::P;
use crate::symbol::{keywords, Ident, Symbol};
use crate::symbol::{keywords, Ident, Symbol, sym};
use crate::ThinVec;
use crate::tokenstream::{self, TokenStream};
@ -871,7 +871,7 @@ impl<'a> ExtCtxt<'a> {
let mut last_macro = None;
loop {
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
return None;
}

View File

@ -4,7 +4,7 @@ use crate::source_map::{hygiene, ExpnInfo, ExpnFormat};
use crate::ext::base::ExtCtxt;
use crate::ext::build::AstBuilder;
use crate::parse::parser::PathStyle;
use crate::symbol::Symbol;
use crate::symbol::{Symbol, sym};
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> {
let mut result = Vec::new();
attrs.retain(|attr| {
if attr.path != "derive" {
if attr.path != sym::derive {
return true;
}
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);
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();
add_derived_markers(&mut self.cx, item.span(), &traits, &mut item_with_markers);
let derives = derives.entry(invoc.expansion_data.mark).or_default();
@ -1109,7 +1109,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
-> Option<ast::Attribute> {
let attr = attrs.iter()
.position(|a| {
if a.path == "derive" {
if a.path == sym::derive {
*after_derive = true;
}
!attr::is_known(a) && !is_builtin_attr(a)
@ -1117,7 +1117,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
.map(|i| attrs.remove(i));
if let Some(attr) = &attr {
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,
attr.span, GateIssue::Language,
"non-builtin inner attributes are unstable");
@ -1167,7 +1167,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
self.check_attribute_inner(attr, features);
// 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")
.note("this may become a hard error in a future release")
.emit();

View File

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

View File

@ -22,13 +22,13 @@ use crate::source_map::Spanned;
use crate::edition::{ALL_EDITIONS, Edition};
use crate::visit::{self, FnKind, Visitor};
use crate::parse::{token, ParseSess};
use crate::symbol::Symbol;
use crate::symbol::{Symbol, keywords, sym};
use crate::tokenstream::TokenTree;
use errors::{DiagnosticBuilder, Handler};
use rustc_data_structures::fx::FxHashMap;
use rustc_target::spec::abi::Abi;
use syntax_pos::{Span, DUMMY_SP, sym};
use syntax_pos::{Span, DUMMY_SP};
use log::debug;
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
// unanticipated results, such as compiler crashes. We warn the user about these
// to alert them.
const INCOMPLETE_FEATURES: &[&str] = &[
"generic_associated_types",
"const_generics"
const INCOMPLETE_FEATURES: &[Symbol] = &[
sym::generic_associated_types,
sym::const_generics
];
declare_features! (
@ -1947,7 +1947,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
fn visit_item(&mut self, i: &'a ast::Item) {
match i.node {
ast::ItemKind::Const(_,_) => {
if i.ident.name == "_" {
if i.ident.name == keywords::Underscore.name() {
gate_feature_post!(&self, underscore_const_names, i.span,
"naming constants with `_` is unstable");
}
@ -2304,7 +2304,7 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
if edition <= crate_edition {
// The `crate_edition` implies its respective umbrella feature-gate
// (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();
if INCOMPLETE_FEATURES.iter().any(|f| name == *f) {
if INCOMPLETE_FEATURES.iter().any(|f| name == f.as_str()) {
span_handler.struct_span_warn(
mi.span(),
&format!(
@ -2345,7 +2345,7 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
).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 {
continue;
}

View File

@ -391,6 +391,8 @@ mod tests {
#[test]
fn string_to_tts_macro () {
with_globals(|| {
use crate::symbol::sym;
let tts: Vec<_> =
string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
let tts: &[TokenTree] = &tts[..];
@ -403,8 +405,8 @@ mod tests {
Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
)
if name_macro_rules.name == "macro_rules"
&& name_zip.name == "zip" => {
if name_macro_rules.name == sym::macro_rules
&& name_zip.name.as_str() == "zip" => {
let tts = &macro_tts.trees().collect::<Vec<_>>();
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::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),
}
let tts = &second_tts.trees().collect::<Vec<_>>();
@ -431,7 +433,7 @@ mod tests {
Some(&TokenTree::Token(_, token::Dollar)),
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),
}
},
@ -584,13 +586,13 @@ mod tests {
let item = parse_item_from_source_str(name_1, source, &sess)
.unwrap().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 source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
let item = parse_item_from_source_str(name_2, source, &sess)
.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<_>>();
let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
assert_eq!(&docs[..], b);
@ -599,7 +601,7 @@ mod tests {
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 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 })
}
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) => {
let prev_span = self.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! {
// 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);
}

View File

@ -272,7 +272,8 @@ fn generate_test_harness(sess: &ParseSess,
test_cases: Vec::new(),
reexport_test_harness_main,
// 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,
ctxt: SyntaxContext::empty().apply_mark(mark),
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<'_>,
sp: Span,
@ -233,13 +233,13 @@ fn parse_inline_asm<'a>(
Options => {
let (option, _) = p.parse_str()?;
if option == "volatile" {
if option == sym::volatile {
// Indicates that the inline assembly has side effects
// and must not be optimized out along with its outputs.
volatile = true;
} else if option == "alignstack" {
} else if option == sym::alignstack {
alignstack = true;
} else if option == "intel" {
} else if option == sym::intel {
dialect = AsmDialect::Intel;
} else {
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::hygiene::{Mark, SyntaxContext};
use syntax::ptr::P;
use syntax::symbol::Symbol;
use syntax::symbol::{Symbol, sym};
use syntax_pos::Span;
macro path_local($x:ident) {
@ -139,7 +139,7 @@ fn call_intrinsic(cx: &ExtCtxt<'_>,
let intrinsic_allowed_via_allow_internal_unstable = cx
.current_expansion.mark.expn_info().unwrap()
.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 {
span = span.with_ctxt(cx.backtrace());

View File

@ -1,3 +1,4 @@
use crate::symbol::{Symbol, sym};
use std::fmt;
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 {
Edition::Edition2015 => "rust_2015_preview",
Edition::Edition2018 => "rust_2018_preview",
Edition::Edition2015 => sym::rust_2015_preview,
Edition::Edition2018 => sym::rust_2018_preview,
}
}

View File

@ -393,7 +393,7 @@ impl Span {
Some(info) => info
.allow_internal_unstable
.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,
}

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.
//
// 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 {
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'");
}
}

View File

@ -23,10 +23,10 @@ declare_lint_pass!(Pass => [TEST_LINT, TEST_GROUP]);
impl EarlyLintPass for Pass {
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'");
}
if it.ident.name == "lintmetoo" {
if it.ident.name.as_str() == "lintmetoo" {
cx.span_lint(TEST_GROUP, it.span, "item is named 'lintmetoo'");
}
}