Refactor away NestedMetaItemKind

Remove methods `Attribute::span` and `MetaItem::span` duplicating public fields
This commit is contained in:
Vadim Petrochenkov
2019-03-03 20:56:24 +03:00
parent 63116d313d
commit 0cf96131f4
26 changed files with 126 additions and 145 deletions

View File

@@ -233,7 +233,7 @@ impl<'a, 'tcx> CheckAttrVisitor<'a, 'tcx> {
_ => continue, _ => continue,
}; };
self.emit_repr_error( self.emit_repr_error(
hint.span, hint.span(),
item.span, item.span,
&format!("attribute should be applied to {}", allowed_targets), &format!("attribute should be applied to {}", allowed_targets),
&format!("not {} {}", article, allowed_targets), &format!("not {} {}", article, allowed_targets),
@@ -242,7 +242,7 @@ impl<'a, 'tcx> CheckAttrVisitor<'a, 'tcx> {
// Just point at all repr hints if there are any incompatibilities. // Just point at all repr hints if there are any incompatibilities.
// This is not ideal, but tracking precisely which ones are at fault is a huge hassle. // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
let hint_spans = hints.iter().map(|hint| hint.span); let hint_spans = hints.iter().map(|hint| hint.span());
// Error on repr(transparent, <anything else>). // Error on repr(transparent, <anything else>).
if is_transparent && hints.len() > 1 { if is_transparent && hints.len() > 1 {

View File

@@ -360,9 +360,7 @@ fn hash_token<'a, 'gcx, W: StableHasherResult>(
} }
} }
impl_stable_hash_for_spanned!(::syntax::ast::NestedMetaItemKind); impl_stable_hash_for!(enum ::syntax::ast::NestedMetaItem {
impl_stable_hash_for!(enum ::syntax::ast::NestedMetaItemKind {
MetaItem(meta_item), MetaItem(meta_item),
Literal(lit) Literal(lit)
}); });

View File

@@ -258,7 +258,7 @@ impl<'a> LintLevelsBuilder<'a> {
let meta_item = match li.meta_item() { let meta_item = match li.meta_item() {
Some(meta_item) if meta_item.is_word() => meta_item, Some(meta_item) if meta_item.is_word() => meta_item,
_ => { _ => {
let mut err = bad_attr(li.span); let mut err = bad_attr(li.span());
if let Some(item) = li.meta_item() { if let Some(item) = li.meta_item() {
if let ast::MetaItemKind::NameValue(_) = item.node { if let ast::MetaItemKind::NameValue(_) = item.node {
if item.path == "reason" { if item.path == "reason" {
@@ -290,7 +290,7 @@ impl<'a> LintLevelsBuilder<'a> {
let name = meta_item.path.segments.last().expect("empty lint name").ident.name; let name = meta_item.path.segments.last().expect("empty lint name").ident.name;
match store.check_lint_name(&name.as_str(), tool_name) { match store.check_lint_name(&name.as_str(), tool_name) {
CheckLintNameResult::Ok(ids) => { CheckLintNameResult::Ok(ids) => {
let src = LintSource::Node(name, li.span, reason); let src = LintSource::Node(name, li.span(), reason);
for id in ids { for id in ids {
specs.insert(*id, (level, src)); specs.insert(*id, (level, src));
} }
@@ -301,7 +301,7 @@ impl<'a> LintLevelsBuilder<'a> {
Ok(ids) => { Ok(ids) => {
let complete_name = &format!("{}::{}", tool_name.unwrap(), name); let complete_name = &format!("{}::{}", tool_name.unwrap(), name);
let src = LintSource::Node( let src = LintSource::Node(
Symbol::intern(complete_name), li.span, reason Symbol::intern(complete_name), li.span(), reason
); );
for id in ids { for id in ids {
specs.insert(*id, (level, src)); specs.insert(*id, (level, src));
@@ -323,18 +323,18 @@ impl<'a> LintLevelsBuilder<'a> {
lint, lint,
lvl, lvl,
src, src,
Some(li.span.into()), Some(li.span().into()),
&msg, &msg,
); );
err.span_suggestion( err.span_suggestion(
li.span, li.span(),
"change it to", "change it to",
new_lint_name.to_string(), new_lint_name.to_string(),
Applicability::MachineApplicable, Applicability::MachineApplicable,
).emit(); ).emit();
let src = LintSource::Node( let src = LintSource::Node(
Symbol::intern(&new_lint_name), li.span, reason Symbol::intern(&new_lint_name), li.span(), reason
); );
for id in ids { for id in ids {
specs.insert(*id, (level, src)); specs.insert(*id, (level, src));
@@ -361,11 +361,11 @@ impl<'a> LintLevelsBuilder<'a> {
lint, lint,
level, level,
src, src,
Some(li.span.into()), Some(li.span().into()),
&msg); &msg);
if let Some(new_name) = renamed { if let Some(new_name) = renamed {
err.span_suggestion( err.span_suggestion(
li.span, li.span(),
"use the new name", "use the new name",
new_name, new_name,
Applicability::MachineApplicable Applicability::MachineApplicable
@@ -384,12 +384,12 @@ impl<'a> LintLevelsBuilder<'a> {
lint, lint,
level, level,
src, src,
Some(li.span.into()), Some(li.span().into()),
&msg); &msg);
if let Some(suggestion) = suggestion { if let Some(suggestion) = suggestion {
db.span_suggestion( db.span_suggestion(
li.span, li.span(),
"did you mean", "did you mean",
suggestion.to_string(), suggestion.to_string(),
Applicability::MachineApplicable, Applicability::MachineApplicable,

View File

@@ -107,7 +107,7 @@ impl<'a, 'gcx, 'tcx> OnUnimplementedDirective {
{ {
if let Some(items) = item.meta_item_list() { if let Some(items) = item.meta_item_list() {
if let Ok(subcommand) = if let Ok(subcommand) =
Self::parse(tcx, trait_def_id, &items, item.span, false) Self::parse(tcx, trait_def_id, &items, item.span(), false)
{ {
subcommands.push(subcommand); subcommands.push(subcommand);
} else { } else {
@@ -118,7 +118,7 @@ impl<'a, 'gcx, 'tcx> OnUnimplementedDirective {
} }
// nothing found // nothing found
parse_error(tcx, item.span, parse_error(tcx, item.span(),
"this attribute must have a valid value", "this attribute must have a valid value",
"expected value here", "expected value here",
Some(r#"eg `#[rustc_on_unimplemented(message="foo")]`"#)); Some(r#"eg `#[rustc_on_unimplemented(message="foo")]`"#));

View File

@@ -104,7 +104,7 @@ impl<'a, 'tcx> IfThisChanged<'a, 'tcx> {
value = Some(ident.name), value = Some(ident.name),
_ => _ =>
// FIXME better-encapsulate meta_item (don't directly access `node`) // FIXME better-encapsulate meta_item (don't directly access `node`)
span_bug!(list_item.span(), "unexpected meta-item {:?}", list_item.node), span_bug!(list_item.span(), "unexpected meta-item {:?}", list_item),
} }
} }
value value

View File

@@ -153,7 +153,7 @@ impl<'a, 'tcx> AssertModuleSource<'a, 'tcx> {
return value; return value;
} else { } else {
self.tcx.sess.span_fatal( self.tcx.sess.span_fatal(
item.span, item.span(),
&format!("associated value expected for `{}`", name)); &format!("associated value expected for `{}`", name));
} }
} }

View File

@@ -430,13 +430,13 @@ impl<'a, 'tcx> DirtyCleanVisitor<'a, 'tcx> {
if DepNode::has_label_string(label) { if DepNode::has_label_string(label) {
if out.contains(label) { if out.contains(label) {
self.tcx.sess.span_fatal( self.tcx.sess.span_fatal(
item.span, item.span(),
&format!("dep-node label `{}` is repeated", label)); &format!("dep-node label `{}` is repeated", label));
} }
out.insert(label.to_string()); out.insert(label.to_string());
} else { } else {
self.tcx.sess.span_fatal( self.tcx.sess.span_fatal(
item.span, item.span(),
&format!("dep-node label `{}` not recognized", label)); &format!("dep-node label `{}` not recognized", label));
} }
} }
@@ -582,7 +582,7 @@ fn expect_associated_value(tcx: TyCtxt<'_, '_, '_>, item: &NestedMetaItem) -> as
"expected an associated value".to_string() "expected an associated value".to_string()
}; };
tcx.sess.span_fatal(item.span, &msg); tcx.sess.span_fatal(item.span(), &msg);
} }
} }

View File

@@ -76,7 +76,7 @@ impl<'a, 'tcx> ItemLikeVisitor<'tcx> for Collector<'a, 'tcx> {
k => { k => {
struct_span_err!(self.tcx.sess, m.span, E0458, struct_span_err!(self.tcx.sess, m.span, E0458,
"unknown kind: `{}`", k) "unknown kind: `{}`", k)
.span_label(item.span, "unknown kind").emit(); .span_label(item.span(), "unknown kind").emit();
cstore::NativeUnknown cstore::NativeUnknown
} }
}; };

View File

@@ -86,7 +86,7 @@ impl<'a, 'tcx> VarianceTest<'a, 'tcx> {
_ => { _ => {
self.tcx.sess.span_err( self.tcx.sess.span_err(
meta_item.span, meta_item.span(),
&format!("unrecognized field name `{}`", name), &format!("unrecognized field name `{}`", name),
); );
} }

View File

@@ -59,7 +59,7 @@ pub fn load_plugins(sess: &Session,
match plugin.ident_str() { match plugin.ident_str() {
Some(name) if !plugin.is_value_str() => { Some(name) if !plugin.is_value_str() => {
let args = plugin.meta_item_list().map(ToOwned::to_owned); 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());
}, },
_ => call_malformed_plugin_attribute(sess, attr.span), _ => call_malformed_plugin_attribute(sess, attr.span),
} }

View File

@@ -813,12 +813,12 @@ impl<'a> Resolver<'a> {
MetaItemKind::List(nested_metas) => for nested_meta in nested_metas { MetaItemKind::List(nested_metas) => for nested_meta in nested_metas {
match nested_meta.ident() { match nested_meta.ident() {
Some(ident) if nested_meta.is_word() => single_imports.push(ident), Some(ident) if nested_meta.is_word() => single_imports.push(ident),
_ => ill_formed(nested_meta.span), _ => ill_formed(nested_meta.span()),
} }
} }
MetaItemKind::NameValue(..) => ill_formed(meta.span), MetaItemKind::NameValue(..) => ill_formed(meta.span),
} }
None => ill_formed(attr.span()), None => ill_formed(attr.span),
} }
} }
} }

View File

@@ -2326,7 +2326,7 @@ fn from_target_feature(
if !item.check_name("enable") { if !item.check_name("enable") {
let msg = "#[target_feature(..)] only accepts sub-keys of `enable` \ let msg = "#[target_feature(..)] only accepts sub-keys of `enable` \
currently"; currently";
tcx.sess.span_err(item.span, &msg); tcx.sess.span_err(item.span(), &msg);
continue; continue;
} }
@@ -2336,7 +2336,7 @@ fn from_target_feature(
None => { None => {
let msg = "#[target_feature] attribute must be of the form \ let msg = "#[target_feature] attribute must be of the form \
#[target_feature(enable = \"..\")]"; #[target_feature(enable = \"..\")]";
tcx.sess.span_err(item.span, &msg); tcx.sess.span_err(item.span(), &msg);
continue; continue;
} }
}; };
@@ -2352,7 +2352,7 @@ fn from_target_feature(
this target", this target",
feature feature
); );
let mut err = tcx.sess.struct_span_err(item.span, &msg); let mut err = tcx.sess.struct_span_err(item.span(), &msg);
if feature.starts_with("+") { if feature.starts_with("+") {
let valid = whitelist.contains_key(&feature[1..]); let valid = whitelist.contains_key(&feature[1..]);
@@ -2387,7 +2387,7 @@ fn from_target_feature(
feature_gate::emit_feature_err( feature_gate::emit_feature_err(
&tcx.sess.parse_sess, &tcx.sess.parse_sess,
feature_gate.as_ref().unwrap(), feature_gate.as_ref().unwrap(),
item.span, item.span(),
feature_gate::GateIssue::Language, feature_gate::GateIssue::Language,
&format!("the target feature `{}` is currently unstable", feature), &format!("the target feature `{}` is currently unstable", feature),
); );
@@ -2549,7 +2549,7 @@ fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> Codegen
} else { } else {
span_err!( span_err!(
tcx.sess.diagnostic(), tcx.sess.diagnostic(),
items[0].span, items[0].span(),
E0535, E0535,
"invalid argument" "invalid argument"
); );
@@ -2583,7 +2583,7 @@ fn codegen_fn_attrs<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefId) -> Codegen
} else if list_contains_name(&items[..], "speed") { } else if list_contains_name(&items[..], "speed") {
OptimizeAttr::Speed OptimizeAttr::Speed
} else { } else {
err(items[0].span, "invalid argument"); err(items[0].span(), "invalid argument");
OptimizeAttr::None OptimizeAttr::None
} }
} }

View File

@@ -8,7 +8,7 @@ use std::fmt::{self, Write};
use std::ops; use std::ops;
use syntax::symbol::Symbol; use syntax::symbol::Symbol;
use syntax::ast::{MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind, LitKind}; use syntax::ast::{MetaItem, MetaItemKind, NestedMetaItem, LitKind};
use syntax::parse::ParseSess; use syntax::parse::ParseSess;
use syntax::feature_gate::Features; use syntax::feature_gate::Features;
@@ -41,9 +41,9 @@ pub struct InvalidCfgError {
impl Cfg { impl Cfg {
/// Parses a `NestedMetaItem` into a `Cfg`. /// Parses a `NestedMetaItem` into a `Cfg`.
fn parse_nested(nested_cfg: &NestedMetaItem) -> Result<Cfg, InvalidCfgError> { fn parse_nested(nested_cfg: &NestedMetaItem) -> Result<Cfg, InvalidCfgError> {
match nested_cfg.node { match nested_cfg {
NestedMetaItemKind::MetaItem(ref cfg) => Cfg::parse(cfg), NestedMetaItem::MetaItem(ref cfg) => Cfg::parse(cfg),
NestedMetaItemKind::Literal(ref lit) => Err(InvalidCfgError { NestedMetaItem::Literal(ref lit) => Err(InvalidCfgError {
msg: "unexpected literal", msg: "unexpected literal",
span: lit.span, span: lit.span,
}), }),
@@ -442,9 +442,9 @@ mod test {
path: Path::from_ident(Ident::from_str(stringify!($name))), path: Path::from_ident(Ident::from_str(stringify!($name))),
node: MetaItemKind::List(vec![ node: MetaItemKind::List(vec![
$( $(
dummy_spanned(NestedMetaItemKind::MetaItem( NestedMetaItem::MetaItem(
dummy_meta_item_word(stringify!($list)), dummy_meta_item_word(stringify!($list)),
)), ),
)* )*
]), ]),
span: DUMMY_SP, span: DUMMY_SP,
@@ -456,7 +456,7 @@ mod test {
path: Path::from_ident(Ident::from_str(stringify!($name))), path: Path::from_ident(Ident::from_str(stringify!($name))),
node: MetaItemKind::List(vec![ node: MetaItemKind::List(vec![
$( $(
dummy_spanned(NestedMetaItemKind::MetaItem($list)), NestedMetaItem::MetaItem($list),
)* )*
]), ]),
span: DUMMY_SP, span: DUMMY_SP,

View File

@@ -777,15 +777,15 @@ pub struct Attributes {
impl Attributes { impl Attributes {
/// Extracts the content from an attribute `#[doc(cfg(content))]`. /// Extracts the content from an attribute `#[doc(cfg(content))]`.
fn extract_cfg(mi: &ast::MetaItem) -> Option<&ast::MetaItem> { fn extract_cfg(mi: &ast::MetaItem) -> Option<&ast::MetaItem> {
use syntax::ast::NestedMetaItemKind::MetaItem; use syntax::ast::NestedMetaItem::MetaItem;
if let ast::MetaItemKind::List(ref nmis) = mi.node { if let ast::MetaItemKind::List(ref nmis) = mi.node {
if nmis.len() == 1 { if nmis.len() == 1 {
if let MetaItem(ref cfg_mi) = nmis[0].node { if let MetaItem(ref cfg_mi) = nmis[0] {
if cfg_mi.check_name("cfg") { if cfg_mi.check_name("cfg") {
if let ast::MetaItemKind::List(ref cfg_nmis) = cfg_mi.node { if let ast::MetaItemKind::List(ref cfg_nmis) = cfg_mi.node {
if cfg_nmis.len() == 1 { if cfg_nmis.len() == 1 {
if let MetaItem(ref content_mi) = cfg_nmis[0].node { if let MetaItem(ref content_mi) = cfg_nmis[0] {
return Some(content_mi); return Some(content_mi);
} }
} }

View File

@@ -443,14 +443,11 @@ pub struct Crate {
pub span: Span, pub span: Span,
} }
/// A spanned compile-time attribute list item.
pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
/// Possible values inside of compile-time attribute lists. /// Possible values inside of compile-time attribute lists.
/// ///
/// E.g., the '..' in `#[name(..)]`. /// E.g., the '..' in `#[name(..)]`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)] #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum NestedMetaItemKind { pub enum NestedMetaItem {
/// A full MetaItem, for recursive meta items. /// A full MetaItem, for recursive meta items.
MetaItem(MetaItem), MetaItem(MetaItem),
/// A literal. /// A literal.
@@ -2207,7 +2204,7 @@ pub struct Item {
impl Item { impl Item {
/// Return the span that encompasses the attributes. /// Return the span that encompasses the attributes.
pub fn span_with_attributes(&self) -> Span { pub fn span_with_attributes(&self) -> Span {
self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span())) self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
} }
} }

View File

@@ -1,6 +1,6 @@
//! Parsing and validation of builtin attributes //! Parsing and validation of builtin attributes
use crate::ast::{self, Attribute, MetaItem, NestedMetaItemKind}; use crate::ast::{self, Attribute, MetaItem, NestedMetaItem};
use crate::feature_gate::{Features, GatedCfg}; use crate::feature_gate::{Features, GatedCfg};
use crate::parse::ParseSess; use crate::parse::ParseSess;
@@ -240,7 +240,7 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
} else { } else {
handle_errors( handle_errors(
sess, sess,
meta.span, meta.span(),
AttrError::UnsupportedLiteral( AttrError::UnsupportedLiteral(
"unsupported literal", "unsupported literal",
false, false,
@@ -271,11 +271,11 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
}) })
} }
(None, _) => { (None, _) => {
handle_errors(sess, attr.span(), AttrError::MissingSince); handle_errors(sess, attr.span, AttrError::MissingSince);
continue continue
} }
_ => { _ => {
span_err!(diagnostic, attr.span(), E0543, "missing 'reason'"); span_err!(diagnostic, attr.span, E0543, "missing 'reason'");
continue continue
} }
} }
@@ -291,13 +291,13 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
if let Some(feature) = feature { if let Some(feature) = feature {
rustc_const_unstable = Some(feature); rustc_const_unstable = Some(feature);
} else { } else {
span_err!(diagnostic, attr.span(), E0629, "missing 'feature'"); span_err!(diagnostic, attr.span, E0629, "missing 'feature'");
continue continue
} }
} }
"unstable" => { "unstable" => {
if stab.is_some() { if stab.is_some() {
handle_errors(sess, attr.span(), AttrError::MultipleStabilityLevels); handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
break break
} }
@@ -313,7 +313,7 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
_ => { _ => {
handle_errors( handle_errors(
sess, sess,
meta.span, meta.span(),
AttrError::UnknownMetaItem( AttrError::UnknownMetaItem(
mi.path.to_string(), mi.path.to_string(),
&["feature", "reason", "issue"] &["feature", "reason", "issue"]
@@ -325,7 +325,7 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
} else { } else {
handle_errors( handle_errors(
sess, sess,
meta.span, meta.span(),
AttrError::UnsupportedLiteral( AttrError::UnsupportedLiteral(
"unsupported literal", "unsupported literal",
false, false,
@@ -344,7 +344,7 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
if let Ok(issue) = issue.as_str().parse() { if let Ok(issue) = issue.as_str().parse() {
issue issue
} else { } else {
span_err!(diagnostic, attr.span(), E0545, span_err!(diagnostic, attr.span, E0545,
"incorrect 'issue'"); "incorrect 'issue'");
continue continue
} }
@@ -357,26 +357,26 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
}) })
} }
(None, _, _) => { (None, _, _) => {
handle_errors(sess, attr.span(), AttrError::MissingFeature); handle_errors(sess, attr.span, AttrError::MissingFeature);
continue continue
} }
_ => { _ => {
span_err!(diagnostic, attr.span(), E0547, "missing 'issue'"); span_err!(diagnostic, attr.span, E0547, "missing 'issue'");
continue continue
} }
} }
} }
"stable" => { "stable" => {
if stab.is_some() { if stab.is_some() {
handle_errors(sess, attr.span(), AttrError::MultipleStabilityLevels); handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels);
break break
} }
let mut feature = None; let mut feature = None;
let mut since = None; let mut since = None;
for meta in metas { for meta in metas {
match &meta.node { match meta {
NestedMetaItemKind::MetaItem(mi) => { NestedMetaItem::MetaItem(mi) => {
match mi.ident_str() { match mi.ident_str() {
Some("feature") => Some("feature") =>
if !get(mi, &mut feature) { continue 'outer }, if !get(mi, &mut feature) { continue 'outer },
@@ -385,7 +385,7 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
_ => { _ => {
handle_errors( handle_errors(
sess, sess,
meta.span, meta.span(),
AttrError::UnknownMetaItem( AttrError::UnknownMetaItem(
mi.path.to_string(), &["since", "note"], mi.path.to_string(), &["since", "note"],
), ),
@@ -394,7 +394,7 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
} }
} }
}, },
NestedMetaItemKind::Literal(lit) => { NestedMetaItem::Literal(lit) => {
handle_errors( handle_errors(
sess, sess,
lit.span, lit.span,
@@ -421,11 +421,11 @@ fn find_stability_generic<'a, I>(sess: &ParseSess,
}) })
} }
(None, _) => { (None, _) => {
handle_errors(sess, attr.span(), AttrError::MissingFeature); handle_errors(sess, attr.span, AttrError::MissingFeature);
continue continue
} }
_ => { _ => {
handle_errors(sess, attr.span(), AttrError::MissingSince); handle_errors(sess, attr.span, AttrError::MissingSince);
continue continue
} }
} }
@@ -520,7 +520,7 @@ pub fn eval_condition<F>(cfg: &ast::MetaItem, sess: &ParseSess, eval: &mut F)
if !mi.is_meta_item() { if !mi.is_meta_item() {
handle_errors( handle_errors(
sess, sess,
mi.span, mi.span(),
AttrError::UnsupportedLiteral( AttrError::UnsupportedLiteral(
"unsupported literal", "unsupported literal",
false false
@@ -633,8 +633,8 @@ fn find_deprecation_generic<'a, I>(sess: &ParseSess,
let mut since = None; let mut since = None;
let mut note = None; let mut note = None;
for meta in list { for meta in list {
match &meta.node { match meta {
NestedMetaItemKind::MetaItem(mi) => { NestedMetaItem::MetaItem(mi) => {
match mi.ident_str() { match mi.ident_str() {
Some("since") => if !get(mi, &mut since) { continue 'outer }, Some("since") => if !get(mi, &mut since) { continue 'outer },
Some("note") => if !get(mi, &mut note) { continue 'outer }, Some("note") => if !get(mi, &mut note) { continue 'outer },
@@ -649,7 +649,7 @@ fn find_deprecation_generic<'a, I>(sess: &ParseSess,
} }
} }
} }
NestedMetaItemKind::Literal(lit) => { NestedMetaItem::Literal(lit) => {
handle_errors( handle_errors(
sess, sess,
lit.span, lit.span,
@@ -718,7 +718,7 @@ pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
if !item.is_meta_item() { if !item.is_meta_item() {
handle_errors( handle_errors(
sess, sess,
item.span, item.span(),
AttrError::UnsupportedLiteral( AttrError::UnsupportedLiteral(
"meta item in `repr` must be an identifier", "meta item in `repr` must be an identifier",
false, false,
@@ -775,7 +775,7 @@ pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
}; };
} }
if let Some(literal_error) = literal_error { if let Some(literal_error) = literal_error {
span_err!(diagnostic, item.span, E0589, span_err!(diagnostic, item.span(), E0589,
"invalid `repr(align)` attribute: {}", literal_error); "invalid `repr(align)` attribute: {}", literal_error);
} }
} else { } else {
@@ -783,12 +783,12 @@ pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
if meta_item.check_name("align") { if meta_item.check_name("align") {
if let MetaItemKind::NameValue(ref value) = meta_item.node { if let MetaItemKind::NameValue(ref value) = meta_item.node {
recognised = true; recognised = true;
let mut err = struct_span_err!(diagnostic, item.span, E0693, let mut err = struct_span_err!(diagnostic, item.span(), E0693,
"incorrect `repr(align)` attribute format"); "incorrect `repr(align)` attribute format");
match value.node { match value.node {
ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => { ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
err.span_suggestion( err.span_suggestion(
item.span, item.span(),
"use parentheses instead", "use parentheses instead",
format!("align({})", int), format!("align({})", int),
Applicability::MachineApplicable Applicability::MachineApplicable
@@ -796,7 +796,7 @@ pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
} }
ast::LitKind::Str(s, _) => { ast::LitKind::Str(s, _) => {
err.span_suggestion( err.span_suggestion(
item.span, item.span(),
"use parentheses instead", "use parentheses instead",
format!("align({})", s), format!("align({})", s),
Applicability::MachineApplicable Applicability::MachineApplicable
@@ -811,7 +811,7 @@ pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> {
} }
if !recognised { if !recognised {
// Not a word we recognize // Not a word we recognize
span_err!(diagnostic, item.span, E0552, span_err!(diagnostic, item.span(), E0552,
"unrecognized representation hint"); "unrecognized representation hint");
} }
} }

View File

@@ -13,7 +13,7 @@ pub use StabilityLevel::*;
use crate::ast; use crate::ast;
use crate::ast::{AttrId, Attribute, AttrStyle, Name, Ident, Path, PathSegment}; use crate::ast::{AttrId, Attribute, AttrStyle, Name, Ident, Path, PathSegment};
use crate::ast::{MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind}; use crate::ast::{MetaItem, MetaItemKind, NestedMetaItem};
use crate::ast::{Lit, LitKind, Expr, ExprKind, Item, Local, Stmt, StmtKind, GenericParam}; use crate::ast::{Lit, LitKind, Expr, ExprKind, Item, Local, Stmt, StmtKind, GenericParam};
use crate::mut_visit::visit_clobber; use crate::mut_visit::visit_clobber;
use crate::source_map::{BytePos, Spanned, respan, dummy_spanned}; use crate::source_map::{BytePos, Spanned, respan, dummy_spanned};
@@ -64,27 +64,22 @@ pub fn is_known_lint_tool(m_item: Ident) -> bool {
} }
impl NestedMetaItem { impl NestedMetaItem {
/// Returns the MetaItem if self is a NestedMetaItemKind::MetaItem. /// Returns the MetaItem if self is a NestedMetaItem::MetaItem.
pub fn meta_item(&self) -> Option<&MetaItem> { pub fn meta_item(&self) -> Option<&MetaItem> {
match self.node { match *self {
NestedMetaItemKind::MetaItem(ref item) => Some(item), NestedMetaItem::MetaItem(ref item) => Some(item),
_ => None _ => None
} }
} }
/// Returns the Lit if self is a NestedMetaItemKind::Literal. /// Returns the Lit if self is a NestedMetaItem::Literal.
pub fn literal(&self) -> Option<&Lit> { pub fn literal(&self) -> Option<&Lit> {
match self.node { match *self {
NestedMetaItemKind::Literal(ref lit) => Some(lit), NestedMetaItem::Literal(ref lit) => Some(lit),
_ => None _ => None
} }
} }
/// Returns the Span for `self`.
pub fn span(&self) -> Span {
self.span
}
/// Returns `true` if this list item is a MetaItem with a name of `name`. /// Returns `true` if this list item is a MetaItem with a name of `name`.
pub fn check_name(&self, name: &str) -> bool { pub fn check_name(&self, name: &str) -> bool {
self.meta_item().map_or(false, |meta_item| meta_item.check_name(name)) self.meta_item().map_or(false, |meta_item| meta_item.check_name(name))
@@ -191,10 +186,6 @@ impl Attribute {
self.tokens.is_empty() self.tokens.is_empty()
} }
pub fn span(&self) -> Span {
self.span
}
pub fn is_meta_item_list(&self) -> bool { pub fn is_meta_item_list(&self) -> bool {
self.meta_item_list().is_some() self.meta_item_list().is_some()
} }
@@ -253,8 +244,6 @@ impl MetaItem {
} }
} }
pub fn span(&self) -> Span { self.span }
pub fn check_name(&self, name: &str) -> bool { pub fn check_name(&self, name: &str) -> bool {
self.path == name self.path == name
} }
@@ -369,7 +358,7 @@ pub fn mk_word_item(ident: Ident) -> MetaItem {
} }
pub fn mk_nested_word_item(ident: Ident) -> NestedMetaItem { pub fn mk_nested_word_item(ident: Ident) -> NestedMetaItem {
respan(ident.span, NestedMetaItemKind::MetaItem(mk_word_item(ident))) NestedMetaItem::MetaItem(mk_word_item(ident))
} }
pub fn mk_attr_id() -> AttrId { pub fn mk_attr_id() -> AttrId {
@@ -545,7 +534,7 @@ impl MetaItemKind {
if i > 0 { if i > 0 {
tokens.push(TokenTree::Token(span, Token::Comma).into()); tokens.push(TokenTree::Token(span, Token::Comma).into());
} }
item.node.tokens().append_to_tree_and_joint_vec(&mut tokens); item.tokens().append_to_tree_and_joint_vec(&mut tokens);
} }
TokenTree::Delimited( TokenTree::Delimited(
DelimSpan::from_single(span), DelimSpan::from_single(span),
@@ -579,8 +568,8 @@ impl MetaItemKind {
let mut tokens = delimited.into_trees().peekable(); let mut tokens = delimited.into_trees().peekable();
let mut result = Vec::new(); let mut result = Vec::new();
while let Some(..) = tokens.peek() { while let Some(..) = tokens.peek() {
let item = NestedMetaItemKind::from_tokens(&mut tokens)?; let item = NestedMetaItem::from_tokens(&mut tokens)?;
result.push(respan(item.span(), item)); result.push(item);
match tokens.next() { match tokens.next() {
None | Some(TokenTree::Token(_, Token::Comma)) => {} None | Some(TokenTree::Token(_, Token::Comma)) => {}
_ => return None, _ => return None,
@@ -590,32 +579,32 @@ impl MetaItemKind {
} }
} }
impl NestedMetaItemKind { impl NestedMetaItem {
fn span(&self) -> Span { pub fn span(&self) -> Span {
match *self { match *self {
NestedMetaItemKind::MetaItem(ref item) => item.span, NestedMetaItem::MetaItem(ref item) => item.span,
NestedMetaItemKind::Literal(ref lit) => lit.span, NestedMetaItem::Literal(ref lit) => lit.span,
} }
} }
fn tokens(&self) -> TokenStream { fn tokens(&self) -> TokenStream {
match *self { match *self {
NestedMetaItemKind::MetaItem(ref item) => item.tokens(), NestedMetaItem::MetaItem(ref item) => item.tokens(),
NestedMetaItemKind::Literal(ref lit) => lit.tokens(), NestedMetaItem::Literal(ref lit) => lit.tokens(),
} }
} }
fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItemKind> fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItem>
where I: Iterator<Item = TokenTree>, where I: Iterator<Item = TokenTree>,
{ {
if let Some(TokenTree::Token(span, token)) = tokens.peek().cloned() { if let Some(TokenTree::Token(span, token)) = tokens.peek().cloned() {
if let Some(node) = LitKind::from_token(token) { if let Some(node) = LitKind::from_token(token) {
tokens.next(); tokens.next();
return Some(NestedMetaItemKind::Literal(respan(span, node))); return Some(NestedMetaItem::Literal(respan(span, node)));
} }
} }
MetaItem::from_tokens(tokens).map(NestedMetaItemKind::MetaItem) MetaItem::from_tokens(tokens).map(NestedMetaItem::MetaItem)
} }
} }

View File

@@ -181,13 +181,13 @@ impl<'a> StripUnconfigured<'a> {
if nested_meta_items.is_empty() { if nested_meta_items.is_empty() {
return error(meta_item.span, "`cfg` predicate is not specified", ""); return error(meta_item.span, "`cfg` predicate is not specified", "");
} else if nested_meta_items.len() > 1 { } else if nested_meta_items.len() > 1 {
return error(nested_meta_items.last().unwrap().span, return error(nested_meta_items.last().unwrap().span(),
"multiple `cfg` predicates are specified", ""); "multiple `cfg` predicates are specified", "");
} }
match nested_meta_items[0].meta_item() { match nested_meta_items[0].meta_item() {
Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features), Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features),
None => error(nested_meta_items[0].span, None => error(nested_meta_items[0].span(),
"`cfg` predicate key cannot be a literal", ""), "`cfg` predicate key cannot be a literal", ""),
} }
}) })

View File

@@ -1520,23 +1520,23 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
self.cx.source_map().new_source_file(filename.into(), src); self.cx.source_map().new_source_file(filename.into(), src);
let include_info = vec![ let include_info = vec![
dummy_spanned(ast::NestedMetaItemKind::MetaItem( ast::NestedMetaItem::MetaItem(
attr::mk_name_value_item_str( attr::mk_name_value_item_str(
Ident::from_str("file"), Ident::from_str("file"),
dummy_spanned(file), dummy_spanned(file),
), ),
)), ),
dummy_spanned(ast::NestedMetaItemKind::MetaItem( ast::NestedMetaItem::MetaItem(
attr::mk_name_value_item_str( attr::mk_name_value_item_str(
Ident::from_str("contents"), Ident::from_str("contents"),
dummy_spanned(src_interned), dummy_spanned(src_interned),
), ),
)), ),
]; ];
let include_ident = Ident::from_str("include"); let include_ident = Ident::from_str("include");
let item = attr::mk_list_item(DUMMY_SP, include_ident, include_info); let item = attr::mk_list_item(DUMMY_SP, include_ident, include_info);
items.push(dummy_spanned(ast::NestedMetaItemKind::MetaItem(item))); items.push(ast::NestedMetaItem::MetaItem(item));
} }
Err(e) => { Err(e) => {
let lit = it let lit = it
@@ -1569,7 +1569,7 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
} }
} else { } else {
let mut err = self.cx.struct_span_err( let mut err = self.cx.struct_span_err(
it.span, it.span(),
&format!("expected path to external documentation"), &format!("expected path to external documentation"),
); );
@@ -1590,7 +1590,7 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
}; };
err.span_suggestion( err.span_suggestion(
it.span, it.span(),
"provide a file path with `=`", "provide a file path with `=`",
format!("include = \"{}\"", path), format!("include = \"{}\"", path),
applicability, applicability,

View File

@@ -2061,7 +2061,7 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
if incomplete_features.iter().any(|f| *f == name) { if incomplete_features.iter().any(|f| *f == name) {
span_handler.struct_span_warn( span_handler.struct_span_warn(
mi.span, mi.span(),
&format!( &format!(
"the feature `{}` is incomplete and may cause the compiler to crash", "the feature `{}` is incomplete and may cause the compiler to crash",
name name
@@ -2102,7 +2102,7 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
let name = match mi.ident() { let name = match mi.ident() {
Some(ident) if mi.is_word() => ident.name, Some(ident) if mi.is_word() => ident.name,
_ => { _ => {
span_err!(span_handler, mi.span, E0556, span_err!(span_handler, mi.span(), E0556,
"malformed feature, expected just one word"); "malformed feature, expected just one word");
continue continue
} }
@@ -2111,7 +2111,7 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
if let Some(edition) = edition_enabled_features.get(&name) { if let Some(edition) = edition_enabled_features.get(&name) {
struct_span_warn!( struct_span_warn!(
span_handler, span_handler,
mi.span, mi.span(),
E0705, E0705,
"the feature `{}` is included in the Rust {} edition", "the feature `{}` is included in the Rust {} edition",
name, name,
@@ -2128,32 +2128,32 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
if let Some((.., set)) = ACTIVE_FEATURES.iter().find(|f| name == f.0) { if let Some((.., set)) = ACTIVE_FEATURES.iter().find(|f| name == f.0) {
if let Some(allowed) = allow_features.as_ref() { if let Some(allowed) = allow_features.as_ref() {
if allowed.iter().find(|f| *f == name.as_str()).is_none() { if allowed.iter().find(|f| *f == name.as_str()).is_none() {
span_err!(span_handler, mi.span, E0725, span_err!(span_handler, mi.span(), E0725,
"the feature `{}` is not in the list of allowed features", "the feature `{}` is not in the list of allowed features",
name); name);
continue; continue;
} }
} }
set(&mut features, mi.span); set(&mut features, mi.span());
features.declared_lang_features.push((name, mi.span, None)); features.declared_lang_features.push((name, mi.span(), None));
continue continue
} }
let removed = REMOVED_FEATURES.iter().find(|f| name == f.0); let removed = REMOVED_FEATURES.iter().find(|f| name == f.0);
let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.0); let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.0);
if let Some((.., reason)) = removed.or(stable_removed) { if let Some((.., reason)) = removed.or(stable_removed) {
feature_removed(span_handler, mi.span, *reason); feature_removed(span_handler, mi.span(), *reason);
continue continue
} }
if let Some((_, since, ..)) = ACCEPTED_FEATURES.iter().find(|f| name == f.0) { if let Some((_, since, ..)) = ACCEPTED_FEATURES.iter().find(|f| name == f.0) {
let since = Some(Symbol::intern(since)); let since = Some(Symbol::intern(since));
features.declared_lang_features.push((name, mi.span, since)); features.declared_lang_features.push((name, mi.span(), since));
continue continue
} }
features.declared_lib_features.push((name, mi.span)); features.declared_lib_features.push((name, mi.span()));
} }
} }

View File

@@ -539,12 +539,10 @@ pub fn noop_visit_macro_def<T: MutVisitor>(macro_def: &mut MacroDef, vis: &mut T
} }
pub fn noop_visit_meta_list_item<T: MutVisitor>(li: &mut NestedMetaItem, vis: &mut T) { pub fn noop_visit_meta_list_item<T: MutVisitor>(li: &mut NestedMetaItem, vis: &mut T) {
let Spanned { node, span } = li; match li {
match node { NestedMetaItem::MetaItem(mi) => vis.visit_meta_item(mi),
NestedMetaItemKind::MetaItem(mi) => vis.visit_meta_item(mi), NestedMetaItem::Literal(_lit) => {}
NestedMetaItemKind::Literal(_lit) => {}
} }
vis.visit_span(span);
} }
pub fn noop_visit_meta_item<T: MutVisitor>(mi: &mut MetaItem, vis: &mut T) { pub fn noop_visit_meta_item<T: MutVisitor>(mi: &mut MetaItem, vis: &mut T) {

View File

@@ -1,6 +1,5 @@
use crate::attr; use crate::attr;
use crate::ast; use crate::ast;
use crate::source_map::respan;
use crate::parse::{SeqSep, PResult}; use crate::parse::{SeqSep, PResult};
use crate::parse::token::{self, Nonterminal, DelimToken}; use crate::parse::token::{self, Nonterminal, DelimToken};
use crate::parse::parser::{Parser, TokenType, PathStyle}; use crate::parse::parser::{Parser, TokenType, PathStyle};
@@ -272,14 +271,14 @@ impl<'a> Parser<'a> {
match self.parse_unsuffixed_lit() { match self.parse_unsuffixed_lit() {
Ok(lit) => { Ok(lit) => {
return Ok(respan(lo.to(self.prev_span), ast::NestedMetaItemKind::Literal(lit))) return Ok(ast::NestedMetaItem::Literal(lit))
} }
Err(ref mut err) => self.diagnostic().cancel(err) Err(ref mut err) => self.diagnostic().cancel(err)
} }
match self.parse_meta_item() { match self.parse_meta_item() {
Ok(mi) => { Ok(mi) => {
return Ok(respan(lo.to(self.prev_span), ast::NestedMetaItemKind::MetaItem(mi))) return Ok(ast::NestedMetaItem::MetaItem(mi))
} }
Err(ref mut err) => self.diagnostic().cancel(err) Err(ref mut err) => self.diagnostic().cancel(err)
} }

View File

@@ -768,11 +768,11 @@ pub trait PrintState<'a> {
} }
fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> { fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
match item.node { match item {
ast::NestedMetaItemKind::MetaItem(ref mi) => { ast::NestedMetaItem::MetaItem(ref mi) => {
self.print_meta_item(mi) self.print_meta_item(mi)
}, },
ast::NestedMetaItemKind::Literal(ref lit) => { ast::NestedMetaItem::Literal(ref lit) => {
self.print_literal(lit) self.print_literal(lit)
} }
} }

View File

@@ -435,7 +435,7 @@ fn get_test_runner(sd: &errors::Handler, krate: &ast::Crate) -> Option<ast::Path
let test_attr = attr::find_by_name(&krate.attrs, "test_runner")?; let test_attr = attr::find_by_name(&krate.attrs, "test_runner")?;
test_attr.meta_item_list().map(|meta_list| { test_attr.meta_item_list().map(|meta_list| {
if meta_list.len() != 1 { if meta_list.len() != 1 {
sd.span_fatal(test_attr.span(), sd.span_fatal(test_attr.span,
"#![test_runner(..)] accepts exactly 1 argument").raise() "#![test_runner(..)] accepts exactly 1 argument").raise()
} }
match meta_list[0].meta_item() { match meta_list[0].meta_item() {

View File

@@ -109,7 +109,7 @@ impl<'a> CollectProcMacros<'a> {
None => return, None => return,
}; };
if list.len() != 1 && list.len() != 2 { if list.len() != 1 && list.len() != 2 {
self.handler.span_err(attr.span(), self.handler.span_err(attr.span,
"attribute must have either one or two arguments"); "attribute must have either one or two arguments");
return return
} }
@@ -129,7 +129,7 @@ impl<'a> CollectProcMacros<'a> {
}; };
if !trait_ident.can_be_raw() { if !trait_ident.can_be_raw() {
self.handler.span_err(trait_attr.span(), self.handler.span_err(trait_attr.span,
&format!("`{}` cannot be a name of derive macro", trait_ident)); &format!("`{}` cannot be a name of derive macro", trait_ident));
} }
if deriving::is_builtin_trait(trait_ident.name) { if deriving::is_builtin_trait(trait_ident.name) {
@@ -164,7 +164,7 @@ impl<'a> CollectProcMacros<'a> {
}; };
if !ident.can_be_raw() { if !ident.can_be_raw() {
self.handler.span_err( self.handler.span_err(
attr.span(), attr.span,
&format!("`{}` cannot be a name of derive helper attribute", ident), &format!("`{}` cannot be a name of derive helper attribute", ident),
); );
} }
@@ -262,8 +262,8 @@ impl<'a> Visitor<'a> for CollectProcMacros<'a> {
to the same function", attr.path, prev_attr.path) to the same function", attr.path, prev_attr.path)
}; };
self.handler.struct_span_err(attr.span(), &msg) self.handler.struct_span_err(attr.span, &msg)
.span_note(prev_attr.span(), "Previous attribute here") .span_note(prev_attr.span, "Previous attribute here")
.emit(); .emit();
return; return;
@@ -288,7 +288,7 @@ impl<'a> Visitor<'a> for CollectProcMacros<'a> {
let msg = format!("the `#[{}]` attribute may only be used on bare functions", let msg = format!("the `#[{}]` attribute may only be used on bare functions",
attr.path); attr.path);
self.handler.span_err(attr.span(), &msg); self.handler.span_err(attr.span, &msg);
return; return;
} }
@@ -300,7 +300,7 @@ impl<'a> Visitor<'a> for CollectProcMacros<'a> {
let msg = format!("the `#[{}]` attribute is only usable with crates of the \ let msg = format!("the `#[{}]` attribute is only usable with crates of the \
`proc-macro` crate type", attr.path); `proc-macro` crate type", attr.path);
self.handler.span_err(attr.span(), &msg); self.handler.span_err(attr.span, &msg);
return; return;
} }

View File

@@ -227,7 +227,7 @@ fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic {
.and_then(|mi| mi.value_str()); .and_then(|mi| mi.value_str());
if list.len() != 1 || msg.is_none() { if list.len() != 1 || msg.is_none() {
sd.struct_span_warn( sd.struct_span_warn(
attr.span(), attr.span,
"argument must be of the form: \ "argument must be of the form: \
`expected = \"error message\"`" `expected = \"error message\"`"
).note("Errors in this attribute were erroneously \ ).note("Errors in this attribute were erroneously \