Return a Symbol from name_or_empty functions.

This commit is contained in:
Nicholas Nethercote 2019-05-08 14:33:06 +10:00
parent 999c1fc281
commit ea9fac5687
15 changed files with 112 additions and 105 deletions

View File

@ -178,9 +178,9 @@ impl<'a, 'tcx> CheckAttrVisitor<'a, 'tcx> {
let mut is_transparent = false;
for hint in &hints {
let (article, allowed_targets) = match hint.name_or_empty().get() {
name @ "C" | name @ "align" => {
is_c |= name == "C";
let (article, allowed_targets) = match hint.name_or_empty() {
name @ sym::C | name @ sym::align => {
is_c |= name == sym::C;
if target != Target::Struct &&
target != Target::Union &&
target != Target::Enum {
@ -189,7 +189,7 @@ impl<'a, 'tcx> CheckAttrVisitor<'a, 'tcx> {
continue
}
}
"packed" => {
sym::packed => {
if target != Target::Struct &&
target != Target::Union {
("a", "struct or union")
@ -197,7 +197,7 @@ impl<'a, 'tcx> CheckAttrVisitor<'a, 'tcx> {
continue
}
}
"simd" => {
sym::simd => {
is_simd = true;
if target != Target::Struct {
("a", "struct")
@ -205,7 +205,7 @@ impl<'a, 'tcx> CheckAttrVisitor<'a, 'tcx> {
continue
}
}
"transparent" => {
sym::transparent => {
is_transparent = true;
if target != Target::Struct {
("a", "struct")
@ -213,9 +213,9 @@ impl<'a, 'tcx> CheckAttrVisitor<'a, 'tcx> {
continue
}
}
"i8" | "u8" | "i16" | "u16" |
"i32" | "u32" | "i64" | "u64" |
"isize" | "usize" => {
sym::i8 | sym::u8 | sym::i16 | sym::u16 |
sym::i32 | sym::u32 | sym::i64 | sym::u64 |
sym::isize | sym::usize => {
int_reprs += 1;
if target != Target::Enum {
("an", "enum")

View File

@ -194,7 +194,7 @@ impl<'a> LintLevelsBuilder<'a> {
struct_span_err!(sess, span, E0452, "malformed lint attribute")
};
for attr in attrs {
let level = match Level::from_str(&attr.name_or_empty()) {
let level = match Level::from_symbol(attr.name_or_empty()) {
None => continue,
Some(lvl) => lvl,
};

View File

@ -38,7 +38,7 @@ use syntax::ast;
use syntax::source_map::{MultiSpan, ExpnFormat};
use syntax::early_buffered_lints::BufferedEarlyLintId;
use syntax::edition::Edition;
use syntax::symbol::Symbol;
use syntax::symbol::{Symbol, sym};
use syntax_pos::Span;
pub use crate::lint::context::{LateContext, EarlyContext, LintContext, LintStore,
@ -570,6 +570,17 @@ impl Level {
_ => None,
}
}
/// Converts a symbol to a level.
pub fn from_symbol(x: Symbol) -> Option<Level> {
match x {
sym::allow => Some(Allow),
sym::warn => Some(Warn),
sym::deny => Some(Deny),
sym::forbid => Some(Forbid),
_ => None,
}
}
}
/// How a lint level was set.
@ -752,7 +763,7 @@ pub fn struct_lint_level<'a>(sess: &'a Session,
pub fn maybe_lint_level_root(tcx: TyCtxt<'_, '_, '_>, id: hir::HirId) -> bool {
let attrs = tcx.hir().attrs_by_hir_id(id);
attrs.iter().any(|attr| Level::from_str(&attr.name_or_empty()).is_some())
attrs.iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some())
}
fn lint_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, cnum: CrateNum)

View File

@ -65,9 +65,9 @@ impl<'a, 'tcx> LibFeatureCollector<'a, 'tcx> {
for meta in metas {
if let Some(mi) = meta.meta_item() {
// Find the `feature = ".."` meta-item.
match (mi.name_or_empty().get(), mi.value_str()) {
("feature", val) => feature = val,
("since", val) => since = val,
match (mi.name_or_empty(), mi.value_str()) {
(sym::feature, val) => feature = val,
(sym::since, val) => since = val,
_ => {}
}
}

View File

@ -195,7 +195,7 @@ impl<'a, 'tcx: 'a> Annotator<'a, 'tcx> {
// Emit errors for non-staged-api crates.
for attr in attrs {
let name = attr.name_or_empty();
if ["unstable", "stable", "rustc_deprecated"].contains(&name.get()) {
if [sym::unstable, sym::stable, sym::rustc_deprecated].contains(&name) {
attr::mark_used(attr);
self.tcx.sess.span_err(attr.span, "stability attributes may not be used \
outside of the standard library");

View File

@ -262,7 +262,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
// Has a plugin registered this attribute as one that must be used at
// the crate level?
let plugin_crate = plugin_attributes.iter()
.find(|&&(ref x, t)| name == x.as_str() && AttributeType::CrateLevel == t)
.find(|&&(x, t)| name == x && AttributeType::CrateLevel == t)
.is_some();
if known_crate || plugin_crate {
let msg = match attr.style {

View File

@ -650,9 +650,8 @@ impl<'a> CrateLoader<'a> {
/// SVH and DefIndex of the registrar function.
pub fn find_plugin_registrar(&mut self,
span: Span,
name: &str)
name: Symbol)
-> Option<(PathBuf, CrateDisambiguator)> {
let name = Symbol::intern(name);
let ekrate = self.read_extension_crate(span, name, name);
if ekrate.target_only {

View File

@ -55,26 +55,26 @@ impl<'a, 'tcx> VarianceTest<'a, 'tcx> {
// The `..` are the names of fields to dump.
let meta_items = attr.meta_item_list().unwrap_or_default();
for meta_item in meta_items {
match meta_item.name_or_empty().get() {
"abi" => {
match meta_item.name_or_empty() {
sym::abi => {
self.tcx
.sess
.span_err(item.span, &format!("abi: {:?}", ty_layout.abi));
}
"align" => {
sym::align => {
self.tcx
.sess
.span_err(item.span, &format!("align: {:?}", ty_layout.align));
}
"size" => {
sym::size => {
self.tcx
.sess
.span_err(item.span, &format!("size: {:?}", ty_layout.size));
}
"homogeneous_aggregate" => {
sym::homogeneous_aggregate => {
self.tcx.sess.span_err(
item.span,
&format!(

View File

@ -11,7 +11,7 @@ use std::mem;
use std::path::PathBuf;
use syntax::ast;
use syntax::span_err;
use syntax::symbol::sym;
use syntax::symbol::{Symbol, keywords, sym};
use syntax_pos::{Span, DUMMY_SP};
/// Pointer to a registrar function.
@ -58,9 +58,9 @@ pub fn load_plugins(sess: &Session,
for plugin in plugins {
// plugins must have a name and can't be key = value
let name = plugin.name_or_empty();
if !name.is_empty() && !plugin.is_value_str() {
if name != keywords::Invalid.name() && !plugin.is_value_str() {
let args = plugin.meta_item_list().map(ToOwned::to_owned);
loader.load_plugin(plugin.span(), &name, args.unwrap_or_default());
loader.load_plugin(plugin.span(), name, args.unwrap_or_default());
} else {
call_malformed_plugin_attribute(sess, attr.span);
}
@ -70,7 +70,7 @@ pub fn load_plugins(sess: &Session,
if let Some(plugins) = addl_plugins {
for plugin in plugins {
loader.load_plugin(DUMMY_SP, &plugin, vec![]);
loader.load_plugin(DUMMY_SP, Symbol::intern(&plugin), vec![]);
}
}
@ -86,7 +86,7 @@ impl<'a> PluginLoader<'a> {
}
}
fn load_plugin(&mut self, span: Span, name: &str, args: Vec<ast::NestedMetaItem>) {
fn load_plugin(&mut self, span: Span, name: Symbol, args: Vec<ast::NestedMetaItem>) {
let registrar = self.reader.find_plugin_registrar(span, name);
if let Some((lib, disambiguator)) = registrar {

View File

@ -421,19 +421,19 @@ pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOpt
let name = attr.name_or_empty();
if attr.is_word() {
if name == "no_default_passes" {
if name == sym::no_default_passes {
report_deprecated_attr("no_default_passes", diag);
if default_passes == passes::DefaultPassOption::Default {
default_passes = passes::DefaultPassOption::None;
}
}
} else if let Some(value) = attr.value_str() {
let sink = match name.get() {
"passes" => {
let sink = match name {
sym::passes => {
report_deprecated_attr("passes = \"...\"", diag);
&mut manual_passes
},
"plugins" => {
sym::plugins => {
report_deprecated_attr("plugins = \"...\"", diag);
eprintln!("WARNING: #![doc(plugins = \"...\")] no longer functions; \
see CVE-2018-1000622");
@ -446,7 +446,7 @@ pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOpt
}
}
if attr.is_word() && name == "document_private_items" {
if attr.is_word() && name == sym::document_private_items {
if default_passes == passes::DefaultPassOption::Default {
default_passes = passes::DefaultPassOption::Private;
}

View File

@ -50,7 +50,7 @@ use syntax::ast;
use syntax::ext::base::MacroKind;
use syntax::source_map::FileName;
use syntax::feature_gate::UnstableFeatures;
use syntax::symbol::sym;
use syntax::symbol::{Symbol, sym};
use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
use rustc::middle::privacy::AccessLevels;
use rustc::middle::stability;
@ -573,23 +573,23 @@ pub fn run(mut krate: clean::Crate,
// going to emit HTML
if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
for attr in attrs.lists(sym::doc) {
match (attr.name_or_empty().get(), attr.value_str()) {
("html_favicon_url", Some(s)) => {
match (attr.name_or_empty(), attr.value_str()) {
(sym::html_favicon_url, Some(s)) => {
scx.layout.favicon = s.to_string();
}
("html_logo_url", Some(s)) => {
(sym::html_logo_url, Some(s)) => {
scx.layout.logo = s.to_string();
}
("html_playground_url", Some(s)) => {
(sym::html_playground_url, Some(s)) => {
markdown::PLAYGROUND.with(|slot| {
let name = krate.name.clone();
*slot.borrow_mut() = Some((Some(name), s.to_string()));
});
}
("issue_tracker_base_url", Some(s)) => {
(sym::issue_tracker_base_url, Some(s)) => {
scx.issue_tracker_base_url = Some(s.to_string());
}
("html_no_source", None) if attr.is_word() => {
(sym::html_no_source, None) if attr.is_word() => {
scx.include_sources = false;
}
_ => {}
@ -3762,22 +3762,22 @@ fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
}
}
const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
"export_name",
"lang",
"link_section",
"must_use",
"no_mangle",
"repr",
"unsafe_destructor_blind_to_params",
"non_exhaustive"
const ATTRIBUTE_WHITELIST: &'static [Symbol] = &[
sym::export_name,
sym::lang,
sym::link_section,
sym::must_use,
sym::no_mangle,
sym::repr,
sym::unsafe_destructor_blind_to_params,
sym::non_exhaustive
];
fn render_attributes(w: &mut dyn fmt::Write, it: &clean::Item) -> fmt::Result {
let mut attrs = String::new();
for attr in &it.attrs.other_attrs {
if !ATTRIBUTE_WHITELIST.contains(&attr.name_or_empty().get()) {
if !ATTRIBUTE_WHITELIST.contains(&attr.name_or_empty()) {
continue;
}
if let Some(s) = render_attribute(&attr.meta().unwrap()) {

View File

@ -229,10 +229,9 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
)+
for meta in metas {
if let Some(mi) = meta.meta_item() {
match mi.name_or_empty().get() {
match mi.name_or_empty() {
$(
stringify!($name)
=> if !get(mi, &mut $name) { continue 'outer },
sym::$name => if !get(mi, &mut $name) { continue 'outer },
)+
_ => {
let expected = &[ $( stringify!($name) ),+ ];
@ -259,8 +258,8 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
}
}
match meta.name_or_empty().get() {
"rustc_deprecated" => {
match meta.name_or_empty() {
sym::rustc_deprecated => {
if rustc_depr.is_some() {
span_err!(diagnostic, item_sp, E0540,
"multiple rustc_deprecated attributes");
@ -287,7 +286,7 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
}
}
}
"rustc_const_unstable" => {
sym::rustc_const_unstable => {
if rustc_const_unstable.is_some() {
span_err!(diagnostic, item_sp, E0553,
"multiple rustc_const_unstable attributes");
@ -302,7 +301,7 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
continue
}
}
"unstable" => {
sym::unstable => {
if stab.is_some() {
handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
break
@ -313,10 +312,10 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
let mut issue = None;
for meta in metas {
if let Some(mi) = meta.meta_item() {
match mi.name_or_empty().get() {
"feature" => if !get(mi, &mut feature) { continue 'outer },
"reason" => if !get(mi, &mut reason) { continue 'outer },
"issue" => if !get(mi, &mut issue) { continue 'outer },
match mi.name_or_empty() {
sym::feature => if !get(mi, &mut feature) { continue 'outer },
sym::reason => if !get(mi, &mut reason) { continue 'outer },
sym::issue => if !get(mi, &mut issue) { continue 'outer },
_ => {
handle_errors(
sess,
@ -374,7 +373,7 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
}
}
}
"stable" => {
sym::stable => {
if stab.is_some() {
handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
break
@ -385,11 +384,9 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
for meta in metas {
match meta {
NestedMetaItem::MetaItem(mi) => {
match mi.name_or_empty().get() {
"feature" =>
if !get(mi, &mut feature) { continue 'outer },
"since" =>
if !get(mi, &mut since) { continue 'outer },
match mi.name_or_empty() {
sym::feature => if !get(mi, &mut feature) { continue 'outer },
sym::since => if !get(mi, &mut since) { continue 'outer },
_ => {
handle_errors(
sess,
@ -542,14 +539,14 @@ pub fn eval_condition<F>(cfg: &ast::MetaItem, sess: &ParseSess, eval: &mut F)
// The unwraps below may look dangerous, but we've already asserted
// that they won't fail with the loop above.
match cfg.name_or_empty().get() {
"any" => mis.iter().any(|mi| {
match cfg.name_or_empty() {
sym::any => mis.iter().any(|mi| {
eval_condition(mi.meta_item().unwrap(), sess, eval)
}),
"all" => mis.iter().all(|mi| {
sym::all => mis.iter().all(|mi| {
eval_condition(mi.meta_item().unwrap(), sess, eval)
}),
"not" => {
sym::not => {
if mis.len() != 1 {
span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern");
return false;
@ -645,9 +642,9 @@ fn find_deprecation_generic<'a, I>(sess: &ParseSess,
for meta in list {
match meta {
NestedMetaItem::MetaItem(mi) => {
match mi.name_or_empty().get() {
"since" => if !get(mi, &mut since) { continue 'outer },
"note" => if !get(mi, &mut note) { continue 'outer },
match mi.name_or_empty() {
sym::since => if !get(mi, &mut since) { continue 'outer },
sym::note => if !get(mi, &mut note) { continue 'outer },
_ => {
handle_errors(
sess,
@ -739,11 +736,11 @@ pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
let mut recognised = false;
if item.is_word() {
let hint = match item.name_or_empty().get() {
"C" => Some(ReprC),
"packed" => Some(ReprPacked(1)),
"simd" => Some(ReprSimd),
"transparent" => Some(ReprTransparent),
let hint = match item.name_or_empty() {
sym::C => Some(ReprC),
sym::packed => Some(ReprPacked(1)),
sym::simd => Some(ReprSimd),
sym::transparent => Some(ReprTransparent),
name => int_type_of_word(name).map(ReprInt),
};
@ -830,22 +827,22 @@ pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
acc
}
fn int_type_of_word(s: &str) -> Option<IntType> {
fn int_type_of_word(s: Symbol) -> Option<IntType> {
use IntType::*;
match s {
"i8" => Some(SignedInt(ast::IntTy::I8)),
"u8" => Some(UnsignedInt(ast::UintTy::U8)),
"i16" => Some(SignedInt(ast::IntTy::I16)),
"u16" => Some(UnsignedInt(ast::UintTy::U16)),
"i32" => Some(SignedInt(ast::IntTy::I32)),
"u32" => Some(UnsignedInt(ast::UintTy::U32)),
"i64" => Some(SignedInt(ast::IntTy::I64)),
"u64" => Some(UnsignedInt(ast::UintTy::U64)),
"i128" => Some(SignedInt(ast::IntTy::I128)),
"u128" => Some(UnsignedInt(ast::UintTy::U128)),
"isize" => Some(SignedInt(ast::IntTy::Isize)),
"usize" => Some(UnsignedInt(ast::UintTy::Usize)),
sym::i8 => Some(SignedInt(ast::IntTy::I8)),
sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
sym::i16 => Some(SignedInt(ast::IntTy::I16)),
sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
sym::i32 => Some(SignedInt(ast::IntTy::I32)),
sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
sym::i64 => Some(SignedInt(ast::IntTy::I64)),
sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
sym::i128 => Some(SignedInt(ast::IntTy::I128)),
sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
sym::isize => Some(SignedInt(ast::IntTy::Isize)),
sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
_ => None
}
}

View File

@ -22,7 +22,7 @@ use crate::parse::parser::Parser;
use crate::parse::{self, ParseSess, PResult};
use crate::parse::token::{self, Token};
use crate::ptr::P;
use crate::symbol::{keywords, LocalInternedString, Symbol};
use crate::symbol::{keywords, Symbol};
use crate::ThinVec;
use crate::tokenstream::{TokenStream, TokenTree, DelimSpan};
use crate::GLOBALS;
@ -89,8 +89,8 @@ impl NestedMetaItem {
pub fn ident(&self) -> Option<Ident> {
self.meta_item().and_then(|meta_item| meta_item.ident())
}
pub fn name_or_empty(&self) -> LocalInternedString {
self.ident().unwrap_or(keywords::Invalid.ident()).name.as_str()
pub fn name_or_empty(&self) -> Symbol {
self.ident().unwrap_or(keywords::Invalid.ident()).name
}
/// Gets the string value if self is a MetaItem and the MetaItem is a
@ -167,8 +167,8 @@ impl Attribute {
None
}
}
pub fn name_or_empty(&self) -> LocalInternedString {
self.ident().unwrap_or(keywords::Invalid.ident()).name.as_str()
pub fn name_or_empty(&self) -> Symbol {
self.ident().unwrap_or(keywords::Invalid.ident()).name
}
pub fn value_str(&self) -> Option<Symbol> {
@ -205,8 +205,8 @@ impl MetaItem {
None
}
}
pub fn name_or_empty(&self) -> LocalInternedString {
self.ident().unwrap_or(keywords::Invalid.ident()).name.as_str()
pub fn name_or_empty(&self) -> Symbol {
self.ident().unwrap_or(keywords::Invalid.ident()).name
}
// #[attribute(name = "value")]

View File

@ -1605,7 +1605,7 @@ impl<'a> Context<'a> {
}
}
if !attr::is_known(attr) {
if attr.name_or_empty().starts_with("rustc_") {
if attr.name_or_empty().as_str().starts_with("rustc_") {
let msg = "unless otherwise specified, attributes with the prefix `rustc_` \
are reserved for internal compiler diagnostics";
gate_feature!(self, rustc_attrs, attr.span, msg);
@ -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.as_str()) {
if INCOMPLETE_FEATURES.iter().any(|f| name == *f) {
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().as_str()) {
if let Some(edition) = ALL_EDITIONS.iter().find(|e| name == e.feature_name()) {
if *edition <= crate_edition {
continue;
}

View File

@ -464,8 +464,8 @@ impl<'a> TraitDef<'a> {
attrs.extend(item.attrs
.iter()
.filter(|a| {
["allow", "warn", "deny", "forbid", "stable", "unstable"]
.contains(&a.name_or_empty().get())
[sym::allow, sym::warn, sym::deny, sym::forbid, sym::stable, sym::unstable]
.contains(&a.name_or_empty())
})
.cloned());
push(Annotatable::Item(P(ast::Item { attrs: attrs, ..(*newitem).clone() })))