Rename ast::Lit as ast::MetaItemLit.

This commit is contained in:
Nicholas Nethercote 2022-11-23 15:39:42 +11:00
parent aa10aad1ac
commit e4a9150872
18 changed files with 103 additions and 84 deletions

View File

@ -13,7 +13,7 @@
//! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration. //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration.
//! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters. //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
//! - [`EnumDef`] and [`Variant`]: Enum declaration. //! - [`EnumDef`] and [`Variant`]: Enum declaration.
//! - [`Lit`] and [`LitKind`]: Literal expressions. //! - [`MetaItemLit`] and [`LitKind`]: Literal expressions.
//! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`], [`MacDelimiter`]: Macro definition and invocation. //! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`], [`MacDelimiter`]: Macro definition and invocation.
//! - [`Attribute`]: Metadata associated with item. //! - [`Attribute`]: Metadata associated with item.
//! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators. //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
@ -489,7 +489,7 @@ pub enum NestedMetaItem {
/// A literal. /// A literal.
/// ///
/// E.g., `"foo"`, `64`, `true`. /// E.g., `"foo"`, `64`, `true`.
Literal(Lit), Literal(MetaItemLit),
} }
/// A spanned compile-time attribute item. /// A spanned compile-time attribute item.
@ -518,7 +518,7 @@ pub enum MetaItemKind {
/// Name value meta item. /// Name value meta item.
/// ///
/// E.g., `feature = "foo"` as in `#[feature = "foo"]`. /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
NameValue(Lit), NameValue(MetaItemLit),
} }
/// A block (`{ .. }`). /// A block (`{ .. }`).
@ -1599,12 +1599,12 @@ pub enum AttrArgs {
} }
// The RHS of an `AttrArgs::Eq` starts out as an expression. Once macro // The RHS of an `AttrArgs::Eq` starts out as an expression. Once macro
// expansion is completed, all cases end up either as a literal, which is the // expansion is completed, all cases end up either as a meta item literal,
// form used after lowering to HIR, or as an error. // which is the form used after lowering to HIR, or as an error.
#[derive(Clone, Encodable, Decodable, Debug)] #[derive(Clone, Encodable, Decodable, Debug)]
pub enum AttrArgsEq { pub enum AttrArgsEq {
Ast(P<Expr>), Ast(P<Expr>),
Hir(Lit), Hir(MetaItemLit),
} }
impl AttrArgs { impl AttrArgs {
@ -1726,14 +1726,13 @@ pub enum StrStyle {
Raw(u8), Raw(u8),
} }
/// An AST literal. /// A literal in a meta item.
#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)] #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
pub struct Lit { pub struct MetaItemLit {
/// The original literal token as written in source code. /// The original literal token as written in source code.
pub token_lit: token::Lit, pub token_lit: token::Lit,
/// The "semantic" representation of the literal lowered from the original tokens. /// The "semantic" representation of the literal lowered from the original tokens.
/// Strings are unescaped, hexadecimal forms are eliminated, etc. /// Strings are unescaped, hexadecimal forms are eliminated, etc.
/// FIXME: Remove this and only create the semantic representation during lowering to HIR.
pub kind: LitKind, pub kind: LitKind,
pub span: Span, pub span: Span,
} }
@ -1783,6 +1782,8 @@ pub enum LitFloatType {
Unsuffixed, Unsuffixed,
} }
/// This type is used within both `ast::MetaItemLit` and `hir::Lit`.
///
/// Note that the entire literal (including the suffix) is considered when /// Note that the entire literal (including the suffix) is considered when
/// deciding the `LitKind`. This means that float literals like `1f32` are /// deciding the `LitKind`. This means that float literals like `1f32` are
/// classified by this type as `Float`. This is different to `token::LitKind` /// classified by this type as `Float`. This is different to `token::LitKind`
@ -3096,9 +3097,9 @@ mod size_asserts {
static_assert_size!(Impl, 184); static_assert_size!(Impl, 184);
static_assert_size!(Item, 184); static_assert_size!(Item, 184);
static_assert_size!(ItemKind, 112); static_assert_size!(ItemKind, 112);
static_assert_size!(Lit, 48);
static_assert_size!(LitKind, 24); static_assert_size!(LitKind, 24);
static_assert_size!(Local, 72); static_assert_size!(Local, 72);
static_assert_size!(MetaItemLit, 48);
static_assert_size!(Param, 40); static_assert_size!(Param, 40);
static_assert_size!(Pat, 88); static_assert_size!(Pat, 88);
static_assert_size!(Path, 24); static_assert_size!(Path, 24);

View File

@ -2,7 +2,7 @@
use crate::ast; use crate::ast;
use crate::ast::{AttrArgs, AttrArgsEq, AttrId, AttrItem, AttrKind, AttrStyle, Attribute}; use crate::ast::{AttrArgs, AttrArgsEq, AttrId, AttrItem, AttrKind, AttrStyle, Attribute};
use crate::ast::{DelimArgs, Lit, LitKind}; use crate::ast::{DelimArgs, LitKind, MetaItemLit};
use crate::ast::{MacDelimiter, MetaItem, MetaItemKind, NestedMetaItem}; use crate::ast::{MacDelimiter, MetaItem, MetaItemKind, NestedMetaItem};
use crate::ast::{Path, PathSegment}; use crate::ast::{Path, PathSegment};
use crate::ptr::P; use crate::ptr::P;
@ -50,8 +50,8 @@ pub fn meta_item(&self) -> Option<&MetaItem> {
} }
} }
/// Returns the `Lit` if `self` is a `NestedMetaItem::Literal`s. /// Returns the `MetaItemLit` if `self` is a `NestedMetaItem::Literal`s.
pub fn literal(&self) -> Option<&Lit> { pub fn literal(&self) -> Option<&MetaItemLit> {
match self { match self {
NestedMetaItem::Literal(lit) => Some(lit), NestedMetaItem::Literal(lit) => Some(lit),
_ => None, _ => None,
@ -78,7 +78,7 @@ pub fn value_str(&self) -> Option<Symbol> {
} }
/// Returns a name and single literal value tuple of the `MetaItem`. /// Returns a name and single literal value tuple of the `MetaItem`.
pub fn name_value_literal(&self) -> Option<(Symbol, &Lit)> { pub fn name_value_literal(&self) -> Option<(Symbol, &MetaItemLit)> {
self.meta_item().and_then(|meta_item| { self.meta_item().and_then(|meta_item| {
meta_item.meta_item_list().and_then(|meta_item_list| { meta_item.meta_item_list().and_then(|meta_item_list| {
if meta_item_list.len() == 1 if meta_item_list.len() == 1
@ -179,7 +179,7 @@ pub fn name_or_empty(&self) -> Symbol {
/// #[attribute(name = "value")] /// #[attribute(name = "value")]
/// ^^^^^^^^^^^^^^ /// ^^^^^^^^^^^^^^
/// ``` /// ```
pub fn name_value_literal(&self) -> Option<&Lit> { pub fn name_value_literal(&self) -> Option<&MetaItemLit> {
match &self.kind { match &self.kind {
MetaItemKind::NameValue(v) => Some(v), MetaItemKind::NameValue(v) => Some(v),
_ => None, _ => None,
@ -334,7 +334,7 @@ pub fn mk_name_value_item_str(ident: Ident, str: Symbol, str_span: Span) -> Meta
} }
pub fn mk_name_value_item(ident: Ident, lit_kind: LitKind, lit_span: Span) -> MetaItem { pub fn mk_name_value_item(ident: Ident, lit_kind: LitKind, lit_span: Span) -> MetaItem {
let lit = Lit::from_lit_kind(lit_kind, lit_span); let lit = MetaItemLit::from_lit_kind(lit_kind, lit_span);
let span = ident.span.to(lit_span); let span = ident.span.to(lit_span);
MetaItem { path: Path::from_ident(ident), span, kind: MetaItemKind::NameValue(lit) } MetaItem { path: Path::from_ident(ident), span, kind: MetaItemKind::NameValue(lit) }
} }
@ -604,7 +604,7 @@ fn name_value_from_tokens(
MetaItemKind::name_value_from_tokens(&mut inner_tokens.into_trees()) MetaItemKind::name_value_from_tokens(&mut inner_tokens.into_trees())
} }
Some(TokenTree::Token(token, _)) => { Some(TokenTree::Token(token, _)) => {
Lit::from_token(&token).map(MetaItemKind::NameValue) MetaItemLit::from_token(&token).map(MetaItemKind::NameValue)
} }
_ => None, _ => None,
} }
@ -622,7 +622,7 @@ fn from_attr_args(args: &AttrArgs) -> Option<MetaItemKind> {
AttrArgs::Eq(_, AttrArgsEq::Ast(expr)) => match expr.kind { AttrArgs::Eq(_, AttrArgsEq::Ast(expr)) => match expr.kind {
ast::ExprKind::Lit(token_lit) => { ast::ExprKind::Lit(token_lit) => {
// Turn failures to `None`, we'll get parse errors elsewhere. // Turn failures to `None`, we'll get parse errors elsewhere.
Lit::from_token_lit(token_lit, expr.span) MetaItemLit::from_token_lit(token_lit, expr.span)
.ok() .ok()
.map(|lit| MetaItemKind::NameValue(lit)) .map(|lit| MetaItemKind::NameValue(lit))
} }
@ -674,7 +674,7 @@ fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItem>
{ {
match tokens.peek() { match tokens.peek() {
Some(TokenTree::Token(token, _)) Some(TokenTree::Token(token, _))
if let Some(lit) = Lit::from_token(token) => if let Some(lit) = MetaItemLit::from_token(token) =>
{ {
tokens.next(); tokens.next();
return Some(NestedMetaItem::Literal(lit)); return Some(NestedMetaItem::Literal(lit));

View File

@ -1,6 +1,6 @@
//! Code related to parsing literals. //! Code related to parsing literals.
use crate::ast::{self, Lit, LitKind}; use crate::ast::{self, LitKind, MetaItemLit};
use crate::token::{self, Token}; use crate::token::{self, Token};
use rustc_lexer::unescape::{byte_from_char, unescape_byte, unescape_char, unescape_literal, Mode}; use rustc_lexer::unescape::{byte_from_char, unescape_byte, unescape_char, unescape_literal, Mode};
use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::symbol::{kw, sym, Symbol};
@ -195,26 +195,26 @@ pub fn to_token_lit(&self) -> token::Lit {
} }
} }
impl Lit { impl MetaItemLit {
/// Converts literal token into an AST literal. /// Converts token literal into a meta item literal.
pub fn from_token_lit(token_lit: token::Lit, span: Span) -> Result<Lit, LitError> { pub fn from_token_lit(token_lit: token::Lit, span: Span) -> Result<MetaItemLit, LitError> {
Ok(Lit { token_lit, kind: LitKind::from_token_lit(token_lit)?, span }) Ok(MetaItemLit { token_lit, kind: LitKind::from_token_lit(token_lit)?, span })
} }
/// Converts an arbitrary token into an AST literal. /// Converts an arbitrary token into meta item literal.
pub fn from_token(token: &Token) -> Option<Lit> { pub fn from_token(token: &Token) -> Option<MetaItemLit> {
token::Lit::from_token(token) token::Lit::from_token(token)
.and_then(|token_lit| Lit::from_token_lit(token_lit, token.span).ok()) .and_then(|token_lit| MetaItemLit::from_token_lit(token_lit, token.span).ok())
} }
/// Attempts to recover an AST literal from semantic literal. /// Attempts to create a meta item literal from a `LitKind`.
/// This function is used when the original token doesn't exist (e.g. the literal is created /// This function is used when the original token doesn't exist (e.g. the literal is created
/// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing). /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
pub fn from_lit_kind(kind: LitKind, span: Span) -> Lit { pub fn from_lit_kind(kind: LitKind, span: Span) -> MetaItemLit {
Lit { token_lit: kind.to_token_lit(), kind, span } MetaItemLit { token_lit: kind.to_token_lit(), kind, span }
} }
/// Losslessly convert an AST literal into a token. /// Losslessly convert a meta item literal into a token.
pub fn to_token(&self) -> Token { pub fn to_token(&self) -> Token {
let kind = match self.token_lit.kind { let kind = match self.token_lit.kind {
token::Bool => token::Ident(self.token_lit.symbol, false), token::Bool => token::Ident(self.token_lit.symbol, false),

View File

@ -948,12 +948,12 @@ fn lower_attr_args(&self, args: &AttrArgs) -> AttrArgs {
AttrArgs::Eq(eq_span, AttrArgsEq::Ast(expr)) => { AttrArgs::Eq(eq_span, AttrArgsEq::Ast(expr)) => {
// In valid code the value always ends up as a single literal. Otherwise, a dummy // In valid code the value always ends up as a single literal. Otherwise, a dummy
// literal suffices because the error is handled elsewhere. // literal suffices because the error is handled elsewhere.
let lit = if let ExprKind::Lit(token_lit) = expr.kind let lit = if let ExprKind::Lit(token_lit) = expr.kind
&& let Ok(lit) = Lit::from_token_lit(token_lit, expr.span) && let Ok(lit) = MetaItemLit::from_token_lit(token_lit, expr.span)
{ {
lit lit
} else { } else {
Lit { MetaItemLit {
token_lit: token::Lit::new(token::LitKind::Err, kw::Empty, None), token_lit: token::Lit::new(token::LitKind::Err, kw::Empty, None),
kind: LitKind::Err, kind: LitKind::Err,
span: DUMMY_SP, span: DUMMY_SP,

View File

@ -371,7 +371,7 @@ fn print_remaining_comments(&mut self) {
} }
} }
fn print_literal(&mut self, lit: &ast::Lit) { fn print_meta_item_lit(&mut self, lit: &ast::MetaItemLit) {
self.print_token_literal(lit.token_lit, lit.span) self.print_token_literal(lit.token_lit, lit.span)
} }
@ -488,7 +488,7 @@ fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) {
self.print_path(&item.path, false, 0); self.print_path(&item.path, false, 0);
self.space(); self.space();
self.word_space("="); self.word_space("=");
let token_str = self.literal_to_string(lit); let token_str = self.meta_item_lit_to_string(lit);
self.word(token_str); self.word(token_str);
} }
} }
@ -498,7 +498,7 @@ fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) {
fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) { fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
match item { match item {
ast::NestedMetaItem::MetaItem(ref mi) => self.print_meta_item(mi), ast::NestedMetaItem::MetaItem(ref mi) => self.print_meta_item(mi),
ast::NestedMetaItem::Literal(ref lit) => self.print_literal(lit), ast::NestedMetaItem::Literal(ref lit) => self.print_meta_item_lit(lit),
} }
} }
@ -510,7 +510,7 @@ fn print_meta_item(&mut self, item: &ast::MetaItem) {
self.print_path(&item.path, false, 0); self.print_path(&item.path, false, 0);
self.space(); self.space();
self.word_space("="); self.word_space("=");
self.print_literal(value); self.print_meta_item_lit(value);
} }
ast::MetaItemKind::List(ref items) => { ast::MetaItemKind::List(ref items) => {
self.print_path(&item.path, false, 0); self.print_path(&item.path, false, 0);
@ -825,8 +825,8 @@ fn expr_to_string(&self, e: &ast::Expr) -> String {
Self::to_string(|s| s.print_expr(e)) Self::to_string(|s| s.print_expr(e))
} }
fn literal_to_string(&self, lit: &ast::Lit) -> String { fn meta_item_lit_to_string(&self, lit: &ast::MetaItemLit) -> String {
Self::to_string(|s| s.print_literal(lit)) Self::to_string(|s| s.print_meta_item_lit(lit))
} }
fn tt_to_string(&self, tt: &TokenTree) -> String { fn tt_to_string(&self, tt: &TokenTree) -> String {

View File

@ -1,7 +1,7 @@
//! Parsing and validation of builtin attributes //! Parsing and validation of builtin attributes
use rustc_ast as ast; use rustc_ast as ast;
use rustc_ast::{Attribute, Lit, LitKind, MetaItem, MetaItemKind, NestedMetaItem, NodeId}; use rustc_ast::{Attribute, LitKind, MetaItem, MetaItemKind, MetaItemLit, NestedMetaItem, NodeId};
use rustc_ast_pretty::pprust; use rustc_ast_pretty::pprust;
use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg}; use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg};
use rustc_macros::HashStable_Generic; use rustc_macros::HashStable_Generic;
@ -658,11 +658,13 @@ pub fn eval_condition(
ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => { ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
try_gate_cfg(sym::version, cfg.span, sess, features); try_gate_cfg(sym::version, cfg.span, sess, features);
let (min_version, span) = match &mis[..] { let (min_version, span) = match &mis[..] {
[NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
(sym, span)
}
[ [
NestedMetaItem::Literal(Lit { span, .. }) NestedMetaItem::Literal(MetaItemLit {
kind: LitKind::Str(sym, ..), span, ..
}),
] => (sym, span),
[
NestedMetaItem::Literal(MetaItemLit { span, .. })
| NestedMetaItem::MetaItem(MetaItem { span, .. }), | NestedMetaItem::MetaItem(MetaItem { span, .. }),
] => { ] => {
sess.emit_err(session_diagnostics::ExpectedVersionLiteral { span: *span }); sess.emit_err(session_diagnostics::ExpectedVersionLiteral { span: *span });

View File

@ -50,7 +50,7 @@ fn expand(
NestedMetaItem::MetaItem(meta) => Some(meta), NestedMetaItem::MetaItem(meta) => Some(meta),
NestedMetaItem::Literal(lit) => { NestedMetaItem::Literal(lit) => {
// Reject `#[derive("Debug")]`. // Reject `#[derive("Debug")]`.
report_unexpected_literal(sess, &lit); report_unexpected_meta_item_lit(sess, &lit);
None None
} }
}) })
@ -127,7 +127,7 @@ fn report_bad_target(sess: &Session, item: &Annotatable, span: Span) -> bool {
bad_target bad_target
} }
fn report_unexpected_literal(sess: &Session, lit: &ast::Lit) { fn report_unexpected_meta_item_lit(sess: &Session, lit: &ast::MetaItemLit) {
let help_msg = match lit.token_lit.kind { let help_msg = match lit.token_lit.kind {
token::Str if rustc_lexer::is_ident(lit.token_lit.symbol.as_str()) => { token::Str if rustc_lexer::is_ident(lit.token_lit.symbol.as_str()) => {
format!("try using `#[derive({})]`", lit.token_lit.symbol) format!("try using `#[derive({})]`", lit.token_lit.symbol)

View File

@ -527,10 +527,7 @@ fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStrea
} }
ast::ExprKind::IncludedBytes(bytes) => { ast::ExprKind::IncludedBytes(bytes) => {
let lit = ast::LitKind::ByteStr(bytes.clone()).to_token_lit(); let lit = ast::LitKind::ByteStr(bytes.clone()).to_token_lit();
Ok(tokenstream::TokenStream::token_alone( Ok(tokenstream::TokenStream::token_alone(token::TokenKind::Literal(lit), expr.span))
token::TokenKind::Literal(lit),
expr.span,
))
} }
ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind { ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
ast::ExprKind::Lit(token_lit) => match token_lit { ast::ExprKind::Lit(token_lit) => match token_lit {

View File

@ -2145,7 +2145,7 @@ fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
} }
fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<u16> { fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<u16> {
use rustc_ast::{Lit, LitIntType, LitKind}; use rustc_ast::{LitIntType, LitKind, MetaItemLit};
if !tcx.features().raw_dylib && tcx.sess.target.arch == "x86" { if !tcx.features().raw_dylib && tcx.sess.target.arch == "x86" {
feature_err( feature_err(
&tcx.sess.parse_sess, &tcx.sess.parse_sess,
@ -2168,7 +2168,9 @@ fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<u16> {
} }
_ => None, _ => None,
}; };
if let Some(Lit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) = sole_meta_list { if let Some(MetaItemLit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) =
sole_meta_list
{
// According to the table at https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-header, // According to the table at https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-header,
// the ordinal must fit into 16 bits. Similarly, the Ordinal field in COFFShortExport (defined // the ordinal must fit into 16 bits. Similarly, the Ordinal field in COFFShortExport (defined
// in llvm/include/llvm/Object/COFFImportFile.h), which we use to communicate import information // in llvm/include/llvm/Object/COFFImportFile.h), which we use to communicate import information

View File

@ -1191,8 +1191,9 @@ pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound<u128>, Bound<u12
debug!("layout_scalar_valid_range: attr={:?}", attr); debug!("layout_scalar_valid_range: attr={:?}", attr);
if let Some( if let Some(
&[ &[
ast::NestedMetaItem::Literal(ast::Lit { ast::NestedMetaItem::Literal(ast::MetaItemLit {
kind: ast::LitKind::Int(a, _), .. kind: ast::LitKind::Int(a, _),
..
}), }),
], ],
) = attr.meta_item_list().as_deref() ) = attr.meta_item_list().as_deref()

View File

@ -315,8 +315,9 @@ pub(crate) fn parse_inner_attributes(&mut self) -> PResult<'a, ast::AttrVec> {
Ok(attrs) Ok(attrs)
} }
pub(crate) fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> { // Note: must be unsuffixed.
let lit = self.parse_ast_lit()?; pub(crate) fn parse_unsuffixed_meta_item_lit(&mut self) -> PResult<'a, ast::MetaItemLit> {
let lit = self.parse_meta_item_lit()?;
debug!("checking if {:?} is unsuffixed", lit); debug!("checking if {:?} is unsuffixed", lit);
if !lit.kind.is_unsuffixed() { if !lit.kind.is_unsuffixed() {
@ -391,7 +392,7 @@ pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> {
pub(crate) fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> { pub(crate) fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
Ok(if self.eat(&token::Eq) { Ok(if self.eat(&token::Eq) {
ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?) ast::MetaItemKind::NameValue(self.parse_unsuffixed_meta_item_lit()?)
} else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) { } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
// Matches `meta_seq = ( COMMASEP(meta_item_inner) )`. // Matches `meta_seq = ( COMMASEP(meta_item_inner) )`.
let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?; let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?;
@ -403,7 +404,7 @@ pub(crate) fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind>
/// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`. /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`.
fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> { fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
match self.parse_unsuffixed_lit() { match self.parse_unsuffixed_meta_item_lit() {
Ok(lit) => return Ok(ast::NestedMetaItem::Literal(lit)), Ok(lit) => return Ok(ast::NestedMetaItem::Literal(lit)),
Err(err) => err.cancel(), Err(err) => err.cancel(),
} }

View File

@ -33,10 +33,10 @@
use rustc_ast::util::classify; use rustc_ast::util::classify;
use rustc_ast::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity}; use rustc_ast::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity};
use rustc_ast::visit::Visitor; use rustc_ast::visit::Visitor;
use rustc_ast::{self as ast, AttrStyle, AttrVec, CaptureBy, ExprField, Lit, UnOp, DUMMY_NODE_ID}; use rustc_ast::{self as ast, AttrStyle, AttrVec, CaptureBy, ExprField, UnOp, DUMMY_NODE_ID};
use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind}; use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind};
use rustc_ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits}; use rustc_ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits};
use rustc_ast::{ClosureBinder, StmtKind}; use rustc_ast::{ClosureBinder, MetaItemLit, StmtKind};
use rustc_ast_pretty::pprust; use rustc_ast_pretty::pprust;
use rustc_errors::{ use rustc_errors::{
Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic, PResult, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic, PResult,
@ -1631,7 +1631,7 @@ pub(super) fn recover_unclosed_char(
&self, &self,
lifetime: Ident, lifetime: Ident,
err: impl FnOnce(&Self) -> DiagnosticBuilder<'a, ErrorGuaranteed>, err: impl FnOnce(&Self) -> DiagnosticBuilder<'a, ErrorGuaranteed>,
) -> ast::Lit { ) -> ast::MetaItemLit {
if let Some(mut diag) = if let Some(mut diag) =
self.sess.span_diagnostic.steal_diagnostic(lifetime.span, StashKey::LifetimeIsChar) self.sess.span_diagnostic.steal_diagnostic(lifetime.span, StashKey::LifetimeIsChar)
{ {
@ -1653,7 +1653,7 @@ pub(super) fn recover_unclosed_char(
.emit(); .emit();
} }
let name = lifetime.without_first_quote().name; let name = lifetime.without_first_quote().name;
ast::Lit { ast::MetaItemLit {
token_lit: token::Lit::new(token::LitKind::Char, name, None), token_lit: token::Lit::new(token::LitKind::Char, name, None),
kind: ast::LitKind::Char(name.as_str().chars().next().unwrap_or('_')), kind: ast::LitKind::Char(name.as_str().chars().next().unwrap_or('_')),
span: lifetime.span, span: lifetime.span,
@ -1768,8 +1768,8 @@ fn parse_yield_expr(&mut self) -> PResult<'a, P<Expr>> {
/// Returns a string literal if the next token is a string literal. /// Returns a string literal if the next token is a string literal.
/// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind, /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
/// and returns `None` if the next token is not literal at all. /// and returns `None` if the next token is not literal at all.
pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> { pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<MetaItemLit>> {
match self.parse_opt_ast_lit() { match self.parse_opt_meta_item_lit() {
Some(lit) => match lit.kind { Some(lit) => match lit.kind {
ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit { ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
style, style,
@ -1784,7 +1784,7 @@ pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
} }
} }
fn handle_missing_lit(&mut self) -> PResult<'a, Lit> { fn handle_missing_lit(&mut self) -> PResult<'a, MetaItemLit> {
if let token::Interpolated(inner) = &self.token.kind { if let token::Interpolated(inner) = &self.token.kind {
let expr = match inner.as_ref() { let expr = match inner.as_ref() {
token::NtExpr(expr) => Some(expr), token::NtExpr(expr) => Some(expr),
@ -1820,8 +1820,8 @@ pub(super) fn parse_token_lit(&mut self) -> PResult<'a, (token::Lit, Span)> {
.or_else(|()| self.handle_missing_lit().map(|lit| (lit.token_lit, lit.span))) .or_else(|()| self.handle_missing_lit().map(|lit| (lit.token_lit, lit.span)))
} }
pub(super) fn parse_ast_lit(&mut self) -> PResult<'a, Lit> { pub(super) fn parse_meta_item_lit(&mut self) -> PResult<'a, MetaItemLit> {
self.parse_opt_ast_lit().ok_or(()).or_else(|()| self.handle_missing_lit()) self.parse_opt_meta_item_lit().ok_or(()).or_else(|()| self.handle_missing_lit())
} }
fn recover_after_dot(&mut self) -> Option<Token> { fn recover_after_dot(&mut self) -> Option<Token> {
@ -1867,12 +1867,12 @@ pub(super) fn parse_opt_token_lit(&mut self) -> Option<(token::Lit, Span)> {
/// Matches `lit = true | false | token_lit`. /// Matches `lit = true | false | token_lit`.
/// Returns `None` if the next token is not a literal. /// Returns `None` if the next token is not a literal.
pub(super) fn parse_opt_ast_lit(&mut self) -> Option<Lit> { pub(super) fn parse_opt_meta_item_lit(&mut self) -> Option<MetaItemLit> {
let recovered = self.recover_after_dot(); let recovered = self.recover_after_dot();
let token = recovered.as_ref().unwrap_or(&self.token); let token = recovered.as_ref().unwrap_or(&self.token);
match token::Lit::from_token(token) { match token::Lit::from_token(token) {
Some(token_lit) => { Some(token_lit) => {
match Lit::from_token_lit(token_lit, token.span) { match MetaItemLit::from_token_lit(token_lit, token.span) {
Ok(lit) => { Ok(lit) => {
self.bump(); self.bump();
Some(lit) Some(lit)
@ -1889,7 +1889,10 @@ pub(super) fn parse_opt_ast_lit(&mut self) -> Option<Lit> {
let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None); let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
let symbol = Symbol::intern(&suffixless_lit.to_string()); let symbol = Symbol::intern(&suffixless_lit.to_string());
let lit = token::Lit::new(token::Err, symbol, lit.suffix); let lit = token::Lit::new(token::Err, symbol, lit.suffix);
Some(Lit::from_token_lit(lit, span).unwrap_or_else(|_| unreachable!())) Some(
MetaItemLit::from_token_lit(lit, span)
.unwrap_or_else(|_| unreachable!()),
)
} }
} }
} }

View File

@ -358,7 +358,7 @@ fn parse_local(&mut self, attrs: AttrVec) -> PResult<'a, P<Local>> {
/// report error for `let 1x = 123` /// report error for `let 1x = 123`
pub fn report_invalid_identifier_error(&mut self) -> PResult<'a, ()> { pub fn report_invalid_identifier_error(&mut self) -> PResult<'a, ()> {
if let token::Literal(lit) = self.token.uninterpolate().kind && if let token::Literal(lit) = self.token.uninterpolate().kind &&
rustc_ast::Lit::from_token(&self.token).is_none() && rustc_ast::MetaItemLit::from_token(&self.token).is_none() &&
(lit.kind == token::LitKind::Integer || lit.kind == token::LitKind::Float) && (lit.kind == token::LitKind::Integer || lit.kind == token::LitKind::Float) &&
self.look_ahead(1, |t| matches!(t.kind, token::Eq) || matches!(t.kind, token::Colon ) ) { self.look_ahead(1, |t| matches!(t.kind, token::Eq) || matches!(t.kind, token::Colon ) ) {
return Err(self.sess.create_err(InvalidIdentiferStartsWithNumber { span: self.token.span })); return Err(self.sess.create_err(InvalidIdentiferStartsWithNumber { span: self.token.span }));

View File

@ -51,7 +51,7 @@ pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Meta
} }
AttrArgs::Eq(_, AttrArgsEq::Ast(expr)) => { AttrArgs::Eq(_, AttrArgsEq::Ast(expr)) => {
if let ast::ExprKind::Lit(token_lit) = expr.kind if let ast::ExprKind::Lit(token_lit) = expr.kind
&& let Ok(lit) = ast::Lit::from_token_lit(token_lit, expr.span) && let Ok(lit) = ast::MetaItemLit::from_token_lit(token_lit, expr.span)
{ {
if token_lit.suffix.is_some() { if token_lit.suffix.is_some() {
let mut err = sess.span_diagnostic.struct_span_err( let mut err = sess.span_diagnostic.struct_span_err(

View File

@ -8,7 +8,7 @@
self, AttrApplication, DebugVisualizerUnreadable, InvalidAttrAtCrateLevel, ObjectLifetimeErr, self, AttrApplication, DebugVisualizerUnreadable, InvalidAttrAtCrateLevel, ObjectLifetimeErr,
OnlyHasEffectOn, TransparentIncompatible, UnrecognizedReprHint, OnlyHasEffectOn, TransparentIncompatible, UnrecognizedReprHint,
}; };
use rustc_ast::{ast, AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem}; use rustc_ast::{ast, AttrStyle, Attribute, LitKind, MetaItemKind, MetaItemLit, NestedMetaItem};
use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::fx::FxHashMap;
use rustc_errors::{fluent, Applicability, MultiSpan}; use rustc_errors::{fluent, Applicability, MultiSpan};
use rustc_expand::base::resolve_path; use rustc_expand::base::resolve_path;
@ -1355,7 +1355,10 @@ fn check_rustc_layout_scalar_valid_range(
return false; return false;
}; };
if matches!(&list[..], &[NestedMetaItem::Literal(Lit { kind: LitKind::Int(..), .. })]) { if matches!(
&list[..],
&[NestedMetaItem::Literal(MetaItemLit { kind: LitKind::Int(..), .. })]
) {
true true
} else { } else {
self.tcx.sess.emit_err(errors::RustcLayoutScalarValidRangeArg { attr_span: attr.span }); self.tcx.sess.emit_err(errors::RustcLayoutScalarValidRangeArg { attr_span: attr.span });

View File

@ -6,7 +6,7 @@
use clippy_utils::source::{first_line_of_span, is_present_in_source, snippet_opt, without_block_comments}; use clippy_utils::source::{first_line_of_span, is_present_in_source, snippet_opt, without_block_comments};
use clippy_utils::{extract_msrv_attr, meets_msrv}; use clippy_utils::{extract_msrv_attr, meets_msrv};
use if_chain::if_chain; use if_chain::if_chain;
use rustc_ast::{AttrKind, AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem}; use rustc_ast::{AttrKind, AttrStyle, Attribute, LitKind, MetaItemKind, MetaItemLit, NestedMetaItem};
use rustc_errors::Applicability; use rustc_errors::Applicability;
use rustc_hir::{ use rustc_hir::{
Block, Expr, ExprKind, ImplItem, ImplItemKind, Item, ItemKind, StmtKind, TraitFn, TraitItem, TraitItemKind, Block, Expr, ExprKind, ImplItem, ImplItemKind, Item, ItemKind, StmtKind, TraitFn, TraitItem, TraitItemKind,
@ -576,7 +576,7 @@ fn check_attrs(cx: &LateContext<'_>, span: Span, name: Symbol, attrs: &[Attribut
} }
} }
fn check_semver(cx: &LateContext<'_>, span: Span, lit: &Lit) { fn check_semver(cx: &LateContext<'_>, span: Span, lit: &MetaItemLit) {
if let LitKind::Str(is, _) = lit.kind { if let LitKind::Str(is, _) = lit.kind {
if Version::parse(is.as_str()).is_ok() { if Version::parse(is.as_str()).is_ok() {
return; return;

View File

@ -527,14 +527,19 @@ fn visit_meta_list(
fn visit_meta_word(&mut self, _meta_item: &'ast ast::MetaItem) {} fn visit_meta_word(&mut self, _meta_item: &'ast ast::MetaItem) {}
fn visit_meta_name_value(&mut self, _meta_item: &'ast ast::MetaItem, _lit: &'ast ast::Lit) {} fn visit_meta_name_value(
&mut self,
_meta_item: &'ast ast::MetaItem,
_lit: &'ast ast::MetaItemLit,
) {
}
fn visit_nested_meta_item(&mut self, nm: &'ast ast::NestedMetaItem) { fn visit_nested_meta_item(&mut self, nm: &'ast ast::NestedMetaItem) {
match nm { match nm {
ast::NestedMetaItem::MetaItem(ref meta_item) => self.visit_meta_item(meta_item), ast::NestedMetaItem::MetaItem(ref meta_item) => self.visit_meta_item(meta_item),
ast::NestedMetaItem::Literal(ref lit) => self.visit_literal(lit), ast::NestedMetaItem::Literal(ref lit) => self.visit_meta_item_lit(lit),
} }
} }
fn visit_literal(&mut self, _lit: &'ast ast::Lit) {} fn visit_meta_item_lit(&mut self, _lit: &'ast ast::MetaItemLit) {}
} }

View File

@ -84,15 +84,19 @@ pub(crate) fn paths(self) -> Vec<String> {
} }
impl<'ast> MetaVisitor<'ast> for PathVisitor { impl<'ast> MetaVisitor<'ast> for PathVisitor {
fn visit_meta_name_value(&mut self, meta_item: &'ast ast::MetaItem, lit: &'ast ast::Lit) { fn visit_meta_name_value(
&mut self,
meta_item: &'ast ast::MetaItem,
lit: &'ast ast::MetaItemLit,
) {
if meta_item.has_name(Symbol::intern("path")) && lit.kind.is_str() { if meta_item.has_name(Symbol::intern("path")) && lit.kind.is_str() {
self.paths.push(lit_to_str(lit)); self.paths.push(meta_item_lit_to_str(lit));
} }
} }
} }
#[cfg(not(windows))] #[cfg(not(windows))]
fn lit_to_str(lit: &ast::Lit) -> String { fn meta_item_lit_to_str(lit: &ast::MetaItemLit) -> String {
match lit.kind { match lit.kind {
ast::LitKind::Str(symbol, ..) => symbol.to_string(), ast::LitKind::Str(symbol, ..) => symbol.to_string(),
_ => unreachable!(), _ => unreachable!(),
@ -100,7 +104,7 @@ fn lit_to_str(lit: &ast::Lit) -> String {
} }
#[cfg(windows)] #[cfg(windows)]
fn lit_to_str(lit: &ast::Lit) -> String { fn meta_item_lit_to_str(lit: &ast::MetaItemLit) -> String {
match lit.kind { match lit.kind {
ast::LitKind::Str(symbol, ..) => symbol.as_str().replace("/", "\\"), ast::LitKind::Str(symbol, ..) => symbol.as_str().replace("/", "\\"),
_ => unreachable!(), _ => unreachable!(),