diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 0d80a0874e6..dd0d13d8f5a 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -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, /// 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, + 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 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| 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::>(); 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() { ... }` 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 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 { 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::ExprKind { @@ -5119,7 +5120,7 @@ impl<'a> LoweringContext<'a> { fn expr_std_path( &mut self, span: Span, - components: &[&str], + components: &[Symbol], params: Option>, attrs: ThinVec, ) -> hir::Expr { @@ -5250,25 +5251,25 @@ impl<'a> LoweringContext<'a> { } fn pat_ok(&mut self, span: Span, pat: P) -> P { - 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) -> P { - 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) -> P { - 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 { - 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 { 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>, 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 { - 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)); diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index 1a48dff213b..b8ee98551a2 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -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 { diff --git a/src/librustc/lint/levels.rs b/src/librustc/lint/levels.rs index a69758e33ba..6481f9af00b 100644 --- a/src/librustc/lint/levels.rs +++ b/src/librustc/lint/levels.rs @@ -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"); } } diff --git a/src/librustc/middle/entry.rs b/src/librustc/middle/entry.rs index e2e76e69dc4..67db2ec2481 100644 --- a/src/librustc/middle/entry.rs +++ b/src/librustc/middle/entry.rs @@ -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 diff --git a/src/librustc/middle/lib_features.rs b/src/librustc/middle/lib_features.rs index 5acd48c77d8..8696e2af8c2 100644 --- a/src/librustc/middle/lib_features.rs +++ b/src/librustc/middle/lib_features.rs @@ -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)); } } diff --git a/src/librustc/middle/stability.rs b/src/librustc/middle/stability.rs index c608c72430c..d9a44714d7d 100644 --- a/src/librustc/middle/stability.rs +++ b/src/librustc/middle/stability.rs @@ -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; } diff --git a/src/librustc/middle/weak_lang_items.rs b/src/librustc/middle/weak_lang_items.rs index 312924e5e90..75c21c738f7 100644 --- a/src/librustc/middle/weak_lang_items.rs +++ b/src/librustc/middle/weak_lang_items.rs @@ -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 { 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 } diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index 12427daa383..f61ffac15d5 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -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()); }); diff --git a/src/librustc/traits/project.rs b/src/librustc/traits/project.rs index b5232e828c4..f05a1937291 100644 --- a/src/librustc/traits/project.rs +++ b/src/librustc/traits/project.rs @@ -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!() diff --git a/src/librustc_codegen_ssa/back/write.rs b/src/librustc_codegen_ssa/back/write.rs index 204ca59efc8..6320d8a671d 100644 --- a/src/librustc_codegen_ssa/back/write.rs +++ b/src/librustc_codegen_ssa/back/write.rs @@ -386,7 +386,7 @@ pub fn start_async_codegen( 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)); diff --git a/src/librustc_codegen_utils/link.rs b/src/librustc_codegen_utils/link.rs index 30f37fefa7c..a2ac64fa7e0 100644 --- a/src/librustc_codegen_utils/link.rs +++ b/src/librustc_codegen_utils/link.rs @@ -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); diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 5b42b049b5b..02f8eee67b1 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -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 } diff --git a/src/librustc_interface/util.rs b/src/librustc_interface/util.rs index 2b1a993d1cc..d2d0d191807 100644 --- a/src/librustc_interface/util.rs +++ b/src/librustc_interface/util.rs @@ -497,22 +497,22 @@ pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec 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 { diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs index 20caad70f2b..b7b17a84aa7 100644 --- a/src/librustc_metadata/creader.rs +++ b/src/librustc_metadata/creader.rs @@ -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; } }); diff --git a/src/librustc_metadata/cstore_impl.rs b/src/librustc_metadata/cstore_impl.rs index dfeaeca323f..087256a9710 100644 --- a/src/librustc_metadata/cstore_impl.rs +++ b/src/librustc_metadata/cstore_impl.rs @@ -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; diff --git a/src/librustc_metadata/link_args.rs b/src/librustc_metadata/link_args.rs index cd5951f0e0e..f4682465a65 100644 --- a/src/librustc_metadata/link_args.rs +++ b/src/librustc_metadata/link_args.rs @@ -11,7 +11,7 @@ pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Vec { 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()); } diff --git a/src/librustc_metadata/locator.rs b/src/librustc_metadata/locator.rs index 116042c53fb..7d7dd1061a9 100644 --- a/src/librustc_metadata/locator.rs +++ b/src/librustc_metadata/locator.rs @@ -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)); } diff --git a/src/librustc_metadata/native_libs.rs b/src/librustc_metadata/native_libs.rs index 3e7e740a15c..fee08f42154 100644 --- a/src/librustc_metadata/native_libs.rs +++ b/src/librustc_metadata/native_libs.rs @@ -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; } diff --git a/src/librustc_plugin/registry.rs b/src/librustc_plugin/registry.rs index 913657b2934..c2d1d5fa65a 100644 --- a/src/librustc_plugin/registry.rs +++ b/src/librustc_plugin/registry.rs @@ -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 { diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index cf09e31bb62..f70ca6f859b 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -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); } diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 0dd6f378730..678f4c23d3e 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -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, + 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::>(); diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index 62f2768888a..9f3e1c308f6 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -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`"); } diff --git a/src/librustc_resolve/resolve_imports.rs b/src/librustc_resolve/resolve_imports.rs index 9e6b8d03545..4058f0bce0f 100644 --- a/src/librustc_resolve/resolve_imports.rs +++ b/src/librustc_resolve/resolve_imports.rs @@ -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 { diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index cb2454aa4b5..e03da2ed608 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -1197,7 +1197,7 @@ fn null_id() -> rls_data::Id { fn lower_attributes(attrs: Vec, scx: &SaveContext<'_, '_>) -> Vec { 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 diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index a184a2daeb6..362b6f0504d 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -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); } } diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 29b47089409..ffba9403743 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -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); diff --git a/src/librustdoc/clean/cfg.rs b/src/librustdoc/clean/cfg.rs index b96ac19c1ea..c795b2dcd7a 100644 --- a/src/librustdoc/clean/cfg.rs +++ b/src/librustdoc/clean/cfg.rs @@ -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, } } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 6790b13dbf8..f9a43ccfbac 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -4383,7 +4383,7 @@ where // Start of code copied from rust-clippy -pub fn path_to_def_local(tcx: TyCtxt<'_, '_, '_>, path: &[&str]) -> Option { +pub fn path_to_def_local(tcx: TyCtxt<'_, '_, '_>, path: &[Symbol]) -> Option { 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, path: &[&str]) -> Option { +pub fn path_to_def(tcx: TyCtxt<'_, '_, '_>, path: &[Symbol]) -> Option { let crates = tcx.crates(); let krate = crates diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 1b099fbd91d..bc87086e106 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -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(); diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index abf19a0a5ef..9e108e605c8 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -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(()) }; diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index aa176c89258..d12240655e6 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -81,12 +81,6 @@ impl PartialEq 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)) diff --git a/src/libsyntax/attr/builtin.rs b/src/libsyntax/attr/builtin.rs index a8310c48b96..43de3f74e4a 100644 --- a/src/libsyntax/attr/builtin.rs +++ b/src/libsyntax/attr/builtin.rs @@ -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 { 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 { }; 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)), diff --git a/src/libsyntax/entry.rs b/src/libsyntax/entry.rs index 267f863ce35..0b6cf30bd27 100644 --- a/src/libsyntax/entry.rs +++ b/src/libsyntax/entry.rs @@ -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 diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index cc19acb61ad..0a88d2f8824 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -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; } diff --git a/src/libsyntax/ext/derive.rs b/src/libsyntax/ext/derive.rs index 6df369133d0..a24e09f127e 100644 --- a/src/libsyntax/ext/derive.rs +++ b/src/libsyntax/ext/derive.rs @@ -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) -> Vec { 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() { diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 7ebfcfd176a..a286fd83e3c 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -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 { 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(); diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 55596210093..06651750de7 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -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: "ed::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: "ed::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: "ed::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), } }, diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index 53ecb0762ab..e7740f1835b 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -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; } diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 64f3704e808..655baafcd2d 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -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 = ¯o_tts.trees().collect::>(); 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::>(); @@ -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::>(); 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 */"); }); } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index d3dd6bb1e01..c0f3c358e98 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -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); diff --git a/src/libsyntax/std_inject.rs b/src/libsyntax/std_inject.rs index 42ca8b7c23c..f08fdcc6fb5 100644 --- a/src/libsyntax/std_inject.rs +++ b/src/libsyntax/std_inject.rs @@ -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> = Cell::new(None); } diff --git a/src/libsyntax/test.rs b/src/libsyntax/test.rs index 8e5e594ce9a..21bc236d00e 100644 --- a/src/libsyntax/test.rs +++ b/src/libsyntax/test.rs @@ -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, diff --git a/src/libsyntax_ext/asm.rs b/src/libsyntax_ext/asm.rs index 6213736ed5f..b8e89c3ecf8 100644 --- a/src/libsyntax_ext/asm.rs +++ b/src/libsyntax_ext/asm.rs @@ -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"); diff --git a/src/libsyntax_ext/deriving/mod.rs b/src/libsyntax_ext/deriving/mod.rs index fff54814a38..c27de692d88 100644 --- a/src/libsyntax_ext/deriving/mod.rs +++ b/src/libsyntax_ext/deriving/mod.rs @@ -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()); diff --git a/src/libsyntax_pos/edition.rs b/src/libsyntax_pos/edition.rs index a0b0052f26d..00cd00f2837 100644 --- a/src/libsyntax_pos/edition.rs +++ b/src/libsyntax_pos/edition.rs @@ -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, } } diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs index c5d6da74eb6..39859f25f97 100644 --- a/src/libsyntax_pos/lib.rs +++ b/src/libsyntax_pos/lib.rs @@ -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, } diff --git a/src/libsyntax_pos/symbol.rs b/src/libsyntax_pos/symbol.rs index ac3f999c537..ec0ce4253fa 100644 --- a/src/libsyntax_pos/symbol.rs +++ b/src/libsyntax_pos/symbol.rs @@ -822,12 +822,6 @@ impl Decodable for Symbol { } } -impl> PartialEq 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 diff --git a/src/test/ui-fulldeps/auxiliary/lint-plugin-test.rs b/src/test/ui-fulldeps/auxiliary/lint-plugin-test.rs index 1d204e7bfcf..0deb1bf0915 100644 --- a/src/test/ui-fulldeps/auxiliary/lint-plugin-test.rs +++ b/src/test/ui-fulldeps/auxiliary/lint-plugin-test.rs @@ -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'"); } } diff --git a/src/test/ui-fulldeps/auxiliary/lint-tool-test.rs b/src/test/ui-fulldeps/auxiliary/lint-tool-test.rs index 182d2899da1..64664377cd9 100644 --- a/src/test/ui-fulldeps/auxiliary/lint-tool-test.rs +++ b/src/test/ui-fulldeps/auxiliary/lint-tool-test.rs @@ -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'"); } }