diff options
| author | Peter <peter.wilkins@polecat.com> | 2019-12-08 23:16:18 +0000 |
|---|---|---|
| committer | Peter <peter.wilkins@polecat.com> | 2019-12-08 23:49:30 +0000 |
| commit | 8f6a06285efe12d778ff7f44067aebeed7b14428 (patch) | |
| tree | 856b9d17a8e4700c44a2794e63ec75ecf9660397 /src/libsyntax | |
| parent | 947772fc31b96ce90f57720f74571f14e35df66b (diff) | |
| parent | 59947fcae6a40df12e33af8c8c7291014b7603e0 (diff) | |
| download | rust-8f6a06285efe12d778ff7f44067aebeed7b14428.tar.gz rust-8f6a06285efe12d778ff7f44067aebeed7b14428.zip | |
move from non zero impls to `libcore/convert/num.rs`
Diffstat (limited to 'src/libsyntax')
52 files changed, 768 insertions, 19874 deletions
diff --git a/src/libsyntax/Cargo.toml b/src/libsyntax/Cargo.toml index 3e17e7949ea..8a00bcbfe17 100644 --- a/src/libsyntax/Cargo.toml +++ b/src/libsyntax/Cargo.toml @@ -18,6 +18,10 @@ lazy_static = "1.0.0" syntax_pos = { path = "../libsyntax_pos" } errors = { path = "../librustc_errors", package = "rustc_errors" } rustc_data_structures = { path = "../librustc_data_structures" } +rustc_feature = { path = "../librustc_feature" } rustc_index = { path = "../librustc_index" } rustc_lexer = { path = "../librustc_lexer" } +rustc_macros = { path = "../librustc_macros" } smallvec = { version = "1.0", features = ["union", "may_dangle"] } +rustc_error_codes = { path = "../librustc_error_codes" } +rustc_session = { path = "../librustc_session" } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index b57d2238991..92ba071a03d 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -27,20 +27,19 @@ pub use syntax_pos::symbol::{Ident, Symbol as Name}; use crate::ptr::P; use crate::source_map::{dummy_spanned, respan, Spanned}; use crate::token::{self, DelimToken}; -use crate::tokenstream::TokenStream; +use crate::tokenstream::{TokenStream, TokenTree, DelimSpan}; use syntax_pos::symbol::{kw, sym, Symbol}; -use syntax_pos::{Span, DUMMY_SP, ExpnId}; +use syntax_pos::{Span, DUMMY_SP}; -use rustc_data_structures::fx::FxHashSet; +use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::Lrc; use rustc_data_structures::thin_vec::ThinVec; use rustc_index::vec::Idx; use rustc_serialize::{self, Decoder, Encoder}; +use rustc_macros::HashStable_Generic; -#[cfg(target_arch = "x86_64")] -use rustc_data_structures::static_assert_size; - +use std::iter; use std::fmt; #[cfg(test)] @@ -56,7 +55,7 @@ mod tests; /// ``` /// /// `'outer` is a label. -#[derive(Clone, RustcEncodable, RustcDecodable, Copy)] +#[derive(Clone, RustcEncodable, RustcDecodable, Copy, HashStable_Generic)] pub struct Label { pub ident: Ident, } @@ -114,6 +113,15 @@ impl PartialEq<Symbol> for Path { } } +impl<CTX> HashStable<CTX> for Path { + fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { + self.segments.len().hash_stable(hcx, hasher); + for segment in &self.segments { + segment.ident.name.hash_stable(hcx, hasher); + } + } +} + impl Path { // Convert a span and an identifier to the corresponding // one-segment path. @@ -259,46 +267,7 @@ impl ParenthesizedArgs { } } -// hack to ensure that we don't try to access the private parts of `NodeId` in this module -mod node_id_inner { - use rustc_index::vec::Idx; - rustc_index::newtype_index! { - pub struct NodeId { - ENCODABLE = custom - DEBUG_FORMAT = "NodeId({})" - } - } -} - -pub use node_id_inner::NodeId; - -impl NodeId { - pub fn placeholder_from_expn_id(expn_id: ExpnId) -> Self { - NodeId::from_u32(expn_id.as_u32()) - } - - pub fn placeholder_to_expn_id(self) -> ExpnId { - ExpnId::from_u32(self.as_u32()) - } -} - -impl fmt::Display for NodeId { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Display::fmt(&self.as_u32(), f) - } -} - -impl rustc_serialize::UseSpecializedEncodable for NodeId { - fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { - s.emit_u32(self.as_u32()) - } -} - -impl rustc_serialize::UseSpecializedDecodable for NodeId { - fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> { - d.read_u32().map(NodeId::from_u32) - } -} +pub use rustc_session::node_id::NodeId; /// `NodeId` used to represent the root of the crate. pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0); @@ -461,9 +430,7 @@ pub struct WhereEqPredicate { pub rhs_ty: P<Ty>, } -/// The set of `MetaItem`s that define the compilation environment of the crate, -/// used to drive conditional compilation. -pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>; +pub use rustc_session::parse::CrateConfig; #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Crate { @@ -475,7 +442,7 @@ pub struct Crate { /// Possible values inside of compile-time attribute lists. /// /// E.g., the '..' in `#[name(..)]`. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug)] +#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub enum NestedMetaItem { /// A full MetaItem, for recursive meta items. MetaItem(MetaItem), @@ -488,7 +455,7 @@ pub enum NestedMetaItem { /// A spanned compile-time attribute item. /// /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug)] +#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub struct MetaItem { pub path: Path, pub kind: MetaItemKind, @@ -498,7 +465,7 @@ pub struct MetaItem { /// A compile-time attribute item. /// /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug)] +#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub enum MetaItemKind { /// Word meta item. /// @@ -537,7 +504,7 @@ pub struct Pat { impl Pat { /// Attempt reparsing the pattern as a type. /// This is intended for use by diagnostics. - pub(super) fn to_ty(&self) -> Option<P<Ty>> { + pub fn to_ty(&self) -> Option<P<Ty>> { let kind = match &self.kind { // In a type expression `_` is an inference variable. PatKind::Wild => TyKind::Infer, @@ -725,14 +692,52 @@ pub enum PatKind { Mac(Mac), } -#[derive( - Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy, -)] +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, + RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)] pub enum Mutability { Mutable, Immutable, } +impl Mutability { + /// Returns `MutMutable` only if both `self` and `other` are mutable. + pub fn and(self, other: Self) -> Self { + match self { + Mutability::Mutable => other, + Mutability::Immutable => Mutability::Immutable, + } + } + + pub fn invert(self) -> Self { + match self { + Mutability::Mutable => Mutability::Immutable, + Mutability::Immutable => Mutability::Mutable, + } + } + + pub fn prefix_str(&self) -> &'static str { + match self { + Mutability::Mutable => "mut ", + Mutability::Immutable => "", + } + } +} + +/// The kind of borrow in an `AddrOf` expression, +/// e.g., `&place` or `&raw const place`. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[derive(RustcEncodable, RustcDecodable, HashStable_Generic)] +pub enum BorrowKind { + /// A raw borrow, `&raw const $expr` or `&raw mut $expr`. + /// The resulting type is either `*const T` or `*mut T` + /// where `T = typeof($expr)`. + Ref, + /// A normal borrow, `&$expr` or `&mut $expr`. + /// The resulting type is either `&'a T` or `&'a mut T` + /// where `T = typeof($expr)` and `'a` is some lifetime. + Raw, +} + #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)] pub enum BinOpKind { /// The `+` operator (addition) @@ -961,12 +966,12 @@ pub struct Arm { /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Field { + pub attrs: ThinVec<Attribute>, + pub id: NodeId, + pub span: Span, pub ident: Ident, pub expr: P<Expr>, - pub span: Span, pub is_shorthand: bool, - pub attrs: ThinVec<Attribute>, - pub id: NodeId, pub is_placeholder: bool, } @@ -1004,7 +1009,7 @@ pub struct Expr { // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(target_arch = "x86_64")] -static_assert_size!(Expr, 96); +rustc_data_structures::static_assert_size!(Expr, 96); impl Expr { /// Returns `true` if this expression would be valid somewhere that expects a value; @@ -1031,7 +1036,7 @@ impl Expr { } } - fn to_bound(&self) -> Option<GenericBound> { + pub fn to_bound(&self) -> Option<GenericBound> { match &self.kind { ExprKind::Path(None, path) => Some(GenericBound::Trait( PolyTraitRef::new(Vec::new(), path.clone(), self.span), @@ -1042,7 +1047,7 @@ impl Expr { } /// Attempts to reparse as `Ty` (for diagnostic purposes). - pub(super) fn to_ty(&self) -> Option<P<Ty>> { + pub fn to_ty(&self) -> Option<P<Ty>> { let kind = match &self.kind { // Trivial conversions. ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()), @@ -1050,7 +1055,7 @@ impl Expr { ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?, - ExprKind::AddrOf(mutbl, expr) => expr + ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => expr .to_ty() .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?, @@ -1241,8 +1246,8 @@ pub enum ExprKind { /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`). Path(Option<QSelf>, Path), - /// A referencing operation (`&a` or `&mut a`). - AddrOf(Mutability, P<Expr>), + /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`). + AddrOf(BorrowKind, Mutability, P<Expr>), /// A `break`, with an optional label to break, and an optional expression. Break(Option<Label>, Option<P<Expr>>), /// A `continue`, with an optional label. @@ -1307,7 +1312,7 @@ pub struct QSelf { } /// A capture clause used in closures and `async` blocks. -#[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)] +#[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub enum CaptureBy { /// `move |x| y + x`. Value, @@ -1315,41 +1320,100 @@ pub enum CaptureBy { Ref, } -/// The movability of a generator / closure literal. -#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)] +/// The movability of a generator / closure literal: +/// whether a generator contains self-references, causing it to be `!Unpin`. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, + RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)] pub enum Movability { + /// May contain self-references, `!Unpin`. Static, + /// Must not contain self-references, `Unpin`. Movable, } -/// Represents a macro invocation. The `Path` indicates which macro -/// is being invoked, and the vector of token-trees contains the source -/// of the macro invocation. -/// -/// N.B., the additional ident for a `macro_rules`-style macro is actually -/// stored in the enclosing item. +/// Represents a macro invocation. The `path` indicates which macro +/// is being invoked, and the `args` are arguments passed to it. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Mac { pub path: Path, - pub delim: MacDelimiter, - pub tts: TokenStream, - pub span: Span, + pub args: P<MacArgs>, pub prior_type_ascription: Option<(Span, bool)>, } -#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)] +impl Mac { + pub fn span(&self) -> Span { + self.path.span.to(self.args.span().unwrap_or(self.path.span)) + } +} + +/// Arguments passed to an attribute or a function-like macro. +#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] +pub enum MacArgs { + /// No arguments - `#[attr]`. + Empty, + /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`. + Delimited(DelimSpan, MacDelimiter, TokenStream), + /// Arguments of a key-value attribute - `#[attr = "value"]`. + Eq( + /// Span of the `=` token. + Span, + /// Token stream of the "value". + TokenStream, + ), +} + +impl MacArgs { + pub fn delim(&self) -> DelimToken { + match self { + MacArgs::Delimited(_, delim, _) => delim.to_token(), + MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim, + } + } + + pub fn span(&self) -> Option<Span> { + match *self { + MacArgs::Empty => None, + MacArgs::Delimited(dspan, ..) => Some(dspan.entire()), + MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))), + } + } + + /// Tokens inside the delimiters or after `=`. + /// Proc macros see these tokens, for example. + pub fn inner_tokens(&self) -> TokenStream { + match self { + MacArgs::Empty => TokenStream::default(), + MacArgs::Delimited(.., tokens) | + MacArgs::Eq(.., tokens) => tokens.clone(), + } + } + + /// Tokens together with the delimiters or `=`. + /// Use of this method generally means that something suboptimal or hacky is happening. + pub fn outer_tokens(&self) -> TokenStream { + match *self { + MacArgs::Empty => TokenStream::default(), + MacArgs::Delimited(dspan, delim, ref tokens) => + TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into(), + MacArgs::Eq(eq_span, ref tokens) => iter::once(TokenTree::token(token::Eq, eq_span)) + .chain(tokens.trees()).collect(), + } + } + + /// Whether a macro with these arguments needs a semicolon + /// when used as a standalone item or statement. + pub fn need_semicolon(&self) -> bool { + !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace ,_)) + } +} + +#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub enum MacDelimiter { Parenthesis, Bracket, Brace, } -impl Mac { - pub fn stream(&self) -> TokenStream { - self.tts.clone() - } -} - impl MacDelimiter { crate fn to_token(self) -> DelimToken { match self { @@ -1358,24 +1422,27 @@ impl MacDelimiter { MacDelimiter::Brace => DelimToken::Brace, } } + + pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> { + match delim { + token::Paren => Some(MacDelimiter::Parenthesis), + token::Bracket => Some(MacDelimiter::Bracket), + token::Brace => Some(MacDelimiter::Brace), + token::NoDelim => None, + } + } } /// Represents a macro definition. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct MacroDef { - pub tokens: TokenStream, + pub body: P<MacArgs>, /// `true` if macro was defined with `macro_rules`. pub legacy: bool, } -impl MacroDef { - pub fn stream(&self) -> TokenStream { - self.tokens.clone().into() - } -} - // Clippy uses Hash and PartialEq -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq, HashStable_Generic)] pub enum StrStyle { /// A regular string, like `"foo"`. Cooked, @@ -1386,7 +1453,7 @@ pub enum StrStyle { } /// An AST literal. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug)] +#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub struct Lit { /// The original literal token as written in source code. pub token: token::Lit, @@ -1397,9 +1464,36 @@ pub struct Lit { pub span: Span, } +/// Same as `Lit`, but restricted to string literals. +#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)] +pub struct StrLit { + /// The original literal token as written in source code. + pub style: StrStyle, + pub symbol: Symbol, + pub suffix: Option<Symbol>, + pub span: Span, + /// The unescaped "semantic" representation of the literal lowered from the original token. + /// FIXME: Remove this and only create the semantic representation during lowering to HIR. + pub symbol_unescaped: Symbol, +} + +impl StrLit { + crate fn as_lit(&self) -> Lit { + let token_kind = match self.style { + StrStyle::Cooked => token::Str, + StrStyle::Raw(n) => token::StrRaw(n), + }; + Lit { + token: token::Lit::new(token_kind, self.symbol, self.suffix), + span: self.span, + kind: LitKind::Str(self.symbol_unescaped, self.style), + } + } +} + // Clippy uses Hash and PartialEq /// Type of the integer literal based on provided suffix. -#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)] +#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)] pub enum LitIntType { /// e.g. `42_i32`. Signed(IntTy), @@ -1410,7 +1504,7 @@ pub enum LitIntType { } /// Type of the float literal based on provided suffix. -#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)] +#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)] pub enum LitFloatType { /// A float literal with a suffix (`1f32` or `1E10f32`). Suffixed(FloatTy), @@ -1422,7 +1516,7 @@ pub enum LitFloatType { /// /// E.g., `"foo"`, `42`, `12.34`, or `bool`. // Clippy uses Hash and PartialEq -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)] pub enum LitKind { /// A string literal (`"foo"`). Str(Symbol, StrStyle), @@ -1515,12 +1609,14 @@ pub struct FnSig { /// signature) or provided (meaning it has a default implementation). #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct TraitItem { + pub attrs: Vec<Attribute>, pub id: NodeId, + pub span: Span, + pub vis: Visibility, pub ident: Ident, - pub attrs: Vec<Attribute>, + pub generics: Generics, pub kind: TraitItemKind, - pub span: Span, /// See `Item::tokens` for what this is. pub tokens: Option<TokenStream>, } @@ -1536,14 +1632,15 @@ pub enum TraitItemKind { /// Represents anything within an `impl` block. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct ImplItem { + pub attrs: Vec<Attribute>, pub id: NodeId, - pub ident: Ident, + pub span: Span, pub vis: Visibility, + pub ident: Ident, + pub defaultness: Defaultness, - pub attrs: Vec<Attribute>, pub generics: Generics, pub kind: ImplItemKind, - pub span: Span, /// See `Item::tokens` for what this is. pub tokens: Option<TokenStream>, } @@ -1554,11 +1651,11 @@ pub enum ImplItemKind { Const(P<Ty>, P<Expr>), Method(FnSig, P<Block>), TyAlias(P<Ty>), - OpaqueTy(GenericBounds), Macro(Mac), } -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug)] +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic, + RustcEncodable, RustcDecodable, Debug)] pub enum FloatTy { F32, F64, @@ -1587,7 +1684,8 @@ impl FloatTy { } } -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug)] +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic, + RustcEncodable, RustcDecodable, Debug)] pub enum IntTy { Isize, I8, @@ -1637,9 +1735,22 @@ impl IntTy { IntTy::I128 => 128, }) } + + pub fn normalize(&self, target_width: u32) -> Self { + match self { + IntTy::Isize => match target_width { + 16 => IntTy::I16, + 32 => IntTy::I32, + 64 => IntTy::I64, + _ => unreachable!(), + }, + _ => *self, + } + } } -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy, Debug)] +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic, + RustcEncodable, RustcDecodable, Copy, Debug)] pub enum UintTy { Usize, U8, @@ -1686,6 +1797,18 @@ impl UintTy { UintTy::U128 => 128, }) } + + pub fn normalize(&self, target_width: u32) -> Self { + match self { + UintTy::Usize => match target_width { + 16 => UintTy::U16, + 32 => UintTy::U32, + 64 => UintTy::U64, + _ => unreachable!(), + }, + _ => *self, + } + } } /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or @@ -1721,7 +1844,7 @@ pub struct Ty { #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct BareFnTy { pub unsafety: Unsafety, - pub abi: Abi, + pub ext: Extern, pub generic_params: Vec<GenericParam>, pub decl: P<FnDecl>, } @@ -1791,6 +1914,15 @@ impl TyKind { false } } + + /// HACK(type_alias_impl_trait, Centril): A temporary crutch used + /// in lowering to avoid making larger changes there and beyond. + pub fn opaque_top_hack(&self) -> Option<&GenericBounds> { + match self { + Self::ImplTrait(_, bounds) => Some(bounds), + _ => None, + } + } } /// Syntax used to declare a trait object. @@ -1803,7 +1935,7 @@ pub enum TraitObjectSyntax { /// Inline assembly dialect. /// /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`. -#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)] +#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)] pub enum AsmDialect { Att, Intel, @@ -1961,18 +2093,40 @@ impl FnDecl { } /// Is the trait definition an auto trait? -#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)] +#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub enum IsAuto { Yes, No, } -#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, + RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub enum Unsafety { Unsafe, Normal, } +impl Unsafety { + pub fn prefix_str(&self) -> &'static str { + match self { + Unsafety::Unsafe => "unsafe ", + Unsafety::Normal => "", + } + } +} + +impl fmt::Display for Unsafety { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt( + match *self { + Unsafety::Normal => "normal", + Unsafety::Unsafe => "unsafe", + }, + f, + ) + } +} + #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)] pub enum IsAsync { Async { @@ -2003,7 +2157,7 @@ impl IsAsync { } } -#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)] +#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub enum Constness { Const, NotConst, @@ -2011,25 +2165,13 @@ pub enum Constness { /// Item defaultness. /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532). -#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)] +#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub enum Defaultness { Default, Final, } -impl fmt::Display for Unsafety { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Display::fmt( - match *self { - Unsafety::Normal => "normal", - Unsafety::Unsafe => "unsafe", - }, - f, - ) - } -} - -#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)] +#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)] pub enum ImplPolarity { /// `impl Trait for Type` Positive, @@ -2085,7 +2227,7 @@ pub struct Mod { /// E.g., `extern { .. }` or `extern C { .. }`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct ForeignMod { - pub abi: Abi, + pub abi: Option<StrLit>, pub items: Vec<ForeignItem>, } @@ -2101,22 +2243,24 @@ pub struct GlobalAsm { pub struct EnumDef { pub variants: Vec<Variant>, } - /// Enum variant. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Variant { - /// Name of the variant. - pub ident: Ident, /// Attributes of the variant. pub attrs: Vec<Attribute>, /// Id of the variant (not the constructor, see `VariantData::ctor_id()`). pub id: NodeId, + /// Span + pub span: Span, + /// The visibility of the variant. Syntactically accepted but not semantically. + pub vis: Visibility, + /// Name of the variant. + pub ident: Ident, + /// Fields and constructor id of the variant. pub data: VariantData, /// Explicit discriminant, e.g., `Foo = 1`. pub disr_expr: Option<AnonConst>, - /// Span - pub span: Span, /// Is a macro placeholder pub is_placeholder: bool, } @@ -2163,7 +2307,7 @@ impl UseTree { /// Distinguishes between `Attribute`s that decorate items and Attributes that /// are contained as statements within items. These two cases need to be /// distinguished for pretty-printing. -#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)] +#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)] pub enum AttrStyle { Outer, Inner, @@ -2193,10 +2337,10 @@ impl rustc_serialize::Decodable for AttrId { } } -#[derive(Clone, RustcEncodable, RustcDecodable, Debug)] +#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub struct AttrItem { pub path: Path, - pub tokens: TokenStream, + pub args: MacArgs, } /// Metadata associated with an item. @@ -2261,7 +2405,7 @@ impl PolyTraitRef { } } -#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)] +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub enum CrateSugar { /// Source is `pub(crate)`. PubCrate, @@ -2295,12 +2439,13 @@ impl VisibilityKind { /// E.g., `bar: usize` as in `struct Foo { bar: usize }`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct StructField { + pub attrs: Vec<Attribute>, + pub id: NodeId, pub span: Span, - pub ident: Option<Ident>, pub vis: Visibility, - pub id: NodeId, + pub ident: Option<Ident>, + pub ty: P<Ty>, - pub attrs: Vec<Attribute>, pub is_placeholder: bool, } @@ -2343,13 +2488,14 @@ impl VariantData { /// /// The name might be a dummy name in case of anonymous items. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] -pub struct Item { - pub ident: Ident, +pub struct Item<K = ItemKind> { pub attrs: Vec<Attribute>, pub id: NodeId, - pub kind: ItemKind, - pub vis: Visibility, pub span: Span, + pub vis: Visibility, + pub ident: Ident, + + pub kind: K, /// Original tokens this item was parsed from. This isn't necessarily /// available for all items, although over time more and more items should @@ -2368,24 +2514,17 @@ impl Item { } } -/// A reference to an ABI. -/// -/// In AST our notion of an ABI is still syntactic unlike in `rustc_target::spec::abi::Abi`. -#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, PartialEq)] -pub struct Abi { - pub symbol: Symbol, - pub span: Span, -} - -impl Abi { - pub fn new(symbol: Symbol, span: Span) -> Self { - Self { symbol, span } - } +/// `extern` qualifier on a function item or function type. +#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)] +pub enum Extern { + None, + Implicit, + Explicit(StrLit), } -impl Default for Abi { - fn default() -> Self { - Self::new(sym::Rust, DUMMY_SP) +impl Extern { + pub fn from_abi(abi: Option<StrLit>) -> Extern { + abi.map_or(Extern::Implicit, Extern::Explicit) } } @@ -2398,7 +2537,7 @@ pub struct FnHeader { pub unsafety: Unsafety, pub asyncness: Spanned<IsAsync>, pub constness: Spanned<Constness>, - pub abi: Abi, + pub ext: Extern, } impl Default for FnHeader { @@ -2407,7 +2546,7 @@ impl Default for FnHeader { unsafety: Unsafety::Normal, asyncness: dummy_spanned(IsAsync::NotAsync), constness: dummy_spanned(Constness::NotConst), - abi: Abi::default(), + ext: Extern::None, } } } @@ -2448,10 +2587,6 @@ pub enum ItemKind { /// /// E.g., `type Foo = Bar<u8>;`. TyAlias(P<Ty>, Generics), - /// An opaque `impl Trait` type alias. - /// - /// E.g., `type Foo = impl Bar + Boo;`. - OpaqueTy(GenericBounds, Generics), /// An enum definition (`enum`). /// /// E.g., `enum Foo<A, B> { C<A>, D<B> }`. @@ -2505,7 +2640,6 @@ impl ItemKind { ItemKind::ForeignMod(..) => "foreign module", ItemKind::GlobalAsm(..) => "global asm", ItemKind::TyAlias(..) => "type alias", - ItemKind::OpaqueTy(..) => "opaque type", ItemKind::Enum(..) => "enum", ItemKind::Struct(..) => "struct", ItemKind::Union(..) => "union", @@ -2516,15 +2650,7 @@ impl ItemKind { } } -#[derive(Clone, RustcEncodable, RustcDecodable, Debug)] -pub struct ForeignItem { - pub ident: Ident, - pub attrs: Vec<Attribute>, - pub kind: ForeignItemKind, - pub id: NodeId, - pub span: Span, - pub vis: Visibility, -} +pub type ForeignItem = Item<ForeignItemKind>; /// An item within an `extern` block. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] diff --git a/src/libsyntax/attr/builtin.rs b/src/libsyntax/attr/builtin.rs index 787d69f5e99..3c10f27b60a 100644 --- a/src/libsyntax/attr/builtin.rs +++ b/src/libsyntax/attr/builtin.rs @@ -1,16 +1,23 @@ //! Parsing and validation of builtin attributes +use super::{mark_used, MetaItemKind}; use crate::ast::{self, Attribute, MetaItem, NestedMetaItem}; -use crate::early_buffered_lints::BufferedEarlyLintId; -use crate::feature_gate::{Features, GatedCfg}; +use crate::feature_gate::feature_err; use crate::print::pprust; use crate::sess::ParseSess; use errors::{Applicability, Handler}; +use std::num::NonZeroU32; use syntax_pos::hygiene::Transparency; use syntax_pos::{symbol::Symbol, symbol::sym, Span}; +use rustc_feature::{Features, find_gated_cfg, GatedCfg, is_builtin_attr_name}; +use rustc_macros::HashStable_Generic; -use super::{mark_used, MetaItemKind}; +use rustc_error_codes::*; + +pub fn is_builtin_attr(attr: &Attribute) -> bool { + attr.ident().filter(|ident| is_builtin_attr_name(ident.name)).is_some() +} enum AttrError { MultipleItem(String), @@ -21,31 +28,6 @@ enum AttrError { UnsupportedLiteral(&'static str, /* is_bytestr */ bool), } -/// A template that the attribute input must match. -/// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now. -#[derive(Clone, Copy)] -pub struct AttributeTemplate { - crate word: bool, - crate list: Option<&'static str>, - crate name_value_str: Option<&'static str>, -} - -impl AttributeTemplate { - pub fn only_word() -> Self { - Self { word: true, list: None, name_value_str: None } - } - - /// Checks that the given meta-item is compatible with this template. - fn compatible(&self, meta_item_kind: &ast::MetaItemKind) -> bool { - match meta_item_kind { - ast::MetaItemKind::Word => self.word, - ast::MetaItemKind::List(..) => self.list.is_some(), - ast::MetaItemKind::NameValue(lit) if lit.kind.is_str() => self.name_value_str.is_some(), - ast::MetaItemKind::NameValue(..) => false, - } - } -} - fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) { let diag = &sess.span_diagnostic; match error { @@ -139,7 +121,8 @@ pub fn find_unwind_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> Op } /// Represents the #[stable], #[unstable], #[rustc_{deprecated,const_unstable}] attributes. -#[derive(RustcEncodable, RustcDecodable, Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(RustcEncodable, RustcDecodable, Copy, Clone, Debug, + PartialEq, Eq, Hash, HashStable_Generic)] pub struct Stability { pub level: StabilityLevel, pub feature: Symbol, @@ -155,10 +138,11 @@ pub struct Stability { } /// The available stability levels. -#[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Copy, Clone, Debug, Eq, Hash)] +#[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, + Copy, Clone, Debug, Eq, Hash, HashStable_Generic)] pub enum StabilityLevel { // Reason for the current stability level and the relevant rust-lang issue - Unstable { reason: Option<Symbol>, issue: u32, is_soft: bool }, + Unstable { reason: Option<Symbol>, issue: Option<NonZeroU32>, is_soft: bool }, Stable { since: Symbol }, } @@ -179,7 +163,8 @@ impl StabilityLevel { } } -#[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Copy, Clone, Debug, Eq, Hash)] +#[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, + Copy, Clone, Debug, Eq, Hash, HashStable_Generic)] pub struct RustcDeprecation { pub since: Symbol, pub reason: Symbol, @@ -395,18 +380,28 @@ fn find_stability_generic<'a, I>(sess: &ParseSess, match (feature, reason, issue) { (Some(feature), reason, Some(issue)) => { + let issue = match &*issue.as_str() { + // FIXME(rossmacarthur): remove "0" because "none" should be used + // See #41260 + "none" | "0" => None, + issue => { + if let Ok(num) = issue.parse() { + NonZeroU32::new(num) + } else { + span_err!( + diagnostic, + attr.span, + E0545, + "incorrect 'issue'" + ); + continue + } + } + }; stab = Some(Stability { level: Unstable { reason, - issue: { - if let Ok(issue) = issue.as_str().parse() { - issue - } else { - span_err!(diagnostic, attr.span, E0545, - "incorrect 'issue'"); - continue - } - }, + issue, is_soft, }, feature, @@ -539,8 +534,9 @@ pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> { /// Tests if a cfg-pattern matches the cfg set pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool { eval_condition(cfg, sess, &mut |cfg| { - if let (Some(feats), Some(gated_cfg)) = (features, GatedCfg::gate(cfg)) { - gated_cfg.check_and_emit(sess, feats); + let gate = find_gated_cfg(|sym| cfg.check_name(sym)); + if let (Some(feats), Some(gated_cfg)) = (features, gate) { + gate_cfg(&gated_cfg, cfg.span, sess, feats); } let error = |span, msg| { sess.span_diagnostic.span_err(span, msg); true }; if cfg.path.segments.len() != 1 { @@ -569,12 +565,21 @@ pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Feat }) } +fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) { + let (cfg, feature, has_feature) = gated_cfg; + if !has_feature(features) && !cfg_span.allows_unstable(*feature) { + let explain = format!("`cfg({})` is experimental and subject to change", cfg); + feature_err(sess, *feature, cfg_span, &explain).emit() + } +} + /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to /// evaluate individual items. -pub fn eval_condition<F>(cfg: &ast::MetaItem, sess: &ParseSess, eval: &mut F) - -> bool - where F: FnMut(&ast::MetaItem) -> bool -{ +pub fn eval_condition( + cfg: &ast::MetaItem, + sess: &ParseSess, + eval: &mut impl FnMut(&ast::MetaItem) -> bool, +) -> bool { match cfg.kind { ast::MetaItemKind::List(ref mis) => { for mi in mis.iter() { @@ -624,7 +629,7 @@ pub fn eval_condition<F>(cfg: &ast::MetaItem, sess: &ParseSess, eval: &mut F) } } -#[derive(RustcEncodable, RustcDecodable, Clone)] +#[derive(RustcEncodable, RustcDecodable, Clone, HashStable_Generic)] pub struct Deprecation { pub since: Option<Symbol>, pub note: Option<Symbol>, @@ -655,7 +660,10 @@ fn find_deprecation_generic<'a, I>(sess: &ParseSess, break } - let meta = attr.meta().unwrap(); + let meta = match attr.meta() { + Some(meta) => meta, + None => continue, + }; depr = match &meta.kind { MetaItemKind::Word => Some(Deprecation { since: None, note: None }), MetaItemKind::NameValue(..) => { @@ -748,7 +756,7 @@ pub enum ReprAttr { ReprAlign(u32), } -#[derive(Eq, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)] +#[derive(Eq, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone, HashStable_Generic)] pub enum IntType { SignedInt(ast::IntTy), UnsignedInt(ast::UintTy) @@ -938,69 +946,3 @@ pub fn find_transparency( let fallback = if is_legacy { Transparency::SemiTransparent } else { Transparency::Opaque }; (transparency.map_or(fallback, |t| t.0), error) } - -pub fn check_builtin_attribute( - sess: &ParseSess, attr: &ast::Attribute, name: Symbol, template: AttributeTemplate -) { - // Some special attributes like `cfg` must be checked - // before the generic check, so we skip them here. - let should_skip = |name| name == sym::cfg; - // Some of previously accepted forms were used in practice, - // report them as warnings for now. - let should_warn = |name| name == sym::doc || name == sym::ignore || - name == sym::inline || name == sym::link || - name == sym::test || name == sym::bench; - - match attr.parse_meta(sess) { - Ok(meta) => if !should_skip(name) && !template.compatible(&meta.kind) { - let error_msg = format!("malformed `{}` attribute input", name); - let mut msg = "attribute must be of the form ".to_owned(); - let mut suggestions = vec![]; - let mut first = true; - if template.word { - first = false; - let code = format!("#[{}]", name); - msg.push_str(&format!("`{}`", &code)); - suggestions.push(code); - } - if let Some(descr) = template.list { - if !first { - msg.push_str(" or "); - } - first = false; - let code = format!("#[{}({})]", name, descr); - msg.push_str(&format!("`{}`", &code)); - suggestions.push(code); - } - if let Some(descr) = template.name_value_str { - if !first { - msg.push_str(" or "); - } - let code = format!("#[{} = \"{}\"]", name, descr); - msg.push_str(&format!("`{}`", &code)); - suggestions.push(code); - } - if should_warn(name) { - sess.buffer_lint( - BufferedEarlyLintId::IllFormedAttributeInput, - meta.span, - ast::CRATE_NODE_ID, - &msg, - ); - } else { - sess.span_diagnostic.struct_span_err(meta.span, &error_msg) - .span_suggestions( - meta.span, - if suggestions.len() == 1 { - "must be of the form" - } else { - "the following are the possible correct uses" - }, - suggestions.into_iter(), - Applicability::HasPlaceholders, - ).emit(); - } - } - Err(mut err) => err.emit(), - } -} diff --git a/src/libsyntax/attr/mod.rs b/src/libsyntax/attr/mod.rs index c639431794c..079a0f6fafa 100644 --- a/src/libsyntax/attr/mod.rs +++ b/src/libsyntax/attr/mod.rs @@ -10,21 +10,17 @@ pub use crate::ast::Attribute; use crate::ast; use crate::ast::{AttrItem, AttrId, AttrKind, AttrStyle, Name, Ident, Path, PathSegment}; -use crate::ast::{MetaItem, MetaItemKind, NestedMetaItem}; +use crate::ast::{MacArgs, MacDelimiter, MetaItem, MetaItemKind, NestedMetaItem}; use crate::ast::{Lit, LitKind, Expr, Item, Local, Stmt, StmtKind, GenericParam}; use crate::mut_visit::visit_clobber; use crate::source_map::{BytePos, Spanned}; -use crate::parse; use crate::token::{self, Token}; use crate::ptr::P; -use crate::sess::ParseSess; use crate::symbol::{sym, Symbol}; use crate::ThinVec; use crate::tokenstream::{DelimSpan, TokenStream, TokenTree, TreeAndJoint}; use crate::GLOBALS; -use errors::PResult; - use log::debug; use syntax_pos::Span; @@ -202,7 +198,7 @@ impl Attribute { pub fn is_word(&self) -> bool { if let AttrKind::Normal(item) = &self.kind { - item.tokens.is_empty() + matches!(item.args, MacArgs::Empty) } else { false } @@ -281,18 +277,10 @@ impl MetaItem { } impl AttrItem { - crate fn meta(&self, span: Span) -> Option<MetaItem> { - let mut tokens = self.tokens.trees().peekable(); + pub fn meta(&self, span: Span) -> Option<MetaItem> { Some(MetaItem { path: self.path.clone(), - kind: if let Some(kind) = MetaItemKind::from_tokens(&mut tokens) { - if tokens.peek().is_some() { - return None; - } - kind - } else { - return None; - }, + kind: MetaItemKind::from_mac_args(&self.args)?, span, }) } @@ -328,21 +316,6 @@ impl Attribute { Some(mk_name_value_item_str(Ident::new(sym::doc, self.span), comment, self.span)), } } - - pub fn parse_meta<'a>(&self, sess: &'a ParseSess) -> PResult<'a, MetaItem> { - match self.kind { - AttrKind::Normal(ref item) => { - Ok(MetaItem { - path: item.path.clone(), - kind: parse::parse_in_attr(sess, self, |parser| parser.parse_meta_item_kind())?, - span: self.span, - }) - } - AttrKind::DocComment(comment) => { - Ok(mk_name_value_item_str(Ident::new(sym::doc, self.span), comment, self.span)) - } - } - } } /* Constructors */ @@ -381,9 +354,13 @@ crate fn mk_attr_id() -> AttrId { AttrId(id) } -pub fn mk_attr(style: AttrStyle, path: Path, tokens: TokenStream, span: Span) -> Attribute { +pub fn mk_attr(style: AttrStyle, path: Path, args: MacArgs, span: Span) -> Attribute { + mk_attr_from_item(style, AttrItem { path, args }, span) +} + +pub fn mk_attr_from_item(style: AttrStyle, item: AttrItem, span: Span) -> Attribute { Attribute { - kind: AttrKind::Normal(AttrItem { path, tokens }), + kind: AttrKind::Normal(item), id: mk_attr_id(), style, span, @@ -392,12 +369,12 @@ pub fn mk_attr(style: AttrStyle, path: Path, tokens: TokenStream, span: Span) -> /// Returns an inner attribute with the given value and span. pub fn mk_attr_inner(item: MetaItem) -> Attribute { - mk_attr(AttrStyle::Inner, item.path, item.kind.tokens(item.span), item.span) + mk_attr(AttrStyle::Inner, item.path, item.kind.mac_args(item.span), item.span) } /// Returns an outer attribute with the given value and span. pub fn mk_attr_outer(item: MetaItem) -> Attribute { - mk_attr(AttrStyle::Outer, item.path, item.kind.tokens(item.span), item.span) + mk_attr(AttrStyle::Outer, item.path, item.kind.mac_args(item.span), item.span) } pub fn mk_doc_comment(style: AttrStyle, comment: Symbol, span: Span) -> Attribute { @@ -535,7 +512,26 @@ impl MetaItem { } impl MetaItemKind { - pub fn token_trees_and_joints(&self, span: Span) -> Vec<TreeAndJoint> { + pub fn mac_args(&self, span: Span) -> MacArgs { + match self { + MetaItemKind::Word => MacArgs::Empty, + MetaItemKind::NameValue(lit) => MacArgs::Eq(span, lit.token_tree().into()), + MetaItemKind::List(list) => { + let mut tts = Vec::new(); + for (i, item) in list.iter().enumerate() { + if i > 0 { + tts.push(TokenTree::token(token::Comma, span).into()); + } + tts.extend(item.token_trees_and_joints()) + } + MacArgs::Delimited( + DelimSpan::from_single(span), MacDelimiter::Parenthesis, TokenStream::new(tts) + ) + } + } + } + + fn token_trees_and_joints(&self, span: Span) -> Vec<TreeAndJoint> { match *self { MetaItemKind::Word => vec![], MetaItemKind::NameValue(ref lit) => { @@ -563,33 +559,8 @@ impl MetaItemKind { } } - // Premature conversions of `TokenTree`s to `TokenStream`s can hurt - // performance. Do not use this function if `token_trees_and_joints()` can - // be used instead. - pub fn tokens(&self, span: Span) -> TokenStream { - TokenStream::new(self.token_trees_and_joints(span)) - } - - fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItemKind> - where I: Iterator<Item = TokenTree>, - { - let delimited = match tokens.peek().cloned() { - Some(TokenTree::Token(token)) if token == token::Eq => { - tokens.next(); - return if let Some(TokenTree::Token(token)) = tokens.next() { - Lit::from_token(&token).ok().map(MetaItemKind::NameValue) - } else { - None - }; - } - Some(TokenTree::Delimited(_, delim, ref tts)) if delim == token::Paren => { - tokens.next(); - tts.clone() - } - _ => return Some(MetaItemKind::Word), - }; - - let mut tokens = delimited.into_trees().peekable(); + fn list_from_tokens(tokens: TokenStream) -> Option<MetaItemKind> { + let mut tokens = tokens.into_trees().peekable(); let mut result = Vec::new(); while let Some(..) = tokens.peek() { let item = NestedMetaItem::from_tokens(&mut tokens)?; @@ -601,6 +572,47 @@ impl MetaItemKind { } Some(MetaItemKind::List(result)) } + + fn name_value_from_tokens( + tokens: &mut impl Iterator<Item = TokenTree>, + ) -> Option<MetaItemKind> { + match tokens.next() { + Some(TokenTree::Token(token)) => + Lit::from_token(&token).ok().map(MetaItemKind::NameValue), + _ => None, + } + } + + fn from_mac_args(args: &MacArgs) -> Option<MetaItemKind> { + match args { + MacArgs::Delimited(_, MacDelimiter::Parenthesis, tokens) => + MetaItemKind::list_from_tokens(tokens.clone()), + MacArgs::Delimited(..) => None, + MacArgs::Eq(_, tokens) => { + assert!(tokens.len() == 1); + MetaItemKind::name_value_from_tokens(&mut tokens.trees()) + } + MacArgs::Empty => Some(MetaItemKind::Word), + } + } + + fn from_tokens( + tokens: &mut iter::Peekable<impl Iterator<Item = TokenTree>>, + ) -> Option<MetaItemKind> { + match tokens.peek() { + Some(TokenTree::Delimited(_, token::Paren, inner_tokens)) => { + let inner_tokens = inner_tokens.clone(); + tokens.next(); + MetaItemKind::list_from_tokens(inner_tokens) + } + Some(TokenTree::Delimited(..)) => None, + Some(TokenTree::Token(Token { kind: token::Eq, .. })) => { + tokens.next(); + MetaItemKind::name_value_from_tokens(tokens) + } + _ => Some(MetaItemKind::Word), + } + } } impl NestedMetaItem { diff --git a/src/libsyntax/config.rs b/src/libsyntax/config.rs deleted file mode 100644 index 5f89ed36e2a..00000000000 --- a/src/libsyntax/config.rs +++ /dev/null @@ -1,352 +0,0 @@ -use crate::attr::HasAttrs; -use crate::feature_gate::{ - feature_err, - EXPLAIN_STMT_ATTR_SYNTAX, - Features, - get_features, - GateIssue, -}; -use crate::attr; -use crate::ast; -use crate::edition::Edition; -use crate::mut_visit::*; -use crate::parse; -use crate::ptr::P; -use crate::sess::ParseSess; -use crate::symbol::sym; -use crate::util::map_in_place::MapInPlace; - -use errors::Applicability; -use smallvec::SmallVec; - -/// A folder that strips out items that do not belong in the current configuration. -pub struct StripUnconfigured<'a> { - pub sess: &'a ParseSess, - pub features: Option<&'a Features>, -} - -// `cfg_attr`-process the crate's attributes and compute the crate's features. -pub fn features(mut krate: ast::Crate, sess: &ParseSess, edition: Edition, - allow_features: &Option<Vec<String>>) -> (ast::Crate, Features) { - let features; - { - let mut strip_unconfigured = StripUnconfigured { - sess, - features: None, - }; - - let unconfigured_attrs = krate.attrs.clone(); - let err_count = sess.span_diagnostic.err_count(); - if let Some(attrs) = strip_unconfigured.configure(krate.attrs) { - krate.attrs = attrs; - } else { // the entire crate is unconfigured - krate.attrs = Vec::new(); - krate.module.items = Vec::new(); - return (krate, Features::new()); - } - - features = get_features(&sess.span_diagnostic, &krate.attrs, edition, allow_features); - - // Avoid reconfiguring malformed `cfg_attr`s - if err_count == sess.span_diagnostic.err_count() { - strip_unconfigured.features = Some(&features); - strip_unconfigured.configure(unconfigured_attrs); - } - } - - (krate, features) -} - -#[macro_export] -macro_rules! configure { - ($this:ident, $node:ident) => { - match $this.configure($node) { - Some(node) => node, - None => return Default::default(), - } - } -} - -impl<'a> StripUnconfigured<'a> { - pub fn configure<T: HasAttrs>(&mut self, mut node: T) -> Option<T> { - self.process_cfg_attrs(&mut node); - if self.in_cfg(node.attrs()) { Some(node) } else { None } - } - - /// Parse and expand all `cfg_attr` attributes into a list of attributes - /// that are within each `cfg_attr` that has a true configuration predicate. - /// - /// Gives compiler warnigns if any `cfg_attr` does not contain any - /// attributes and is in the original source code. Gives compiler errors if - /// the syntax of any `cfg_attr` is incorrect. - pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: &mut T) { - node.visit_attrs(|attrs| { - attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr)); - }); - } - - /// Parse and expand a single `cfg_attr` attribute into a list of attributes - /// when the configuration predicate is true, or otherwise expand into an - /// empty list of attributes. - /// - /// Gives a compiler warning when the `cfg_attr` contains no attributes and - /// is in the original source file. Gives a compiler error if the syntax of - /// the attribute is incorrect. - fn process_cfg_attr(&mut self, attr: ast::Attribute) -> Vec<ast::Attribute> { - if !attr.has_name(sym::cfg_attr) { - return vec![attr]; - } - if attr.get_normal_item().tokens.is_empty() { - self.sess.span_diagnostic - .struct_span_err( - attr.span, - "malformed `cfg_attr` attribute input", - ).span_suggestion( - attr.span, - "missing condition and attribute", - "#[cfg_attr(condition, attribute, other_attribute, ...)]".to_owned(), - Applicability::HasPlaceholders, - ).note("for more information, visit \ - <https://doc.rust-lang.org/reference/conditional-compilation.html\ - #the-cfg_attr-attribute>") - .emit(); - return vec![]; - } - - let res = parse::parse_in_attr(self.sess, &attr, |p| p.parse_cfg_attr()); - let (cfg_predicate, expanded_attrs) = match res { - Ok(result) => result, - Err(mut e) => { - e.emit(); - return vec![]; - } - }; - - // Lint on zero attributes in source. - if expanded_attrs.is_empty() { - return vec![attr]; - } - - // At this point we know the attribute is considered used. - attr::mark_used(&attr); - - if attr::cfg_matches(&cfg_predicate, self.sess, self.features) { - // We call `process_cfg_attr` recursively in case there's a - // `cfg_attr` inside of another `cfg_attr`. E.g. - // `#[cfg_attr(false, cfg_attr(true, some_attr))]`. - expanded_attrs.into_iter() - .flat_map(|(item, span)| self.process_cfg_attr(ast::Attribute { - kind: ast::AttrKind::Normal(item), - id: attr::mk_attr_id(), - style: attr.style, - span, - })) - .collect() - } else { - vec![] - } - } - - /// Determines if a node with the given attributes should be included in this configuration. - pub fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool { - attrs.iter().all(|attr| { - if !is_cfg(attr) { - return true; - } - - let error = |span, msg, suggestion: &str| { - let mut err = self.sess.span_diagnostic.struct_span_err(span, msg); - if !suggestion.is_empty() { - err.span_suggestion( - span, - "expected syntax is", - suggestion.into(), - Applicability::MaybeIncorrect, - ); - } - err.emit(); - true - }; - - let meta_item = match attr.parse_meta(self.sess) { - Ok(meta_item) => meta_item, - Err(mut err) => { err.emit(); return true; } - }; - let nested_meta_items = if let Some(nested_meta_items) = meta_item.meta_item_list() { - nested_meta_items - } else { - return error(meta_item.span, "`cfg` is not followed by parentheses", - "cfg(/* predicate */)"); - }; - - if nested_meta_items.is_empty() { - return error(meta_item.span, "`cfg` predicate is not specified", ""); - } else if nested_meta_items.len() > 1 { - return error(nested_meta_items.last().unwrap().span(), - "multiple `cfg` predicates are specified", ""); - } - - match nested_meta_items[0].meta_item() { - Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features), - None => error(nested_meta_items[0].span(), - "`cfg` predicate key cannot be a literal", ""), - } - }) - } - - /// Visit attributes on expression and statements (but not attributes on items in blocks). - fn visit_expr_attrs(&mut self, attrs: &[ast::Attribute]) { - // flag the offending attributes - for attr in attrs.iter() { - self.maybe_emit_expr_attr_err(attr); - } - } - - /// If attributes are not allowed on expressions, emit an error for `attr` - pub fn maybe_emit_expr_attr_err(&self, attr: &ast::Attribute) { - if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) { - let mut err = feature_err(self.sess, - sym::stmt_expr_attributes, - attr.span, - GateIssue::Language, - EXPLAIN_STMT_ATTR_SYNTAX); - - if attr.is_doc_comment() { - err.help("`///` is for documentation comments. For a plain comment, use `//`."); - } - - err.emit(); - } - } - - pub fn configure_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) { - let ast::ForeignMod { abi: _, items } = foreign_mod; - items.flat_map_in_place(|item| self.configure(item)); - } - - pub fn configure_generic_params(&mut self, params: &mut Vec<ast::GenericParam>) { - params.flat_map_in_place(|param| self.configure(param)); - } - - fn configure_variant_data(&mut self, vdata: &mut ast::VariantData) { - match vdata { - ast::VariantData::Struct(fields, ..) | ast::VariantData::Tuple(fields, _) => - fields.flat_map_in_place(|field| self.configure(field)), - ast::VariantData::Unit(_) => {} - } - } - - pub fn configure_item_kind(&mut self, item: &mut ast::ItemKind) { - match item { - ast::ItemKind::Struct(def, _generics) | - ast::ItemKind::Union(def, _generics) => self.configure_variant_data(def), - ast::ItemKind::Enum(ast::EnumDef { variants }, _generics) => { - variants.flat_map_in_place(|variant| self.configure(variant)); - for variant in variants { - self.configure_variant_data(&mut variant.data); - } - } - _ => {} - } - } - - pub fn configure_expr_kind(&mut self, expr_kind: &mut ast::ExprKind) { - match expr_kind { - ast::ExprKind::Match(_m, arms) => { - arms.flat_map_in_place(|arm| self.configure(arm)); - } - ast::ExprKind::Struct(_path, fields, _base) => { - fields.flat_map_in_place(|field| self.configure(field)); - } - _ => {} - } - } - - pub fn configure_expr(&mut self, expr: &mut P<ast::Expr>) { - self.visit_expr_attrs(expr.attrs()); - - // If an expr is valid to cfg away it will have been removed by the - // outer stmt or expression folder before descending in here. - // Anything else is always required, and thus has to error out - // in case of a cfg attr. - // - // N.B., this is intentionally not part of the visit_expr() function - // in order for filter_map_expr() to be able to avoid this check - if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) { - let msg = "removing an expression is not supported in this position"; - self.sess.span_diagnostic.span_err(attr.span, msg); - } - - self.process_cfg_attrs(expr) - } - - pub fn configure_pat(&mut self, pat: &mut P<ast::Pat>) { - if let ast::PatKind::Struct(_path, fields, _etc) = &mut pat.kind { - fields.flat_map_in_place(|field| self.configure(field)); - } - } - - pub fn configure_fn_decl(&mut self, fn_decl: &mut ast::FnDecl) { - fn_decl.inputs.flat_map_in_place(|arg| self.configure(arg)); - } -} - -impl<'a> MutVisitor for StripUnconfigured<'a> { - fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) { - self.configure_foreign_mod(foreign_mod); - noop_visit_foreign_mod(foreign_mod, self); - } - - fn visit_item_kind(&mut self, item: &mut ast::ItemKind) { - self.configure_item_kind(item); - noop_visit_item_kind(item, self); - } - - fn visit_expr(&mut self, expr: &mut P<ast::Expr>) { - self.configure_expr(expr); - self.configure_expr_kind(&mut expr.kind); - noop_visit_expr(expr, self); - } - - fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> { - let mut expr = configure!(self, expr); - self.configure_expr_kind(&mut expr.kind); - noop_visit_expr(&mut expr, self); - Some(expr) - } - - fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> { - noop_flat_map_stmt(configure!(self, stmt), self) - } - - fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> { - noop_flat_map_item(configure!(self, item), self) - } - - fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> { - noop_flat_map_impl_item(configure!(self, item), self) - } - - fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> { - noop_flat_map_trait_item(configure!(self, item), self) - } - - fn visit_mac(&mut self, _mac: &mut ast::Mac) { - // Don't configure interpolated AST (cf. issue #34171). - // Interpolated AST will get configured once the surrounding tokens are parsed. - } - - fn visit_pat(&mut self, pat: &mut P<ast::Pat>) { - self.configure_pat(pat); - noop_visit_pat(pat, self) - } - - fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) { - self.configure_fn_decl(&mut fn_decl); - noop_visit_fn_decl(fn_decl, self); - } -} - -fn is_cfg(attr: &ast::Attribute) -> bool { - attr.check_name(sym::cfg) -} diff --git a/src/libsyntax/diagnostics/macros.rs b/src/libsyntax/diagnostics/macros.rs index c95c5bd5d02..6679b4459a0 100644 --- a/src/libsyntax/diagnostics/macros.rs +++ b/src/libsyntax/diagnostics/macros.rs @@ -1,7 +1,7 @@ #[macro_export] macro_rules! diagnostic_used { ($code:ident) => ( - let _ = crate::error_codes::$code; + let _ = $code; ) } @@ -167,25 +167,3 @@ macro_rules! help { ($err).help(&format!($($message)*)); }) } - -#[macro_export] -macro_rules! register_diagnostics { - ($($ecode:ident: $message:expr,)*) => ( - $crate::register_diagnostics!{$($ecode:$message,)* ;} - ); - - ($($ecode:ident: $message:expr,)* ; $($code:ident,)*) => ( - pub static DIAGNOSTICS: &[(&str, &str)] = &[ - $( (stringify!($ecode), $message), )* - ]; - - $( - #[deny(unused)] - pub(crate) const $ecode: &str = $message; - )* - $( - #[deny(unused)] - pub(crate) const $code: () = (); - )* - ) -} diff --git a/src/libsyntax/early_buffered_lints.rs b/src/libsyntax/early_buffered_lints.rs index 5cc953b9066..2c32894a23b 100644 --- a/src/libsyntax/early_buffered_lints.rs +++ b/src/libsyntax/early_buffered_lints.rs @@ -3,28 +3,28 @@ //! Since we cannot have a dependency on `librustc`, we implement some types here that are somewhat //! redundant. Later, these types can be converted to types for use by the rest of the compiler. -use crate::ast::NodeId; -use syntax_pos::MultiSpan; +use rustc_session::lint::FutureIncompatibleInfo; +use rustc_session::declare_lint; +pub use rustc_session::lint::BufferedEarlyLint; -/// Since we cannot import `LintId`s from `rustc::lint`, we define some Ids here which can later be -/// passed to `rustc::lint::Lint::from_parser_lint_id` to get a `rustc::lint::Lint`. -pub enum BufferedEarlyLintId { - IllFormedAttributeInput, - MetaVariableMisuse, - IncompleteInclude, +declare_lint! { + pub ILL_FORMED_ATTRIBUTE_INPUT, + Deny, + "ill-formed attribute inputs that were previously accepted and used in practice", + @future_incompatible = FutureIncompatibleInfo { + reference: "issue #57571 <https://github.com/rust-lang/rust/issues/57571>", + edition: None, + }; } -/// Stores buffered lint info which can later be passed to `librustc`. -pub struct BufferedEarlyLint { - /// The span of code that we are linting on. - pub span: MultiSpan, - - /// The lint message. - pub msg: String, - - /// The `NodeId` of the AST node that generated the lint. - pub id: NodeId, +declare_lint! { + pub META_VARIABLE_MISUSE, + Allow, + "possible meta-variable misuse at macro definition" +} - /// A lint Id that can be passed to `rustc::lint::Lint::from_parser_lint_id`. - pub lint_id: BufferedEarlyLintId, +declare_lint! { + pub INCOMPLETE_INCLUDE, + Deny, + "trailing content in included file" } diff --git a/src/libsyntax/error_codes.rs b/src/libsyntax/error_codes.rs deleted file mode 100644 index c23c8d65a7f..00000000000 --- a/src/libsyntax/error_codes.rs +++ /dev/null @@ -1,544 +0,0 @@ -// Error messages for EXXXX errors. -// Each message should start and end with a new line, and be wrapped to 80 -// characters. In vim you can `:set tw=80` and use `gq` to wrap paragraphs. Use -// `:set tw=0` to disable. -register_diagnostics! { - -E0178: r##" -In types, the `+` type operator has low precedence, so it is often necessary -to use parentheses. - -For example: - -```compile_fail,E0178 -trait Foo {} - -struct Bar<'a> { - w: &'a Foo + Copy, // error, use &'a (Foo + Copy) - x: &'a Foo + 'a, // error, use &'a (Foo + 'a) - y: &'a mut Foo + 'a, // error, use &'a mut (Foo + 'a) - z: fn() -> Foo + 'a, // error, use fn() -> (Foo + 'a) -} -``` - -More details can be found in [RFC 438]. - -[RFC 438]: https://github.com/rust-lang/rfcs/pull/438 -"##, - -E0536: r##" -The `not` cfg-predicate was malformed. - -Erroneous code example: - -```compile_fail,E0536 -#[cfg(not())] // error: expected 1 cfg-pattern -pub fn something() {} - -pub fn main() {} -``` - -The `not` predicate expects one cfg-pattern. Example: - -``` -#[cfg(not(target_os = "linux"))] // ok! -pub fn something() {} - -pub fn main() {} -``` - -For more information about the cfg attribute, read: -https://doc.rust-lang.org/reference.html#conditional-compilation -"##, - -E0537: r##" -An unknown predicate was used inside the `cfg` attribute. - -Erroneous code example: - -```compile_fail,E0537 -#[cfg(unknown())] // error: invalid predicate `unknown` -pub fn something() {} - -pub fn main() {} -``` - -The `cfg` attribute supports only three kinds of predicates: - - * any - * all - * not - -Example: - -``` -#[cfg(not(target_os = "linux"))] // ok! -pub fn something() {} - -pub fn main() {} -``` - -For more information about the cfg attribute, read: -https://doc.rust-lang.org/reference.html#conditional-compilation -"##, - -E0538: r##" -Attribute contains same meta item more than once. - -Erroneous code example: - -```compile_fail,E0538 -#[deprecated( - since="1.0.0", - note="First deprecation note.", - note="Second deprecation note." // error: multiple same meta item -)] -fn deprecated_function() {} -``` - -Meta items are the key-value pairs inside of an attribute. Each key may only be -used once in each attribute. - -To fix the problem, remove all but one of the meta items with the same key. - -Example: - -``` -#[deprecated( - since="1.0.0", - note="First deprecation note." -)] -fn deprecated_function() {} -``` -"##, - -E0541: r##" -An unknown meta item was used. - -Erroneous code example: - -```compile_fail,E0541 -#[deprecated( - since="1.0.0", - // error: unknown meta item - reason="Example invalid meta item. Should be 'note'") -] -fn deprecated_function() {} -``` - -Meta items are the key-value pairs inside of an attribute. The keys provided -must be one of the valid keys for the specified attribute. - -To fix the problem, either remove the unknown meta item, or rename it if you -provided the wrong name. - -In the erroneous code example above, the wrong name was provided, so changing -to a correct one it will fix the error. Example: - -``` -#[deprecated( - since="1.0.0", - note="This is a valid meta item for the deprecated attribute." -)] -fn deprecated_function() {} -``` -"##, - -E0550: r##" -More than one `deprecated` attribute has been put on an item. - -Erroneous code example: - -```compile_fail,E0550 -#[deprecated(note = "because why not?")] -#[deprecated(note = "right?")] // error! -fn the_banished() {} -``` - -The `deprecated` attribute can only be present **once** on an item. - -``` -#[deprecated(note = "because why not, right?")] -fn the_banished() {} // ok! -``` -"##, - -E0551: r##" -An invalid meta-item was used inside an attribute. - -Erroneous code example: - -```compile_fail,E0551 -#[deprecated(note)] // error! -fn i_am_deprecated() {} -``` - -Meta items are the key-value pairs inside of an attribute. To fix this issue, -you need to give a value to the `note` key. Example: - -``` -#[deprecated(note = "because")] // ok! -fn i_am_deprecated() {} -``` -"##, - -E0552: r##" -A unrecognized representation attribute was used. - -Erroneous code example: - -```compile_fail,E0552 -#[repr(D)] // error: unrecognized representation hint -struct MyStruct { - my_field: usize -} -``` - -You can use a `repr` attribute to tell the compiler how you want a struct or -enum to be laid out in memory. - -Make sure you're using one of the supported options: - -``` -#[repr(C)] // ok! -struct MyStruct { - my_field: usize -} -``` - -For more information about specifying representations, see the ["Alternative -Representations" section] of the Rustonomicon. - -["Alternative Representations" section]: https://doc.rust-lang.org/nomicon/other-reprs.html -"##, - -E0554: r##" -Feature attributes are only allowed on the nightly release channel. Stable or -beta compilers will not comply. - -Example of erroneous code (on a stable compiler): - -```ignore (depends on release channel) -#![feature(non_ascii_idents)] // error: `#![feature]` may not be used on the - // stable release channel -``` - -If you need the feature, make sure to use a nightly release of the compiler -(but be warned that the feature may be removed or altered in the future). -"##, - -E0556: r##" -The `feature` attribute was badly formed. - -Erroneous code example: - -```compile_fail,E0556 -#![feature(foo_bar_baz, foo(bar), foo = "baz", foo)] // error! -#![feature] // error! -#![feature = "foo"] // error! -``` - -The `feature` attribute only accept a "feature flag" and can only be used on -nightly. Example: - -```ignore (only works in nightly) -#![feature(flag)] -``` -"##, - -E0557: r##" -A feature attribute named a feature that has been removed. - -Erroneous code example: - -```compile_fail,E0557 -#![feature(managed_boxes)] // error: feature has been removed -``` - -Delete the offending feature attribute. -"##, - -E0565: r##" -A literal was used in a built-in attribute that doesn't support literals. - -Erroneous code example: - -```ignore (compile_fail not working here; see Issue #43707) -#[inline("always")] // error: unsupported literal -pub fn something() {} -``` - -Literals in attributes are new and largely unsupported in built-in attributes. -Work to support literals where appropriate is ongoing. Try using an unquoted -name instead: - -``` -#[inline(always)] -pub fn something() {} -``` -"##, - -E0583: r##" -A file wasn't found for an out-of-line module. - -Erroneous code example: - -```ignore (compile_fail not working here; see Issue #43707) -mod file_that_doesnt_exist; // error: file not found for module - -fn main() {} -``` - -Please be sure that a file corresponding to the module exists. If you -want to use a module named `file_that_doesnt_exist`, you need to have a file -named `file_that_doesnt_exist.rs` or `file_that_doesnt_exist/mod.rs` in the -same directory. -"##, - -E0584: r##" -A doc comment that is not attached to anything has been encountered. - -Erroneous code example: - -```compile_fail,E0584 -trait Island { - fn lost(); - - /// I'm lost! -} -``` - -A little reminder: a doc comment has to be placed before the item it's supposed -to document. So if you want to document the `Island` trait, you need to put a -doc comment before it, not inside it. Same goes for the `lost` method: the doc -comment needs to be before it: - -``` -/// I'm THE island! -trait Island { - /// I'm lost! - fn lost(); -} -``` -"##, - -E0585: r##" -A documentation comment that doesn't document anything was found. - -Erroneous code example: - -```compile_fail,E0585 -fn main() { - // The following doc comment will fail: - /// This is a useless doc comment! -} -``` - -Documentation comments need to be followed by items, including functions, -types, modules, etc. Examples: - -``` -/// I'm documenting the following struct: -struct Foo; - -/// I'm documenting the following function: -fn foo() {} -``` -"##, - -E0586: r##" -An inclusive range was used with no end. - -Erroneous code example: - -```compile_fail,E0586 -fn main() { - let tmp = vec![0, 1, 2, 3, 4, 4, 3, 3, 2, 1]; - let x = &tmp[1..=]; // error: inclusive range was used with no end -} -``` - -An inclusive range needs an end in order to *include* it. If you just need a -start and no end, use a non-inclusive range (with `..`): - -``` -fn main() { - let tmp = vec![0, 1, 2, 3, 4, 4, 3, 3, 2, 1]; - let x = &tmp[1..]; // ok! -} -``` - -Or put an end to your inclusive range: - -``` -fn main() { - let tmp = vec![0, 1, 2, 3, 4, 4, 3, 3, 2, 1]; - let x = &tmp[1..=3]; // ok! -} -``` -"##, - -E0589: r##" -The value of `N` that was specified for `repr(align(N))` was not a power -of two, or was greater than 2^29. - -```compile_fail,E0589 -#[repr(align(15))] // error: invalid `repr(align)` attribute: not a power of two -enum Foo { - Bar(u64), -} -``` -"##, - -E0658: r##" -An unstable feature was used. - -Erroneous code example: - -```compile_fail,E658 -#[repr(u128)] // error: use of unstable library feature 'repr128' -enum Foo { - Bar(u64), -} -``` - -If you're using a stable or a beta version of rustc, you won't be able to use -any unstable features. In order to do so, please switch to a nightly version of -rustc (by using rustup). - -If you're using a nightly version of rustc, just add the corresponding feature -to be able to use it: - -``` -#![feature(repr128)] - -#[repr(u128)] // ok! -enum Foo { - Bar(u64), -} -``` -"##, - -E0633: r##" -The `unwind` attribute was malformed. - -Erroneous code example: - -```ignore (compile_fail not working here; see Issue #43707) -#[unwind()] // error: expected one argument -pub extern fn something() {} - -fn main() {} -``` - -The `#[unwind]` attribute should be used as follows: - -- `#[unwind(aborts)]` -- specifies that if a non-Rust ABI function - should abort the process if it attempts to unwind. This is the safer - and preferred option. - -- `#[unwind(allowed)]` -- specifies that a non-Rust ABI function - should be allowed to unwind. This can easily result in Undefined - Behavior (UB), so be careful. - -NB. The default behavior here is "allowed", but this is unspecified -and likely to change in the future. - -"##, - -E0704: r##" -This error indicates that a incorrect visibility restriction was specified. - -Example of erroneous code: - -```compile_fail,E0704 -mod foo { - pub(foo) struct Bar { - x: i32 - } -} -``` - -To make struct `Bar` only visible in module `foo` the `in` keyword should be -used: -``` -mod foo { - pub(in crate::foo) struct Bar { - x: i32 - } -} -# fn main() {} -``` - -For more information see the Rust Reference on [Visibility]. - -[Visibility]: https://doc.rust-lang.org/reference/visibility-and-privacy.html -"##, - -E0705: r##" -A `#![feature]` attribute was declared for a feature that is stable in -the current edition, but not in all editions. - -Erroneous code example: - -```ignore (limited to a warning during 2018 edition development) -#![feature(rust_2018_preview)] -#![feature(test_2018_feature)] // error: the feature - // `test_2018_feature` is - // included in the Rust 2018 edition -``` -"##, - -E0725: r##" -A feature attribute named a feature that was disallowed in the compiler -command line flags. - -Erroneous code example: - -```ignore (can't specify compiler flags from doctests) -#![feature(never_type)] // error: the feature `never_type` is not in - // the list of allowed features -``` - -Delete the offending feature attribute, or add it to the list of allowed -features in the `-Z allow_features` flag. -"##, - -E0743: r##" -C-variadic has been used on a non-foreign function. - -Erroneous code example: - -```compile_fail,E0743 -fn foo2(x: u8, ...) {} // error! -``` - -Only foreign functions can use C-variadic (`...`). It is used to give an -undefined number of parameters to a given function (like `printf` in C). The -equivalent in Rust would be to use macros directly. -"##, - -; - - E0539, // incorrect meta item - E0540, // multiple rustc_deprecated attributes - E0542, // missing 'since' - E0543, // missing 'reason' - E0544, // multiple stability levels - E0545, // incorrect 'issue' - E0546, // missing 'feature' - E0547, // missing 'issue' -// E0548, // replaced with a generic attribute input check - // rustc_deprecated attribute must be paired with either stable or unstable - // attribute - E0549, - E0553, // multiple rustc_const_unstable attributes -// E0555, // replaced with a generic attribute input check - E0629, // missing 'feature' (rustc_const_unstable) - // rustc_const_unstable attribute must be paired with stable/unstable - // attribute - E0630, - E0693, // incorrect `repr(align)` attribute format -// E0694, // an unknown tool name found in scoped attributes - E0717, // rustc_promotable without stability attribute -} diff --git a/src/libsyntax/expand/allocator.rs b/src/libsyntax/expand/allocator.rs index 20487b9af03..cc3eeed04a6 100644 --- a/src/libsyntax/expand/allocator.rs +++ b/src/libsyntax/expand/allocator.rs @@ -5,16 +5,14 @@ use syntax_pos::Span; #[derive(Clone, Copy)] pub enum AllocatorKind { Global, - DefaultLib, - DefaultExe, + Default, } impl AllocatorKind { pub fn fn_name(&self, base: &str) -> String { match *self { AllocatorKind::Global => format!("__rg_{}", base), - AllocatorKind::DefaultLib => format!("__rdl_{}", base), - AllocatorKind::DefaultExe => format!("__rde_{}", base), + AllocatorKind::Default => format!("__rdl_{}", base), } } } diff --git a/src/libsyntax/feature_gate/accepted.rs b/src/libsyntax/feature_gate/accepted.rs deleted file mode 100644 index 0107611460b..00000000000 --- a/src/libsyntax/feature_gate/accepted.rs +++ /dev/null @@ -1,263 +0,0 @@ -//! List of the accepted feature gates. - -use crate::symbol::sym; -use super::{State, Feature}; - -macro_rules! declare_features { - ($( - $(#[doc = $doc:tt])* (accepted, $feature:ident, $ver:expr, $issue:expr, None), - )+) => { - /// Those language feature has since been Accepted (it was once Active) - pub const ACCEPTED_FEATURES: &[Feature] = &[ - $( - Feature { - state: State::Accepted, - name: sym::$feature, - since: $ver, - issue: $issue, - edition: None, - description: concat!($($doc,)*), - } - ),+ - ]; - } -} - -declare_features! ( - // ------------------------------------------------------------------------- - // feature-group-start: for testing purposes - // ------------------------------------------------------------------------- - - /// A temporary feature gate used to enable parser extensions needed - /// to bootstrap fix for #5723. - (accepted, issue_5723_bootstrap, "1.0.0", None, None), - /// These are used to test this portion of the compiler, - /// they don't actually mean anything. - (accepted, test_accepted_feature, "1.0.0", None, None), - - // ------------------------------------------------------------------------- - // feature-group-end: for testing purposes - // ------------------------------------------------------------------------- - - // ------------------------------------------------------------------------- - // feature-group-start: accepted features - // ------------------------------------------------------------------------- - - /// Allows using associated `type`s in `trait`s. - (accepted, associated_types, "1.0.0", None, None), - /// Allows using assigning a default type to type parameters in algebraic data type definitions. - (accepted, default_type_params, "1.0.0", None, None), - // FIXME: explain `globs`. - (accepted, globs, "1.0.0", None, None), - /// Allows `macro_rules!` items. - (accepted, macro_rules, "1.0.0", None, None), - /// Allows use of `&foo[a..b]` as a slicing syntax. - (accepted, slicing_syntax, "1.0.0", None, None), - /// Allows struct variants `Foo { baz: u8, .. }` in enums (RFC 418). - (accepted, struct_variant, "1.0.0", None, None), - /// Allows indexing tuples. - (accepted, tuple_indexing, "1.0.0", None, None), - /// Allows the use of `if let` expressions. - (accepted, if_let, "1.0.0", None, None), - /// Allows the use of `while let` expressions. - (accepted, while_let, "1.0.0", None, None), - /// Allows using `#![no_std]`. - (accepted, no_std, "1.6.0", None, None), - /// Allows overloading augmented assignment operations like `a += b`. - (accepted, augmented_assignments, "1.8.0", Some(28235), None), - /// Allows empty structs and enum variants with braces. - (accepted, braced_empty_structs, "1.8.0", Some(29720), None), - /// Allows `#[deprecated]` attribute. - (accepted, deprecated, "1.9.0", Some(29935), None), - /// Allows macros to appear in the type position. - (accepted, type_macros, "1.13.0", Some(27245), None), - /// Allows use of the postfix `?` operator in expressions. - (accepted, question_mark, "1.13.0", Some(31436), None), - /// Allows `..` in tuple (struct) patterns. - (accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627), None), - /// Allows some increased flexibility in the name resolution rules, - /// especially around globs and shadowing (RFC 1560). - (accepted, item_like_imports, "1.15.0", Some(35120), None), - /// Allows using `Self` and associated types in struct expressions and patterns. - (accepted, more_struct_aliases, "1.16.0", Some(37544), None), - /// Allows elision of `'static` lifetimes in `static`s and `const`s. - (accepted, static_in_const, "1.17.0", Some(35897), None), - /// Allows field shorthands (`x` meaning `x: x`) in struct literal expressions. - (accepted, field_init_shorthand, "1.17.0", Some(37340), None), - /// Allows the definition recursive static items. - (accepted, static_recursion, "1.17.0", Some(29719), None), - /// Allows `pub(restricted)` visibilities (RFC 1422). - (accepted, pub_restricted, "1.18.0", Some(32409), None), - /// Allows `#![windows_subsystem]`. - (accepted, windows_subsystem, "1.18.0", Some(37499), None), - /// Allows `break {expr}` with a value inside `loop`s. - (accepted, loop_break_value, "1.19.0", Some(37339), None), - /// Allows numeric fields in struct expressions and patterns. - (accepted, relaxed_adts, "1.19.0", Some(35626), None), - /// Allows coercing non capturing closures to function pointers. - (accepted, closure_to_fn_coercion, "1.19.0", Some(39817), None), - /// Allows attributes on struct literal fields. - (accepted, struct_field_attributes, "1.20.0", Some(38814), None), - /// Allows the definition of associated constants in `trait` or `impl` blocks. - (accepted, associated_consts, "1.20.0", Some(29646), None), - /// Allows usage of the `compile_error!` macro. - (accepted, compile_error, "1.20.0", Some(40872), None), - /// Allows code like `let x: &'static u32 = &42` to work (RFC 1414). - (accepted, rvalue_static_promotion, "1.21.0", Some(38865), None), - /// Allows `Drop` types in constants (RFC 1440). - (accepted, drop_types_in_const, "1.22.0", Some(33156), None), - /// Allows the sysV64 ABI to be specified on all platforms - /// instead of just the platforms on which it is the C ABI. - (accepted, abi_sysv64, "1.24.0", Some(36167), None), - /// Allows `repr(align(16))` struct attribute (RFC 1358). - (accepted, repr_align, "1.25.0", Some(33626), None), - /// Allows '|' at beginning of match arms (RFC 1925). - (accepted, match_beginning_vert, "1.25.0", Some(44101), None), - /// Allows nested groups in `use` items (RFC 2128). - (accepted, use_nested_groups, "1.25.0", Some(44494), None), - /// Allows indexing into constant arrays. - (accepted, const_indexing, "1.26.0", Some(29947), None), - /// Allows using `a..=b` and `..=b` as inclusive range syntaxes. - (accepted, inclusive_range_syntax, "1.26.0", Some(28237), None), - /// Allows `..=` in patterns (RFC 1192). - (accepted, dotdoteq_in_patterns, "1.26.0", Some(28237), None), - /// Allows `fn main()` with return types which implements `Termination` (RFC 1937). - (accepted, termination_trait, "1.26.0", Some(43301), None), - /// Allows implementing `Clone` for closures where possible (RFC 2132). - (accepted, clone_closures, "1.26.0", Some(44490), None), - /// Allows implementing `Copy` for closures where possible (RFC 2132). - (accepted, copy_closures, "1.26.0", Some(44490), None), - /// Allows `impl Trait` in function arguments. - (accepted, universal_impl_trait, "1.26.0", Some(34511), None), - /// Allows `impl Trait` in function return types. - (accepted, conservative_impl_trait, "1.26.0", Some(34511), None), - /// Allows using the `u128` and `i128` types. - (accepted, i128_type, "1.26.0", Some(35118), None), - /// Allows default match binding modes (RFC 2005). - (accepted, match_default_bindings, "1.26.0", Some(42640), None), - /// Allows `'_` placeholder lifetimes. - (accepted, underscore_lifetimes, "1.26.0", Some(44524), None), - /// Allows attributes on lifetime/type formal parameters in generics (RFC 1327). - (accepted, generic_param_attrs, "1.27.0", Some(48848), None), - /// Allows `cfg(target_feature = "...")`. - (accepted, cfg_target_feature, "1.27.0", Some(29717), None), - /// Allows `#[target_feature(...)]`. - (accepted, target_feature, "1.27.0", None, None), - /// Allows using `dyn Trait` as a syntax for trait objects. - (accepted, dyn_trait, "1.27.0", Some(44662), None), - /// Allows `#[must_use]` on functions, and introduces must-use operators (RFC 1940). - (accepted, fn_must_use, "1.27.0", Some(43302), None), - /// Allows use of the `:lifetime` macro fragment specifier. - (accepted, macro_lifetime_matcher, "1.27.0", Some(34303), None), - /// Allows `#[test]` functions where the return type implements `Termination` (RFC 1937). - (accepted, termination_trait_test, "1.27.0", Some(48854), None), - /// Allows the `#[global_allocator]` attribute. - (accepted, global_allocator, "1.28.0", Some(27389), None), - /// Allows `#[repr(transparent)]` attribute on newtype structs. - (accepted, repr_transparent, "1.28.0", Some(43036), None), - /// Allows procedural macros in `proc-macro` crates. - (accepted, proc_macro, "1.29.0", Some(38356), None), - /// Allows `foo.rs` as an alternative to `foo/mod.rs`. - (accepted, non_modrs_mods, "1.30.0", Some(44660), None), - /// Allows use of the `:vis` macro fragment specifier - (accepted, macro_vis_matcher, "1.30.0", Some(41022), None), - /// Allows importing and reexporting macros with `use`, - /// enables macro modularization in general. - (accepted, use_extern_macros, "1.30.0", Some(35896), None), - /// Allows keywords to be escaped for use as identifiers. - (accepted, raw_identifiers, "1.30.0", Some(48589), None), - /// Allows attributes scoped to tools. - (accepted, tool_attributes, "1.30.0", Some(44690), None), - /// Allows multi-segment paths in attributes and derives. - (accepted, proc_macro_path_invoc, "1.30.0", Some(38356), None), - /// Allows all literals in attribute lists and values of key-value pairs. - (accepted, attr_literals, "1.30.0", Some(34981), None), - /// Allows inferring outlives requirements (RFC 2093). - (accepted, infer_outlives_requirements, "1.30.0", Some(44493), None), - /// Allows annotating functions conforming to `fn(&PanicInfo) -> !` with `#[panic_handler]`. - /// This defines the behavior of panics. - (accepted, panic_handler, "1.30.0", Some(44489), None), - /// Allows `#[used]` to preserve symbols (see llvm.used). - (accepted, used, "1.30.0", Some(40289), None), - /// Allows `crate` in paths. - (accepted, crate_in_paths, "1.30.0", Some(45477), None), - /// Allows resolving absolute paths as paths from other crates. - (accepted, extern_absolute_paths, "1.30.0", Some(44660), None), - /// Allows access to crate names passed via `--extern` through prelude. - (accepted, extern_prelude, "1.30.0", Some(44660), None), - /// Allows parentheses in patterns. - (accepted, pattern_parentheses, "1.31.0", Some(51087), None), - /// Allows the definition of `const fn` functions. - (accepted, min_const_fn, "1.31.0", Some(53555), None), - /// Allows scoped lints. - (accepted, tool_lints, "1.31.0", Some(44690), None), - /// Allows lifetime elision in `impl` headers. For example: - /// + `impl<I:Iterator> Iterator for &mut Iterator` - /// + `impl Debug for Foo<'_>` - (accepted, impl_header_lifetime_elision, "1.31.0", Some(15872), None), - /// Allows `extern crate foo as bar;`. This puts `bar` into extern prelude. - (accepted, extern_crate_item_prelude, "1.31.0", Some(55599), None), - /// Allows use of the `:literal` macro fragment specifier (RFC 1576). - (accepted, macro_literal_matcher, "1.32.0", Some(35625), None), - /// Allows use of `?` as the Kleene "at most one" operator in macros. - (accepted, macro_at_most_once_rep, "1.32.0", Some(48075), None), - /// Allows `Self` struct constructor (RFC 2302). - (accepted, self_struct_ctor, "1.32.0", Some(51994), None), - /// Allows `Self` in type definitions (RFC 2300). - (accepted, self_in_typedefs, "1.32.0", Some(49303), None), - /// Allows `use x::y;` to search `x` in the current scope. - (accepted, uniform_paths, "1.32.0", Some(53130), None), - /// Allows integer match exhaustiveness checking (RFC 2591). - (accepted, exhaustive_integer_patterns, "1.33.0", Some(50907), None), - /// Allows `use path as _;` and `extern crate c as _;`. - (accepted, underscore_imports, "1.33.0", Some(48216), None), - /// Allows `#[repr(packed(N))]` attribute on structs. - (accepted, repr_packed, "1.33.0", Some(33158), None), - /// Allows irrefutable patterns in `if let` and `while let` statements (RFC 2086). - (accepted, irrefutable_let_patterns, "1.33.0", Some(44495), None), - /// Allows calling `const unsafe fn` inside `unsafe` blocks in `const fn` functions. - (accepted, min_const_unsafe_fn, "1.33.0", Some(55607), None), - /// Allows let bindings, assignments and destructuring in `const` functions and constants. - /// As long as control flow is not implemented in const eval, `&&` and `||` may not be used - /// at the same time as let bindings. - (accepted, const_let, "1.33.0", Some(48821), None), - /// Allows `#[cfg_attr(predicate, multiple, attributes, here)]`. - (accepted, cfg_attr_multi, "1.33.0", Some(54881), None), - /// Allows top level or-patterns (`p | q`) in `if let` and `while let`. - (accepted, if_while_or_patterns, "1.33.0", Some(48215), None), - /// Allows `cfg(target_vendor = "...")`. - (accepted, cfg_target_vendor, "1.33.0", Some(29718), None), - /// Allows `extern crate self as foo;`. - /// This puts local crate root into extern prelude under name `foo`. - (accepted, extern_crate_self, "1.34.0", Some(56409), None), - /// Allows arbitrary delimited token streams in non-macro attributes. - (accepted, unrestricted_attribute_tokens, "1.34.0", Some(55208), None), - /// Allows paths to enum variants on type aliases including `Self`. - (accepted, type_alias_enum_variants, "1.37.0", Some(49683), None), - /// Allows using `#[repr(align(X))]` on enums with equivalent semantics - /// to wrapping an enum in a wrapper struct with `#[repr(align(X))]`. - (accepted, repr_align_enum, "1.37.0", Some(57996), None), - /// Allows `const _: TYPE = VALUE`. - (accepted, underscore_const_names, "1.37.0", Some(54912), None), - /// Allows free and inherent `async fn`s, `async` blocks, and `<expr>.await` expressions. - (accepted, async_await, "1.39.0", Some(50547), None), - /// Allows mixing bind-by-move in patterns and references to those identifiers in guards. - (accepted, bind_by_move_pattern_guards, "1.39.0", Some(15287), None), - /// Allows attributes in formal function parameters. - (accepted, param_attrs, "1.39.0", Some(60406), None), - /// Allows macro invocations in `extern {}` blocks. - (accepted, macros_in_extern, "1.40.0", Some(49476), None), - /// Allows future-proofing enums/structs with the `#[non_exhaustive]` attribute (RFC 2008). - (accepted, non_exhaustive, "1.40.0", Some(44109), None), - /// Allows calling constructor functions in `const fn`. - (accepted, const_constructor, "1.40.0", Some(61456), None), - /// Allows the use of `#[cfg(doctest)]`, set when rustdoc is collecting doctests. - (accepted, cfg_doctest, "1.40.0", Some(62210), None), - /// Allows relaxing the coherence rules such that - /// `impl<T> ForeignTrait<LocalType> for ForeignType<T>` is permitted. - (accepted, re_rebalance_coherence, "1.41.0", Some(55437), None), - - // ------------------------------------------------------------------------- - // feature-group-end: accepted features - // ------------------------------------------------------------------------- -); diff --git a/src/libsyntax/feature_gate/active.rs b/src/libsyntax/feature_gate/active.rs deleted file mode 100644 index 1d198fca56b..00000000000 --- a/src/libsyntax/feature_gate/active.rs +++ /dev/null @@ -1,545 +0,0 @@ -//! List of the active feature gates. - -use super::{State, Feature}; - -use crate::edition::Edition; -use crate::symbol::{Symbol, sym}; - -use syntax_pos::Span; - -macro_rules! set { - ($field: ident) => {{ - fn f(features: &mut Features, _: Span) { - features.$field = true; - } - f as fn(&mut Features, Span) - }} -} - -macro_rules! declare_features { - ($( - $(#[doc = $doc:tt])* (active, $feature:ident, $ver:expr, $issue:expr, $edition:expr), - )+) => { - /// Represents active features that are currently being implemented or - /// currently being considered for addition/removal. - pub const ACTIVE_FEATURES: - &[Feature] = - &[$( - // (sym::$feature, $ver, $issue, $edition, set!($feature)) - Feature { - state: State::Active { set: set!($feature) }, - name: sym::$feature, - since: $ver, - issue: $issue, - edition: $edition, - description: concat!($($doc,)*), - } - ),+]; - - /// A set of features to be used by later passes. - #[derive(Clone)] - pub struct Features { - /// `#![feature]` attrs for language features, for error reporting. - pub declared_lang_features: Vec<(Symbol, Span, Option<Symbol>)>, - /// `#![feature]` attrs for non-language (library) features. - pub declared_lib_features: Vec<(Symbol, Span)>, - $( - $(#[doc = $doc])* - pub $feature: bool - ),+ - } - - impl Features { - pub fn new() -> Features { - Features { - declared_lang_features: Vec::new(), - declared_lib_features: Vec::new(), - $($feature: false),+ - } - } - - pub fn walk_feature_fields<F>(&self, mut f: F) - where F: FnMut(&str, bool) - { - $(f(stringify!($feature), self.$feature);)+ - } - } - }; -} - -impl Feature { - /// Sets this feature in `Features`. Panics if called on a non-active feature. - pub fn set(&self, features: &mut Features, span: Span) { - match self.state { - State::Active { set } => set(features, span), - _ => panic!("called `set` on feature `{}` which is not `active`", self.name) - } - } -} - -// If you change this, please modify `src/doc/unstable-book` as well. -// -// Don't ever remove anything from this list; move them to `removed.rs`. -// -// The version numbers here correspond to the version in which the current status -// was set. This is most important for knowing when a particular feature became -// stable (active). -// -// Note that the features are grouped into internal/user-facing and then -// sorted by version inside those groups. This is enforced with tidy. -// -// N.B., `tools/tidy/src/features.rs` parses this information directly out of the -// source, so take care when modifying it. - -declare_features! ( - // ------------------------------------------------------------------------- - // feature-group-start: internal feature gates - // ------------------------------------------------------------------------- - - // no-tracking-issue-start - - /// Allows using compiler's own crates. - (active, rustc_private, "1.0.0", Some(27812), None), - - /// Allows using the `rust-intrinsic`'s "ABI". - (active, intrinsics, "1.0.0", None, None), - - /// Allows using `#[lang = ".."]` attribute for linking items to special compiler logic. - (active, lang_items, "1.0.0", None, None), - - /// Allows using the `#[stable]` and `#[unstable]` attributes. - (active, staged_api, "1.0.0", None, None), - - /// Allows using `#[allow_internal_unstable]`. This is an - /// attribute on `macro_rules!` and can't use the attribute handling - /// below (it has to be checked before expansion possibly makes - /// macros disappear). - (active, allow_internal_unstable, "1.0.0", None, None), - - /// Allows using `#[allow_internal_unsafe]`. This is an - /// attribute on `macro_rules!` and can't use the attribute handling - /// below (it has to be checked before expansion possibly makes - /// macros disappear). - (active, allow_internal_unsafe, "1.0.0", None, None), - - /// Allows using `#[rustc_const_unstable(feature = "foo", ..)]` which - /// lets a function to be `const` when opted into with `#![feature(foo)]`. - (active, rustc_const_unstable, "1.0.0", None, None), - - /// no-tracking-issue-end - - /// Allows using `#[link_name="llvm.*"]`. - (active, link_llvm_intrinsics, "1.0.0", Some(29602), None), - - /// Allows using `rustc_*` attributes (RFC 572). - (active, rustc_attrs, "1.0.0", Some(29642), None), - - /// Allows using the `box $expr` syntax. - (active, box_syntax, "1.0.0", Some(49733), None), - - /// Allows using `#[main]` to replace the entrypoint `#[lang = "start"]` calls. - (active, main, "1.0.0", Some(29634), None), - - /// Allows using `#[start]` on a function indicating that it is the program entrypoint. - (active, start, "1.0.0", Some(29633), None), - - /// Allows using the `#[fundamental]` attribute. - (active, fundamental, "1.0.0", Some(29635), None), - - /// Allows using the `rust-call` ABI. - (active, unboxed_closures, "1.0.0", Some(29625), None), - - /// Allows using the `#[linkage = ".."]` attribute. - (active, linkage, "1.0.0", Some(29603), None), - - /// Allows features specific to OIBIT (auto traits). - (active, optin_builtin_traits, "1.0.0", Some(13231), None), - - /// Allows using `box` in patterns (RFC 469). - (active, box_patterns, "1.0.0", Some(29641), None), - - // no-tracking-issue-start - - /// Allows using `#[prelude_import]` on glob `use` items. - (active, prelude_import, "1.2.0", None, None), - - // no-tracking-issue-end - - // no-tracking-issue-start - - /// Allows using `#[omit_gdb_pretty_printer_section]`. - (active, omit_gdb_pretty_printer_section, "1.5.0", None, None), - - /// Allows using the `vectorcall` ABI. - (active, abi_vectorcall, "1.7.0", None, None), - - // no-tracking-issue-end - - /// Allows using `#[structural_match]` which indicates that a type is structurally matchable. - (active, structural_match, "1.8.0", Some(31434), None), - - /// Allows using the `may_dangle` attribute (RFC 1327). - (active, dropck_eyepatch, "1.10.0", Some(34761), None), - - /// Allows using the `#![panic_runtime]` attribute. - (active, panic_runtime, "1.10.0", Some(32837), None), - - /// Allows declaring with `#![needs_panic_runtime]` that a panic runtime is needed. - (active, needs_panic_runtime, "1.10.0", Some(32837), None), - - // no-tracking-issue-start - - /// Allows identifying the `compiler_builtins` crate. - (active, compiler_builtins, "1.13.0", None, None), - - /// Allows using the `unadjusted` ABI; perma-unstable. - (active, abi_unadjusted, "1.16.0", None, None), - - /// Allows identifying crates that contain sanitizer runtimes. - (active, sanitizer_runtime, "1.17.0", None, None), - - /// Used to identify crates that contain the profiler runtime. - (active, profiler_runtime, "1.18.0", None, None), - - /// Allows using the `thiscall` ABI. - (active, abi_thiscall, "1.19.0", None, None), - - /// Allows using `#![needs_allocator]`, an implementation detail of `#[global_allocator]`. - (active, allocator_internals, "1.20.0", None, None), - - // no-tracking-issue-end - - /// Added for testing E0705; perma-unstable. - (active, test_2018_feature, "1.31.0", Some(0), Some(Edition::Edition2018)), - - // ------------------------------------------------------------------------- - // feature-group-end: internal feature gates - // ------------------------------------------------------------------------- - - // ------------------------------------------------------------------------- - // feature-group-start: actual feature gates (target features) - // ------------------------------------------------------------------------- - - // FIXME: Document these and merge with the list below. - - // Unstable `#[target_feature]` directives. - (active, arm_target_feature, "1.27.0", Some(44839), None), - (active, aarch64_target_feature, "1.27.0", Some(44839), None), - (active, hexagon_target_feature, "1.27.0", Some(44839), None), - (active, powerpc_target_feature, "1.27.0", Some(44839), None), - (active, mips_target_feature, "1.27.0", Some(44839), None), - (active, avx512_target_feature, "1.27.0", Some(44839), None), - (active, mmx_target_feature, "1.27.0", Some(44839), None), - (active, sse4a_target_feature, "1.27.0", Some(44839), None), - (active, tbm_target_feature, "1.27.0", Some(44839), None), - (active, wasm_target_feature, "1.30.0", Some(44839), None), - (active, adx_target_feature, "1.32.0", Some(44839), None), - (active, cmpxchg16b_target_feature, "1.32.0", Some(44839), None), - (active, movbe_target_feature, "1.34.0", Some(44839), None), - (active, rtm_target_feature, "1.35.0", Some(44839), None), - (active, f16c_target_feature, "1.36.0", Some(44839), None), - - // ------------------------------------------------------------------------- - // feature-group-end: actual feature gates (target features) - // ------------------------------------------------------------------------- - - // ------------------------------------------------------------------------- - // feature-group-start: actual feature gates - // ------------------------------------------------------------------------- - - /// Allows using the `#[link_args]` attribute. - (active, link_args, "1.0.0", Some(29596), None), - - /// Allows defining identifiers beyond ASCII. - (active, non_ascii_idents, "1.0.0", Some(55467), None), - - /// Allows using `#[plugin_registrar]` on functions. - (active, plugin_registrar, "1.0.0", Some(29597), None), - - /// Allows using `#![plugin(myplugin)]`. - (active, plugin, "1.0.0", Some(29597), None), - - /// Allows using `#[thread_local]` on `static` items. - (active, thread_local, "1.0.0", Some(29594), None), - - /// Allows the use of SIMD types in functions declared in `extern` blocks. - (active, simd_ffi, "1.0.0", Some(27731), None), - - /// Allows using custom attributes (RFC 572). - (active, custom_attribute, "1.0.0", Some(29642), None), - - /// Allows using non lexical lifetimes (RFC 2094). - (active, nll, "1.0.0", Some(43234), None), - - /// Allows using slice patterns. - (active, slice_patterns, "1.0.0", Some(62254), None), - - /// Allows the definition of `const` functions with some advanced features. - (active, const_fn, "1.2.0", Some(57563), None), - - /// Allows associated type defaults. - (active, associated_type_defaults, "1.2.0", Some(29661), None), - - /// Allows `#![no_core]`. - (active, no_core, "1.3.0", Some(29639), None), - - /// Allows default type parameters to influence type inference. - (active, default_type_parameter_fallback, "1.3.0", Some(27336), None), - - /// Allows `repr(simd)` and importing the various simd intrinsics. - (active, repr_simd, "1.4.0", Some(27731), None), - - /// Allows `extern "platform-intrinsic" { ... }`. - (active, platform_intrinsics, "1.4.0", Some(27731), None), - - /// Allows `#[unwind(..)]`. - /// - /// Permits specifying whether a function should permit unwinding or abort on unwind. - (active, unwind_attributes, "1.4.0", Some(58760), None), - - /// Allows `#[no_debug]`. - (active, no_debug, "1.5.0", Some(29721), None), - - /// Allows attributes on expressions and non-item statements. - (active, stmt_expr_attributes, "1.6.0", Some(15701), None), - - /// Allows the use of type ascription in expressions. - (active, type_ascription, "1.6.0", Some(23416), None), - - /// Allows `cfg(target_thread_local)`. - (active, cfg_target_thread_local, "1.7.0", Some(29594), None), - - /// Allows specialization of implementations (RFC 1210). - (active, specialization, "1.7.0", Some(31844), None), - - /// Allows using `#[naked]` on functions. - (active, naked_functions, "1.9.0", Some(32408), None), - - /// Allows `cfg(target_has_atomic = "...")`. - (active, cfg_target_has_atomic, "1.9.0", Some(32976), None), - - /// Allows `X..Y` patterns. - (active, exclusive_range_pattern, "1.11.0", Some(37854), None), - - /// Allows the `!` type. Does not imply 'exhaustive_patterns' (below) any more. - (active, never_type, "1.13.0", Some(35121), None), - - /// Allows exhaustive pattern matching on types that contain uninhabited types. - (active, exhaustive_patterns, "1.13.0", Some(51085), None), - - /// Allows `union`s to implement `Drop`. Moreover, `union`s may now include fields - /// that don't implement `Copy` as long as they don't have any drop glue. - /// This is checked recursively. On encountering type variable where no progress can be made, - /// `T: Copy` is used as a substitute for "no drop glue". - /// - /// NOTE: A limited form of `union U { ... }` was accepted in 1.19.0. - (active, untagged_unions, "1.13.0", Some(55149), None), - - /// Allows `#[link(..., cfg(..))]`. - (active, link_cfg, "1.14.0", Some(37406), None), - - /// Allows `extern "ptx-*" fn()`. - (active, abi_ptx, "1.15.0", Some(38788), None), - - /// Allows the `#[repr(i128)]` attribute for enums. - (active, repr128, "1.16.0", Some(35118), None), - - /// Allows `#[link(kind="static-nobundle"...)]`. - (active, static_nobundle, "1.16.0", Some(37403), None), - - /// Allows `extern "msp430-interrupt" fn()`. - (active, abi_msp430_interrupt, "1.16.0", Some(38487), None), - - /// Allows declarative macros 2.0 (`macro`). - (active, decl_macro, "1.17.0", Some(39412), None), - - /// Allows `extern "x86-interrupt" fn()`. - (active, abi_x86_interrupt, "1.17.0", Some(40180), None), - - /// Allows overlapping impls of marker traits. - (active, overlapping_marker_traits, "1.18.0", Some(29864), None), - - /// Allows a test to fail without failing the whole suite. - (active, allow_fail, "1.19.0", Some(46488), None), - - /// Allows unsized tuple coercion. - (active, unsized_tuple_coercion, "1.20.0", Some(42877), None), - - /// Allows defining generators. - (active, generators, "1.21.0", Some(43122), None), - - /// Allows `#[doc(cfg(...))]`. - (active, doc_cfg, "1.21.0", Some(43781), None), - - /// Allows `#[doc(masked)]`. - (active, doc_masked, "1.21.0", Some(44027), None), - - /// Allows `#[doc(spotlight)]`. - (active, doc_spotlight, "1.22.0", Some(45040), None), - - /// Allows `#[doc(include = "some-file")]`. - (active, external_doc, "1.22.0", Some(44732), None), - - /// Allows using `crate` as visibility modifier, synonymous with `pub(crate)`. - (active, crate_visibility_modifier, "1.23.0", Some(53120), None), - - /// Allows defining `extern type`s. - (active, extern_types, "1.23.0", Some(43467), None), - - /// Allows trait methods with arbitrary self types. - (active, arbitrary_self_types, "1.23.0", Some(44874), None), - - /// Allows in-band quantification of lifetime bindings (e.g., `fn foo(x: &'a u8) -> &'a u8`). - (active, in_band_lifetimes, "1.23.0", Some(44524), None), - - /// Allows associated types to be generic, e.g., `type Foo<T>;` (RFC 1598). - (active, generic_associated_types, "1.23.0", Some(44265), None), - - /// Allows defining `trait X = A + B;` alias items. - (active, trait_alias, "1.24.0", Some(41517), None), - - /// Allows infering `'static` outlives requirements (RFC 2093). - (active, infer_static_outlives_requirements, "1.26.0", Some(54185), None), - - /// Allows accessing fields of unions inside `const` functions. - (active, const_fn_union, "1.27.0", Some(51909), None), - - /// Allows casting raw pointers to `usize` during const eval. - (active, const_raw_ptr_to_usize_cast, "1.27.0", Some(51910), None), - - /// Allows dereferencing raw pointers during const eval. - (active, const_raw_ptr_deref, "1.27.0", Some(51911), None), - - /// Allows comparing raw pointers during const eval. - (active, const_compare_raw_pointers, "1.27.0", Some(53020), None), - - /// Allows `#[doc(alias = "...")]`. - (active, doc_alias, "1.27.0", Some(50146), None), - - /// Allows inconsistent bounds in where clauses. - (active, trivial_bounds, "1.28.0", Some(48214), None), - - /// Allows `'a: { break 'a; }`. - (active, label_break_value, "1.28.0", Some(48594), None), - - /// Allows using `#[doc(keyword = "...")]`. - (active, doc_keyword, "1.28.0", Some(51315), None), - - /// Allows reinterpretation of the bits of a value of one type as another - /// type during const eval. - (active, const_transmute, "1.29.0", Some(53605), None), - - /// Allows using `try {...}` expressions. - (active, try_blocks, "1.29.0", Some(31436), None), - - /// Allows defining an `#[alloc_error_handler]`. - (active, alloc_error_handler, "1.29.0", Some(51540), None), - - /// Allows using the `amdgpu-kernel` ABI. - (active, abi_amdgpu_kernel, "1.29.0", Some(51575), None), - - /// Allows panicking during const eval (producing compile-time errors). - (active, const_panic, "1.30.0", Some(51999), None), - - /// Allows `#[marker]` on certain traits allowing overlapping implementations. - (active, marker_trait_attr, "1.30.0", Some(29864), None), - - /// Allows macro invocations on modules expressions and statements and - /// procedural macros to expand to non-items. - (active, proc_macro_hygiene, "1.30.0", Some(54727), None), - - /// Allows unsized rvalues at arguments and parameters. - (active, unsized_locals, "1.30.0", Some(48055), None), - - /// Allows custom test frameworks with `#![test_runner]` and `#[test_case]`. - (active, custom_test_frameworks, "1.30.0", Some(50297), None), - - /// Allows non-builtin attributes in inner attribute position. - (active, custom_inner_attributes, "1.30.0", Some(54726), None), - - /// Allows `impl Trait` in bindings (`let`, `const`, `static`). - (active, impl_trait_in_bindings, "1.30.0", Some(63065), None), - - /// Allows using `reason` in lint attributes and the `#[expect(lint)]` lint check. - (active, lint_reasons, "1.31.0", Some(54503), None), - - /// Allows exhaustive integer pattern matching on `usize` and `isize`. - (active, precise_pointer_size_matching, "1.32.0", Some(56354), None), - - /// Allows using `#[ffi_returns_twice]` on foreign functions. - (active, ffi_returns_twice, "1.34.0", Some(58314), None), - - /// Allows const generic types (e.g. `struct Foo<const N: usize>(...);`). - (active, const_generics, "1.34.0", Some(44580), None), - - /// Allows using `#[optimize(X)]`. - (active, optimize_attribute, "1.34.0", Some(54882), None), - - /// Allows using C-variadics. - (active, c_variadic, "1.34.0", Some(44930), None), - - /// Allows the user of associated type bounds. - (active, associated_type_bounds, "1.34.0", Some(52662), None), - - /// Allows `if/while p && let q = r && ...` chains. - (active, let_chains, "1.37.0", Some(53667), None), - - /// Allows #[repr(transparent)] on enums (RFC 2645). - (active, transparent_enums, "1.37.0", Some(60405), None), - - /// Allows #[repr(transparent)] on unions (RFC 2645). - (active, transparent_unions, "1.37.0", Some(60405), None), - - /// Allows explicit discriminants on non-unit enum variants. - (active, arbitrary_enum_discriminant, "1.37.0", Some(60553), None), - - /// Allows `impl Trait` with multiple unrelated lifetimes. - (active, member_constraints, "1.37.0", Some(61977), None), - - /// Allows `async || body` closures. - (active, async_closure, "1.37.0", Some(62290), None), - - /// Allows `[x; N]` where `x` is a constant (RFC 2203). - (active, const_in_array_repeat_expressions, "1.37.0", Some(49147), None), - - /// Allows `impl Trait` to be used inside type aliases (RFC 2515). - (active, type_alias_impl_trait, "1.38.0", Some(63063), None), - - /// Allows the use of or-patterns (e.g., `0 | 1`). - (active, or_patterns, "1.38.0", Some(54883), None), - - /// Allows the definition of `const extern fn` and `const unsafe extern fn`. - (active, const_extern_fn, "1.40.0", Some(64926), None), - - /// Allows the use of raw-dylibs (RFC 2627). - (active, raw_dylib, "1.40.0", Some(58713), None), - - /// Allows `#[track_caller]` to be used which provides - /// accurate caller location reporting during panic (RFC 2091). - (active, track_caller, "1.40.0", Some(47809), None), - - /// Allows making `dyn Trait` well-formed even if `Trait` is not object safe. - /// In that case, `dyn Trait: Trait` does not hold. Moreover, coercions and - /// casts in safe Rust to `dyn Trait` for such a `Trait` is also forbidden. - (active, object_safe_for_dispatch, "1.40.0", Some(43561), None), - - /// Allows using the `efiapi` ABI. - (active, abi_efiapi, "1.40.0", Some(65815), None), - - // ------------------------------------------------------------------------- - // feature-group-end: actual feature gates - // ------------------------------------------------------------------------- -); - -/// Some features are known to be incomplete and using them is likely to have -/// unanticipated results, such as compiler crashes. We warn the user about these -/// to alert them. -pub const INCOMPLETE_FEATURES: &[Symbol] = &[ - sym::impl_trait_in_bindings, - sym::generic_associated_types, - sym::const_generics, - sym::or_patterns, - sym::let_chains, - sym::raw_dylib, - sym::track_caller, -]; diff --git a/src/libsyntax/feature_gate/builtin_attrs.rs b/src/libsyntax/feature_gate/builtin_attrs.rs deleted file mode 100644 index b32a887c6b2..00000000000 --- a/src/libsyntax/feature_gate/builtin_attrs.rs +++ /dev/null @@ -1,598 +0,0 @@ -//! Built-in attributes and `cfg` flag gating. - -use AttributeType::*; -use AttributeGate::*; - -use super::check::{emit_feature_err, GateIssue}; -use super::check::{Stability, EXPLAIN_ALLOW_INTERNAL_UNSAFE, EXPLAIN_ALLOW_INTERNAL_UNSTABLE}; -use super::active::Features; - -use crate::ast; -use crate::attr::AttributeTemplate; -use crate::sess::ParseSess; -use crate::symbol::{Symbol, sym}; - -use syntax_pos::Span; -use rustc_data_structures::fx::FxHashMap; -use lazy_static::lazy_static; - -type GateFn = fn(&Features) -> bool; - -macro_rules! cfg_fn { - ($field: ident) => { - (|features| { features.$field }) as GateFn - } -} - -/// `cfg(...)`'s that are feature gated. -const GATED_CFGS: &[(Symbol, Symbol, GateFn)] = &[ - // (name in cfg, feature, function to check if the feature is enabled) - (sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)), - (sym::target_has_atomic, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)), - (sym::target_has_atomic_load_store, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)), - (sym::rustdoc, sym::doc_cfg, cfg_fn!(doc_cfg)), -]; - -#[derive(Debug)] -pub struct GatedCfg { - span: Span, - index: usize, -} - -impl GatedCfg { - pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> { - GATED_CFGS.iter() - .position(|info| cfg.check_name(info.0)) - .map(|idx| { - GatedCfg { - span: cfg.span, - index: idx - } - }) - } - - pub fn check_and_emit(&self, sess: &ParseSess, features: &Features) { - let (cfg, feature, has_feature) = GATED_CFGS[self.index]; - if !has_feature(features) && !self.span.allows_unstable(feature) { - let explain = format!("`cfg({})` is experimental and subject to change", cfg); - emit_feature_err(sess, feature, self.span, GateIssue::Language, &explain); - } - } -} - -// If you change this, please modify `src/doc/unstable-book` as well. You must -// move that documentation into the relevant place in the other docs, and -// remove the chapter on the flag. - -#[derive(Copy, Clone, PartialEq, Debug)] -pub enum AttributeType { - /// Normal, builtin attribute that is consumed - /// by the compiler before the unused_attribute check - Normal, - - /// Builtin attribute that may not be consumed by the compiler - /// before the unused_attribute check. These attributes - /// will be ignored by the unused_attribute lint - Whitelisted, - - /// Builtin attribute that is only allowed at the crate level - CrateLevel, -} - -#[derive(Clone, Copy)] -pub enum AttributeGate { - /// Is gated by a given feature gate, reason - /// and function to check if enabled - Gated(Stability, Symbol, &'static str, fn(&Features) -> bool), - - /// Ungated attribute, can be used on all release channels - Ungated, -} - -// fn() is not Debug -impl std::fmt::Debug for AttributeGate { - fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match *self { - Self::Gated(ref stab, name, expl, _) => - write!(fmt, "Gated({:?}, {}, {})", stab, name, expl), - Self::Ungated => write!(fmt, "Ungated") - } - } -} - -impl AttributeGate { - fn is_deprecated(&self) -> bool { - match *self { - Self::Gated(Stability::Deprecated(_, _), ..) => true, - _ => false, - } - } -} - -/// A convenience macro for constructing attribute templates. -/// E.g., `template!(Word, List: "description")` means that the attribute -/// supports forms `#[attr]` and `#[attr(description)]`. -macro_rules! template { - (Word) => { template!(@ true, None, None) }; - (List: $descr: expr) => { template!(@ false, Some($descr), None) }; - (NameValueStr: $descr: expr) => { template!(@ false, None, Some($descr)) }; - (Word, List: $descr: expr) => { template!(@ true, Some($descr), None) }; - (Word, NameValueStr: $descr: expr) => { template!(@ true, None, Some($descr)) }; - (List: $descr1: expr, NameValueStr: $descr2: expr) => { - template!(@ false, Some($descr1), Some($descr2)) - }; - (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => { - template!(@ true, Some($descr1), Some($descr2)) - }; - (@ $word: expr, $list: expr, $name_value_str: expr) => { AttributeTemplate { - word: $word, list: $list, name_value_str: $name_value_str - } }; -} - -macro_rules! ungated { - ($attr:ident, $typ:expr, $tpl:expr $(,)?) => { - (sym::$attr, $typ, $tpl, Ungated) - }; -} - -macro_rules! gated { - ($attr:ident, $typ:expr, $tpl:expr, $gate:ident, $msg:expr $(,)?) => { - (sym::$attr, $typ, $tpl, Gated(Stability::Unstable, sym::$gate, $msg, cfg_fn!($gate))) - }; - ($attr:ident, $typ:expr, $tpl:expr, $msg:expr $(,)?) => { - (sym::$attr, $typ, $tpl, Gated(Stability::Unstable, sym::$attr, $msg, cfg_fn!($attr))) - }; -} - -macro_rules! rustc_attr { - (TEST, $attr:ident, $typ:expr, $tpl:expr $(,)?) => { - rustc_attr!( - $attr, $typ, $tpl, - concat!("the `#[", stringify!($attr), "]` attribute is just used for rustc unit tests \ - and will never be stable", - ), - ) - }; - ($attr:ident, $typ:expr, $tpl:expr, $msg:expr $(,)?) => { - (sym::$attr, $typ, $tpl, - Gated(Stability::Unstable, sym::rustc_attrs, $msg, cfg_fn!(rustc_attrs))) - }; -} - -macro_rules! experimental { - ($attr:ident) => { - concat!("the `#[", stringify!($attr), "]` attribute is an experimental feature") - } -} - -const IMPL_DETAIL: &str = "internal implementation detail"; -const INTERNAL_UNSTABLE: &str = "this is an internal attribute that will never be stable"; - -pub type BuiltinAttribute = (Symbol, AttributeType, AttributeTemplate, AttributeGate); - -/// Attributes that have a special meaning to rustc or rustdoc. -pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ - // ========================================================================== - // Stable attributes: - // ========================================================================== - - // Condtional compilation: - ungated!(cfg, Normal, template!(List: "predicate")), - ungated!(cfg_attr, Normal, template!(List: "predicate, attr1, attr2, ...")), - - // Testing: - ungated!(ignore, Normal, template!(Word, NameValueStr: "reason")), - ungated!( - should_panic, Normal, - template!(Word, List: r#"expected = "reason"#, NameValueStr: "reason"), - ), - // FIXME(Centril): This can be used on stable but shouldn't. - ungated!(reexport_test_harness_main, Normal, template!(NameValueStr: "name")), - - // Macros: - ungated!(derive, Normal, template!(List: "Trait1, Trait2, ...")), - ungated!(automatically_derived, Normal, template!(Word)), - // FIXME(#14407) - ungated!(macro_use, Normal, template!(Word, List: "name1, name2, ...")), - ungated!(macro_escape, Normal, template!(Word)), // Deprecated synonym for `macro_use`. - ungated!(macro_export, Normal, template!(Word, List: "local_inner_macros")), - ungated!(proc_macro, Normal, template!(Word)), - ungated!( - proc_macro_derive, Normal, - template!(List: "TraitName, /*opt*/ attributes(name1, name2, ...)"), - ), - ungated!(proc_macro_attribute, Normal, template!(Word)), - - // Lints: - ungated!(warn, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)), - ungated!(allow, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)), - ungated!(forbid, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)), - ungated!(deny, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)), - ungated!(must_use, Whitelisted, template!(Word, NameValueStr: "reason")), - // FIXME(#14407) - ungated!( - deprecated, Normal, - template!( - Word, - List: r#"/*opt*/ since = "version", /*opt*/ note = "reason""#, - NameValueStr: "reason" - ), - ), - - // Crate properties: - ungated!(crate_name, CrateLevel, template!(NameValueStr: "name")), - ungated!(crate_type, CrateLevel, template!(NameValueStr: "bin|lib|...")), - ungated!(crate_id, CrateLevel, template!(NameValueStr: "ignored")), - - // ABI, linking, symbols, and FFI - ungated!( - link, Whitelisted, - template!(List: r#"name = "...", /*opt*/ kind = "dylib|static|...", /*opt*/ cfg = "...""#), - ), - ungated!(link_name, Whitelisted, template!(NameValueStr: "name")), - ungated!(no_link, Normal, template!(Word)), - ungated!(repr, Normal, template!(List: "C, packed, ...")), - ungated!(export_name, Whitelisted, template!(NameValueStr: "name")), - ungated!(link_section, Whitelisted, template!(NameValueStr: "name")), - ungated!(no_mangle, Whitelisted, template!(Word)), - ungated!(used, Whitelisted, template!(Word)), - - // Limits: - ungated!(recursion_limit, CrateLevel, template!(NameValueStr: "N")), - ungated!(type_length_limit, CrateLevel, template!(NameValueStr: "N")), - - // Entry point: - ungated!(main, Normal, template!(Word)), - ungated!(start, Normal, template!(Word)), - ungated!(no_start, CrateLevel, template!(Word)), - ungated!(no_main, CrateLevel, template!(Word)), - - // Modules, prelude, and resolution: - ungated!(path, Normal, template!(NameValueStr: "file")), - ungated!(no_std, CrateLevel, template!(Word)), - ungated!(no_implicit_prelude, Normal, template!(Word)), - ungated!(non_exhaustive, Whitelisted, template!(Word)), - - // Runtime - ungated!(windows_subsystem, Whitelisted, template!(NameValueStr: "windows|console")), - ungated!(panic_handler, Normal, template!(Word)), // RFC 2070 - - // Code generation: - ungated!(inline, Whitelisted, template!(Word, List: "always|never")), - ungated!(cold, Whitelisted, template!(Word)), - ungated!(no_builtins, Whitelisted, template!(Word)), - ungated!(target_feature, Whitelisted, template!(List: r#"enable = "name""#)), - - // FIXME: #14408 whitelist docs since rustdoc looks at them - ungated!(doc, Whitelisted, template!(List: "hidden|inline|...", NameValueStr: "string")), - - // ========================================================================== - // Unstable attributes: - // ========================================================================== - - // Linking: - gated!(naked, Whitelisted, template!(Word), naked_functions, experimental!(naked)), - gated!( - link_args, Normal, template!(NameValueStr: "args"), - "the `link_args` attribute is experimental and not portable across platforms, \ - it is recommended to use `#[link(name = \"foo\")] instead", - ), - gated!( - link_ordinal, Whitelisted, template!(List: "ordinal"), raw_dylib, - experimental!(link_ordinal) - ), - - // Plugins: - ( - sym::plugin_registrar, Normal, template!(Word), - Gated( - Stability::Deprecated( - "https://github.com/rust-lang/rust/pull/64675", - Some("may be removed in a future compiler version"), - ), - sym::plugin_registrar, - "compiler plugins are deprecated", - cfg_fn!(plugin_registrar) - ) - ), - ( - sym::plugin, CrateLevel, template!(List: "name|name(args)"), - Gated( - Stability::Deprecated( - "https://github.com/rust-lang/rust/pull/64675", - Some("may be removed in a future compiler version"), - ), - sym::plugin, - "compiler plugins are deprecated", - cfg_fn!(plugin) - ) - ), - - // Testing: - gated!(allow_fail, Normal, template!(Word), experimental!(allow_fail)), - gated!( - test_runner, CrateLevel, template!(List: "path"), custom_test_frameworks, - "custom test frameworks are an unstable feature", - ), - // RFC #1268 - gated!(marker, Normal, template!(Word), marker_trait_attr, experimental!(marker)), - gated!( - thread_local, Whitelisted, template!(Word), - "`#[thread_local]` is an experimental feature, and does not currently handle destructors", - ), - gated!(no_core, CrateLevel, template!(Word), experimental!(no_core)), - // RFC 2412 - gated!( - optimize, Whitelisted, template!(List: "size|speed"), optimize_attribute, - experimental!(optimize), - ), - - gated!(ffi_returns_twice, Whitelisted, template!(Word), experimental!(ffi_returns_twice)), - gated!(track_caller, Whitelisted, template!(Word), experimental!(track_caller)), - - // ========================================================================== - // Internal attributes: Stability, deprecation, and unsafe: - // ========================================================================== - - ungated!(feature, CrateLevel, template!(List: "name1, name1, ...")), - // FIXME(#14407) -- only looked at on-demand so we can't - // guarantee they'll have already been checked. - ungated!( - rustc_deprecated, Whitelisted, - template!(List: r#"since = "version", reason = "...""#) - ), - // FIXME(#14407) - ungated!(stable, Whitelisted, template!(List: r#"feature = "name", since = "version""#)), - // FIXME(#14407) - ungated!( - unstable, Whitelisted, - template!(List: r#"feature = "name", reason = "...", issue = "N""#), - ), - gated!( - rustc_const_unstable, Normal, template!(List: r#"feature = "name""#), - "the `#[rustc_const_unstable]` attribute is an internal feature", - ), - gated!( - allow_internal_unstable, Normal, template!(Word, List: "feat1, feat2, ..."), - EXPLAIN_ALLOW_INTERNAL_UNSTABLE, - ), - gated!(allow_internal_unsafe, Normal, template!(Word), EXPLAIN_ALLOW_INTERNAL_UNSAFE), - - // ========================================================================== - // Internal attributes: Type system related: - // ========================================================================== - - gated!(fundamental, Whitelisted, template!(Word), experimental!(fundamental)), - gated!( - // RFC #1445. - structural_match, Whitelisted, template!(Word), - "the semantics of constant patterns is not yet settled", - ), - gated!( - may_dangle, Normal, template!(Word), dropck_eyepatch, - "`may_dangle` has unstable semantics and may be removed in the future", - ), - - // ========================================================================== - // Internal attributes: Runtime related: - // ========================================================================== - - rustc_attr!(rustc_allocator, Whitelisted, template!(Word), IMPL_DETAIL), - rustc_attr!(rustc_allocator_nounwind, Whitelisted, template!(Word), IMPL_DETAIL), - gated!(alloc_error_handler, Normal, template!(Word), experimental!(alloc_error_handler)), - gated!( - default_lib_allocator, Whitelisted, template!(Word), allocator_internals, - experimental!(default_lib_allocator), - ), - gated!( - needs_allocator, Normal, template!(Word), allocator_internals, - experimental!(needs_allocator), - ), - gated!(panic_runtime, Whitelisted, template!(Word), experimental!(panic_runtime)), - gated!(needs_panic_runtime, Whitelisted, template!(Word), experimental!(needs_panic_runtime)), - gated!( - unwind, Whitelisted, template!(List: "allowed|aborts"), unwind_attributes, - experimental!(unwind), - ), - gated!( - compiler_builtins, Whitelisted, template!(Word), - "the `#[compiler_builtins]` attribute is used to identify the `compiler_builtins` crate \ - which contains compiler-rt intrinsics and will never be stable", - ), - gated!( - sanitizer_runtime, Whitelisted, template!(Word), - "the `#[sanitizer_runtime]` attribute is used to identify crates that contain the runtime \ - of a sanitizer and will never be stable", - ), - gated!( - profiler_runtime, Whitelisted, template!(Word), - "the `#[profiler_runtime]` attribute is used to identify the `profiler_builtins` crate \ - which contains the profiler runtime and will never be stable", - ), - - // ========================================================================== - // Internal attributes, Linkage: - // ========================================================================== - - gated!( - linkage, Whitelisted, template!(NameValueStr: "external|internal|..."), - "the `linkage` attribute is experimental and not portable across platforms", - ), - rustc_attr!(rustc_std_internal_symbol, Whitelisted, template!(Word), INTERNAL_UNSTABLE), - - // ========================================================================== - // Internal attributes, Macro related: - // ========================================================================== - - rustc_attr!(rustc_builtin_macro, Whitelisted, template!(Word), IMPL_DETAIL), - rustc_attr!(rustc_proc_macro_decls, Normal, template!(Word), INTERNAL_UNSTABLE), - rustc_attr!( - rustc_macro_transparency, Whitelisted, - template!(NameValueStr: "transparent|semitransparent|opaque"), - "used internally for testing macro hygiene", - ), - - // ========================================================================== - // Internal attributes, Diagnostics related: - // ========================================================================== - - rustc_attr!( - rustc_on_unimplemented, Whitelisted, - template!( - List: r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#, - NameValueStr: "message" - ), - INTERNAL_UNSTABLE - ), - // Whitelists "identity-like" conversion methods to suggest on type mismatch. - rustc_attr!(rustc_conversion_suggestion, Whitelisted, template!(Word), INTERNAL_UNSTABLE), - - // ========================================================================== - // Internal attributes, Const related: - // ========================================================================== - - rustc_attr!(rustc_promotable, Whitelisted, template!(Word), IMPL_DETAIL), - rustc_attr!(rustc_allow_const_fn_ptr, Whitelisted, template!(Word), IMPL_DETAIL), - rustc_attr!(rustc_args_required_const, Whitelisted, template!(List: "N"), INTERNAL_UNSTABLE), - - // ========================================================================== - // Internal attributes, Layout related: - // ========================================================================== - - rustc_attr!( - rustc_layout_scalar_valid_range_start, Whitelisted, template!(List: "value"), - "the `#[rustc_layout_scalar_valid_range_start]` attribute is just used to enable \ - niche optimizations in libcore and will never be stable", - ), - rustc_attr!( - rustc_layout_scalar_valid_range_end, Whitelisted, template!(List: "value"), - "the `#[rustc_layout_scalar_valid_range_end]` attribute is just used to enable \ - niche optimizations in libcore and will never be stable", - ), - rustc_attr!( - rustc_nonnull_optimization_guaranteed, Whitelisted, template!(Word), - "the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to enable \ - niche optimizations in libcore and will never be stable", - ), - - // ========================================================================== - // Internal attributes, Misc: - // ========================================================================== - gated!( - lang, Normal, template!(NameValueStr: "name"), lang_items, - "language items are subject to change", - ), - ( - sym::rustc_diagnostic_item, - Normal, - template!(NameValueStr: "name"), - Gated( - Stability::Unstable, - sym::rustc_attrs, - "diagnostic items compiler internal support for linting", - cfg_fn!(rustc_attrs), - ), - ), - ( - sym::no_debug, Whitelisted, template!(Word), - Gated( - Stability::Deprecated("https://github.com/rust-lang/rust/issues/29721", None), - sym::no_debug, - "the `#[no_debug]` attribute was an experimental feature that has been \ - deprecated due to lack of demand", - cfg_fn!(no_debug) - ) - ), - gated!( - // Used in resolve: - prelude_import, Whitelisted, template!(Word), - "`#[prelude_import]` is for use by rustc only", - ), - gated!( - rustc_paren_sugar, Normal, template!(Word), unboxed_closures, - "unboxed_closures are still evolving", - ), - rustc_attr!( - rustc_inherit_overflow_checks, Whitelisted, template!(Word), - "the `#[rustc_inherit_overflow_checks]` attribute is just used to control \ - overflow checking behavior of several libcore functions that are inlined \ - across crates and will never be stable", - ), - rustc_attr!(rustc_reservation_impl, Normal, template!(NameValueStr: "reservation message"), - "the `#[rustc_reservation_impl]` attribute is internally used \ - for reserving for `for<T> From<!> for T` impl" - ), - rustc_attr!( - rustc_test_marker, Normal, template!(Word), - "the `#[rustc_test_marker]` attribute is used internally to track tests", - ), - - // ========================================================================== - // Internal attributes, Testing: - // ========================================================================== - - rustc_attr!(TEST, rustc_outlives, Normal, template!(Word)), - rustc_attr!(TEST, rustc_variance, Normal, template!(Word)), - rustc_attr!(TEST, rustc_layout, Normal, template!(List: "field1, field2, ...")), - rustc_attr!(TEST, rustc_regions, Normal, template!(Word)), - rustc_attr!(TEST, rustc_error, Whitelisted, template!(Word)), - rustc_attr!(TEST, rustc_dump_user_substs, Whitelisted, template!(Word)), - rustc_attr!(TEST, rustc_if_this_changed, Whitelisted, template!(Word, List: "DepNode")), - rustc_attr!(TEST, rustc_then_this_would_need, Whitelisted, template!(List: "DepNode")), - rustc_attr!( - TEST, rustc_dirty, Whitelisted, - template!(List: r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#), - ), - rustc_attr!( - TEST, rustc_clean, Whitelisted, - template!(List: r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#), - ), - rustc_attr!( - TEST, rustc_partition_reused, Whitelisted, - template!(List: r#"cfg = "...", module = "...""#), - ), - rustc_attr!( - TEST, rustc_partition_codegened, Whitelisted, - template!(List: r#"cfg = "...", module = "...""#), - ), - rustc_attr!( - TEST, rustc_expected_cgu_reuse, Whitelisted, - template!(List: r#"cfg = "...", module = "...", kind = "...""#), - ), - rustc_attr!(TEST, rustc_synthetic, Whitelisted, template!(Word)), - rustc_attr!(TEST, rustc_symbol_name, Whitelisted, template!(Word)), - rustc_attr!(TEST, rustc_def_path, Whitelisted, template!(Word)), - rustc_attr!(TEST, rustc_mir, Whitelisted, template!(List: "arg1, arg2, ...")), - rustc_attr!(TEST, rustc_dump_program_clauses, Whitelisted, template!(Word)), - rustc_attr!(TEST, rustc_dump_env_program_clauses, Whitelisted, template!(Word)), - rustc_attr!(TEST, rustc_object_lifetime_default, Whitelisted, template!(Word)), - rustc_attr!(TEST, rustc_dummy, Normal, template!(Word /* doesn't matter*/)), - gated!( - omit_gdb_pretty_printer_section, Whitelisted, template!(Word), - "the `#[omit_gdb_pretty_printer_section]` attribute is just used for the Rust test suite", - ), -]; - -pub fn deprecated_attributes() -> Vec<&'static BuiltinAttribute> { - BUILTIN_ATTRIBUTES.iter().filter(|(.., gate)| gate.is_deprecated()).collect() -} - -pub fn is_builtin_attr_name(name: ast::Name) -> bool { - BUILTIN_ATTRIBUTE_MAP.get(&name).is_some() -} - -pub fn is_builtin_attr(attr: &ast::Attribute) -> bool { - attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).is_some() -} - -lazy_static! { - pub static ref BUILTIN_ATTRIBUTE_MAP: FxHashMap<Symbol, &'static BuiltinAttribute> = { - let mut map = FxHashMap::default(); - for attr in BUILTIN_ATTRIBUTES.iter() { - if map.insert(attr.0, attr).is_some() { - panic!("duplicate builtin attribute `{}`", attr.0); - } - } - map - }; -} diff --git a/src/libsyntax/feature_gate/check.rs b/src/libsyntax/feature_gate/check.rs index ecff89ad59b..3d2c3b1d4f9 100644 --- a/src/libsyntax/feature_gate/check.rs +++ b/src/libsyntax/feature_gate/check.rs @@ -1,35 +1,23 @@ -use super::{active::{ACTIVE_FEATURES, Features}, Feature, State as FeatureState}; -use super::accepted::ACCEPTED_FEATURES; -use super::removed::{REMOVED_FEATURES, STABLE_REMOVED_FEATURES}; -use super::builtin_attrs::{AttributeGate, BUILTIN_ATTRIBUTE_MAP}; - -use crate::ast::{ - self, AssocTyConstraint, AssocTyConstraintKind, NodeId, GenericParam, GenericParamKind, - PatKind, RangeEnd, VariantData, -}; -use crate::attr::{self, check_builtin_attribute}; +use rustc_feature::{ACCEPTED_FEATURES, ACTIVE_FEATURES, REMOVED_FEATURES, STABLE_REMOVED_FEATURES}; +use rustc_feature::{AttributeGate, BUILTIN_ATTRIBUTE_MAP}; +use rustc_feature::{Features, Feature, State as FeatureState, UnstableFeatures}; +use rustc_feature::{find_feature_issue, GateIssue}; + +use crate::ast::{self, AssocTyConstraint, AssocTyConstraintKind, NodeId}; +use crate::ast::{GenericParam, GenericParamKind, PatKind, RangeEnd, VariantData}; +use crate::attr; use crate::source_map::Spanned; use crate::edition::{ALL_EDITIONS, Edition}; use crate::visit::{self, FnKind, Visitor}; -use crate::token; use crate::sess::ParseSess; use crate::symbol::{Symbol, sym}; -use crate::tokenstream::TokenTree; use errors::{Applicability, DiagnosticBuilder, Handler}; use rustc_data_structures::fx::FxHashMap; use syntax_pos::{Span, DUMMY_SP, MultiSpan}; use log::debug; -use std::env; - -#[derive(Copy, Clone, Debug)] -pub enum Stability { - Unstable, - // First argument is tracking issue link; second argument is an optional - // help message, which defaults to "remove this attribute" - Deprecated(&'static str, Option<&'static str>), -} +use rustc_error_codes::*; macro_rules! gate_feature_fn { ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{ @@ -59,27 +47,6 @@ pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: PostExpansionVisitor { parse_sess, features }.visit_attribute(attr) } -fn find_lang_feature_issue(feature: Symbol) -> Option<u32> { - if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.name == feature) { - // FIXME (#28244): enforce that active features have issue numbers - // assert!(info.issue.is_some()) - info.issue - } else { - // search in Accepted, Removed, or Stable Removed features - let found = ACCEPTED_FEATURES.iter().chain(REMOVED_FEATURES).chain(STABLE_REMOVED_FEATURES) - .find(|t| t.name == feature); - match found { - Some(&Feature { issue, .. }) => issue, - None => panic!("Feature `{}` is not declared anywhere", feature), - } - } -} - -pub enum GateIssue { - Language, - Library(Option<u32>) -} - #[derive(Debug, Copy, Clone, PartialEq)] pub enum GateStrength { /// A hard error. (Most feature gates should use this.) @@ -88,41 +55,35 @@ pub enum GateStrength { Soft, } -pub fn emit_feature_err( - sess: &ParseSess, +pub fn feature_err<'a>( + sess: &'a ParseSess, feature: Symbol, - span: Span, - issue: GateIssue, + span: impl Into<MultiSpan>, explain: &str, -) { - feature_err(sess, feature, span, issue, explain).emit(); +) -> DiagnosticBuilder<'a> { + feature_err_issue(sess, feature, span, GateIssue::Language, explain) } -pub fn feature_err<'a, S: Into<MultiSpan>>( +pub fn feature_err_issue<'a>( sess: &'a ParseSess, feature: Symbol, - span: S, + span: impl Into<MultiSpan>, issue: GateIssue, explain: &str, ) -> DiagnosticBuilder<'a> { leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard) } -fn leveled_feature_err<'a, S: Into<MultiSpan>>( +fn leveled_feature_err<'a>( sess: &'a ParseSess, feature: Symbol, - span: S, + span: impl Into<MultiSpan>, issue: GateIssue, explain: &str, level: GateStrength, ) -> DiagnosticBuilder<'a> { let diag = &sess.span_diagnostic; - let issue = match issue { - GateIssue::Language => find_lang_feature_issue(feature), - GateIssue::Library(lib) => lib, - }; - let mut err = match level { GateStrength::Hard => { diag.struct_span_err_with_code(span, explain, stringify_error_code!(E0658)) @@ -130,14 +91,11 @@ fn leveled_feature_err<'a, S: Into<MultiSpan>>( GateStrength::Soft => diag.struct_span_warn(span, explain), }; - match issue { - None | Some(0) => {} // We still accept `0` as a stand-in for backwards compatibility - Some(n) => { - err.note(&format!( - "for more information, see https://github.com/rust-lang/rust/issues/{}", - n, - )); - } + if let Some(n) = find_feature_issue(feature, issue) { + err.note(&format!( + "for more information, see https://github.com/rust-lang/rust/issues/{}", + n, + )); } // #23973: do not suggest `#![feature(...)]` if we are in beta/stable @@ -156,20 +114,6 @@ fn leveled_feature_err<'a, S: Into<MultiSpan>>( } -const EXPLAIN_BOX_SYNTAX: &str = - "box expression syntax is experimental; you can call `Box::new` instead"; - -pub const EXPLAIN_STMT_ATTR_SYNTAX: &str = - "attributes on expressions are experimental"; - -pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &str = - "allow_internal_unstable side-steps feature gating and stability checks"; -pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &str = - "allow_internal_unsafe side-steps the unsafe_code lint"; - -pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &str = - "unsized tuple coercion is not stable enough for use and is subject to change"; - struct PostExpansionVisitor<'a> { parse_sess: &'a ParseSess, features: &'a Features, @@ -191,10 +135,10 @@ macro_rules! gate_feature_post { } impl<'a> PostExpansionVisitor<'a> { - fn check_abi(&self, abi: ast::Abi) { - let ast::Abi { symbol, span } = abi; + fn check_abi(&self, abi: ast::StrLit) { + let ast::StrLit { symbol_unescaped, span, .. } = abi; - match &*symbol.as_str() { + match &*symbol_unescaped.as_str() { // Stable "Rust" | "C" | @@ -258,6 +202,12 @@ impl<'a> PostExpansionVisitor<'a> { } } + fn check_extern(&self, ext: ast::Extern) { + if let ast::Extern::Explicit(abi) = ext { + self.check_abi(abi); + } + } + fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) { let has_fields = variants.iter().any(|variant| match variant.data { VariantData::Tuple(..) | VariantData::Struct(..) => true, @@ -276,7 +226,6 @@ impl<'a> PostExpansionVisitor<'a> { self.parse_sess, sym::arbitrary_enum_discriminant, discriminant_spans.clone(), - crate::feature_gate::GateIssue::Language, "custom discriminant values are not allowed in enums with tuple or struct variants", ); for sp in discriminant_spans { @@ -321,6 +270,27 @@ impl<'a> PostExpansionVisitor<'a> { ); } } + + /// Feature gate `impl Trait` inside `type Alias = $type_expr;`. + fn check_impl_trait(&self, ty: &ast::Ty) { + struct ImplTraitVisitor<'a> { + vis: &'a PostExpansionVisitor<'a>, + } + impl Visitor<'_> for ImplTraitVisitor<'_> { + fn visit_ty(&mut self, ty: &ast::Ty) { + if let ast::TyKind::ImplTrait(..) = ty.kind { + gate_feature_post!( + &self.vis, + type_alias_impl_trait, + ty.span, + "`impl Trait` in type aliases is unstable" + ); + } + visit::walk_ty(self, ty); + } + } + ImplTraitVisitor { vis: self }.visit_ty(ty); + } } impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { @@ -331,19 +301,6 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { if let Some((.., AttributeGate::Gated(_, name, descr, has_feature))) = attr_info { gate_feature_fn!(self, has_feature, attr.span, name, descr, GateStrength::Hard); } - // Check input tokens for built-in and key-value attributes. - match attr_info { - // `rustc_dummy` doesn't have any restrictions specific to built-in attributes. - Some((name, _, template, _)) if name != sym::rustc_dummy => - check_builtin_attribute(self.parse_sess, attr, name, template), - _ => if let Some(TokenTree::Token(token)) = - attr.get_normal_item().tokens.trees().next() { - if token == token::Eq { - // All key-value attributes are restricted to meta-item syntax. - attr.parse_meta(self.parse_sess).map_err(|mut err| err.emit()).ok(); - } - } - } // Check unstable flavors of the `#[doc]` attribute. if attr.check_name(sym::doc) { for nested_meta in attr.meta_item_list().unwrap_or_default() { @@ -380,7 +337,9 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { fn visit_item(&mut self, i: &'a ast::Item) { match i.kind { ast::ItemKind::ForeignMod(ref foreign_module) => { - self.check_abi(foreign_module.abi); + if let Some(abi) = foreign_module.abi { + self.check_abi(abi); + } } ast::ItemKind::Fn(..) => { @@ -468,14 +427,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { gate_feature_post!(&self, decl_macro, i.span, msg); } - ast::ItemKind::OpaqueTy(..) => { - gate_feature_post!( - &self, - type_alias_impl_trait, - i.span, - "`impl Trait` in type aliases is unstable" - ); - } + ast::ItemKind::TyAlias(ref ty, ..) => self.check_impl_trait(&ty), _ => {} } @@ -510,31 +462,20 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { fn visit_ty(&mut self, ty: &'a ast::Ty) { match ty.kind { ast::TyKind::BareFn(ref bare_fn_ty) => { - self.check_abi(bare_fn_ty.abi); - } - ast::TyKind::Never => { - gate_feature_post!(&self, never_type, ty.span, - "The `!` type is experimental"); + self.check_extern(bare_fn_ty.ext); } _ => {} } visit::walk_ty(self, ty) } - fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) { - if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty { - if let ast::TyKind::Never = output_ty.kind { - // Do nothing. - } else { - self.visit_ty(output_ty) - } - } - } - fn visit_expr(&mut self, e: &'a ast::Expr) { match e.kind { ast::ExprKind::Box(_) => { - gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX); + gate_feature_post!( + &self, box_syntax, e.span, + "box expression syntax is experimental; you can call `Box::new` instead" + ); } ast::ExprKind::Type(..) => { // To avoid noise about type ascription in common syntax errors, only emit if it @@ -558,10 +499,6 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { visit::walk_expr(self, e) } - fn visit_arm(&mut self, arm: &'a ast::Arm) { - visit::walk_arm(self, arm) - } - fn visit_pat(&mut self, pattern: &'a ast::Pat) { match &pattern.kind { PatKind::Slice(pats) => { @@ -604,7 +541,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { // Stability of const fn methods are covered in // `visit_trait_item` and `visit_impl_item` below; this is // because default methods don't pass through this point. - self.check_abi(header.abi); + self.check_extern(header.ext); } if fn_decl.c_variadic() { @@ -638,7 +575,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { match ti.kind { ast::TraitItemKind::Method(ref sig, ref block) => { if block.is_none() { - self.check_abi(sig.header.abi); + self.check_extern(sig.header.ext); } if sig.decl.c_variadic() { gate_feature_post!(&self, c_variadic, ti.span, @@ -649,9 +586,8 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { } } ast::TraitItemKind::Type(_, ref default) => { - // We use three if statements instead of something like match guards so that all - // of these errors can be emitted if all cases apply. - if default.is_some() { + if let Some(ty) = default { + self.check_impl_trait(ty); gate_feature_post!(&self, associated_type_defaults, ti.span, "associated type defaults are unstable"); } @@ -676,15 +612,8 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { "C-variadic functions are unstable"); } } - ast::ImplItemKind::OpaqueTy(..) => { - gate_feature_post!( - &self, - type_alias_impl_trait, - ii.span, - "`impl Trait` in type aliases is unstable" - ); - } - ast::ImplItemKind::TyAlias(_) => { + ast::ImplItemKind::TyAlias(ref ty) => { + self.check_impl_trait(ty); self.check_gat(&ii.generics, ii.span); } _ => {} @@ -705,15 +634,14 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute], crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features { fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) { let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed"); + err.span_label(span, "feature has been removed"); if let Some(reason) = reason { - err.span_note(span, reason); - } else { - err.span_label(span, "feature has been removed"); + err.note(reason); } err.emit(); } - let mut features = Features::new(); + let mut features = Features::default(); let mut edition_enabled_features = FxHashMap::default(); for &edition in ALL_EDITIONS { @@ -883,6 +811,7 @@ pub fn check_crate(krate: &ast::Crate, gate_all!(generators, "yield syntax is experimental"); gate_all!(or_patterns, "or-patterns syntax is experimental"); gate_all!(const_extern_fn, "`const extern fn` definitions are unstable"); + gate_all!(raw_ref_op, "raw address of syntax is experimental"); // All uses of `gate_all!` below this point were added in #65742, // and subsequently disabled (with the non-early gating readded). @@ -917,40 +846,6 @@ pub fn check_crate(krate: &ast::Crate, visit::walk_crate(&mut visitor, krate); } -#[derive(Clone, Copy, Hash)] -pub enum UnstableFeatures { - /// Hard errors for unstable features are active, as on beta/stable channels. - Disallow, - /// Allow features to be activated, as on nightly. - Allow, - /// Errors are bypassed for bootstrapping. This is required any time - /// during the build that feature-related lints are set to warn or above - /// because the build turns on warnings-as-errors and uses lots of unstable - /// features. As a result, this is always required for building Rust itself. - Cheat -} - -impl UnstableFeatures { - pub fn from_environment() -> UnstableFeatures { - // `true` if this is a feature-staged build, i.e., on the beta or stable channel. - let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some(); - // `true` if we should enable unstable features for bootstrapping. - let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok(); - match (disable_unstable_features, bootstrap) { - (_, true) => UnstableFeatures::Cheat, - (true, _) => UnstableFeatures::Disallow, - (false, _) => UnstableFeatures::Allow - } - } - - pub fn is_nightly_build(&self) -> bool { - match *self { - UnstableFeatures::Allow | UnstableFeatures::Cheat => true, - UnstableFeatures::Disallow => false, - } - } -} - fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate, unstable: UnstableFeatures) { if !unstable.is_nightly_build() { for attr in krate.attrs.iter().filter(|attr| attr.check_name(sym::feature)) { diff --git a/src/libsyntax/feature_gate/mod.rs b/src/libsyntax/feature_gate/mod.rs deleted file mode 100644 index ba970618c0e..00000000000 --- a/src/libsyntax/feature_gate/mod.rs +++ /dev/null @@ -1,64 +0,0 @@ -//! # Feature gating -//! -//! This module implements the gating necessary for preventing certain compiler -//! features from being used by default. This module will crawl a pre-expanded -//! AST to ensure that there are no features which are used that are not -//! enabled. -//! -//! Features are enabled in programs via the crate-level attributes of -//! `#![feature(...)]` with a comma-separated list of features. -//! -//! For the purpose of future feature-tracking, once code for detection of feature -//! gate usage is added, *do not remove it again* even once the feature -//! becomes stable. - -mod accepted; -mod removed; -mod active; -mod builtin_attrs; -mod check; - -use std::fmt; -use crate::{edition::Edition, symbol::Symbol}; -use syntax_pos::Span; - -#[derive(Clone, Copy)] -pub enum State { - Accepted, - Active { set: fn(&mut Features, Span) }, - Removed { reason: Option<&'static str> }, - Stabilized { reason: Option<&'static str> }, -} - -impl fmt::Debug for State { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - State::Accepted { .. } => write!(f, "accepted"), - State::Active { .. } => write!(f, "active"), - State::Removed { .. } => write!(f, "removed"), - State::Stabilized { .. } => write!(f, "stabilized"), - } - } -} - -#[derive(Debug, Clone)] -pub struct Feature { - state: State, - name: Symbol, - since: &'static str, - issue: Option<u32>, - edition: Option<Edition>, - description: &'static str, -} - -pub use active::{Features, INCOMPLETE_FEATURES}; -pub use builtin_attrs::{ - AttributeGate, AttributeType, GatedCfg, - BuiltinAttribute, BUILTIN_ATTRIBUTES, BUILTIN_ATTRIBUTE_MAP, - deprecated_attributes, is_builtin_attr, is_builtin_attr_name, -}; -pub use check::{ - check_crate, check_attribute, get_features, feature_err, emit_feature_err, - Stability, GateIssue, UnstableFeatures, - EXPLAIN_STMT_ATTR_SYNTAX, EXPLAIN_UNSIZED_TUPLE_COERCION, -}; diff --git a/src/libsyntax/feature_gate/removed.rs b/src/libsyntax/feature_gate/removed.rs deleted file mode 100644 index c7b931a6f70..00000000000 --- a/src/libsyntax/feature_gate/removed.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! List of the removed feature gates. - -use crate::symbol::sym; -use super::{State, Feature}; - -macro_rules! declare_features { - ($( - $(#[doc = $doc:tt])* (removed, $feature:ident, $ver:expr, $issue:expr, None, $reason:expr), - )+) => { - /// Represents unstable features which have since been removed (it was once Active) - pub const REMOVED_FEATURES: &[Feature] = &[ - $( - Feature { - state: State::Removed { reason: $reason }, - name: sym::$feature, - since: $ver, - issue: $issue, - edition: None, - description: concat!($($doc,)*), - } - ),+ - ]; - }; - - ($( - $(#[doc = $doc:tt])* (stable_removed, $feature:ident, $ver:expr, $issue:expr, None), - )+) => { - /// Represents stable features which have since been removed (it was once Accepted) - pub const STABLE_REMOVED_FEATURES: &[Feature] = &[ - $( - Feature { - state: State::Stabilized { reason: None }, - name: sym::$feature, - since: $ver, - issue: $issue, - edition: None, - description: concat!($($doc,)*), - } - ),+ - ]; - }; -} - -declare_features! ( - // ------------------------------------------------------------------------- - // feature-group-start: removed features - // ------------------------------------------------------------------------- - - (removed, import_shadowing, "1.0.0", None, None, None), - (removed, managed_boxes, "1.0.0", None, None, None), - /// Allows use of unary negate on unsigned integers, e.g., -e for e: u8 - (removed, negate_unsigned, "1.0.0", Some(29645), None, None), - (removed, reflect, "1.0.0", Some(27749), None, None), - /// A way to temporarily opt out of opt in copy. This will *never* be accepted. - (removed, opt_out_copy, "1.0.0", None, None, None), - (removed, quad_precision_float, "1.0.0", None, None, None), - (removed, struct_inherit, "1.0.0", None, None, None), - (removed, test_removed_feature, "1.0.0", None, None, None), - (removed, visible_private_types, "1.0.0", None, None, None), - (removed, unsafe_no_drop_flag, "1.0.0", None, None, None), - /// Allows using items which are missing stability attributes - (removed, unmarked_api, "1.0.0", None, None, None), - (removed, allocator, "1.0.0", None, None, None), - (removed, simd, "1.0.0", Some(27731), None, - Some("removed in favor of `#[repr(simd)]`")), - (removed, advanced_slice_patterns, "1.0.0", Some(62254), None, - Some("merged into `#![feature(slice_patterns)]`")), - (removed, macro_reexport, "1.0.0", Some(29638), None, - Some("subsumed by `pub use`")), - (removed, pushpop_unsafe, "1.2.0", None, None, None), - (removed, needs_allocator, "1.4.0", Some(27389), None, - Some("subsumed by `#![feature(allocator_internals)]`")), - (removed, proc_macro_mod, "1.27.0", Some(54727), None, - Some("subsumed by `#![feature(proc_macro_hygiene)]`")), - (removed, proc_macro_expr, "1.27.0", Some(54727), None, - Some("subsumed by `#![feature(proc_macro_hygiene)]`")), - (removed, proc_macro_non_items, "1.27.0", Some(54727), None, - Some("subsumed by `#![feature(proc_macro_hygiene)]`")), - (removed, proc_macro_gen, "1.27.0", Some(54727), None, - Some("subsumed by `#![feature(proc_macro_hygiene)]`")), - (removed, panic_implementation, "1.28.0", Some(44489), None, - Some("subsumed by `#[panic_handler]`")), - /// Allows the use of `#[derive(Anything)]` as sugar for `#[derive_Anything]`. - (removed, custom_derive, "1.32.0", Some(29644), None, - Some("subsumed by `#[proc_macro_derive]`")), - /// Paths of the form: `extern::foo::bar` - (removed, extern_in_paths, "1.33.0", Some(55600), None, - Some("subsumed by `::foo::bar` paths")), - (removed, quote, "1.33.0", Some(29601), None, None), - /// Allows using `#[unsafe_destructor_blind_to_params]` (RFC 1238). - (removed, dropck_parametricity, "1.38.0", Some(28498), None, None), - (removed, await_macro, "1.38.0", Some(50547), None, - Some("subsumed by `.await` syntax")), - /// Allows defining `existential type`s. - (removed, existential_type, "1.38.0", Some(63063), None, - Some("removed in favor of `#![feature(type_alias_impl_trait)]`")), - /// Allows using the macros: - /// + `__diagnostic_used` - /// + `__register_diagnostic` - /// +`__build_diagnostic_array` - (removed, rustc_diagnostic_macros, "1.38.0", None, None, None), - /// Allows using `#[on_unimplemented(..)]` on traits. - /// (Moved to `rustc_attrs`.) - (removed, on_unimplemented, "1.40.0", None, None, None), - - // ------------------------------------------------------------------------- - // feature-group-end: removed features - // ------------------------------------------------------------------------- -); - -declare_features! ( - (stable_removed, no_stack_check, "1.0.0", None, None), -); diff --git a/src/libsyntax/json.rs b/src/libsyntax/json.rs deleted file mode 100644 index 0b157938375..00000000000 --- a/src/libsyntax/json.rs +++ /dev/null @@ -1,434 +0,0 @@ -//! A JSON emitter for errors. -//! -//! This works by converting errors to a simplified structural format (see the -//! structs at the start of the file) and then serializing them. These should -//! contain as much information about the error as possible. -//! -//! The format of the JSON output should be considered *unstable*. For now the -//! structs at the end of this file (Diagnostic*) specify the error format. - -// FIXME: spec the JSON output properly. - -use crate::source_map::{SourceMap, FilePathMapping}; - -use errors::registry::Registry; -use errors::{SubDiagnostic, CodeSuggestion, SourceMapper, SourceMapperDyn}; -use errors::{DiagnosticId, Applicability}; -use errors::emitter::{Emitter, HumanReadableErrorType}; - -use syntax_pos::{MacroBacktrace, Span, SpanLabel, MultiSpan}; -use rustc_data_structures::sync::{self, Lrc}; -use std::io::{self, Write}; -use std::path::Path; -use std::vec; -use std::sync::{Arc, Mutex}; - -use rustc_serialize::json::{as_json, as_pretty_json}; - -#[cfg(test)] -mod tests; - -pub struct JsonEmitter { - dst: Box<dyn Write + Send>, - registry: Option<Registry>, - sm: Lrc<dyn SourceMapper + sync::Send + sync::Sync>, - pretty: bool, - ui_testing: bool, - json_rendered: HumanReadableErrorType, - external_macro_backtrace: bool, -} - -impl JsonEmitter { - pub fn stderr( - registry: Option<Registry>, - source_map: Lrc<SourceMap>, - pretty: bool, - json_rendered: HumanReadableErrorType, - external_macro_backtrace: bool, - ) -> JsonEmitter { - JsonEmitter { - dst: Box::new(io::stderr()), - registry, - sm: source_map, - pretty, - ui_testing: false, - json_rendered, - external_macro_backtrace, - } - } - - pub fn basic( - pretty: bool, - json_rendered: HumanReadableErrorType, - external_macro_backtrace: bool, - ) -> JsonEmitter { - let file_path_mapping = FilePathMapping::empty(); - JsonEmitter::stderr(None, Lrc::new(SourceMap::new(file_path_mapping)), - pretty, json_rendered, external_macro_backtrace) - } - - pub fn new( - dst: Box<dyn Write + Send>, - registry: Option<Registry>, - source_map: Lrc<SourceMap>, - pretty: bool, - json_rendered: HumanReadableErrorType, - external_macro_backtrace: bool, - ) -> JsonEmitter { - JsonEmitter { - dst, - registry, - sm: source_map, - pretty, - ui_testing: false, - json_rendered, - external_macro_backtrace, - } - } - - pub fn ui_testing(self, ui_testing: bool) -> Self { - Self { ui_testing, ..self } - } -} - -impl Emitter for JsonEmitter { - fn emit_diagnostic(&mut self, diag: &errors::Diagnostic) { - let data = Diagnostic::from_errors_diagnostic(diag, self); - let result = if self.pretty { - writeln!(&mut self.dst, "{}", as_pretty_json(&data)) - } else { - writeln!(&mut self.dst, "{}", as_json(&data)) - }; - if let Err(e) = result { - panic!("failed to print diagnostics: {:?}", e); - } - } - - fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) { - let data = ArtifactNotification { artifact: path, emit: artifact_type }; - let result = if self.pretty { - writeln!(&mut self.dst, "{}", as_pretty_json(&data)) - } else { - writeln!(&mut self.dst, "{}", as_json(&data)) - }; - if let Err(e) = result { - panic!("failed to print notification: {:?}", e); - } - } - - fn source_map(&self) -> Option<&Lrc<SourceMapperDyn>> { - Some(&self.sm) - } - - fn should_show_explain(&self) -> bool { - match self.json_rendered { - HumanReadableErrorType::Short(_) => false, - _ => true, - } - } -} - -// The following data types are provided just for serialisation. - -#[derive(RustcEncodable)] -struct Diagnostic { - /// The primary error message. - message: String, - code: Option<DiagnosticCode>, - /// "error: internal compiler error", "error", "warning", "note", "help". - level: &'static str, - spans: Vec<DiagnosticSpan>, - /// Associated diagnostic messages. - children: Vec<Diagnostic>, - /// The message as rustc would render it. - rendered: Option<String>, -} - -#[derive(RustcEncodable)] -struct DiagnosticSpan { - file_name: String, - byte_start: u32, - byte_end: u32, - /// 1-based. - line_start: usize, - line_end: usize, - /// 1-based, character offset. - column_start: usize, - column_end: usize, - /// Is this a "primary" span -- meaning the point, or one of the points, - /// where the error occurred? - is_primary: bool, - /// Source text from the start of line_start to the end of line_end. - text: Vec<DiagnosticSpanLine>, - /// Label that should be placed at this location (if any) - label: Option<String>, - /// If we are suggesting a replacement, this will contain text - /// that should be sliced in atop this span. - suggested_replacement: Option<String>, - /// If the suggestion is approximate - suggestion_applicability: Option<Applicability>, - /// Macro invocations that created the code at this span, if any. - expansion: Option<Box<DiagnosticSpanMacroExpansion>>, -} - -#[derive(RustcEncodable)] -struct DiagnosticSpanLine { - text: String, - - /// 1-based, character offset in self.text. - highlight_start: usize, - - highlight_end: usize, -} - -#[derive(RustcEncodable)] -struct DiagnosticSpanMacroExpansion { - /// span where macro was applied to generate this code; note that - /// this may itself derive from a macro (if - /// `span.expansion.is_some()`) - span: DiagnosticSpan, - - /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]") - macro_decl_name: String, - - /// span where macro was defined (if known) - def_site_span: DiagnosticSpan, -} - -#[derive(RustcEncodable)] -struct DiagnosticCode { - /// The code itself. - code: String, - /// An explanation for the code. - explanation: Option<&'static str>, -} - -#[derive(RustcEncodable)] -struct ArtifactNotification<'a> { - /// The path of the artifact. - artifact: &'a Path, - /// What kind of artifact we're emitting. - emit: &'a str, -} - -impl Diagnostic { - fn from_errors_diagnostic(diag: &errors::Diagnostic, - je: &JsonEmitter) - -> Diagnostic { - let sugg = diag.suggestions.iter().map(|sugg| { - Diagnostic { - message: sugg.msg.clone(), - code: None, - level: "help", - spans: DiagnosticSpan::from_suggestion(sugg, je), - children: vec![], - rendered: None, - } - }); - - // generate regular command line output and store it in the json - - // A threadsafe buffer for writing. - #[derive(Default, Clone)] - struct BufWriter(Arc<Mutex<Vec<u8>>>); - - impl Write for BufWriter { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.0.lock().unwrap().write(buf) - } - fn flush(&mut self) -> io::Result<()> { - self.0.lock().unwrap().flush() - } - } - let buf = BufWriter::default(); - let output = buf.clone(); - je.json_rendered.new_emitter( - Box::new(buf), Some(je.sm.clone()), false, None, je.external_macro_backtrace - ).ui_testing(je.ui_testing).emit_diagnostic(diag); - let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap(); - let output = String::from_utf8(output).unwrap(); - - Diagnostic { - message: diag.message(), - code: DiagnosticCode::map_opt_string(diag.code.clone(), je), - level: diag.level.to_str(), - spans: DiagnosticSpan::from_multispan(&diag.span, je), - children: diag.children.iter().map(|c| { - Diagnostic::from_sub_diagnostic(c, je) - }).chain(sugg).collect(), - rendered: Some(output), - } - } - - fn from_sub_diagnostic(diag: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic { - Diagnostic { - message: diag.message(), - code: None, - level: diag.level.to_str(), - spans: diag.render_span.as_ref() - .map(|sp| DiagnosticSpan::from_multispan(sp, je)) - .unwrap_or_else(|| DiagnosticSpan::from_multispan(&diag.span, je)), - children: vec![], - rendered: None, - } - } -} - -impl DiagnosticSpan { - fn from_span_label(span: SpanLabel, - suggestion: Option<(&String, Applicability)>, - je: &JsonEmitter) - -> DiagnosticSpan { - Self::from_span_etc(span.span, - span.is_primary, - span.label, - suggestion, - je) - } - - fn from_span_etc(span: Span, - is_primary: bool, - label: Option<String>, - suggestion: Option<(&String, Applicability)>, - je: &JsonEmitter) - -> DiagnosticSpan { - // obtain the full backtrace from the `macro_backtrace` - // helper; in some ways, it'd be better to expand the - // backtrace ourselves, but the `macro_backtrace` helper makes - // some decision, such as dropping some frames, and I don't - // want to duplicate that logic here. - let backtrace = span.macro_backtrace().into_iter(); - DiagnosticSpan::from_span_full(span, - is_primary, - label, - suggestion, - backtrace, - je) - } - - fn from_span_full(span: Span, - is_primary: bool, - label: Option<String>, - suggestion: Option<(&String, Applicability)>, - mut backtrace: vec::IntoIter<MacroBacktrace>, - je: &JsonEmitter) - -> DiagnosticSpan { - let start = je.sm.lookup_char_pos(span.lo()); - let end = je.sm.lookup_char_pos(span.hi()); - let backtrace_step = backtrace.next().map(|bt| { - let call_site = - Self::from_span_full(bt.call_site, - false, - None, - None, - backtrace, - je); - let def_site_span = - Self::from_span_full(bt.def_site_span, - false, - None, - None, - vec![].into_iter(), - je); - Box::new(DiagnosticSpanMacroExpansion { - span: call_site, - macro_decl_name: bt.macro_decl_name, - def_site_span, - }) - }); - - DiagnosticSpan { - file_name: start.file.name.to_string(), - byte_start: start.file.original_relative_byte_pos(span.lo()).0, - byte_end: start.file.original_relative_byte_pos(span.hi()).0, - line_start: start.line, - line_end: end.line, - column_start: start.col.0 + 1, - column_end: end.col.0 + 1, - is_primary, - text: DiagnosticSpanLine::from_span(span, je), - suggested_replacement: suggestion.map(|x| x.0.clone()), - suggestion_applicability: suggestion.map(|x| x.1), - expansion: backtrace_step, - label, - } - } - - fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> { - msp.span_labels() - .into_iter() - .map(|span_str| Self::from_span_label(span_str, None, je)) - .collect() - } - - fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter) - -> Vec<DiagnosticSpan> { - suggestion.substitutions - .iter() - .flat_map(|substitution| { - substitution.parts.iter().map(move |suggestion_inner| { - let span_label = SpanLabel { - span: suggestion_inner.span, - is_primary: true, - label: None, - }; - DiagnosticSpan::from_span_label(span_label, - Some((&suggestion_inner.snippet, - suggestion.applicability)), - je) - }) - }) - .collect() - } -} - -impl DiagnosticSpanLine { - fn line_from_source_file(fm: &syntax_pos::SourceFile, - index: usize, - h_start: usize, - h_end: usize) - -> DiagnosticSpanLine { - DiagnosticSpanLine { - text: fm.get_line(index).map_or(String::new(), |l| l.into_owned()), - highlight_start: h_start, - highlight_end: h_end, - } - } - - /// Creates a list of DiagnosticSpanLines from span - each line with any part - /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the - /// `span` within the line. - fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> { - je.sm.span_to_lines(span) - .map(|lines| { - let fm = &*lines.file; - lines.lines - .iter() - .map(|line| DiagnosticSpanLine::line_from_source_file( - fm, - line.line_index, - line.start_col.0 + 1, - line.end_col.0 + 1, - )).collect() - }).unwrap_or_else(|_| vec![]) - } -} - -impl DiagnosticCode { - fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> { - s.map(|s| { - let s = match s { - DiagnosticId::Error(s) => s, - DiagnosticId::Lint(s) => s, - }; - let explanation = je.registry - .as_ref() - .and_then(|registry| registry.find_description(&s)); - - DiagnosticCode { - code: s, - explanation, - } - }) - } -} diff --git a/src/libsyntax/json/tests.rs b/src/libsyntax/json/tests.rs deleted file mode 100644 index eb0d9ef3947..00000000000 --- a/src/libsyntax/json/tests.rs +++ /dev/null @@ -1,186 +0,0 @@ -use super::*; - -use crate::json::JsonEmitter; -use crate::source_map::{FilePathMapping, SourceMap}; -use crate::tests::Shared; -use crate::with_default_globals; - -use errors::emitter::{ColorConfig, HumanReadableErrorType}; -use errors::Handler; -use rustc_serialize::json::decode; -use syntax_pos::{BytePos, Span}; - -use std::str; - -#[derive(RustcDecodable, Debug, PartialEq, Eq)] -struct TestData { - spans: Vec<SpanTestData>, -} - -#[derive(RustcDecodable, Debug, PartialEq, Eq)] -struct SpanTestData { - pub byte_start: u32, - pub byte_end: u32, - pub line_start: u32, - pub column_start: u32, - pub line_end: u32, - pub column_end: u32, -} - -/// Test the span yields correct positions in JSON. -fn test_positions(code: &str, span: (u32, u32), expected_output: SpanTestData) { - let expected_output = TestData { spans: vec![expected_output] }; - - with_default_globals(|| { - let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - sm.new_source_file(Path::new("test.rs").to_owned().into(), code.to_owned()); - - let output = Arc::new(Mutex::new(Vec::new())); - let je = JsonEmitter::new( - Box::new(Shared { data: output.clone() }), - None, - sm, - true, - HumanReadableErrorType::Short(ColorConfig::Never), - false, - ); - - let span = Span::with_root_ctxt(BytePos(span.0), BytePos(span.1)); - let handler = Handler::with_emitter(true, None, Box::new(je)); - handler.span_err(span, "foo"); - - let bytes = output.lock().unwrap(); - let actual_output = str::from_utf8(&bytes).unwrap(); - let actual_output: TestData = decode(actual_output).unwrap(); - - assert_eq!(expected_output, actual_output) - }) -} - -#[test] -fn empty() { - test_positions( - " ", - (0, 1), - SpanTestData { - byte_start: 0, - byte_end: 1, - line_start: 1, - column_start: 1, - line_end: 1, - column_end: 2, - }, - ) -} - -#[test] -fn bom() { - test_positions( - "\u{feff} ", - (0, 1), - SpanTestData { - byte_start: 3, - byte_end: 4, - line_start: 1, - column_start: 1, - line_end: 1, - column_end: 2, - }, - ) -} - -#[test] -fn lf_newlines() { - test_positions( - "\nmod foo;\nmod bar;\n", - (5, 12), - SpanTestData { - byte_start: 5, - byte_end: 12, - line_start: 2, - column_start: 5, - line_end: 3, - column_end: 3, - }, - ) -} - -#[test] -fn crlf_newlines() { - test_positions( - "\r\nmod foo;\r\nmod bar;\r\n", - (5, 12), - SpanTestData { - byte_start: 6, - byte_end: 14, - line_start: 2, - column_start: 5, - line_end: 3, - column_end: 3, - }, - ) -} - -#[test] -fn crlf_newlines_with_bom() { - test_positions( - "\u{feff}\r\nmod foo;\r\nmod bar;\r\n", - (5, 12), - SpanTestData { - byte_start: 9, - byte_end: 17, - line_start: 2, - column_start: 5, - line_end: 3, - column_end: 3, - }, - ) -} - -#[test] -fn span_before_crlf() { - test_positions( - "foo\r\nbar", - (2, 3), - SpanTestData { - byte_start: 2, - byte_end: 3, - line_start: 1, - column_start: 3, - line_end: 1, - column_end: 4, - }, - ) -} - -#[test] -fn span_on_crlf() { - test_positions( - "foo\r\nbar", - (3, 4), - SpanTestData { - byte_start: 3, - byte_end: 5, - line_start: 1, - column_start: 4, - line_end: 2, - column_end: 1, - }, - ) -} - -#[test] -fn span_after_crlf() { - test_positions( - "foo\r\nbar", - (4, 5), - SpanTestData { - byte_start: 5, - byte_end: 6, - line_start: 2, - column_start: 1, - line_end: 2, - column_end: 2, - }, - ) -} diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index 1b17de529c4..36173801eae 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -7,11 +7,13 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/", test(attr(deny(warnings))))] +#![feature(bool_to_option)] #![feature(box_syntax)] #![feature(const_fn)] #![feature(const_transmute)] #![feature(crate_visibility_modifier)] #![feature(label_break_value)] +#![feature(matches_macro)] #![feature(nll)] #![feature(try_trait)] #![feature(slice_patterns)] @@ -26,11 +28,6 @@ pub use rustc_data_structures::thin_vec::ThinVec; use ast::AttrId; use syntax_pos::edition::Edition; -#[cfg(test)] -mod tests; - -pub const MACRO_ARGUMENTS: Option<&'static str> = Some("macro arguments"); - #[macro_export] macro_rules! unwrap_or { ($opt:expr, $default:expr) => { @@ -82,34 +79,31 @@ pub mod diagnostics { pub mod macros; } -pub mod error_codes; - pub mod util { - crate mod classify; + pub mod classify; pub mod comments; pub mod lev_distance; - crate mod literal; + pub mod literal; pub mod node_count; pub mod parser; pub mod map_in_place; } -pub mod json; - pub mod ast; pub mod attr; pub mod expand; -pub mod source_map; -#[macro_use] pub mod config; +pub use syntax_pos::source_map; pub mod entry; -pub mod feature_gate; +pub mod feature_gate { + mod check; + pub use check::{check_crate, check_attribute, get_features, feature_err, feature_err_issue}; +} pub mod mut_visit; -pub mod parse; pub mod ptr; pub mod show_span; pub use syntax_pos::edition; pub use syntax_pos::symbol; -pub mod sess; +pub use rustc_session::parse as sess; pub mod token; pub mod tokenstream; pub mod visit; @@ -121,3 +115,8 @@ pub mod print { } pub mod early_buffered_lints; + +/// Requirements for a `StableHashingContext` to be used in this crate. +/// This is a hack to allow using the `HashStable_Generic` derive macro +/// instead of implementing everything in librustc. +pub trait HashStableContext: syntax_pos::HashStableContext {} diff --git a/src/libsyntax/mut_visit.rs b/src/libsyntax/mut_visit.rs index 7696ea48f93..f8795d885d2 100644 --- a/src/libsyntax/mut_visit.rs +++ b/src/libsyntax/mut_visit.rs @@ -22,9 +22,6 @@ use rustc_data_structures::sync::Lrc; use std::ops::DerefMut; use std::{panic, process, ptr}; -#[cfg(test)] -mod tests; - pub trait ExpectOne<A: Array> { fn expect_one(self, err: &'static str) -> A::Item; } @@ -362,6 +359,26 @@ pub fn visit_fn_sig<T: MutVisitor>(FnSig { header, decl }: &mut FnSig, vis: &mut vis.visit_fn_decl(decl); } +// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`. +pub fn visit_mac_args<T: MutVisitor>(args: &mut MacArgs, vis: &mut T) { + match args { + MacArgs::Empty => {} + MacArgs::Delimited(dspan, _delim, tokens) => { + visit_delim_span(dspan, vis); + vis.visit_tts(tokens); + } + MacArgs::Eq(eq_span, tokens) => { + vis.visit_span(eq_span); + vis.visit_tts(tokens); + } + } +} + +pub fn visit_delim_span<T: MutVisitor>(dspan: &mut DelimSpan, vis: &mut T) { + vis.visit_span(&mut dspan.open); + vis.visit_span(&mut dspan.close); +} + pub fn noop_flat_map_field_pattern<T: MutVisitor>( mut fp: FieldPat, vis: &mut T, @@ -444,7 +461,7 @@ pub fn noop_visit_ty<T: MutVisitor>(ty: &mut P<Ty>, vis: &mut T) { vis.visit_mt(mt); } TyKind::BareFn(bft) => { - let BareFnTy { unsafety: _, abi: _, generic_params, decl } = bft.deref_mut(); + let BareFnTy { unsafety: _, ext: _, generic_params, decl } = bft.deref_mut(); generic_params.flat_map_in_place(|param| vis.flat_map_generic_param(param)); vis.visit_fn_decl(decl); } @@ -475,16 +492,17 @@ pub fn noop_visit_foreign_mod<T: MutVisitor>(foreign_mod: &mut ForeignMod, vis: items.flat_map_in_place(|item| vis.flat_map_foreign_item(item)); } -pub fn noop_flat_map_variant<T: MutVisitor>(mut variant: Variant, vis: &mut T) +pub fn noop_flat_map_variant<T: MutVisitor>(mut variant: Variant, visitor: &mut T) -> SmallVec<[Variant; 1]> { - let Variant { ident, attrs, id, data, disr_expr, span, is_placeholder: _ } = &mut variant; - vis.visit_ident(ident); - visit_attrs(attrs, vis); - vis.visit_id(id); - vis.visit_variant_data(data); - visit_opt(disr_expr, |disr_expr| vis.visit_anon_const(disr_expr)); - vis.visit_span(span); + let Variant { ident, vis, attrs, id, data, disr_expr, span, is_placeholder: _ } = &mut variant; + visitor.visit_ident(ident); + visitor.visit_vis(vis); + visit_attrs(attrs, visitor); + visitor.visit_id(id); + visitor.visit_variant_data(data); + visit_opt(disr_expr, |disr_expr| visitor.visit_anon_const(disr_expr)); + visitor.visit_span(span); smallvec![variant] } @@ -552,9 +570,9 @@ pub fn noop_visit_local<T: MutVisitor>(local: &mut P<Local>, vis: &mut T) { pub fn noop_visit_attribute<T: MutVisitor>(attr: &mut Attribute, vis: &mut T) { let Attribute { kind, id: _, style: _, span } = attr; match kind { - AttrKind::Normal(AttrItem { path, tokens }) => { + AttrKind::Normal(AttrItem { path, args }) => { vis.visit_path(path); - vis.visit_tts(tokens); + visit_mac_args(args, vis); } AttrKind::DocComment(_) => {} } @@ -562,15 +580,14 @@ pub fn noop_visit_attribute<T: MutVisitor>(attr: &mut Attribute, vis: &mut T) { } pub fn noop_visit_mac<T: MutVisitor>(mac: &mut Mac, vis: &mut T) { - let Mac { path, delim: _, tts, span, prior_type_ascription: _ } = mac; + let Mac { path, args, prior_type_ascription: _ } = mac; vis.visit_path(path); - vis.visit_tts(tts); - vis.visit_span(span); + visit_mac_args(args, vis); } pub fn noop_visit_macro_def<T: MutVisitor>(macro_def: &mut MacroDef, vis: &mut T) { - let MacroDef { tokens, legacy: _ } = macro_def; - vis.visit_tts(tokens); + let MacroDef { body, legacy: _ } = macro_def; + visit_mac_args(body, vis); } pub fn noop_visit_meta_list_item<T: MutVisitor>(li: &mut NestedMetaItem, vis: &mut T) { @@ -684,9 +701,9 @@ pub fn noop_visit_interpolated<T: MutVisitor>(nt: &mut token::Nonterminal, vis: token::NtIdent(ident, _is_raw) => vis.visit_ident(ident), token::NtLifetime(ident) => vis.visit_ident(ident), token::NtLiteral(expr) => vis.visit_expr(expr), - token::NtMeta(AttrItem { path, tokens }) => { + token::NtMeta(AttrItem { path, args }) => { vis.visit_path(path); - vis.visit_tts(tokens); + visit_mac_args(args, vis); } token::NtPath(path) => vis.visit_path(path), token::NtTT(tt) => vis.visit_tt(tt), @@ -890,10 +907,6 @@ pub fn noop_visit_item_kind<T: MutVisitor>(kind: &mut ItemKind, vis: &mut T) { vis.visit_ty(ty); vis.visit_generics(generics); } - ItemKind::OpaqueTy(bounds, generics) => { - visit_bounds(bounds, vis); - vis.visit_generics(generics); - } ItemKind::Enum(EnumDef { variants }, generics) => { variants.flat_map_in_place(|variant| vis.flat_map_variant(variant)); vis.visit_generics(generics); @@ -923,32 +936,33 @@ pub fn noop_visit_item_kind<T: MutVisitor>(kind: &mut ItemKind, vis: &mut T) { } } -pub fn noop_flat_map_trait_item<T: MutVisitor>(mut item: TraitItem, vis: &mut T) +pub fn noop_flat_map_trait_item<T: MutVisitor>(mut item: TraitItem, visitor: &mut T) -> SmallVec<[TraitItem; 1]> { - let TraitItem { id, ident, attrs, generics, kind, span, tokens: _ } = &mut item; - vis.visit_id(id); - vis.visit_ident(ident); - visit_attrs(attrs, vis); - vis.visit_generics(generics); + let TraitItem { id, ident, vis, attrs, generics, kind, span, tokens: _ } = &mut item; + visitor.visit_id(id); + visitor.visit_ident(ident); + visitor.visit_vis(vis); + visit_attrs(attrs, visitor); + visitor.visit_generics(generics); match kind { TraitItemKind::Const(ty, default) => { - vis.visit_ty(ty); - visit_opt(default, |default| vis.visit_expr(default)); + visitor.visit_ty(ty); + visit_opt(default, |default| visitor.visit_expr(default)); } TraitItemKind::Method(sig, body) => { - visit_fn_sig(sig, vis); - visit_opt(body, |body| vis.visit_block(body)); + visit_fn_sig(sig, visitor); + visit_opt(body, |body| visitor.visit_block(body)); } TraitItemKind::Type(bounds, default) => { - visit_bounds(bounds, vis); - visit_opt(default, |default| vis.visit_ty(default)); + visit_bounds(bounds, visitor); + visit_opt(default, |default| visitor.visit_ty(default)); } TraitItemKind::Macro(mac) => { - vis.visit_mac(mac); + visitor.visit_mac(mac); } } - vis.visit_span(span); + visitor.visit_span(span); smallvec![item] } @@ -973,7 +987,6 @@ pub fn noop_flat_map_impl_item<T: MutVisitor>(mut item: ImplItem, visitor: &mut visitor.visit_block(body); } ImplItemKind::TyAlias(ty) => visitor.visit_ty(ty), - ImplItemKind::OpaqueTy(bounds) => visit_bounds(bounds, visitor), ImplItemKind::Macro(mac) => visitor.visit_mac(mac), } visitor.visit_span(span); @@ -982,7 +995,7 @@ pub fn noop_flat_map_impl_item<T: MutVisitor>(mut item: ImplItem, visitor: &mut } pub fn noop_visit_fn_header<T: MutVisitor>(header: &mut FnHeader, vis: &mut T) { - let FnHeader { unsafety: _, asyncness, constness: _, abi: _ } = header; + let FnHeader { unsafety: _, asyncness, constness: _, ext: _ } = header; vis.visit_asyncness(&mut asyncness.node); } @@ -1040,7 +1053,7 @@ pub fn noop_flat_map_item<T: MutVisitor>(mut item: P<Item>, visitor: &mut T) pub fn noop_flat_map_foreign_item<T: MutVisitor>(mut item: ForeignItem, visitor: &mut T) -> SmallVec<[ForeignItem; 1]> { - let ForeignItem { ident, attrs, kind, id, span, vis } = &mut item; + let ForeignItem { ident, attrs, id, kind, vis, span, tokens: _ } = &mut item; visitor.visit_ident(ident); visit_attrs(attrs, visitor); match kind { @@ -1134,7 +1147,7 @@ pub fn noop_visit_expr<T: MutVisitor>(Expr { kind, id, span, attrs }: &mut Expr, vis.visit_expr(expr); vis.visit_ty(ty); } - ExprKind::AddrOf(_m, ohs) => vis.visit_expr(ohs), + ExprKind::AddrOf(_, _, ohs) => vis.visit_expr(ohs), ExprKind::Let(pat, scrutinee) => { vis.visit_pat(pat); vis.visit_expr(scrutinee); diff --git a/src/libsyntax/mut_visit/tests.rs b/src/libsyntax/mut_visit/tests.rs deleted file mode 100644 index f779e0d0a60..00000000000 --- a/src/libsyntax/mut_visit/tests.rs +++ /dev/null @@ -1,71 +0,0 @@ -use super::*; - -use crate::ast::{self, Ident}; -use crate::tests::{string_to_crate, matches_codepattern}; -use crate::print::pprust; -use crate::mut_visit; -use crate::with_default_globals; - -// This version doesn't care about getting comments or doc-strings in. -fn fake_print_crate(s: &mut pprust::State<'_>, - krate: &ast::Crate) { - s.print_mod(&krate.module, &krate.attrs) -} - -// Change every identifier to "zz". -struct ToZzIdentMutVisitor; - -impl MutVisitor for ToZzIdentMutVisitor { - fn visit_ident(&mut self, ident: &mut ast::Ident) { - *ident = Ident::from_str("zz"); - } - fn visit_mac(&mut self, mac: &mut ast::Mac) { - mut_visit::noop_visit_mac(mac, self) - } -} - -// Maybe add to `expand.rs`. -macro_rules! assert_pred { - ($pred:expr, $predname:expr, $a:expr , $b:expr) => ( - { - let pred_val = $pred; - let a_val = $a; - let b_val = $b; - if !(pred_val(&a_val, &b_val)) { - panic!("expected args satisfying {}, got {} and {}", - $predname, a_val, b_val); - } - } - ) -} - -// Make sure idents get transformed everywhere. -#[test] fn ident_transformation () { - with_default_globals(|| { - let mut zz_visitor = ToZzIdentMutVisitor; - let mut krate = string_to_crate( - "#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string()); - zz_visitor.visit_crate(&mut krate); - assert_pred!( - matches_codepattern, - "matches_codepattern", - pprust::to_string(|s| fake_print_crate(s, &krate)), - "#[zz]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string()); - }) -} - -// Make sure idents get transformed even inside macro defs. -#[test] fn ident_transformation_in_defs () { - with_default_globals(|| { - let mut zz_visitor = ToZzIdentMutVisitor; - let mut krate = string_to_crate( - "macro_rules! a {(b $c:expr $(d $e:token)f+ => \ - (g $(d $d $e)+))} ".to_string()); - zz_visitor.visit_crate(&mut krate); - assert_pred!( - matches_codepattern, - "matches_codepattern", - pprust::to_string(|s| fake_print_crate(s, &krate)), - "macro_rules! zz{(zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+))}".to_string()); - }) -} diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs deleted file mode 100644 index b1b7b08c78a..00000000000 --- a/src/libsyntax/parse/lexer/mod.rs +++ /dev/null @@ -1,645 +0,0 @@ -use crate::token::{self, Token, TokenKind}; -use crate::sess::ParseSess; -use crate::symbol::{sym, Symbol}; -use crate::util::comments; - -use errors::{FatalError, DiagnosticBuilder}; -use syntax_pos::{BytePos, Pos, Span}; -use rustc_lexer::Base; -use rustc_lexer::unescape; - -use std::char; -use std::convert::TryInto; -use rustc_data_structures::sync::Lrc; -use log::debug; - -#[cfg(test)] -mod tests; - -mod tokentrees; -mod unicode_chars; -mod unescape_error_reporting; -use unescape_error_reporting::{emit_unescape_error, push_escaped_char}; - -#[derive(Clone, Debug)] -pub struct UnmatchedBrace { - pub expected_delim: token::DelimToken, - pub found_delim: Option<token::DelimToken>, - pub found_span: Span, - pub unclosed_span: Option<Span>, - pub candidate_span: Option<Span>, -} - -pub struct StringReader<'a> { - sess: &'a ParseSess, - /// Initial position, read-only. - start_pos: BytePos, - /// The absolute offset within the source_map of the current character. - pos: BytePos, - /// Stop reading src at this index. - end_src_index: usize, - /// Source text to tokenize. - src: Lrc<String>, - override_span: Option<Span>, -} - -impl<'a> StringReader<'a> { - pub fn new(sess: &'a ParseSess, - source_file: Lrc<syntax_pos::SourceFile>, - override_span: Option<Span>) -> Self { - if source_file.src.is_none() { - sess.span_diagnostic.bug(&format!("cannot lex `source_file` without source: {}", - source_file.name)); - } - - let src = (*source_file.src.as_ref().unwrap()).clone(); - - StringReader { - sess, - start_pos: source_file.start_pos, - pos: source_file.start_pos, - end_src_index: src.len(), - src, - override_span, - } - } - - pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self { - let begin = sess.source_map().lookup_byte_offset(span.lo()); - let end = sess.source_map().lookup_byte_offset(span.hi()); - - // Make the range zero-length if the span is invalid. - if begin.sf.start_pos != end.sf.start_pos { - span = span.shrink_to_lo(); - } - - let mut sr = StringReader::new(sess, begin.sf, None); - - // Seek the lexer to the right byte range. - sr.end_src_index = sr.src_index(span.hi()); - - sr - } - - - fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span { - self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi)) - } - - /// Returns the next token, including trivia like whitespace or comments. - /// - /// `Err(())` means that some errors were encountered, which can be - /// retrieved using `buffer_fatal_errors`. - pub fn next_token(&mut self) -> Token { - let start_src_index = self.src_index(self.pos); - let text: &str = &self.src[start_src_index..self.end_src_index]; - - if text.is_empty() { - let span = self.mk_sp(self.pos, self.pos); - return Token::new(token::Eof, span); - } - - { - let is_beginning_of_file = self.pos == self.start_pos; - if is_beginning_of_file { - if let Some(shebang_len) = rustc_lexer::strip_shebang(text) { - let start = self.pos; - self.pos = self.pos + BytePos::from_usize(shebang_len); - - let sym = self.symbol_from(start + BytePos::from_usize("#!".len())); - let kind = token::Shebang(sym); - - let span = self.mk_sp(start, self.pos); - return Token::new(kind, span); - } - } - } - - let token = rustc_lexer::first_token(text); - - let start = self.pos; - self.pos = self.pos + BytePos::from_usize(token.len); - - debug!("try_next_token: {:?}({:?})", token.kind, self.str_from(start)); - - // This could use `?`, but that makes code significantly (10-20%) slower. - // https://github.com/rust-lang/rust/issues/37939 - let kind = self.cook_lexer_token(token.kind, start); - - let span = self.mk_sp(start, self.pos); - Token::new(kind, span) - } - - /// Report a fatal lexical error with a given span. - fn fatal_span(&self, sp: Span, m: &str) -> FatalError { - self.sess.span_diagnostic.span_fatal(sp, m) - } - - /// Report a lexical error with a given span. - fn err_span(&self, sp: Span, m: &str) { - self.sess.span_diagnostic.struct_span_err(sp, m).emit(); - } - - - /// Report a fatal error spanning [`from_pos`, `to_pos`). - fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError { - self.fatal_span(self.mk_sp(from_pos, to_pos), m) - } - - /// Report a lexical error spanning [`from_pos`, `to_pos`). - fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) { - self.err_span(self.mk_sp(from_pos, to_pos), m) - } - - fn struct_span_fatal(&self, from_pos: BytePos, to_pos: BytePos, m: &str) - -> DiagnosticBuilder<'a> - { - self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), m) - } - - fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) - -> DiagnosticBuilder<'a> - { - let mut m = m.to_string(); - m.push_str(": "); - push_escaped_char(&mut m, c); - - self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..]) - } - - /// Turns simple `rustc_lexer::TokenKind` enum into a rich - /// `libsyntax::TokenKind`. This turns strings into interned - /// symbols and runs additional validation. - fn cook_lexer_token( - &self, - token: rustc_lexer::TokenKind, - start: BytePos, - ) -> TokenKind { - match token { - rustc_lexer::TokenKind::LineComment => { - let string = self.str_from(start); - // comments with only more "/"s are not doc comments - let tok = if comments::is_line_doc_comment(string) { - self.forbid_bare_cr(start, string, "bare CR not allowed in doc-comment"); - token::DocComment(Symbol::intern(string)) - } else { - token::Comment - }; - - tok - } - rustc_lexer::TokenKind::BlockComment { terminated } => { - let string = self.str_from(start); - // block comments starting with "/**" or "/*!" are doc-comments - // but comments with only "*"s between two "/"s are not - let is_doc_comment = comments::is_block_doc_comment(string); - - if !terminated { - let msg = if is_doc_comment { - "unterminated block doc-comment" - } else { - "unterminated block comment" - }; - let last_bpos = self.pos; - self.fatal_span_(start, last_bpos, msg).raise(); - } - - let tok = if is_doc_comment { - self.forbid_bare_cr(start, - string, - "bare CR not allowed in block doc-comment"); - token::DocComment(Symbol::intern(string)) - } else { - token::Comment - }; - - tok - } - rustc_lexer::TokenKind::Whitespace => token::Whitespace, - rustc_lexer::TokenKind::Ident | rustc_lexer::TokenKind::RawIdent => { - let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent; - let mut ident_start = start; - if is_raw_ident { - ident_start = ident_start + BytePos(2); - } - // FIXME: perform NFKC normalization here. (Issue #2253) - let sym = self.symbol_from(ident_start); - if is_raw_ident { - let span = self.mk_sp(start, self.pos); - if !sym.can_be_raw() { - self.err_span(span, &format!("`{}` cannot be a raw identifier", sym)); - } - self.sess.raw_identifier_spans.borrow_mut().push(span); - } - token::Ident(sym, is_raw_ident) - } - rustc_lexer::TokenKind::Literal { kind, suffix_start } => { - let suffix_start = start + BytePos(suffix_start as u32); - let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind); - let suffix = if suffix_start < self.pos { - let string = self.str_from(suffix_start); - if string == "_" { - self.sess.span_diagnostic - .struct_span_warn(self.mk_sp(suffix_start, self.pos), - "underscore literal suffix is not allowed") - .warn("this was previously accepted by the compiler but is \ - being phased out; it will become a hard error in \ - a future release!") - .note("for more information, see issue #42326 \ - <https://github.com/rust-lang/rust/issues/42326>") - .emit(); - None - } else { - Some(Symbol::intern(string)) - } - } else { - None - }; - token::Literal(token::Lit { kind, symbol, suffix }) - } - rustc_lexer::TokenKind::Lifetime { starts_with_number } => { - // Include the leading `'` in the real identifier, for macro - // expansion purposes. See #12512 for the gory details of why - // this is necessary. - let lifetime_name = self.str_from(start); - if starts_with_number { - self.err_span_( - start, - self.pos, - "lifetimes cannot start with a number", - ); - } - let ident = Symbol::intern(lifetime_name); - token::Lifetime(ident) - } - rustc_lexer::TokenKind::Semi => token::Semi, - rustc_lexer::TokenKind::Comma => token::Comma, - rustc_lexer::TokenKind::Dot => token::Dot, - rustc_lexer::TokenKind::OpenParen => token::OpenDelim(token::Paren), - rustc_lexer::TokenKind::CloseParen => token::CloseDelim(token::Paren), - rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(token::Brace), - rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(token::Brace), - rustc_lexer::TokenKind::OpenBracket => token::OpenDelim(token::Bracket), - rustc_lexer::TokenKind::CloseBracket => token::CloseDelim(token::Bracket), - rustc_lexer::TokenKind::At => token::At, - rustc_lexer::TokenKind::Pound => token::Pound, - rustc_lexer::TokenKind::Tilde => token::Tilde, - rustc_lexer::TokenKind::Question => token::Question, - rustc_lexer::TokenKind::Colon => token::Colon, - rustc_lexer::TokenKind::Dollar => token::Dollar, - rustc_lexer::TokenKind::Eq => token::Eq, - rustc_lexer::TokenKind::Not => token::Not, - rustc_lexer::TokenKind::Lt => token::Lt, - rustc_lexer::TokenKind::Gt => token::Gt, - rustc_lexer::TokenKind::Minus => token::BinOp(token::Minus), - rustc_lexer::TokenKind::And => token::BinOp(token::And), - rustc_lexer::TokenKind::Or => token::BinOp(token::Or), - rustc_lexer::TokenKind::Plus => token::BinOp(token::Plus), - rustc_lexer::TokenKind::Star => token::BinOp(token::Star), - rustc_lexer::TokenKind::Slash => token::BinOp(token::Slash), - rustc_lexer::TokenKind::Caret => token::BinOp(token::Caret), - rustc_lexer::TokenKind::Percent => token::BinOp(token::Percent), - - rustc_lexer::TokenKind::Unknown => { - let c = self.str_from(start).chars().next().unwrap(); - let mut err = self.struct_fatal_span_char(start, - self.pos, - "unknown start of token", - c); - // FIXME: the lexer could be used to turn the ASCII version of unicode homoglyphs, - // instead of keeping a table in `check_for_substitution`into the token. Ideally, - // this should be inside `rustc_lexer`. However, we should first remove compound - // tokens like `<<` from `rustc_lexer`, and then add fancier error recovery to it, - // as there will be less overall work to do this way. - let token = unicode_chars::check_for_substitution(self, start, c, &mut err) - .unwrap_or_else(|| token::Unknown(self.symbol_from(start))); - err.emit(); - token - } - } - } - - fn cook_lexer_literal( - &self, - start: BytePos, - suffix_start: BytePos, - kind: rustc_lexer::LiteralKind - ) -> (token::LitKind, Symbol) { - match kind { - rustc_lexer::LiteralKind::Char { terminated } => { - if !terminated { - self.fatal_span_(start, suffix_start, - "unterminated character literal".into()) - .raise() - } - let content_start = start + BytePos(1); - let content_end = suffix_start - BytePos(1); - self.validate_char_escape(content_start, content_end); - let id = self.symbol_from_to(content_start, content_end); - (token::Char, id) - }, - rustc_lexer::LiteralKind::Byte { terminated } => { - if !terminated { - self.fatal_span_(start + BytePos(1), suffix_start, - "unterminated byte constant".into()) - .raise() - } - let content_start = start + BytePos(2); - let content_end = suffix_start - BytePos(1); - self.validate_byte_escape(content_start, content_end); - let id = self.symbol_from_to(content_start, content_end); - (token::Byte, id) - }, - rustc_lexer::LiteralKind::Str { terminated } => { - if !terminated { - self.fatal_span_(start, suffix_start, - "unterminated double quote string".into()) - .raise() - } - let content_start = start + BytePos(1); - let content_end = suffix_start - BytePos(1); - self.validate_str_escape(content_start, content_end); - let id = self.symbol_from_to(content_start, content_end); - (token::Str, id) - } - rustc_lexer::LiteralKind::ByteStr { terminated } => { - if !terminated { - self.fatal_span_(start + BytePos(1), suffix_start, - "unterminated double quote byte string".into()) - .raise() - } - let content_start = start + BytePos(2); - let content_end = suffix_start - BytePos(1); - self.validate_byte_str_escape(content_start, content_end); - let id = self.symbol_from_to(content_start, content_end); - (token::ByteStr, id) - } - rustc_lexer::LiteralKind::RawStr { n_hashes, started, terminated } => { - if !started { - self.report_non_started_raw_string(start); - } - if !terminated { - self.report_unterminated_raw_string(start, n_hashes) - } - let n_hashes: u16 = self.restrict_n_hashes(start, n_hashes); - let n = u32::from(n_hashes); - let content_start = start + BytePos(2 + n); - let content_end = suffix_start - BytePos(1 + n); - self.validate_raw_str_escape(content_start, content_end); - let id = self.symbol_from_to(content_start, content_end); - (token::StrRaw(n_hashes), id) - } - rustc_lexer::LiteralKind::RawByteStr { n_hashes, started, terminated } => { - if !started { - self.report_non_started_raw_string(start); - } - if !terminated { - self.report_unterminated_raw_string(start, n_hashes) - } - let n_hashes: u16 = self.restrict_n_hashes(start, n_hashes); - let n = u32::from(n_hashes); - let content_start = start + BytePos(3 + n); - let content_end = suffix_start - BytePos(1 + n); - self.validate_raw_byte_str_escape(content_start, content_end); - let id = self.symbol_from_to(content_start, content_end); - (token::ByteStrRaw(n_hashes), id) - } - rustc_lexer::LiteralKind::Int { base, empty_int } => { - if empty_int { - self.err_span_(start, suffix_start, "no valid digits found for number"); - (token::Integer, sym::integer(0)) - } else { - self.validate_int_literal(base, start, suffix_start); - (token::Integer, self.symbol_from_to(start, suffix_start)) - } - }, - rustc_lexer::LiteralKind::Float { base, empty_exponent } => { - if empty_exponent { - let mut err = self.struct_span_fatal( - start, self.pos, - "expected at least one digit in exponent" - ); - err.emit(); - } - - match base { - Base::Hexadecimal => { - self.err_span_(start, suffix_start, - "hexadecimal float literal is not supported") - } - Base::Octal => { - self.err_span_(start, suffix_start, - "octal float literal is not supported") - } - Base::Binary => { - self.err_span_(start, suffix_start, - "binary float literal is not supported") - } - _ => () - } - - let id = self.symbol_from_to(start, suffix_start); - (token::Float, id) - }, - } - } - - #[inline] - fn src_index(&self, pos: BytePos) -> usize { - (pos - self.start_pos).to_usize() - } - - /// Slice of the source text from `start` up to but excluding `self.pos`, - /// meaning the slice does not include the character `self.ch`. - fn str_from(&self, start: BytePos) -> &str - { - self.str_from_to(start, self.pos) - } - - /// Creates a Symbol from a given offset to the current offset. - fn symbol_from(&self, start: BytePos) -> Symbol { - debug!("taking an ident from {:?} to {:?}", start, self.pos); - Symbol::intern(self.str_from(start)) - } - - /// As symbol_from, with an explicit endpoint. - fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol { - debug!("taking an ident from {:?} to {:?}", start, end); - Symbol::intern(self.str_from_to(start, end)) - } - - /// Slice of the source text spanning from `start` up to but excluding `end`. - fn str_from_to(&self, start: BytePos, end: BytePos) -> &str - { - &self.src[self.src_index(start)..self.src_index(end)] - } - - fn forbid_bare_cr(&self, start: BytePos, s: &str, errmsg: &str) { - let mut idx = 0; - loop { - idx = match s[idx..].find('\r') { - None => break, - Some(it) => idx + it + 1 - }; - self.err_span_(start + BytePos(idx as u32 - 1), - start + BytePos(idx as u32), - errmsg); - } - } - - fn report_non_started_raw_string(&self, start: BytePos) -> ! { - let bad_char = self.str_from(start).chars().last().unwrap(); - self - .struct_fatal_span_char( - start, - self.pos, - "found invalid character; only `#` is allowed \ - in raw string delimitation", - bad_char, - ) - .emit(); - FatalError.raise() - } - - fn report_unterminated_raw_string(&self, start: BytePos, n_hashes: usize) -> ! { - let mut err = self.struct_span_fatal( - start, start, - "unterminated raw string", - ); - err.span_label( - self.mk_sp(start, start), - "unterminated raw string", - ); - - if n_hashes > 0 { - err.note(&format!("this raw string should be terminated with `\"{}`", - "#".repeat(n_hashes as usize))); - } - - err.emit(); - FatalError.raise() - } - - fn restrict_n_hashes(&self, start: BytePos, n_hashes: usize) -> u16 { - match n_hashes.try_into() { - Ok(n_hashes) => n_hashes, - Err(_) => { - self.fatal_span_(start, - self.pos, - "too many `#` symbols: raw strings may be \ - delimited by up to 65535 `#` symbols").raise(); - } - } - } - - fn validate_char_escape(&self, content_start: BytePos, content_end: BytePos) { - let lit = self.str_from_to(content_start, content_end); - if let Err((off, err)) = unescape::unescape_char(lit) { - emit_unescape_error( - &self.sess.span_diagnostic, - lit, - self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)), - unescape::Mode::Char, - 0..off, - err, - ) - } - } - - fn validate_byte_escape(&self, content_start: BytePos, content_end: BytePos) { - let lit = self.str_from_to(content_start, content_end); - if let Err((off, err)) = unescape::unescape_byte(lit) { - emit_unescape_error( - &self.sess.span_diagnostic, - lit, - self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)), - unescape::Mode::Byte, - 0..off, - err, - ) - } - } - - fn validate_str_escape(&self, content_start: BytePos, content_end: BytePos) { - let lit = self.str_from_to(content_start, content_end); - unescape::unescape_str(lit, &mut |range, c| { - if let Err(err) = c { - emit_unescape_error( - &self.sess.span_diagnostic, - lit, - self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)), - unescape::Mode::Str, - range, - err, - ) - } - }) - } - - fn validate_raw_str_escape(&self, content_start: BytePos, content_end: BytePos) { - let lit = self.str_from_to(content_start, content_end); - unescape::unescape_raw_str(lit, &mut |range, c| { - if let Err(err) = c { - emit_unescape_error( - &self.sess.span_diagnostic, - lit, - self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)), - unescape::Mode::Str, - range, - err, - ) - } - }) - } - - fn validate_raw_byte_str_escape(&self, content_start: BytePos, content_end: BytePos) { - let lit = self.str_from_to(content_start, content_end); - unescape::unescape_raw_byte_str(lit, &mut |range, c| { - if let Err(err) = c { - emit_unescape_error( - &self.sess.span_diagnostic, - lit, - self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)), - unescape::Mode::ByteStr, - range, - err, - ) - } - }) - } - - fn validate_byte_str_escape(&self, content_start: BytePos, content_end: BytePos) { - let lit = self.str_from_to(content_start, content_end); - unescape::unescape_byte_str(lit, &mut |range, c| { - if let Err(err) = c { - emit_unescape_error( - &self.sess.span_diagnostic, - lit, - self.mk_sp(content_start - BytePos(1), content_end + BytePos(1)), - unescape::Mode::ByteStr, - range, - err, - ) - } - }) - } - - fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) { - let base = match base { - Base::Binary => 2, - Base::Octal => 8, - _ => return, - }; - let s = self.str_from_to(content_start + BytePos(2), content_end); - for (idx, c) in s.char_indices() { - let idx = idx as u32; - if c != '_' && c.to_digit(base).is_none() { - let lo = content_start + BytePos(2 + idx); - let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32); - self.err_span_(lo, hi, - &format!("invalid digit for a base {} literal", base)); - - } - } - } -} diff --git a/src/libsyntax/parse/lexer/tests.rs b/src/libsyntax/parse/lexer/tests.rs deleted file mode 100644 index baa6fb59537..00000000000 --- a/src/libsyntax/parse/lexer/tests.rs +++ /dev/null @@ -1,270 +0,0 @@ -use super::*; - -use crate::symbol::Symbol; -use crate::source_map::{SourceMap, FilePathMapping}; -use crate::token; -use crate::util::comments::is_doc_comment; -use crate::with_default_globals; - -use errors::{Handler, emitter::EmitterWriter}; -use std::io; -use std::path::PathBuf; -use syntax_pos::{BytePos, Span}; - -fn mk_sess(sm: Lrc<SourceMap>) -> ParseSess { - let emitter = EmitterWriter::new( - Box::new(io::sink()), - Some(sm.clone()), - false, - false, - false, - None, - false, - ); - ParseSess::with_span_handler(Handler::with_emitter(true, None, Box::new(emitter)), sm) -} - -// Creates a string reader for the given string. -fn setup<'a>(sm: &SourceMap, - sess: &'a ParseSess, - teststr: String) - -> StringReader<'a> { - let sf = sm.new_source_file(PathBuf::from(teststr.clone()).into(), teststr); - StringReader::new(sess, sf, None) -} - -#[test] -fn t1() { - with_default_globals(|| { - let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let sh = mk_sess(sm.clone()); - let mut string_reader = setup( - &sm, - &sh, - "/* my source file */ fn main() { println!(\"zebra\"); }\n".to_string(), - ); - assert_eq!(string_reader.next_token(), token::Comment); - assert_eq!(string_reader.next_token(), token::Whitespace); - let tok1 = string_reader.next_token(); - let tok2 = Token::new( - mk_ident("fn"), - Span::with_root_ctxt(BytePos(21), BytePos(23)), - ); - assert_eq!(tok1.kind, tok2.kind); - assert_eq!(tok1.span, tok2.span); - assert_eq!(string_reader.next_token(), token::Whitespace); - // Read another token. - let tok3 = string_reader.next_token(); - assert_eq!(string_reader.pos.clone(), BytePos(28)); - let tok4 = Token::new( - mk_ident("main"), - Span::with_root_ctxt(BytePos(24), BytePos(28)), - ); - assert_eq!(tok3.kind, tok4.kind); - assert_eq!(tok3.span, tok4.span); - - assert_eq!(string_reader.next_token(), token::OpenDelim(token::Paren)); - assert_eq!(string_reader.pos.clone(), BytePos(29)) - }) -} - -// Checks that the given reader produces the desired stream -// of tokens (stop checking after exhausting `expected`). -fn check_tokenization(mut string_reader: StringReader<'_>, expected: Vec<TokenKind>) { - for expected_tok in &expected { - assert_eq!(&string_reader.next_token(), expected_tok); - } -} - -// Makes the identifier by looking up the string in the interner. -fn mk_ident(id: &str) -> TokenKind { - token::Ident(Symbol::intern(id), false) -} - -fn mk_lit(kind: token::LitKind, symbol: &str, suffix: Option<&str>) -> TokenKind { - TokenKind::lit(kind, Symbol::intern(symbol), suffix.map(Symbol::intern)) -} - -#[test] -fn doublecolon_parsing() { - with_default_globals(|| { - let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let sh = mk_sess(sm.clone()); - check_tokenization( - setup(&sm, &sh, "a b".to_string()), - vec![mk_ident("a"), token::Whitespace, mk_ident("b")], - ); - }) -} - -#[test] -fn doublecolon_parsing_2() { - with_default_globals(|| { - let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let sh = mk_sess(sm.clone()); - check_tokenization( - setup(&sm, &sh, "a::b".to_string()), - vec![mk_ident("a"), token::Colon, token::Colon, mk_ident("b")], - ); - }) -} - -#[test] -fn doublecolon_parsing_3() { - with_default_globals(|| { - let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let sh = mk_sess(sm.clone()); - check_tokenization( - setup(&sm, &sh, "a ::b".to_string()), - vec![mk_ident("a"), token::Whitespace, token::Colon, token::Colon, mk_ident("b")], - ); - }) -} - -#[test] -fn doublecolon_parsing_4() { - with_default_globals(|| { - let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let sh = mk_sess(sm.clone()); - check_tokenization( - setup(&sm, &sh, "a:: b".to_string()), - vec![mk_ident("a"), token::Colon, token::Colon, token::Whitespace, mk_ident("b")], - ); - }) -} - -#[test] -fn character_a() { - with_default_globals(|| { - let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let sh = mk_sess(sm.clone()); - assert_eq!( - setup(&sm, &sh, "'a'".to_string()).next_token(), - mk_lit(token::Char, "a", None), - ); - }) -} - -#[test] -fn character_space() { - with_default_globals(|| { - let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let sh = mk_sess(sm.clone()); - assert_eq!( - setup(&sm, &sh, "' '".to_string()).next_token(), - mk_lit(token::Char, " ", None), - ); - }) -} - -#[test] -fn character_escaped() { - with_default_globals(|| { - let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let sh = mk_sess(sm.clone()); - assert_eq!( - setup(&sm, &sh, "'\\n'".to_string()).next_token(), - mk_lit(token::Char, "\\n", None), - ); - }) -} - -#[test] -fn lifetime_name() { - with_default_globals(|| { - let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let sh = mk_sess(sm.clone()); - assert_eq!( - setup(&sm, &sh, "'abc".to_string()).next_token(), - token::Lifetime(Symbol::intern("'abc")), - ); - }) -} - -#[test] -fn raw_string() { - with_default_globals(|| { - let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let sh = mk_sess(sm.clone()); - assert_eq!( - setup(&sm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string()).next_token(), - mk_lit(token::StrRaw(3), "\"#a\\b\x00c\"", None), - ); - }) -} - -#[test] -fn literal_suffixes() { - with_default_globals(|| { - let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let sh = mk_sess(sm.clone()); - macro_rules! test { - ($input: expr, $tok_type: ident, $tok_contents: expr) => {{ - assert_eq!( - setup(&sm, &sh, format!("{}suffix", $input)).next_token(), - mk_lit(token::$tok_type, $tok_contents, Some("suffix")), - ); - // with a whitespace separator - assert_eq!( - setup(&sm, &sh, format!("{} suffix", $input)).next_token(), - mk_lit(token::$tok_type, $tok_contents, None), - ); - }} - } - - test!("'a'", Char, "a"); - test!("b'a'", Byte, "a"); - test!("\"a\"", Str, "a"); - test!("b\"a\"", ByteStr, "a"); - test!("1234", Integer, "1234"); - test!("0b101", Integer, "0b101"); - test!("0xABC", Integer, "0xABC"); - test!("1.0", Float, "1.0"); - test!("1.0e10", Float, "1.0e10"); - - assert_eq!( - setup(&sm, &sh, "2us".to_string()).next_token(), - mk_lit(token::Integer, "2", Some("us")), - ); - assert_eq!( - setup(&sm, &sh, "r###\"raw\"###suffix".to_string()).next_token(), - mk_lit(token::StrRaw(3), "raw", Some("suffix")), - ); - assert_eq!( - setup(&sm, &sh, "br###\"raw\"###suffix".to_string()).next_token(), - mk_lit(token::ByteStrRaw(3), "raw", Some("suffix")), - ); - }) -} - -#[test] -fn line_doc_comments() { - assert!(is_doc_comment("///")); - assert!(is_doc_comment("/// blah")); - assert!(!is_doc_comment("////")); -} - -#[test] -fn nested_block_comments() { - with_default_globals(|| { - let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let sh = mk_sess(sm.clone()); - let mut lexer = setup(&sm, &sh, "/* /* */ */'a'".to_string()); - assert_eq!(lexer.next_token(), token::Comment); - assert_eq!(lexer.next_token(), mk_lit(token::Char, "a", None)); - }) -} - -#[test] -fn crlf_comments() { - with_default_globals(|| { - let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let sh = mk_sess(sm.clone()); - let mut lexer = setup(&sm, &sh, "// test\r\n/// test\r\n".to_string()); - let comment = lexer.next_token(); - assert_eq!(comment.kind, token::Comment); - assert_eq!((comment.span.lo(), comment.span.hi()), (BytePos(0), BytePos(7))); - assert_eq!(lexer.next_token(), token::Whitespace); - assert_eq!(lexer.next_token(), token::DocComment(Symbol::intern("/// test"))); - }) -} diff --git a/src/libsyntax/parse/lexer/tokentrees.rs b/src/libsyntax/parse/lexer/tokentrees.rs deleted file mode 100644 index 2b056434d4d..00000000000 --- a/src/libsyntax/parse/lexer/tokentrees.rs +++ /dev/null @@ -1,280 +0,0 @@ -use rustc_data_structures::fx::FxHashMap; -use syntax_pos::Span; - -use super::{StringReader, UnmatchedBrace}; - -use crate::print::pprust::token_to_string; -use crate::token::{self, Token}; -use crate::tokenstream::{DelimSpan, IsJoint::{self, *}, TokenStream, TokenTree, TreeAndJoint}; - -use errors::PResult; - -impl<'a> StringReader<'a> { - crate fn into_token_trees(self) -> (PResult<'a, TokenStream>, Vec<UnmatchedBrace>) { - let mut tt_reader = TokenTreesReader { - string_reader: self, - token: Token::dummy(), - joint_to_prev: Joint, - open_braces: Vec::new(), - unmatched_braces: Vec::new(), - matching_delim_spans: Vec::new(), - last_unclosed_found_span: None, - last_delim_empty_block_spans: FxHashMap::default() - }; - let res = tt_reader.parse_all_token_trees(); - (res, tt_reader.unmatched_braces) - } -} - -struct TokenTreesReader<'a> { - string_reader: StringReader<'a>, - token: Token, - joint_to_prev: IsJoint, - /// Stack of open delimiters and their spans. Used for error message. - open_braces: Vec<(token::DelimToken, Span)>, - unmatched_braces: Vec<UnmatchedBrace>, - /// The type and spans for all braces - /// - /// Used only for error recovery when arriving to EOF with mismatched braces. - matching_delim_spans: Vec<(token::DelimToken, Span, Span)>, - last_unclosed_found_span: Option<Span>, - last_delim_empty_block_spans: FxHashMap<token::DelimToken, Span> -} - -impl<'a> TokenTreesReader<'a> { - // Parse a stream of tokens into a list of `TokenTree`s, up to an `Eof`. - fn parse_all_token_trees(&mut self) -> PResult<'a, TokenStream> { - let mut buf = TokenStreamBuilder::default(); - - self.real_token(); - while self.token != token::Eof { - buf.push(self.parse_token_tree()?); - } - - Ok(buf.into_token_stream()) - } - - // Parse a stream of tokens into a list of `TokenTree`s, up to a `CloseDelim`. - fn parse_token_trees_until_close_delim(&mut self) -> TokenStream { - let mut buf = TokenStreamBuilder::default(); - loop { - if let token::CloseDelim(..) = self.token.kind { - return buf.into_token_stream(); - } - - match self.parse_token_tree() { - Ok(tree) => buf.push(tree), - Err(mut e) => { - e.emit(); - return buf.into_token_stream(); - } - } - } - } - - fn parse_token_tree(&mut self) -> PResult<'a, TreeAndJoint> { - let sm = self.string_reader.sess.source_map(); - match self.token.kind { - token::Eof => { - let msg = "this file contains an un-closed delimiter"; - let mut err = self.string_reader.sess.span_diagnostic - .struct_span_err(self.token.span, msg); - for &(_, sp) in &self.open_braces { - err.span_label(sp, "un-closed delimiter"); - self.unmatched_braces.push(UnmatchedBrace { - expected_delim: token::DelimToken::Brace, - found_delim: None, - found_span: self.token.span, - unclosed_span: Some(sp), - candidate_span: None, - }); - } - - if let Some((delim, _)) = self.open_braces.last() { - if let Some((_, open_sp, close_sp)) = self.matching_delim_spans.iter() - .filter(|(d, open_sp, close_sp)| { - if let Some(close_padding) = sm.span_to_margin(*close_sp) { - if let Some(open_padding) = sm.span_to_margin(*open_sp) { - return delim == d && close_padding != open_padding; - } - } - false - }).next() // these are in reverse order as they get inserted on close, but - { // we want the last open/first close - err.span_label( - *open_sp, - "this delimiter might not be properly closed...", - ); - err.span_label( - *close_sp, - "...as it matches this but it has different indentation", - ); - } - } - Err(err) - }, - token::OpenDelim(delim) => { - // The span for beginning of the delimited section - let pre_span = self.token.span; - - // Parse the open delimiter. - self.open_braces.push((delim, self.token.span)); - self.real_token(); - - // Parse the token trees within the delimiters. - // We stop at any delimiter so we can try to recover if the user - // uses an incorrect delimiter. - let tts = self.parse_token_trees_until_close_delim(); - - // Expand to cover the entire delimited token tree - let delim_span = DelimSpan::from_pair(pre_span, self.token.span); - - match self.token.kind { - // Correct delimiter. - token::CloseDelim(d) if d == delim => { - let (open_brace, open_brace_span) = self.open_braces.pop().unwrap(); - let close_brace_span = self.token.span; - - if tts.is_empty() { - let empty_block_span = open_brace_span.to(close_brace_span); - self.last_delim_empty_block_spans.insert(delim, empty_block_span); - } - - if self.open_braces.len() == 0 { - // Clear up these spans to avoid suggesting them as we've found - // properly matched delimiters so far for an entire block. - self.matching_delim_spans.clear(); - } else { - self.matching_delim_spans.push( - (open_brace, open_brace_span, close_brace_span), - ); - } - // Parse the close delimiter. - self.real_token(); - } - // Incorrect delimiter. - token::CloseDelim(other) => { - let mut unclosed_delimiter = None; - let mut candidate = None; - if self.last_unclosed_found_span != Some(self.token.span) { - // do not complain about the same unclosed delimiter multiple times - self.last_unclosed_found_span = Some(self.token.span); - // This is a conservative error: only report the last unclosed - // delimiter. The previous unclosed delimiters could actually be - // closed! The parser just hasn't gotten to them yet. - if let Some(&(_, sp)) = self.open_braces.last() { - unclosed_delimiter = Some(sp); - }; - if let Some(current_padding) = sm.span_to_margin(self.token.span) { - for (brace, brace_span) in &self.open_braces { - if let Some(padding) = sm.span_to_margin(*brace_span) { - // high likelihood of these two corresponding - if current_padding == padding && brace == &other { - candidate = Some(*brace_span); - } - } - } - } - let (tok, _) = self.open_braces.pop().unwrap(); - self.unmatched_braces.push(UnmatchedBrace { - expected_delim: tok, - found_delim: Some(other), - found_span: self.token.span, - unclosed_span: unclosed_delimiter, - candidate_span: candidate, - }); - } else { - self.open_braces.pop(); - } - - // If the incorrect delimiter matches an earlier opening - // delimiter, then don't consume it (it can be used to - // close the earlier one). Otherwise, consume it. - // E.g., we try to recover from: - // fn foo() { - // bar(baz( - // } // Incorrect delimiter but matches the earlier `{` - if !self.open_braces.iter().any(|&(b, _)| b == other) { - self.real_token(); - } - } - token::Eof => { - // Silently recover, the EOF token will be seen again - // and an error emitted then. Thus we don't pop from - // self.open_braces here. - }, - _ => {} - } - - Ok(TokenTree::Delimited( - delim_span, - delim, - tts.into() - ).into()) - }, - token::CloseDelim(delim) => { - // An unexpected closing delimiter (i.e., there is no - // matching opening delimiter). - let token_str = token_to_string(&self.token); - let msg = format!("unexpected close delimiter: `{}`", token_str); - let mut err = self.string_reader.sess.span_diagnostic - .struct_span_err(self.token.span, &msg); - - if let Some(span) = self.last_delim_empty_block_spans.remove(&delim) { - err.span_label( - span, - "this block is empty, you might have not meant to close it" - ); - } - err.span_label(self.token.span, "unexpected close delimiter"); - Err(err) - }, - _ => { - let tt = TokenTree::Token(self.token.take()); - self.real_token(); - let is_joint = self.joint_to_prev == Joint && self.token.is_op(); - Ok((tt, if is_joint { Joint } else { NonJoint })) - } - } - } - - fn real_token(&mut self) { - self.joint_to_prev = Joint; - loop { - let token = self.string_reader.next_token(); - match token.kind { - token::Whitespace | token::Comment | token::Shebang(_) | token::Unknown(_) => { - self.joint_to_prev = NonJoint; - } - _ => { - self.token = token; - return; - } - } - } - } -} - -#[derive(Default)] -struct TokenStreamBuilder { - buf: Vec<TreeAndJoint>, -} - -impl TokenStreamBuilder { - fn push(&mut self, (tree, joint): TreeAndJoint) { - if let Some((TokenTree::Token(prev_token), Joint)) = self.buf.last() { - if let TokenTree::Token(token) = &tree { - if let Some(glued) = prev_token.glue(token) { - self.buf.pop(); - self.buf.push((TokenTree::Token(glued), joint)); - return; - } - } - } - self.buf.push((tree, joint)) - } - - fn into_token_stream(self) -> TokenStream { - TokenStream::new(self.buf) - } -} diff --git a/src/libsyntax/parse/lexer/unescape_error_reporting.rs b/src/libsyntax/parse/lexer/unescape_error_reporting.rs deleted file mode 100644 index 5565015179c..00000000000 --- a/src/libsyntax/parse/lexer/unescape_error_reporting.rs +++ /dev/null @@ -1,215 +0,0 @@ -//! Utilities for rendering escape sequence errors as diagnostics. - -use std::ops::Range; -use std::iter::once; - -use rustc_lexer::unescape::{EscapeError, Mode}; -use syntax_pos::{Span, BytePos}; - -use crate::errors::{Handler, Applicability}; - -pub(crate) fn emit_unescape_error( - handler: &Handler, - // interior part of the literal, without quotes - lit: &str, - // full span of the literal, including quotes - span_with_quotes: Span, - mode: Mode, - // range of the error inside `lit` - range: Range<usize>, - error: EscapeError, -) { - log::debug!("emit_unescape_error: {:?}, {:?}, {:?}, {:?}, {:?}", - lit, span_with_quotes, mode, range, error); - let span = { - let Range { start, end } = range; - let (start, end) = (start as u32, end as u32); - let lo = span_with_quotes.lo() + BytePos(start + 1); - let hi = lo + BytePos(end - start); - span_with_quotes - .with_lo(lo) - .with_hi(hi) - }; - let last_char = || { - let c = lit[range.clone()].chars().rev().next().unwrap(); - let span = span.with_lo(span.hi() - BytePos(c.len_utf8() as u32)); - (c, span) - }; - match error { - EscapeError::LoneSurrogateUnicodeEscape => { - handler.struct_span_err(span, "invalid unicode character escape") - .help("unicode escape must not be a surrogate") - .emit(); - } - EscapeError::OutOfRangeUnicodeEscape => { - handler.struct_span_err(span, "invalid unicode character escape") - .help("unicode escape must be at most 10FFFF") - .emit(); - } - EscapeError::MoreThanOneChar => { - let msg = if mode.is_bytes() { - "if you meant to write a byte string literal, use double quotes" - } else { - "if you meant to write a `str` literal, use double quotes" - }; - - handler - .struct_span_err( - span_with_quotes, - "character literal may only contain one codepoint", - ) - .span_suggestion( - span_with_quotes, - msg, - format!("\"{}\"", lit), - Applicability::MachineApplicable, - ).emit() - } - EscapeError::EscapeOnlyChar => { - let (c, _span) = last_char(); - - let mut msg = if mode.is_bytes() { - "byte constant must be escaped: " - } else { - "character constant must be escaped: " - }.to_string(); - push_escaped_char(&mut msg, c); - - handler.span_err(span, msg.as_str()) - } - EscapeError::BareCarriageReturn => { - let msg = if mode.in_double_quotes() { - "bare CR not allowed in string, use \\r instead" - } else { - "character constant must be escaped: \\r" - }; - handler.span_err(span, msg); - } - EscapeError::BareCarriageReturnInRawString => { - assert!(mode.in_double_quotes()); - let msg = "bare CR not allowed in raw string"; - handler.span_err(span, msg); - } - EscapeError::InvalidEscape => { - let (c, span) = last_char(); - - let label = if mode.is_bytes() { - "unknown byte escape" - } else { - "unknown character escape" - }; - let mut msg = label.to_string(); - msg.push_str(": "); - push_escaped_char(&mut msg, c); - - let mut diag = handler.struct_span_err(span, msg.as_str()); - diag.span_label(span, label); - if c == '{' || c == '}' && !mode.is_bytes() { - diag.help("if used in a formatting string, \ - curly braces are escaped with `{{` and `}}`"); - } else if c == '\r' { - diag.help("this is an isolated carriage return; \ - consider checking your editor and version control settings"); - } - diag.emit(); - } - EscapeError::TooShortHexEscape => { - handler.span_err(span, "numeric character escape is too short") - } - EscapeError::InvalidCharInHexEscape | EscapeError::InvalidCharInUnicodeEscape => { - let (c, span) = last_char(); - - let mut msg = if error == EscapeError::InvalidCharInHexEscape { - "invalid character in numeric character escape: " - } else { - "invalid character in unicode escape: " - }.to_string(); - push_escaped_char(&mut msg, c); - - handler.span_err(span, msg.as_str()) - } - EscapeError::NonAsciiCharInByte => { - assert!(mode.is_bytes()); - let (_c, span) = last_char(); - handler.span_err(span, "byte constant must be ASCII. \ - Use a \\xHH escape for a non-ASCII byte") - } - EscapeError::NonAsciiCharInByteString => { - assert!(mode.is_bytes()); - let (_c, span) = last_char(); - handler.span_err(span, "raw byte string must be ASCII") - } - EscapeError::OutOfRangeHexEscape => { - handler.span_err(span, "this form of character escape may only be used \ - with characters in the range [\\x00-\\x7f]") - } - EscapeError::LeadingUnderscoreUnicodeEscape => { - let (_c, span) = last_char(); - handler.span_err(span, "invalid start of unicode escape") - } - EscapeError::OverlongUnicodeEscape => { - handler.span_err(span, "overlong unicode escape (must have at most 6 hex digits)") - } - EscapeError::UnclosedUnicodeEscape => { - handler.span_err(span, "unterminated unicode escape (needed a `}`)") - } - EscapeError::NoBraceInUnicodeEscape => { - let msg = "incorrect unicode escape sequence"; - let mut diag = handler.struct_span_err(span, msg); - - let mut suggestion = "\\u{".to_owned(); - let mut suggestion_len = 0; - let (c, char_span) = last_char(); - let chars = once(c).chain(lit[range.end..].chars()); - for c in chars.take(6).take_while(|c| c.is_digit(16)) { - suggestion.push(c); - suggestion_len += c.len_utf8(); - } - - if suggestion_len > 0 { - suggestion.push('}'); - let lo = char_span.lo(); - let hi = lo + BytePos(suggestion_len as u32); - diag.span_suggestion( - span.with_lo(lo).with_hi(hi), - "format of unicode escape sequences uses braces", - suggestion, - Applicability::MaybeIncorrect, - ); - } else { - diag.span_label(span, msg); - diag.help( - "format of unicode escape sequences is `\\u{...}`", - ); - } - - diag.emit(); - } - EscapeError::UnicodeEscapeInByte => { - handler.span_err(span, "unicode escape sequences cannot be used \ - as a byte or in a byte string") - } - EscapeError::EmptyUnicodeEscape => { - handler.span_err(span, "empty unicode escape (must have at least 1 hex digit)") - } - EscapeError::ZeroChars => { - handler.span_err(span, "empty character literal") - } - EscapeError::LoneSlash => { - handler.span_err(span, "invalid trailing slash in literal") - } - } -} - -/// Pushes a character to a message string for error reporting -pub(crate) fn push_escaped_char(msg: &mut String, c: char) { - match c { - '\u{20}'..='\u{7e}' => { - // Don't escape \, ' or " for user-facing messages - msg.push(c); - } - _ => { - msg.extend(c.escape_default()); - } - } -} diff --git a/src/libsyntax/parse/lexer/unicode_chars.rs b/src/libsyntax/parse/lexer/unicode_chars.rs deleted file mode 100644 index 6eb995b61d3..00000000000 --- a/src/libsyntax/parse/lexer/unicode_chars.rs +++ /dev/null @@ -1,392 +0,0 @@ -// Characters and their corresponding confusables were collected from -// http://www.unicode.org/Public/security/10.0.0/confusables.txt - -use super::StringReader; -use errors::{Applicability, DiagnosticBuilder}; -use syntax_pos::{BytePos, Pos, Span, symbol::kw}; -use crate::token; - -#[rustfmt::skip] // for line breaks -const UNICODE_ARRAY: &[(char, &str, char)] = &[ - (' ', "Line Separator", ' '), - (' ', "Paragraph Separator", ' '), - (' ', "Ogham Space mark", ' '), - (' ', "En Quad", ' '), - (' ', "Em Quad", ' '), - (' ', "En Space", ' '), - (' ', "Em Space", ' '), - (' ', "Three-Per-Em Space", ' '), - (' ', "Four-Per-Em Space", ' '), - (' ', "Six-Per-Em Space", ' '), - (' ', "Punctuation Space", ' '), - (' ', "Thin Space", ' '), - (' ', "Hair Space", ' '), - (' ', "Medium Mathematical Space", ' '), - (' ', "No-Break Space", ' '), - (' ', "Figure Space", ' '), - (' ', "Narrow No-Break Space", ' '), - (' ', "Ideographic Space", ' '), - - ('ߺ', "Nko Lajanyalan", '_'), - ('﹍', "Dashed Low Line", '_'), - ('﹎', "Centreline Low Line", '_'), - ('﹏', "Wavy Low Line", '_'), - ('_', "Fullwidth Low Line", '_'), - - ('‐', "Hyphen", '-'), - ('‑', "Non-Breaking Hyphen", '-'), - ('‒', "Figure Dash", '-'), - ('–', "En Dash", '-'), - ('—', "Em Dash", '-'), - ('﹘', "Small Em Dash", '-'), - ('۔', "Arabic Full Stop", '-'), - ('⁃', "Hyphen Bullet", '-'), - ('˗', "Modifier Letter Minus Sign", '-'), - ('−', "Minus Sign", '-'), - ('➖', "Heavy Minus Sign", '-'), - ('Ⲻ', "Coptic Letter Dialect-P Ni", '-'), - ('ー', "Katakana-Hiragana Prolonged Sound Mark", '-'), - ('-', "Fullwidth Hyphen-Minus", '-'), - ('―', "Horizontal Bar", '-'), - ('─', "Box Drawings Light Horizontal", '-'), - ('━', "Box Drawings Heavy Horizontal", '-'), - ('㇐', "CJK Stroke H", '-'), - ('ꟷ', "Latin Epigraphic Letter Sideways I", '-'), - ('ᅳ', "Hangul Jungseong Eu", '-'), - ('ㅡ', "Hangul Letter Eu", '-'), - ('一', "CJK Unified Ideograph-4E00", '-'), - ('⼀', "Kangxi Radical One", '-'), - - ('؍', "Arabic Date Separator", ','), - ('٫', "Arabic Decimal Separator", ','), - ('‚', "Single Low-9 Quotation Mark", ','), - ('¸', "Cedilla", ','), - ('ꓹ', "Lisu Letter Tone Na Po", ','), - (',', "Fullwidth Comma", ','), - - (';', "Greek Question Mark", ';'), - (';', "Fullwidth Semicolon", ';'), - ('︔', "Presentation Form For Vertical Semicolon", ';'), - - ('ः', "Devanagari Sign Visarga", ':'), - ('ઃ', "Gujarati Sign Visarga", ':'), - (':', "Fullwidth Colon", ':'), - ('։', "Armenian Full Stop", ':'), - ('܃', "Syriac Supralinear Colon", ':'), - ('܄', "Syriac Sublinear Colon", ':'), - ('᛬', "Runic Multiple Punctuation", ':'), - ('︰', "Presentation Form For Vertical Two Dot Leader", ':'), - ('᠃', "Mongolian Full Stop", ':'), - ('᠉', "Mongolian Manchu Full Stop", ':'), - ('⁚', "Two Dot Punctuation", ':'), - ('׃', "Hebrew Punctuation Sof Pasuq", ':'), - ('˸', "Modifier Letter Raised Colon", ':'), - ('꞉', "Modifier Letter Colon", ':'), - ('∶', "Ratio", ':'), - ('ː', "Modifier Letter Triangular Colon", ':'), - ('ꓽ', "Lisu Letter Tone Mya Jeu", ':'), - ('︓', "Presentation Form For Vertical Colon", ':'), - - ('!', "Fullwidth Exclamation Mark", '!'), - ('ǃ', "Latin Letter Retroflex Click", '!'), - ('ⵑ', "Tifinagh Letter Tuareg Yang", '!'), - ('︕', "Presentation Form For Vertical Exclamation Mark", '!'), - - ('ʔ', "Latin Letter Glottal Stop", '?'), - ('Ɂ', "Latin Capital Letter Glottal Stop", '?'), - ('ॽ', "Devanagari Letter Glottal Stop", '?'), - ('Ꭾ', "Cherokee Letter He", '?'), - ('ꛫ', "Bamum Letter Ntuu", '?'), - ('?', "Fullwidth Question Mark", '?'), - ('︖', "Presentation Form For Vertical Question Mark", '?'), - - ('𝅭', "Musical Symbol Combining Augmentation Dot", '.'), - ('․', "One Dot Leader", '.'), - ('܁', "Syriac Supralinear Full Stop", '.'), - ('܂', "Syriac Sublinear Full Stop", '.'), - ('꘎', "Vai Full Stop", '.'), - ('𐩐', "Kharoshthi Punctuation Dot", '.'), - ('٠', "Arabic-Indic Digit Zero", '.'), - ('۰', "Extended Arabic-Indic Digit Zero", '.'), - ('ꓸ', "Lisu Letter Tone Mya Ti", '.'), - ('·', "Middle Dot", '.'), - ('・', "Katakana Middle Dot", '.'), - ('・', "Halfwidth Katakana Middle Dot", '.'), - ('᛫', "Runic Single Punctuation", '.'), - ('·', "Greek Ano Teleia", '.'), - ('⸱', "Word Separator Middle Dot", '.'), - ('𐄁', "Aegean Word Separator Dot", '.'), - ('•', "Bullet", '.'), - ('‧', "Hyphenation Point", '.'), - ('∙', "Bullet Operator", '.'), - ('⋅', "Dot Operator", '.'), - ('ꞏ', "Latin Letter Sinological Dot", '.'), - ('ᐧ', "Canadian Syllabics Final Middle Dot", '.'), - ('ᐧ', "Canadian Syllabics Final Middle Dot", '.'), - ('.', "Fullwidth Full Stop", '.'), - ('。', "Ideographic Full Stop", '.'), - ('︒', "Presentation Form For Vertical Ideographic Full Stop", '.'), - - ('՝', "Armenian Comma", '\''), - (''', "Fullwidth Apostrophe", '\''), - ('‘', "Left Single Quotation Mark", '\''), - ('’', "Right Single Quotation Mark", '\''), - ('‛', "Single High-Reversed-9 Quotation Mark", '\''), - ('′', "Prime", '\''), - ('‵', "Reversed Prime", '\''), - ('՚', "Armenian Apostrophe", '\''), - ('׳', "Hebrew Punctuation Geresh", '\''), - ('`', "Grave Accent", '\''), - ('`', "Greek Varia", '\''), - ('`', "Fullwidth Grave Accent", '\''), - ('´', "Acute Accent", '\''), - ('΄', "Greek Tonos", '\''), - ('´', "Greek Oxia", '\''), - ('᾽', "Greek Koronis", '\''), - ('᾿', "Greek Psili", '\''), - ('῾', "Greek Dasia", '\''), - ('ʹ', "Modifier Letter Prime", '\''), - ('ʹ', "Greek Numeral Sign", '\''), - ('ˈ', "Modifier Letter Vertical Line", '\''), - ('ˊ', "Modifier Letter Acute Accent", '\''), - ('ˋ', "Modifier Letter Grave Accent", '\''), - ('˴', "Modifier Letter Middle Grave Accent", '\''), - ('ʻ', "Modifier Letter Turned Comma", '\''), - ('ʽ', "Modifier Letter Reversed Comma", '\''), - ('ʼ', "Modifier Letter Apostrophe", '\''), - ('ʾ', "Modifier Letter Right Half Ring", '\''), - ('ꞌ', "Latin Small Letter Saltillo", '\''), - ('י', "Hebrew Letter Yod", '\''), - ('ߴ', "Nko High Tone Apostrophe", '\''), - ('ߵ', "Nko Low Tone Apostrophe", '\''), - ('ᑊ', "Canadian Syllabics West-Cree P", '\''), - ('ᛌ', "Runic Letter Short-Twig-Sol S", '\''), - ('𖽑', "Miao Sign Aspiration", '\''), - ('𖽒', "Miao Sign Reformed Voicing", '\''), - - ('᳓', "Vedic Sign Nihshvasa", '"'), - ('"', "Fullwidth Quotation Mark", '"'), - ('“', "Left Double Quotation Mark", '"'), - ('”', "Right Double Quotation Mark", '"'), - ('‟', "Double High-Reversed-9 Quotation Mark", '"'), - ('″', "Double Prime", '"'), - ('‶', "Reversed Double Prime", '"'), - ('〃', "Ditto Mark", '"'), - ('״', "Hebrew Punctuation Gershayim", '"'), - ('˝', "Double Acute Accent", '"'), - ('ʺ', "Modifier Letter Double Prime", '"'), - ('˶', "Modifier Letter Middle Double Acute Accent", '"'), - ('˵', "Modifier Letter Middle Double Grave Accent", '"'), - ('ˮ', "Modifier Letter Double Apostrophe", '"'), - ('ײ', "Hebrew Ligature Yiddish Double Yod", '"'), - ('❞', "Heavy Double Comma Quotation Mark Ornament", '"'), - ('❝', "Heavy Double Turned Comma Quotation Mark Ornament", '"'), - - ('(', "Fullwidth Left Parenthesis", '('), - ('❨', "Medium Left Parenthesis Ornament", '('), - ('﴾', "Ornate Left Parenthesis", '('), - - (')', "Fullwidth Right Parenthesis", ')'), - ('❩', "Medium Right Parenthesis Ornament", ')'), - ('﴿', "Ornate Right Parenthesis", ')'), - - ('[', "Fullwidth Left Square Bracket", '['), - ('❲', "Light Left Tortoise Shell Bracket Ornament", '['), - ('「', "Left Corner Bracket", '['), - ('『', "Left White Corner Bracket", '['), - ('【', "Left Black Lenticular Bracket", '['), - ('〔', "Left Tortoise Shell Bracket", '['), - ('〖', "Left White Lenticular Bracket", '['), - ('〘', "Left White Tortoise Shell Bracket", '['), - ('〚', "Left White Square Bracket", '['), - - (']', "Fullwidth Right Square Bracket", ']'), - ('❳', "Light Right Tortoise Shell Bracket Ornament", ']'), - ('」', "Right Corner Bracket", ']'), - ('』', "Right White Corner Bracket", ']'), - ('】', "Right Black Lenticular Bracket", ']'), - ('〕', "Right Tortoise Shell Bracket", ']'), - ('〗', "Right White Lenticular Bracket", ']'), - ('〙', "Right White Tortoise Shell Bracket", ']'), - ('〛', "Right White Square Bracket", ']'), - - ('❴', "Medium Left Curly Bracket Ornament", '{'), - ('𝄔', "Musical Symbol Brace", '{'), - ('{', "Fullwidth Left Curly Bracket", '{'), - - ('❵', "Medium Right Curly Bracket Ornament", '}'), - ('}', "Fullwidth Right Curly Bracket", '}'), - - ('⁎', "Low Asterisk", '*'), - ('٭', "Arabic Five Pointed Star", '*'), - ('∗', "Asterisk Operator", '*'), - ('𐌟', "Old Italic Letter Ess", '*'), - ('*', "Fullwidth Asterisk", '*'), - - ('᜵', "Philippine Single Punctuation", '/'), - ('⁁', "Caret Insertion Point", '/'), - ('∕', "Division Slash", '/'), - ('⁄', "Fraction Slash", '/'), - ('╱', "Box Drawings Light Diagonal Upper Right To Lower Left", '/'), - ('⟋', "Mathematical Rising Diagonal", '/'), - ('⧸', "Big Solidus", '/'), - ('𝈺', "Greek Instrumental Notation Symbol-47", '/'), - ('㇓', "CJK Stroke Sp", '/'), - ('〳', "Vertical Kana Repeat Mark Upper Half", '/'), - ('Ⳇ', "Coptic Capital Letter Old Coptic Esh", '/'), - ('ノ', "Katakana Letter No", '/'), - ('丿', "CJK Unified Ideograph-4E3F", '/'), - ('⼃', "Kangxi Radical Slash", '/'), - ('/', "Fullwidth Solidus", '/'), - - ('\', "Fullwidth Reverse Solidus", '\\'), - ('﹨', "Small Reverse Solidus", '\\'), - ('∖', "Set Minus", '\\'), - ('⟍', "Mathematical Falling Diagonal", '\\'), - ('⧵', "Reverse Solidus Operator", '\\'), - ('⧹', "Big Reverse Solidus", '\\'), - ('⧹', "Greek Vocal Notation Symbol-16", '\\'), - ('⧹', "Greek Instrumental Symbol-48", '\\'), - ('㇔', "CJK Stroke D", '\\'), - ('丶', "CJK Unified Ideograph-4E36", '\\'), - ('⼂', "Kangxi Radical Dot", '\\'), - ('、', "Ideographic Comma", '\\'), - ('ヽ', "Katakana Iteration Mark", '\\'), - - ('ꝸ', "Latin Small Letter Um", '&'), - ('&', "Fullwidth Ampersand", '&'), - - ('᛭', "Runic Cross Punctuation", '+'), - ('➕', "Heavy Plus Sign", '+'), - ('𐊛', "Lycian Letter H", '+'), - ('﬩', "Hebrew Letter Alternative Plus Sign", '+'), - ('+', "Fullwidth Plus Sign", '+'), - - ('‹', "Single Left-Pointing Angle Quotation Mark", '<'), - ('❮', "Heavy Left-Pointing Angle Quotation Mark Ornament", '<'), - ('˂', "Modifier Letter Left Arrowhead", '<'), - ('𝈶', "Greek Instrumental Symbol-40", '<'), - ('ᐸ', "Canadian Syllabics Pa", '<'), - ('ᚲ', "Runic Letter Kauna", '<'), - ('❬', "Medium Left-Pointing Angle Bracket Ornament", '<'), - ('⟨', "Mathematical Left Angle Bracket", '<'), - ('〈', "Left-Pointing Angle Bracket", '<'), - ('〈', "Left Angle Bracket", '<'), - ('㇛', "CJK Stroke Pd", '<'), - ('く', "Hiragana Letter Ku", '<'), - ('𡿨', "CJK Unified Ideograph-21FE8", '<'), - ('《', "Left Double Angle Bracket", '<'), - ('<', "Fullwidth Less-Than Sign", '<'), - - ('᐀', "Canadian Syllabics Hyphen", '='), - ('⹀', "Double Hyphen", '='), - ('゠', "Katakana-Hiragana Double Hyphen", '='), - ('꓿', "Lisu Punctuation Full Stop", '='), - ('=', "Fullwidth Equals Sign", '='), - - ('›', "Single Right-Pointing Angle Quotation Mark", '>'), - ('❯', "Heavy Right-Pointing Angle Quotation Mark Ornament", '>'), - ('˃', "Modifier Letter Right Arrowhead", '>'), - ('𝈷', "Greek Instrumental Symbol-42", '>'), - ('ᐳ', "Canadian Syllabics Po", '>'), - ('𖼿', "Miao Letter Archaic Zza", '>'), - ('❭', "Medium Right-Pointing Angle Bracket Ornament", '>'), - ('⟩', "Mathematical Right Angle Bracket", '>'), - ('〉', "Right-Pointing Angle Bracket", '>'), - ('〉', "Right Angle Bracket", '>'), - ('》', "Right Double Angle Bracket", '>'), - ('>', "Fullwidth Greater-Than Sign", '>'), -]; - -// FIXME: the lexer could be used to turn the ASCII version of unicode homoglyphs, instead of -// keeping the substitution token in this table. Ideally, this should be inside `rustc_lexer`. -// However, we should first remove compound tokens like `<<` from `rustc_lexer`, and then add -// fancier error recovery to it, as there will be less overall work to do this way. -const ASCII_ARRAY: &[(char, &str, Option<token::TokenKind>)] = &[ - (' ', "Space", Some(token::Whitespace)), - ('_', "Underscore", Some(token::Ident(kw::Underscore, false))), - ('-', "Minus/Hyphen", Some(token::BinOp(token::Minus))), - (',', "Comma", Some(token::Comma)), - (';', "Semicolon", Some(token::Semi)), - (':', "Colon", Some(token::Colon)), - ('!', "Exclamation Mark", Some(token::Not)), - ('?', "Question Mark", Some(token::Question)), - ('.', "Period", Some(token::Dot)), - ('(', "Left Parenthesis", Some(token::OpenDelim(token::Paren))), - (')', "Right Parenthesis", Some(token::CloseDelim(token::Paren))), - ('[', "Left Square Bracket", Some(token::OpenDelim(token::Bracket))), - (']', "Right Square Bracket", Some(token::CloseDelim(token::Bracket))), - ('{', "Left Curly Brace", Some(token::OpenDelim(token::Brace))), - ('}', "Right Curly Brace", Some(token::CloseDelim(token::Brace))), - ('*', "Asterisk", Some(token::BinOp(token::Star))), - ('/', "Slash", Some(token::BinOp(token::Slash))), - ('\\', "Backslash", None), - ('&', "Ampersand", Some(token::BinOp(token::And))), - ('+', "Plus Sign", Some(token::BinOp(token::Plus))), - ('<', "Less-Than Sign", Some(token::Lt)), - ('=', "Equals Sign", Some(token::Eq)), - ('>', "Greater-Than Sign", Some(token::Gt)), - // FIXME: Literals are already lexed by this point, so we can't recover gracefully just by - // spitting the correct token out. - ('\'', "Single Quote", None), - ('"', "Quotation Mark", None), -]; - -crate fn check_for_substitution<'a>( - reader: &StringReader<'a>, - pos: BytePos, - ch: char, - err: &mut DiagnosticBuilder<'a>, -) -> Option<token::TokenKind> { - let (u_name, ascii_char) = match UNICODE_ARRAY.iter().find(|&&(c, _, _)| c == ch) { - Some(&(_u_char, u_name, ascii_char)) => (u_name, ascii_char), - None => return None, - }; - - let span = Span::with_root_ctxt(pos, pos + Pos::from_usize(ch.len_utf8())); - - let (ascii_name, token) = match ASCII_ARRAY.iter().find(|&&(c, _, _)| c == ascii_char) { - Some((_ascii_char, ascii_name, token)) => (ascii_name, token), - None => { - let msg = format!("substitution character not found for '{}'", ch); - reader.sess.span_diagnostic.span_bug_no_panic(span, &msg); - return None; - } - }; - - // special help suggestion for "directed" double quotes - if let Some(s) = peek_delimited(&reader.src[reader.src_index(pos)..], '“', '”') { - let msg = format!( - "Unicode characters '“' (Left Double Quotation Mark) and \ - '”' (Right Double Quotation Mark) look like '{}' ({}), but are not", - ascii_char, ascii_name - ); - err.span_suggestion( - Span::with_root_ctxt( - pos, - pos + Pos::from_usize('“'.len_utf8() + s.len() + '”'.len_utf8()), - ), - &msg, - format!("\"{}\"", s), - Applicability::MaybeIncorrect, - ); - } else { - let msg = format!( - "Unicode character '{}' ({}) looks like '{}' ({}), but it is not", - ch, u_name, ascii_char, ascii_name - ); - err.span_suggestion(span, &msg, ascii_char.to_string(), Applicability::MaybeIncorrect); - } - token.clone() -} - -/// Extract string if found at current position with given delimiters -fn peek_delimited(text: &str, from_ch: char, to_ch: char) -> Option<&str> { - let mut chars = text.chars(); - let first_char = chars.next()?; - if first_char != from_ch { - return None; - } - let last_char_idx = chars.as_str().find(to_ch)?; - Some(&chars.as_str()[..last_char_idx]) -} diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs deleted file mode 100644 index b54f4862f12..00000000000 --- a/src/libsyntax/parse/mod.rs +++ /dev/null @@ -1,420 +0,0 @@ -//! The main parser interface. - -use crate::ast; -use crate::parse::parser::{Parser, emit_unclosed_delims, make_unclosed_delims_error}; -use crate::token::{self, Nonterminal}; -use crate::tokenstream::{self, TokenStream, TokenTree}; -use crate::print::pprust; -use crate::sess::ParseSess; - -use errors::{PResult, FatalError, Level, Diagnostic}; -use rustc_data_structures::sync::Lrc; -use syntax_pos::{Span, SourceFile, FileName}; - -use std::borrow::Cow; -use std::path::Path; -use std::str; - -use log::info; - -#[cfg(test)] -mod tests; - -#[macro_use] -pub mod parser; -pub mod lexer; - -#[derive(Clone)] -pub struct Directory<'a> { - pub path: Cow<'a, Path>, - pub ownership: DirectoryOwnership, -} - -#[derive(Copy, Clone)] -pub enum DirectoryOwnership { - Owned { - // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`. - relative: Option<ast::Ident>, - }, - UnownedViaBlock, - UnownedViaMod, -} - -// A bunch of utility functions of the form `parse_<thing>_from_<source>` -// where <thing> includes crate, expr, item, stmt, tts, and one that -// uses a HOF to parse anything, and <source> includes file and -// `source_str`. - -/// A variant of 'panictry!' that works on a Vec<Diagnostic> instead of a single DiagnosticBuilder. -macro_rules! panictry_buffer { - ($handler:expr, $e:expr) => ({ - use std::result::Result::{Ok, Err}; - use errors::FatalError; - match $e { - Ok(e) => e, - Err(errs) => { - for e in errs { - $handler.emit_diagnostic(&e); - } - FatalError.raise() - } - } - }) -} - -pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> { - let mut parser = new_parser_from_file(sess, input); - parser.parse_crate_mod() -} - -pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess) - -> PResult<'a, Vec<ast::Attribute>> { - let mut parser = new_parser_from_file(sess, input); - parser.parse_inner_attributes() -} - -pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess) - -> PResult<'_, ast::Crate> { - new_parser_from_source_str(sess, name, source).parse_crate_mod() -} - -pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess) - -> PResult<'_, Vec<ast::Attribute>> { - new_parser_from_source_str(sess, name, source).parse_inner_attributes() -} - -pub fn parse_stream_from_source_str( - name: FileName, - source: String, - sess: &ParseSess, - override_span: Option<Span>, -) -> TokenStream { - let (stream, mut errors) = source_file_to_stream( - sess, - sess.source_map().new_source_file(name, source), - override_span, - ); - emit_unclosed_delims(&mut errors, &sess); - stream -} - -/// Creates a new parser from a source string. -pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> { - panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source)) -} - -/// Creates a new parser from a source string. Returns any buffered errors from lexing the initial -/// token stream. -pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) - -> Result<Parser<'_>, Vec<Diagnostic>> -{ - let mut parser = maybe_source_file_to_parser(sess, - sess.source_map().new_source_file(name, source))?; - parser.recurse_into_file_modules = false; - Ok(parser) -} - -/// Creates a new parser, handling errors as appropriate if the file doesn't exist. -pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> { - source_file_to_parser(sess, file_to_source_file(sess, path, None)) -} - -/// Creates a new parser, returning buffered diagnostics if the file doesn't exist, -/// or from lexing the initial token stream. -pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) - -> Result<Parser<'a>, Vec<Diagnostic>> { - let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?; - maybe_source_file_to_parser(sess, file) -} - -/// Given a session, a crate config, a path, and a span, add -/// the file at the given path to the `source_map`, and returns a parser. -/// On an error, uses the given span as the source of the problem. -pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess, - path: &Path, - directory_ownership: DirectoryOwnership, - module_name: Option<String>, - sp: Span) -> Parser<'a> { - let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp))); - p.directory.ownership = directory_ownership; - p.root_module_name = module_name; - p -} - -/// Given a `source_file` and config, returns a parser. -fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> { - panictry_buffer!(&sess.span_diagnostic, - maybe_source_file_to_parser(sess, source_file)) -} - -/// Given a `source_file` and config, return a parser. Returns any buffered errors from lexing the -/// initial token stream. -fn maybe_source_file_to_parser( - sess: &ParseSess, - source_file: Lrc<SourceFile>, -) -> Result<Parser<'_>, Vec<Diagnostic>> { - let end_pos = source_file.end_pos; - let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?; - let mut parser = stream_to_parser(sess, stream, None); - parser.unclosed_delims = unclosed_delims; - if parser.token == token::Eof && parser.token.span.is_dummy() { - parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt()); - } - - Ok(parser) -} - -// Must preserve old name for now, because `quote!` from the *existing* -// compiler expands into it. -pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> { - stream_to_parser(sess, tts.into_iter().collect(), crate::MACRO_ARGUMENTS) -} - - -// Base abstractions - -/// Given a session and a path and an optional span (for error reporting), -/// add the path to the session's source_map and return the new source_file or -/// error when a file can't be read. -fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) - -> Result<Lrc<SourceFile>, Diagnostic> { - sess.source_map().load_file(path) - .map_err(|e| { - let msg = format!("couldn't read {}: {}", path.display(), e); - let mut diag = Diagnostic::new(Level::Fatal, &msg); - if let Some(sp) = spanopt { - diag.set_span(sp); - } - diag - }) -} - -/// Given a session and a path and an optional span (for error reporting), -/// adds the path to the session's `source_map` and returns the new `source_file`. -fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) - -> Lrc<SourceFile> { - match try_file_to_source_file(sess, path, spanopt) { - Ok(source_file) => source_file, - Err(d) => { - sess.span_diagnostic.emit_diagnostic(&d); - FatalError.raise(); - } - } -} - -/// Given a `source_file`, produces a sequence of token trees. -pub fn source_file_to_stream( - sess: &ParseSess, - source_file: Lrc<SourceFile>, - override_span: Option<Span>, -) -> (TokenStream, Vec<lexer::UnmatchedBrace>) { - panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span)) -} - -/// Given a source file, produces a sequence of token trees. Returns any buffered errors from -/// parsing the token stream. -pub fn maybe_file_to_stream( - sess: &ParseSess, - source_file: Lrc<SourceFile>, - override_span: Option<Span>, -) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> { - let srdr = lexer::StringReader::new(sess, source_file, override_span); - let (token_trees, unmatched_braces) = srdr.into_token_trees(); - - match token_trees { - Ok(stream) => Ok((stream, unmatched_braces)), - Err(err) => { - let mut buffer = Vec::with_capacity(1); - err.buffer(&mut buffer); - // Not using `emit_unclosed_delims` to use `db.buffer` - for unmatched in unmatched_braces { - if let Some(err) = make_unclosed_delims_error(unmatched, &sess) { - err.buffer(&mut buffer); - } - } - Err(buffer) - } - } -} - -/// Given a stream and the `ParseSess`, produces a parser. -pub fn stream_to_parser<'a>( - sess: &'a ParseSess, - stream: TokenStream, - subparser_name: Option<&'static str>, -) -> Parser<'a> { - Parser::new(sess, stream, None, true, false, subparser_name) -} - -/// Given a stream, the `ParseSess` and the base directory, produces a parser. -/// -/// Use this function when you are creating a parser from the token stream -/// and also care about the current working directory of the parser (e.g., -/// you are trying to resolve modules defined inside a macro invocation). -/// -/// # Note -/// -/// The main usage of this function is outside of rustc, for those who uses -/// libsyntax as a library. Please do not remove this function while refactoring -/// just because it is not used in rustc codebase! -pub fn stream_to_parser_with_base_dir<'a>( - sess: &'a ParseSess, - stream: TokenStream, - base_dir: Directory<'a>, -) -> Parser<'a> { - Parser::new(sess, stream, Some(base_dir), true, false, None) -} - -/// Runs the given subparser `f` on the tokens of the given `attr`'s item. -pub fn parse_in_attr<'a, T>( - sess: &'a ParseSess, - attr: &ast::Attribute, - mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, -) -> PResult<'a, T> { - let mut parser = Parser::new( - sess, - attr.get_normal_item().tokens.clone(), - None, - false, - false, - Some("attribute"), - ); - let result = f(&mut parser)?; - if parser.token != token::Eof { - parser.unexpected()?; - } - Ok(result) -} - -// NOTE(Centril): The following probably shouldn't be here but it acknowledges the -// fact that architecturally, we are using parsing (read on below to understand why). - -pub fn nt_to_tokenstream(nt: &Nonterminal, sess: &ParseSess, span: Span) -> TokenStream { - // A `Nonterminal` is often a parsed AST item. At this point we now - // need to convert the parsed AST to an actual token stream, e.g. - // un-parse it basically. - // - // Unfortunately there's not really a great way to do that in a - // guaranteed lossless fashion right now. The fallback here is to just - // stringify the AST node and reparse it, but this loses all span - // information. - // - // As a result, some AST nodes are annotated with the token stream they - // came from. Here we attempt to extract these lossless token streams - // before we fall back to the stringification. - let tokens = match *nt { - Nonterminal::NtItem(ref item) => { - prepend_attrs(sess, &item.attrs, item.tokens.as_ref(), span) - } - Nonterminal::NtTraitItem(ref item) => { - prepend_attrs(sess, &item.attrs, item.tokens.as_ref(), span) - } - Nonterminal::NtImplItem(ref item) => { - prepend_attrs(sess, &item.attrs, item.tokens.as_ref(), span) - } - Nonterminal::NtIdent(ident, is_raw) => { - Some(tokenstream::TokenTree::token(token::Ident(ident.name, is_raw), ident.span).into()) - } - Nonterminal::NtLifetime(ident) => { - Some(tokenstream::TokenTree::token(token::Lifetime(ident.name), ident.span).into()) - } - Nonterminal::NtTT(ref tt) => { - Some(tt.clone().into()) - } - _ => None, - }; - - // FIXME(#43081): Avoid this pretty-print + reparse hack - let source = pprust::nonterminal_to_string(nt); - let filename = FileName::macro_expansion_source_code(&source); - let tokens_for_real = parse_stream_from_source_str(filename, source, sess, Some(span)); - - // During early phases of the compiler the AST could get modified - // directly (e.g., attributes added or removed) and the internal cache - // of tokens my not be invalidated or updated. Consequently if the - // "lossless" token stream disagrees with our actual stringification - // (which has historically been much more battle-tested) then we go - // with the lossy stream anyway (losing span information). - // - // Note that the comparison isn't `==` here to avoid comparing spans, - // but it *also* is a "probable" equality which is a pretty weird - // definition. We mostly want to catch actual changes to the AST - // like a `#[cfg]` being processed or some weird `macro_rules!` - // expansion. - // - // What we *don't* want to catch is the fact that a user-defined - // literal like `0xf` is stringified as `15`, causing the cached token - // stream to not be literal `==` token-wise (ignoring spans) to the - // token stream we got from stringification. - // - // Instead the "probably equal" check here is "does each token - // recursively have the same discriminant?" We basically don't look at - // the token values here and assume that such fine grained token stream - // modifications, including adding/removing typically non-semantic - // tokens such as extra braces and commas, don't happen. - if let Some(tokens) = tokens { - if tokens.probably_equal_for_proc_macro(&tokens_for_real) { - return tokens - } - info!("cached tokens found, but they're not \"probably equal\", \ - going with stringified version"); - } - return tokens_for_real -} - -fn prepend_attrs( - sess: &ParseSess, - attrs: &[ast::Attribute], - tokens: Option<&tokenstream::TokenStream>, - span: syntax_pos::Span -) -> Option<tokenstream::TokenStream> { - let tokens = tokens?; - if attrs.len() == 0 { - return Some(tokens.clone()) - } - let mut builder = tokenstream::TokenStreamBuilder::new(); - for attr in attrs { - assert_eq!(attr.style, ast::AttrStyle::Outer, - "inner attributes should prevent cached tokens from existing"); - - let source = pprust::attribute_to_string(attr); - let macro_filename = FileName::macro_expansion_source_code(&source); - - let item = match attr.kind { - ast::AttrKind::Normal(ref item) => item, - ast::AttrKind::DocComment(_) => { - let stream = parse_stream_from_source_str(macro_filename, source, sess, Some(span)); - builder.push(stream); - continue - } - }; - - // synthesize # [ $path $tokens ] manually here - let mut brackets = tokenstream::TokenStreamBuilder::new(); - - // For simple paths, push the identifier directly - if item.path.segments.len() == 1 && item.path.segments[0].args.is_none() { - let ident = item.path.segments[0].ident; - let token = token::Ident(ident.name, ident.as_str().starts_with("r#")); - brackets.push(tokenstream::TokenTree::token(token, ident.span)); - - // ... and for more complicated paths, fall back to a reparse hack that - // should eventually be removed. - } else { - let stream = parse_stream_from_source_str(macro_filename, source, sess, Some(span)); - brackets.push(stream); - } - - brackets.push(item.tokens.clone()); - - // The span we list here for `#` and for `[ ... ]` are both wrong in - // that it encompasses more than each token, but it hopefully is "good - // enough" for now at least. - builder.push(tokenstream::TokenTree::token(token::Pound, attr.span)); - let delim_span = tokenstream::DelimSpan::from_single(attr.span); - builder.push(tokenstream::TokenTree::Delimited( - delim_span, token::DelimToken::Bracket, brackets.build().into())); - } - builder.push(tokens.clone()); - Some(builder.build()) -} diff --git a/src/libsyntax/parse/parser/attr.rs b/src/libsyntax/parse/parser/attr.rs deleted file mode 100644 index 31f0a02a483..00000000000 --- a/src/libsyntax/parse/parser/attr.rs +++ /dev/null @@ -1,358 +0,0 @@ -use super::{SeqSep, Parser, TokenType, PathStyle}; -use crate::attr; -use crate::ast; -use crate::util::comments; -use crate::token::{self, Nonterminal, DelimToken}; -use crate::tokenstream::{TokenStream, TokenTree}; -use crate::source_map::Span; - -use syntax_pos::Symbol; -use errors::PResult; - -use log::debug; - -#[derive(Debug)] -enum InnerAttributeParsePolicy<'a> { - Permitted, - NotPermitted { reason: &'a str, saw_doc_comment: bool, prev_attr_sp: Option<Span> }, -} - -const DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG: &str = "an inner attribute is not \ - permitted in this context"; - -impl<'a> Parser<'a> { - /// Parses attributes that appear before an item. - pub(super) fn parse_outer_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> { - let mut attrs: Vec<ast::Attribute> = Vec::new(); - let mut just_parsed_doc_comment = false; - loop { - debug!("parse_outer_attributes: self.token={:?}", self.token); - match self.token.kind { - token::Pound => { - let inner_error_reason = if just_parsed_doc_comment { - "an inner attribute is not permitted following an outer doc comment" - } else if !attrs.is_empty() { - "an inner attribute is not permitted following an outer attribute" - } else { - DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG - }; - let inner_parse_policy = - InnerAttributeParsePolicy::NotPermitted { - reason: inner_error_reason, - saw_doc_comment: just_parsed_doc_comment, - prev_attr_sp: attrs.last().and_then(|a| Some(a.span)) - }; - let attr = self.parse_attribute_with_inner_parse_policy(inner_parse_policy)?; - attrs.push(attr); - just_parsed_doc_comment = false; - } - token::DocComment(s) => { - let attr = self.mk_doc_comment(s); - if attr.style != ast::AttrStyle::Outer { - let mut err = self.fatal("expected outer doc comment"); - err.note("inner doc comments like this (starting with \ - `//!` or `/*!`) can only appear before items"); - return Err(err); - } - attrs.push(attr); - self.bump(); - just_parsed_doc_comment = true; - } - _ => break, - } - } - Ok(attrs) - } - - fn mk_doc_comment(&self, s: Symbol) -> ast::Attribute { - let style = comments::doc_comment_style(&s.as_str()); - attr::mk_doc_comment(style, s, self.token.span) - } - - /// Matches `attribute = # ! [ meta_item ]`. - /// - /// If `permit_inner` is `true`, then a leading `!` indicates an inner - /// attribute. - pub fn parse_attribute(&mut self, permit_inner: bool) -> PResult<'a, ast::Attribute> { - debug!("parse_attribute: permit_inner={:?} self.token={:?}", - permit_inner, - self.token); - let inner_parse_policy = if permit_inner { - InnerAttributeParsePolicy::Permitted - } else { - InnerAttributeParsePolicy::NotPermitted { - reason: DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG, - saw_doc_comment: false, - prev_attr_sp: None - } - }; - self.parse_attribute_with_inner_parse_policy(inner_parse_policy) - } - - /// The same as `parse_attribute`, except it takes in an `InnerAttributeParsePolicy` - /// that prescribes how to handle inner attributes. - fn parse_attribute_with_inner_parse_policy( - &mut self, - inner_parse_policy: InnerAttributeParsePolicy<'_> - ) -> PResult<'a, ast::Attribute> { - debug!("parse_attribute_with_inner_parse_policy: inner_parse_policy={:?} self.token={:?}", - inner_parse_policy, - self.token); - let (span, item, style) = match self.token.kind { - token::Pound => { - let lo = self.token.span; - self.bump(); - - if let InnerAttributeParsePolicy::Permitted = inner_parse_policy { - self.expected_tokens.push(TokenType::Token(token::Not)); - } - - let style = if self.token == token::Not { - self.bump(); - ast::AttrStyle::Inner - } else { - ast::AttrStyle::Outer - }; - - self.expect(&token::OpenDelim(token::Bracket))?; - let item = self.parse_attr_item()?; - self.expect(&token::CloseDelim(token::Bracket))?; - let hi = self.prev_span; - - let attr_sp = lo.to(hi); - - // Emit error if inner attribute is encountered and not permitted - if style == ast::AttrStyle::Inner { - if let InnerAttributeParsePolicy::NotPermitted { reason, - saw_doc_comment, prev_attr_sp } = inner_parse_policy { - let prev_attr_note = if saw_doc_comment { - "previous doc comment" - } else { - "previous outer attribute" - }; - - let mut diagnostic = self - .diagnostic() - .struct_span_err(attr_sp, reason); - - if let Some(prev_attr_sp) = prev_attr_sp { - diagnostic - .span_label(attr_sp, "not permitted following an outer attibute") - .span_label(prev_attr_sp, prev_attr_note); - } - - diagnostic - .note("inner attributes, like `#![no_std]`, annotate the item \ - enclosing them, and are usually found at the beginning of \ - source files. Outer attributes, like `#[test]`, annotate the \ - item following them.") - .emit() - } - } - - (attr_sp, item, style) - } - _ => { - let token_str = self.this_token_to_string(); - return Err(self.fatal(&format!("expected `#`, found `{}`", token_str))); - } - }; - - Ok(ast::Attribute { - kind: ast::AttrKind::Normal(item), - id: attr::mk_attr_id(), - style, - span, - }) - } - - /// Parses an inner part of an attribute (the path and following tokens). - /// The tokens must be either a delimited token stream, or empty token stream, - /// or the "legacy" key-value form. - /// PATH `(` TOKEN_STREAM `)` - /// PATH `[` TOKEN_STREAM `]` - /// PATH `{` TOKEN_STREAM `}` - /// PATH - /// PATH `=` UNSUFFIXED_LIT - /// The delimiters or `=` are still put into the resulting token stream. - pub fn parse_attr_item(&mut self) -> PResult<'a, ast::AttrItem> { - let item = match self.token.kind { - token::Interpolated(ref nt) => match **nt { - Nonterminal::NtMeta(ref item) => Some(item.clone()), - _ => None, - }, - _ => None, - }; - Ok(if let Some(item) = item { - self.bump(); - item - } else { - let path = self.parse_path(PathStyle::Mod)?; - let tokens = if self.check(&token::OpenDelim(DelimToken::Paren)) || - self.check(&token::OpenDelim(DelimToken::Bracket)) || - self.check(&token::OpenDelim(DelimToken::Brace)) { - self.parse_token_tree().into() - } else if self.eat(&token::Eq) { - let eq = TokenTree::token(token::Eq, self.prev_span); - let mut is_interpolated_expr = false; - if let token::Interpolated(nt) = &self.token.kind { - if let token::NtExpr(..) = **nt { - is_interpolated_expr = true; - } - } - let token_tree = if is_interpolated_expr { - // We need to accept arbitrary interpolated expressions to continue - // supporting things like `doc = $expr` that work on stable. - // Non-literal interpolated expressions are rejected after expansion. - self.parse_token_tree() - } else { - self.parse_unsuffixed_lit()?.token_tree() - }; - TokenStream::new(vec![eq.into(), token_tree.into()]) - } else { - TokenStream::default() - }; - ast::AttrItem { path, tokens } - }) - } - - /// Parses attributes that appear after the opening of an item. These should - /// be preceded by an exclamation mark, but we accept and warn about one - /// terminated by a semicolon. - /// - /// Matches `inner_attrs*`. - crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> { - let mut attrs: Vec<ast::Attribute> = vec![]; - loop { - match self.token.kind { - token::Pound => { - // Don't even try to parse if it's not an inner attribute. - if !self.look_ahead(1, |t| t == &token::Not) { - break; - } - - let attr = self.parse_attribute(true)?; - assert_eq!(attr.style, ast::AttrStyle::Inner); - attrs.push(attr); - } - token::DocComment(s) => { - // We need to get the position of this token before we bump. - let attr = self.mk_doc_comment(s); - if attr.style == ast::AttrStyle::Inner { - attrs.push(attr); - self.bump(); - } else { - break; - } - } - _ => break, - } - } - Ok(attrs) - } - - fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> { - let lit = self.parse_lit()?; - debug!("checking if {:?} is unusuffixed", lit); - - if !lit.kind.is_unsuffixed() { - let msg = "suffixed literals are not allowed in attributes"; - self.diagnostic().struct_span_err(lit.span, msg) - .help("instead of using a suffixed literal \ - (1u8, 1.0f32, etc.), use an unsuffixed version \ - (1, 1.0, etc.).") - .emit() - } - - Ok(lit) - } - - /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited. - crate fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> { - self.expect(&token::OpenDelim(token::Paren))?; - - let cfg_predicate = self.parse_meta_item()?; - self.expect(&token::Comma)?; - - // Presumably, the majority of the time there will only be one attr. - let mut expanded_attrs = Vec::with_capacity(1); - - while !self.check(&token::CloseDelim(token::Paren)) { - let lo = self.token.span.lo(); - let item = self.parse_attr_item()?; - expanded_attrs.push((item, self.prev_span.with_lo(lo))); - self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Paren)])?; - } - - self.expect(&token::CloseDelim(token::Paren))?; - Ok((cfg_predicate, expanded_attrs)) - } - - /// Matches the following grammar (per RFC 1559). - /// - /// meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ; - /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ; - pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> { - let nt_meta = match self.token.kind { - token::Interpolated(ref nt) => match **nt { - token::NtMeta(ref e) => Some(e.clone()), - _ => None, - }, - _ => None, - }; - - if let Some(item) = nt_meta { - return match item.meta(item.path.span) { - Some(meta) => { - self.bump(); - Ok(meta) - } - None => self.unexpected(), - } - } - - let lo = self.token.span; - let path = self.parse_path(PathStyle::Mod)?; - let kind = self.parse_meta_item_kind()?; - let span = lo.to(self.prev_span); - Ok(ast::MetaItem { path, kind, span }) - } - - crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> { - Ok(if self.eat(&token::Eq) { - ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?) - } else if self.eat(&token::OpenDelim(token::Paren)) { - ast::MetaItemKind::List(self.parse_meta_seq()?) - } else { - ast::MetaItemKind::Word - }) - } - - /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`. - fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> { - match self.parse_unsuffixed_lit() { - Ok(lit) => { - return Ok(ast::NestedMetaItem::Literal(lit)) - } - Err(ref mut err) => err.cancel(), - } - - match self.parse_meta_item() { - Ok(mi) => { - return Ok(ast::NestedMetaItem::MetaItem(mi)) - } - Err(ref mut err) => err.cancel(), - } - - let found = self.this_token_to_string(); - let msg = format!("expected unsuffixed literal or identifier, found `{}`", found); - Err(self.diagnostic().struct_span_err(self.token.span, &msg)) - } - - /// Matches `meta_seq = ( COMMASEP(meta_item_inner) )`. - fn parse_meta_seq(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> { - self.parse_seq_to_end(&token::CloseDelim(token::Paren), - SeqSep::trailing_allowed(token::Comma), - |p: &mut Parser<'a>| p.parse_meta_item_inner()) - } -} diff --git a/src/libsyntax/parse/parser/diagnostics.rs b/src/libsyntax/parse/parser/diagnostics.rs deleted file mode 100644 index 5df24804a76..00000000000 --- a/src/libsyntax/parse/parser/diagnostics.rs +++ /dev/null @@ -1,1547 +0,0 @@ -use super::{BlockMode, PathStyle, SemiColonMode, TokenType, TokenExpectType, SeqSep, Parser}; -use crate::ast::{ - self, Param, BinOpKind, BindingMode, BlockCheckMode, Expr, ExprKind, Ident, Item, ItemKind, - Mutability, Pat, PatKind, PathSegment, QSelf, Ty, TyKind, -}; -use crate::token::{self, TokenKind, token_can_begin_expr}; -use crate::print::pprust; -use crate::ptr::P; -use crate::symbol::{kw, sym}; -use crate::ThinVec; -use crate::util::parser::AssocOp; - -use errors::{PResult, Applicability, DiagnosticBuilder, DiagnosticId, pluralize}; -use rustc_data_structures::fx::FxHashSet; -use syntax_pos::{Span, DUMMY_SP, MultiSpan, SpanSnippetError}; -use log::{debug, trace}; -use std::mem; - -const TURBOFISH: &'static str = "use `::<...>` instead of `<...>` to specify type arguments"; - -/// Creates a placeholder argument. -pub(super) fn dummy_arg(ident: Ident) -> Param { - let pat = P(Pat { - id: ast::DUMMY_NODE_ID, - kind: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None), - span: ident.span, - }); - let ty = Ty { - kind: TyKind::Err, - span: ident.span, - id: ast::DUMMY_NODE_ID - }; - Param { - attrs: ThinVec::default(), - id: ast::DUMMY_NODE_ID, - pat, - span: ident.span, - ty: P(ty), - is_placeholder: false, - } -} - -pub enum Error { - FileNotFoundForModule { - mod_name: String, - default_path: String, - secondary_path: String, - dir_path: String, - }, - DuplicatePaths { - mod_name: String, - default_path: String, - secondary_path: String, - }, - UselessDocComment, - InclusiveRangeWithNoEnd, -} - -impl Error { - fn span_err<S: Into<MultiSpan>>( - self, - sp: S, - handler: &errors::Handler, - ) -> DiagnosticBuilder<'_> { - match self { - Error::FileNotFoundForModule { - ref mod_name, - ref default_path, - ref secondary_path, - ref dir_path, - } => { - let mut err = struct_span_err!( - handler, - sp, - E0583, - "file not found for module `{}`", - mod_name, - ); - err.help(&format!( - "name the file either {} or {} inside the directory \"{}\"", - default_path, - secondary_path, - dir_path, - )); - err - } - Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => { - let mut err = struct_span_err!( - handler, - sp, - E0584, - "file for module `{}` found at both {} and {}", - mod_name, - default_path, - secondary_path, - ); - err.help("delete or rename one of them to remove the ambiguity"); - err - } - Error::UselessDocComment => { - let mut err = struct_span_err!( - handler, - sp, - E0585, - "found a documentation comment that doesn't document anything", - ); - err.help("doc comments must come before what they document, maybe a comment was \ - intended with `//`?"); - err - } - Error::InclusiveRangeWithNoEnd => { - let mut err = struct_span_err!( - handler, - sp, - E0586, - "inclusive range with no end", - ); - err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)"); - err - } - } - } -} - -pub(super) trait RecoverQPath: Sized + 'static { - const PATH_STYLE: PathStyle = PathStyle::Expr; - fn to_ty(&self) -> Option<P<Ty>>; - fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self; -} - -impl RecoverQPath for Ty { - const PATH_STYLE: PathStyle = PathStyle::Type; - fn to_ty(&self) -> Option<P<Ty>> { - Some(P(self.clone())) - } - fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self { - Self { - span: path.span, - kind: TyKind::Path(qself, path), - id: ast::DUMMY_NODE_ID, - } - } -} - -impl RecoverQPath for Pat { - fn to_ty(&self) -> Option<P<Ty>> { - self.to_ty() - } - fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self { - Self { - span: path.span, - kind: PatKind::Path(qself, path), - id: ast::DUMMY_NODE_ID, - } - } -} - -impl RecoverQPath for Expr { - fn to_ty(&self) -> Option<P<Ty>> { - self.to_ty() - } - fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self { - Self { - span: path.span, - kind: ExprKind::Path(qself, path), - attrs: ThinVec::new(), - id: ast::DUMMY_NODE_ID, - } - } -} - -/// Control whether the closing delimiter should be consumed when calling `Parser::consume_block`. -crate enum ConsumeClosingDelim { - Yes, - No, -} - -impl<'a> Parser<'a> { - pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> { - self.span_fatal(self.token.span, m) - } - - crate fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> { - self.sess.span_diagnostic.struct_span_fatal(sp, m) - } - - pub(super) fn span_fatal_err<S: Into<MultiSpan>>( - &self, - sp: S, - err: Error, - ) -> DiagnosticBuilder<'a> { - err.span_err(sp, self.diagnostic()) - } - - pub(super) fn bug(&self, m: &str) -> ! { - self.sess.span_diagnostic.span_bug(self.token.span, m) - } - - pub(super) fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) { - self.sess.span_diagnostic.span_err(sp, m) - } - - pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> { - self.sess.span_diagnostic.struct_span_err(sp, m) - } - - pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! { - self.sess.span_diagnostic.span_bug(sp, m) - } - - pub(super) fn diagnostic(&self) -> &'a errors::Handler { - &self.sess.span_diagnostic - } - - pub(super) fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> { - self.sess.source_map().span_to_snippet(span) - } - - pub(super) fn expected_ident_found(&self) -> DiagnosticBuilder<'a> { - let mut err = self.struct_span_err( - self.token.span, - &format!("expected identifier, found {}", self.this_token_descr()), - ); - if let token::Ident(name, false) = self.token.kind { - if Ident::new(name, self.token.span).is_raw_guess() { - err.span_suggestion( - self.token.span, - "you can escape reserved keywords to use them as identifiers", - format!("r#{}", name), - Applicability::MaybeIncorrect, - ); - } - } - if let Some(token_descr) = self.token_descr() { - err.span_label(self.token.span, format!("expected identifier, found {}", token_descr)); - } else { - err.span_label(self.token.span, "expected identifier"); - if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) { - err.span_suggestion( - self.token.span, - "remove this comma", - String::new(), - Applicability::MachineApplicable, - ); - } - } - err - } - - pub(super) fn expected_one_of_not_found( - &mut self, - edible: &[TokenKind], - inedible: &[TokenKind], - ) -> PResult<'a, bool /* recovered */> { - fn tokens_to_string(tokens: &[TokenType]) -> String { - let mut i = tokens.iter(); - // This might be a sign we need a connect method on `Iterator`. - let b = i.next() - .map_or(String::new(), |t| t.to_string()); - i.enumerate().fold(b, |mut b, (i, a)| { - if tokens.len() > 2 && i == tokens.len() - 2 { - b.push_str(", or "); - } else if tokens.len() == 2 && i == tokens.len() - 2 { - b.push_str(" or "); - } else { - b.push_str(", "); - } - b.push_str(&a.to_string()); - b - }) - } - - let mut expected = edible.iter() - .map(|x| TokenType::Token(x.clone())) - .chain(inedible.iter().map(|x| TokenType::Token(x.clone()))) - .chain(self.expected_tokens.iter().cloned()) - .collect::<Vec<_>>(); - expected.sort_by_cached_key(|x| x.to_string()); - expected.dedup(); - let expect = tokens_to_string(&expected[..]); - let actual = self.this_token_descr(); - let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 { - let short_expect = if expected.len() > 6 { - format!("{} possible tokens", expected.len()) - } else { - expect.clone() - }; - (format!("expected one of {}, found {}", expect, actual), - (self.sess.source_map().next_point(self.prev_span), - format!("expected one of {}", short_expect))) - } else if expected.is_empty() { - (format!("unexpected token: {}", actual), - (self.prev_span, "unexpected token after this".to_string())) - } else { - (format!("expected {}, found {}", expect, actual), - (self.sess.source_map().next_point(self.prev_span), - format!("expected {}", expect))) - }; - self.last_unexpected_token_span = Some(self.token.span); - let mut err = self.fatal(&msg_exp); - if self.token.is_ident_named(sym::and) { - err.span_suggestion_short( - self.token.span, - "use `&&` instead of `and` for the boolean operator", - "&&".to_string(), - Applicability::MaybeIncorrect, - ); - } - if self.token.is_ident_named(sym::or) { - err.span_suggestion_short( - self.token.span, - "use `||` instead of `or` for the boolean operator", - "||".to_string(), - Applicability::MaybeIncorrect, - ); - } - let sp = if self.token == token::Eof { - // This is EOF; don't want to point at the following char, but rather the last token. - self.prev_span - } else { - label_sp - }; - match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt { - TokenType::Token(t) => Some(t.clone()), - _ => None, - }).collect::<Vec<_>>(), err) { - Err(e) => err = e, - Ok(recovered) => { - return Ok(recovered); - } - } - - let sm = self.sess.source_map(); - if self.prev_span == DUMMY_SP { - // Account for macro context where the previous span might not be - // available to avoid incorrect output (#54841). - err.span_label(self.token.span, label_exp); - } else if !sm.is_multiline(self.token.span.shrink_to_hi().until(sp.shrink_to_lo())) { - // When the spans are in the same line, it means that the only content between - // them is whitespace, point at the found token in that case: - // - // X | () => { syntax error }; - // | ^^^^^ expected one of 8 possible tokens here - // - // instead of having: - // - // X | () => { syntax error }; - // | -^^^^^ unexpected token - // | | - // | expected one of 8 possible tokens here - err.span_label(self.token.span, label_exp); - } else { - err.span_label(sp, label_exp); - err.span_label(self.token.span, "unexpected token"); - } - self.maybe_annotate_with_ascription(&mut err, false); - Err(err) - } - - pub fn maybe_annotate_with_ascription( - &mut self, - err: &mut DiagnosticBuilder<'_>, - maybe_expected_semicolon: bool, - ) { - if let Some((sp, likely_path)) = self.last_type_ascription.take() { - let sm = self.sess.source_map(); - let next_pos = sm.lookup_char_pos(self.token.span.lo()); - let op_pos = sm.lookup_char_pos(sp.hi()); - - let allow_unstable = self.sess.unstable_features.is_nightly_build(); - - if likely_path { - err.span_suggestion( - sp, - "maybe write a path separator here", - "::".to_string(), - if allow_unstable { - Applicability::MaybeIncorrect - } else { - Applicability::MachineApplicable - }, - ); - } else if op_pos.line != next_pos.line && maybe_expected_semicolon { - err.span_suggestion( - sp, - "try using a semicolon", - ";".to_string(), - Applicability::MaybeIncorrect, - ); - } else if allow_unstable { - err.span_label(sp, "tried to parse a type due to this type ascription"); - } else { - err.span_label(sp, "tried to parse a type due to this"); - } - if allow_unstable { - // Give extra information about type ascription only if it's a nightly compiler. - err.note("`#![feature(type_ascription)]` lets you annotate an expression with a \ - type: `<expr>: <type>`"); - err.note("for more information, see \ - https://github.com/rust-lang/rust/issues/23416"); - } - } - } - - /// Eats and discards tokens until one of `kets` is encountered. Respects token trees, - /// passes through any errors encountered. Used for error recovery. - pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) { - if let Err(ref mut err) = self.parse_seq_to_before_tokens( - kets, - SeqSep::none(), - TokenExpectType::Expect, - |p| Ok(p.parse_token_tree()), - ) { - err.cancel(); - } - } - - /// This function checks if there are trailing angle brackets and produces - /// a diagnostic to suggest removing them. - /// - /// ```ignore (diagnostic) - /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>(); - /// ^^ help: remove extra angle brackets - /// ``` - pub(super) fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: TokenKind) { - // This function is intended to be invoked after parsing a path segment where there are two - // cases: - // - // 1. A specific token is expected after the path segment. - // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call), - // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path). - // 2. No specific token is expected after the path segment. - // eg. `x.foo` (field access) - // - // This function is called after parsing `.foo` and before parsing the token `end` (if - // present). This includes any angle bracket arguments, such as `.foo::<u32>` or - // `Foo::<Bar>`. - - // We only care about trailing angle brackets if we previously parsed angle bracket - // arguments. This helps stop us incorrectly suggesting that extra angle brackets be - // removed in this case: - // - // `x.foo >> (3)` (where `x.foo` is a `u32` for example) - // - // This case is particularly tricky as we won't notice it just looking at the tokens - - // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will - // have already been parsed): - // - // `x.foo::<u32>>>(3)` - let parsed_angle_bracket_args = segment.args - .as_ref() - .map(|args| args.is_angle_bracketed()) - .unwrap_or(false); - - debug!( - "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}", - parsed_angle_bracket_args, - ); - if !parsed_angle_bracket_args { - return; - } - - // Keep the span at the start so we can highlight the sequence of `>` characters to be - // removed. - let lo = self.token.span; - - // We need to look-ahead to see if we have `>` characters without moving the cursor forward - // (since we might have the field access case and the characters we're eating are - // actual operators and not trailing characters - ie `x.foo >> 3`). - let mut position = 0; - - // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how - // many of each (so we can correctly pluralize our error messages) and continue to - // advance. - let mut number_of_shr = 0; - let mut number_of_gt = 0; - while self.look_ahead(position, |t| { - trace!("check_trailing_angle_brackets: t={:?}", t); - if *t == token::BinOp(token::BinOpToken::Shr) { - number_of_shr += 1; - true - } else if *t == token::Gt { - number_of_gt += 1; - true - } else { - false - } - }) { - position += 1; - } - - // If we didn't find any trailing `>` characters, then we have nothing to error about. - debug!( - "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}", - number_of_gt, number_of_shr, - ); - if number_of_gt < 1 && number_of_shr < 1 { - return; - } - - // Finally, double check that we have our end token as otherwise this is the - // second case. - if self.look_ahead(position, |t| { - trace!("check_trailing_angle_brackets: t={:?}", t); - *t == end - }) { - // Eat from where we started until the end token so that parsing can continue - // as if we didn't have those extra angle brackets. - self.eat_to_tokens(&[&end]); - let span = lo.until(self.token.span); - - let total_num_of_gt = number_of_gt + number_of_shr * 2; - self.diagnostic() - .struct_span_err( - span, - &format!("unmatched angle bracket{}", pluralize!(total_num_of_gt)), - ) - .span_suggestion( - span, - &format!("remove extra angle bracket{}", pluralize!(total_num_of_gt)), - String::new(), - Applicability::MachineApplicable, - ) - .emit(); - } - } - - /// Produces an error if comparison operators are chained (RFC #558). - /// We only need to check the LHS, not the RHS, because all comparison ops have same - /// precedence (see `fn precedence`) and are left-associative (see `fn fixity`). - /// - /// This can also be hit if someone incorrectly writes `foo<bar>()` when they should have used - /// the turbofish (`foo::<bar>()`) syntax. We attempt some heuristic recovery if that is the - /// case. - /// - /// Keep in mind that given that `outer_op.is_comparison()` holds and comparison ops are left - /// associative we can infer that we have: - /// - /// outer_op - /// / \ - /// inner_op r2 - /// / \ - /// l1 r1 - pub(super) fn check_no_chained_comparison( - &mut self, - lhs: &Expr, - outer_op: &AssocOp, - ) -> PResult<'a, Option<P<Expr>>> { - debug_assert!( - outer_op.is_comparison(), - "check_no_chained_comparison: {:?} is not comparison", - outer_op, - ); - - let mk_err_expr = |this: &Self, span| { - Ok(Some(this.mk_expr(span, ExprKind::Err, ThinVec::new()))) - }; - - match lhs.kind { - ExprKind::Binary(op, _, _) if op.node.is_comparison() => { - // Respan to include both operators. - let op_span = op.span.to(self.prev_span); - let mut err = self.struct_span_err( - op_span, - "chained comparison operators require parentheses", - ); - - let suggest = |err: &mut DiagnosticBuilder<'_>| { - err.span_suggestion_verbose( - op_span.shrink_to_lo(), - TURBOFISH, - "::".to_string(), - Applicability::MaybeIncorrect, - ); - }; - - if op.node == BinOpKind::Lt && - *outer_op == AssocOp::Less || // Include `<` to provide this recommendation - *outer_op == AssocOp::Greater // even in a case like the following: - { // Foo<Bar<Baz<Qux, ()>>> - if *outer_op == AssocOp::Less { - let snapshot = self.clone(); - self.bump(); - // So far we have parsed `foo<bar<`, consume the rest of the type args. - let modifiers = [ - (token::Lt, 1), - (token::Gt, -1), - (token::BinOp(token::Shr), -2), - ]; - self.consume_tts(1, &modifiers[..]); - - if !&[ - token::OpenDelim(token::Paren), - token::ModSep, - ].contains(&self.token.kind) { - // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the - // parser and bail out. - mem::replace(self, snapshot.clone()); - } - } - return if token::ModSep == self.token.kind { - // We have some certainty that this was a bad turbofish at this point. - // `foo< bar >::` - suggest(&mut err); - - let snapshot = self.clone(); - self.bump(); // `::` - - // Consume the rest of the likely `foo<bar>::new()` or return at `foo<bar>`. - match self.parse_expr() { - Ok(_) => { - // 99% certain that the suggestion is correct, continue parsing. - err.emit(); - // FIXME: actually check that the two expressions in the binop are - // paths and resynthesize new fn call expression instead of using - // `ExprKind::Err` placeholder. - mk_err_expr(self, lhs.span.to(self.prev_span)) - } - Err(mut expr_err) => { - expr_err.cancel(); - // Not entirely sure now, but we bubble the error up with the - // suggestion. - mem::replace(self, snapshot); - Err(err) - } - } - } else if token::OpenDelim(token::Paren) == self.token.kind { - // We have high certainty that this was a bad turbofish at this point. - // `foo< bar >(` - suggest(&mut err); - // Consume the fn call arguments. - match self.consume_fn_args() { - Err(()) => Err(err), - Ok(()) => { - err.emit(); - // FIXME: actually check that the two expressions in the binop are - // paths and resynthesize new fn call expression instead of using - // `ExprKind::Err` placeholder. - mk_err_expr(self, lhs.span.to(self.prev_span)) - } - } - } else { - // All we know is that this is `foo < bar >` and *nothing* else. Try to - // be helpful, but don't attempt to recover. - err.help(TURBOFISH); - err.help("or use `(...)` if you meant to specify fn arguments"); - // These cases cause too many knock-down errors, bail out (#61329). - Err(err) - }; - } - err.emit(); - } - _ => {} - } - Ok(None) - } - - fn consume_fn_args(&mut self) -> Result<(), ()> { - let snapshot = self.clone(); - self.bump(); // `(` - - // Consume the fn call arguments. - let modifiers = [ - (token::OpenDelim(token::Paren), 1), - (token::CloseDelim(token::Paren), -1), - ]; - self.consume_tts(1, &modifiers[..]); - - if self.token.kind == token::Eof { - // Not entirely sure that what we consumed were fn arguments, rollback. - mem::replace(self, snapshot); - Err(()) - } else { - // 99% certain that the suggestion is correct, continue parsing. - Ok(()) - } - } - - pub(super) fn maybe_report_ambiguous_plus( - &mut self, - allow_plus: bool, - impl_dyn_multi: bool, - ty: &Ty, - ) { - if !allow_plus && impl_dyn_multi { - let sum_with_parens = format!("({})", pprust::ty_to_string(&ty)); - self.struct_span_err(ty.span, "ambiguous `+` in a type") - .span_suggestion( - ty.span, - "use parentheses to disambiguate", - sum_with_parens, - Applicability::MachineApplicable, - ) - .emit(); - } - } - - pub(super) fn maybe_recover_from_bad_type_plus( - &mut self, - allow_plus: bool, - ty: &Ty, - ) -> PResult<'a, ()> { - // Do not add `+` to expected tokens. - if !allow_plus || !self.token.is_like_plus() { - return Ok(()); - } - - self.bump(); // `+` - let bounds = self.parse_generic_bounds(None)?; - let sum_span = ty.span.to(self.prev_span); - - let mut err = struct_span_err!( - self.sess.span_diagnostic, - sum_span, - E0178, - "expected a path on the left-hand side of `+`, not `{}`", - pprust::ty_to_string(ty) - ); - - match ty.kind { - TyKind::Rptr(ref lifetime, ref mut_ty) => { - let sum_with_parens = pprust::to_string(|s| { - s.s.word("&"); - s.print_opt_lifetime(lifetime); - s.print_mutability(mut_ty.mutbl); - s.popen(); - s.print_type(&mut_ty.ty); - s.print_type_bounds(" +", &bounds); - s.pclose() - }); - err.span_suggestion( - sum_span, - "try adding parentheses", - sum_with_parens, - Applicability::MachineApplicable, - ); - } - TyKind::Ptr(..) | TyKind::BareFn(..) => { - err.span_label(sum_span, "perhaps you forgot parentheses?"); - } - _ => { - err.span_label(sum_span, "expected a path"); - } - } - err.emit(); - Ok(()) - } - - /// Tries to recover from associated item paths like `[T]::AssocItem` / `(T, U)::AssocItem`. - /// Attempts to convert the base expression/pattern/type into a type, parses the `::AssocItem` - /// tail, and combines them into a `<Ty>::AssocItem` expression/pattern/type. - pub(super) fn maybe_recover_from_bad_qpath<T: RecoverQPath>( - &mut self, - base: P<T>, - allow_recovery: bool, - ) -> PResult<'a, P<T>> { - // Do not add `::` to expected tokens. - if allow_recovery && self.token == token::ModSep { - if let Some(ty) = base.to_ty() { - return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty); - } - } - Ok(base) - } - - /// Given an already parsed `Ty`, parses the `::AssocItem` tail and - /// combines them into a `<Ty>::AssocItem` expression/pattern/type. - pub(super) fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>( - &mut self, - ty_span: Span, - ty: P<Ty>, - ) -> PResult<'a, P<T>> { - self.expect(&token::ModSep)?; - - let mut path = ast::Path { - segments: Vec::new(), - span: DUMMY_SP, - }; - self.parse_path_segments(&mut path.segments, T::PATH_STYLE)?; - path.span = ty_span.to(self.prev_span); - - let ty_str = self - .span_to_snippet(ty_span) - .unwrap_or_else(|_| pprust::ty_to_string(&ty)); - self.diagnostic() - .struct_span_err(path.span, "missing angle brackets in associated item path") - .span_suggestion( - // This is a best-effort recovery. - path.span, - "try", - format!("<{}>::{}", ty_str, pprust::path_to_string(&path)), - Applicability::MaybeIncorrect, - ) - .emit(); - - let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`. - Ok(P(T::recovered( - Some(QSelf { - ty, - path_span, - position: 0, - }), - path, - ))) - } - - pub(super) fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool { - if self.eat(&token::Semi) { - let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`"); - err.span_suggestion_short( - self.prev_span, - "remove this semicolon", - String::new(), - Applicability::MachineApplicable, - ); - if !items.is_empty() { - let previous_item = &items[items.len() - 1]; - let previous_item_kind_name = match previous_item.kind { - // Say "braced struct" because tuple-structs and - // braceless-empty-struct declarations do take a semicolon. - ItemKind::Struct(..) => Some("braced struct"), - ItemKind::Enum(..) => Some("enum"), - ItemKind::Trait(..) => Some("trait"), - ItemKind::Union(..) => Some("union"), - _ => None, - }; - if let Some(name) = previous_item_kind_name { - err.help(&format!( - "{} declarations are not followed by a semicolon", - name - )); - } - } - err.emit(); - true - } else { - false - } - } - - /// Creates a `DiagnosticBuilder` for an unexpected token `t` and tries to recover if it is a - /// closing delimiter. - pub(super) fn unexpected_try_recover( - &mut self, - t: &TokenKind, - ) -> PResult<'a, bool /* recovered */> { - let token_str = pprust::token_kind_to_string(t); - let this_token_str = self.this_token_descr(); - let (prev_sp, sp) = match (&self.token.kind, self.subparser_name) { - // Point at the end of the macro call when reaching end of macro arguments. - (token::Eof, Some(_)) => { - let sp = self.sess.source_map().next_point(self.token.span); - (sp, sp) - } - // We don't want to point at the following span after DUMMY_SP. - // This happens when the parser finds an empty TokenStream. - _ if self.prev_span == DUMMY_SP => (self.token.span, self.token.span), - // EOF, don't want to point at the following char, but rather the last token. - (token::Eof, None) => (self.prev_span, self.token.span), - _ => (self.sess.source_map().next_point(self.prev_span), self.token.span), - }; - let msg = format!( - "expected `{}`, found {}", - token_str, - match (&self.token.kind, self.subparser_name) { - (token::Eof, Some(origin)) => format!("end of {}", origin), - _ => this_token_str, - }, - ); - let mut err = self.struct_span_err(sp, &msg); - let label_exp = format!("expected `{}`", token_str); - match self.recover_closing_delimiter(&[t.clone()], err) { - Err(e) => err = e, - Ok(recovered) => { - return Ok(recovered); - } - } - let sm = self.sess.source_map(); - if !sm.is_multiline(prev_sp.until(sp)) { - // When the spans are in the same line, it means that the only content - // between them is whitespace, point only at the found token. - err.span_label(sp, label_exp); - } else { - err.span_label(prev_sp, label_exp); - err.span_label(sp, "unexpected token"); - } - Err(err) - } - - pub(super) fn expect_semi(&mut self) -> PResult<'a, ()> { - if self.eat(&token::Semi) { - return Ok(()); - } - let sm = self.sess.source_map(); - let msg = format!("expected `;`, found `{}`", self.this_token_descr()); - let appl = Applicability::MachineApplicable; - if self.token.span == DUMMY_SP || self.prev_span == DUMMY_SP { - // Likely inside a macro, can't provide meaninful suggestions. - return self.expect(&token::Semi).map(|_| ()); - } else if !sm.is_multiline(self.prev_span.until(self.token.span)) { - // The current token is in the same line as the prior token, not recoverable. - } else if self.look_ahead(1, |t| t == &token::CloseDelim(token::Brace) - || token_can_begin_expr(t) && t.kind != token::Colon - ) && [token::Comma, token::Colon].contains(&self.token.kind) { - // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is - // either `,` or `:`, and the next token could either start a new statement or is a - // block close. For example: - // - // let x = 32: - // let y = 42; - self.bump(); - let sp = self.prev_span; - self.struct_span_err(sp, &msg) - .span_suggestion(sp, "change this to `;`", ";".to_string(), appl) - .emit(); - return Ok(()) - } else if self.look_ahead(0, |t| t == &token::CloseDelim(token::Brace) || ( - token_can_begin_expr(t) - && t != &token::Semi - && t != &token::Pound // Avoid triggering with too many trailing `#` in raw string. - )) { - // Missing semicolon typo. This is triggered if the next token could either start a - // new statement or is a block close. For example: - // - // let x = 32 - // let y = 42; - let sp = self.prev_span.shrink_to_hi(); - self.struct_span_err(sp, &msg) - .span_label(self.token.span, "unexpected token") - .span_suggestion_short(sp, "add `;` here", ";".to_string(), appl) - .emit(); - return Ok(()) - } - self.expect(&token::Semi).map(|_| ()) // Error unconditionally - } - - pub(super) fn parse_semi_or_incorrect_foreign_fn_body( - &mut self, - ident: &Ident, - extern_sp: Span, - ) -> PResult<'a, ()> { - if self.token != token::Semi { - // This might be an incorrect fn definition (#62109). - let parser_snapshot = self.clone(); - match self.parse_inner_attrs_and_block() { - Ok((_, body)) => { - self.struct_span_err(ident.span, "incorrect `fn` inside `extern` block") - .span_label(ident.span, "can't have a body") - .span_label(body.span, "this body is invalid here") - .span_label( - extern_sp, - "`extern` blocks define existing foreign functions and `fn`s \ - inside of them cannot have a body") - .help("you might have meant to write a function accessible through ffi, \ - which can be done by writing `extern fn` outside of the \ - `extern` block") - .note("for more information, visit \ - https://doc.rust-lang.org/std/keyword.extern.html") - .emit(); - } - Err(mut err) => { - err.cancel(); - mem::replace(self, parser_snapshot); - self.expect_semi()?; - } - } - } else { - self.bump(); - } - Ok(()) - } - - /// Consumes alternative await syntaxes like `await!(<expr>)`, `await <expr>`, - /// `await? <expr>`, `await(<expr>)`, and `await { <expr> }`. - pub(super) fn parse_incorrect_await_syntax( - &mut self, - lo: Span, - await_sp: Span, - ) -> PResult<'a, (Span, ExprKind)> { - if self.token == token::Not { - // Handle `await!(<expr>)`. - self.expect(&token::Not)?; - self.expect(&token::OpenDelim(token::Paren))?; - let expr = self.parse_expr()?; - self.expect(&token::CloseDelim(token::Paren))?; - let sp = self.error_on_incorrect_await(lo, self.prev_span, &expr, false); - return Ok((sp, ExprKind::Await(expr))) - } - - let is_question = self.eat(&token::Question); // Handle `await? <expr>`. - let expr = if self.token == token::OpenDelim(token::Brace) { - // Handle `await { <expr> }`. - // This needs to be handled separatedly from the next arm to avoid - // interpreting `await { <expr> }?` as `<expr>?.await`. - self.parse_block_expr( - None, - self.token.span, - BlockCheckMode::Default, - ThinVec::new(), - ) - } else { - self.parse_expr() - }.map_err(|mut err| { - err.span_label(await_sp, "while parsing this incorrect await expression"); - err - })?; - let sp = self.error_on_incorrect_await(lo, expr.span, &expr, is_question); - Ok((sp, ExprKind::Await(expr))) - } - - fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span { - let expr_str = self.span_to_snippet(expr.span) - .unwrap_or_else(|_| pprust::expr_to_string(&expr)); - let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" }); - let sp = lo.to(hi); - let app = match expr.kind { - ExprKind::Try(_) => Applicability::MaybeIncorrect, // `await <expr>?` - _ => Applicability::MachineApplicable, - }; - self.struct_span_err(sp, "incorrect use of `await`") - .span_suggestion(sp, "`await` is a postfix operation", suggestion, app) - .emit(); - sp - } - - /// If encountering `future.await()`, consumes and emits an error. - pub(super) fn recover_from_await_method_call(&mut self) { - if self.token == token::OpenDelim(token::Paren) && - self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren)) - { - // future.await() - let lo = self.token.span; - self.bump(); // ( - let sp = lo.to(self.token.span); - self.bump(); // ) - self.struct_span_err(sp, "incorrect use of `await`") - .span_suggestion( - sp, - "`await` is not a method call, remove the parentheses", - String::new(), - Applicability::MachineApplicable, - ).emit() - } - } - - /// Recovers a situation like `for ( $pat in $expr )` - /// and suggest writing `for $pat in $expr` instead. - /// - /// This should be called before parsing the `$block`. - pub(super) fn recover_parens_around_for_head( - &mut self, - pat: P<Pat>, - expr: &Expr, - begin_paren: Option<Span>, - ) -> P<Pat> { - match (&self.token.kind, begin_paren) { - (token::CloseDelim(token::Paren), Some(begin_par_sp)) => { - self.bump(); - - let pat_str = self - // Remove the `(` from the span of the pattern: - .span_to_snippet(pat.span.trim_start(begin_par_sp).unwrap()) - .unwrap_or_else(|_| pprust::pat_to_string(&pat)); - - self.struct_span_err(self.prev_span, "unexpected closing `)`") - .span_label(begin_par_sp, "opening `(`") - .span_suggestion( - begin_par_sp.to(self.prev_span), - "remove parenthesis in `for` loop", - format!("{} in {}", pat_str, pprust::expr_to_string(&expr)), - // With e.g. `for (x) in y)` this would replace `(x) in y)` - // with `x) in y)` which is syntactically invalid. - // However, this is prevented before we get here. - Applicability::MachineApplicable, - ) - .emit(); - - // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint. - pat.and_then(|pat| match pat.kind { - PatKind::Paren(pat) => pat, - _ => P(pat), - }) - } - _ => pat, - } - } - - pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool { - (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish. - self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) - ) || - self.token.is_ident() && - match node { - // `foo::` → `foo:` or `foo.bar::` → `foo.bar:` - ast::ExprKind::Path(..) | ast::ExprKind::Field(..) => true, - _ => false, - } && - !self.token.is_reserved_ident() && // v `foo:bar(baz)` - self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) || - self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz` - self.look_ahead(2, |t| t.is_ident()) || - self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz` - self.look_ahead(2, |t| t.is_ident()) || - self.look_ahead(1, |t| t == &token::ModSep) && - (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz` - self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>` - } - - pub(super) fn recover_seq_parse_error( - &mut self, - delim: token::DelimToken, - lo: Span, - result: PResult<'a, P<Expr>>, - ) -> P<Expr> { - match result { - Ok(x) => x, - Err(mut err) => { - err.emit(); - // Recover from parse error, callers expect the closing delim to be consumed. - self.consume_block(delim, ConsumeClosingDelim::Yes); - self.mk_expr(lo.to(self.prev_span), ExprKind::Err, ThinVec::new()) - } - } - } - - pub(super) fn recover_closing_delimiter( - &mut self, - tokens: &[TokenKind], - mut err: DiagnosticBuilder<'a>, - ) -> PResult<'a, bool> { - let mut pos = None; - // We want to use the last closing delim that would apply. - for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() { - if tokens.contains(&token::CloseDelim(unmatched.expected_delim)) - && Some(self.token.span) > unmatched.unclosed_span - { - pos = Some(i); - } - } - match pos { - Some(pos) => { - // Recover and assume that the detected unclosed delimiter was meant for - // this location. Emit the diagnostic and act as if the delimiter was - // present for the parser's sake. - - // Don't attempt to recover from this unclosed delimiter more than once. - let unmatched = self.unclosed_delims.remove(pos); - let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim)); - if unmatched.found_delim.is_none() { - // We encountered `Eof`, set this fact here to avoid complaining about missing - // `fn main()` when we found place to suggest the closing brace. - *self.sess.reached_eof.borrow_mut() = true; - } - - // We want to suggest the inclusion of the closing delimiter where it makes - // the most sense, which is immediately after the last token: - // - // {foo(bar {}} - // - ^ - // | | - // | help: `)` may belong here - // | - // unclosed delimiter - if let Some(sp) = unmatched.unclosed_span { - err.span_label(sp, "unclosed delimiter"); - } - err.span_suggestion_short( - self.sess.source_map().next_point(self.prev_span), - &format!("{} may belong here", delim.to_string()), - delim.to_string(), - Applicability::MaybeIncorrect, - ); - if unmatched.found_delim.is_none() { - // Encountered `Eof` when lexing blocks. Do not recover here to avoid knockdown - // errors which would be emitted elsewhere in the parser and let other error - // recovery consume the rest of the file. - Err(err) - } else { - err.emit(); - self.expected_tokens.clear(); // Reduce the number of errors. - Ok(true) - } - } - _ => Err(err), - } - } - - /// Recovers from `pub` keyword in places where it seems _reasonable_ but isn't valid. - pub(super) fn eat_bad_pub(&mut self) { - // When `unclosed_delims` is populated, it means that the code being parsed is already - // quite malformed, which might mean that, for example, a pub struct definition could be - // parsed as being a trait item, which is invalid and this error would trigger - // unconditionally, resulting in misleading diagnostics. Because of this, we only attempt - // this nice to have recovery for code that is otherwise well formed. - if self.token.is_keyword(kw::Pub) && self.unclosed_delims.is_empty() { - match self.parse_visibility(false) { - Ok(vis) => { - self.diagnostic() - .struct_span_err(vis.span, "unnecessary visibility qualifier") - .span_label(vis.span, "`pub` not permitted here") - .emit(); - } - Err(mut err) => err.emit(), - } - } - } - - /// Eats tokens until we can be relatively sure we reached the end of the - /// statement. This is something of a best-effort heuristic. - /// - /// We terminate when we find an unmatched `}` (without consuming it). - pub(super) fn recover_stmt(&mut self) { - self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore) - } - - /// If `break_on_semi` is `Break`, then we will stop consuming tokens after - /// finding (and consuming) a `;` outside of `{}` or `[]` (note that this is - /// approximate -- it can mean we break too early due to macros, but that - /// should only lead to sub-optimal recovery, not inaccurate parsing). - /// - /// If `break_on_block` is `Break`, then we will stop consuming tokens - /// after finding (and consuming) a brace-delimited block. - pub(super) fn recover_stmt_( - &mut self, - break_on_semi: SemiColonMode, - break_on_block: BlockMode, - ) { - let mut brace_depth = 0; - let mut bracket_depth = 0; - let mut in_block = false; - debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", - break_on_semi, break_on_block); - loop { - debug!("recover_stmt_ loop {:?}", self.token); - match self.token.kind { - token::OpenDelim(token::DelimToken::Brace) => { - brace_depth += 1; - self.bump(); - if break_on_block == BlockMode::Break && - brace_depth == 1 && - bracket_depth == 0 { - in_block = true; - } - } - token::OpenDelim(token::DelimToken::Bracket) => { - bracket_depth += 1; - self.bump(); - } - token::CloseDelim(token::DelimToken::Brace) => { - if brace_depth == 0 { - debug!("recover_stmt_ return - close delim {:?}", self.token); - break; - } - brace_depth -= 1; - self.bump(); - if in_block && bracket_depth == 0 && brace_depth == 0 { - debug!("recover_stmt_ return - block end {:?}", self.token); - break; - } - } - token::CloseDelim(token::DelimToken::Bracket) => { - bracket_depth -= 1; - if bracket_depth < 0 { - bracket_depth = 0; - } - self.bump(); - } - token::Eof => { - debug!("recover_stmt_ return - Eof"); - break; - } - token::Semi => { - self.bump(); - if break_on_semi == SemiColonMode::Break && - brace_depth == 0 && - bracket_depth == 0 { - debug!("recover_stmt_ return - Semi"); - break; - } - } - token::Comma if break_on_semi == SemiColonMode::Comma && - brace_depth == 0 && - bracket_depth == 0 => - { - debug!("recover_stmt_ return - Semi"); - break; - } - _ => { - self.bump() - } - } - } - } - - pub(super) fn check_for_for_in_in_typo(&mut self, in_span: Span) { - if self.eat_keyword(kw::In) { - // a common typo: `for _ in in bar {}` - self.struct_span_err(self.prev_span, "expected iterable, found keyword `in`") - .span_suggestion_short( - in_span.until(self.prev_span), - "remove the duplicated `in`", - String::new(), - Applicability::MachineApplicable, - ) - .emit(); - } - } - - pub(super) fn expected_semi_or_open_brace<T>(&mut self) -> PResult<'a, T> { - let token_str = self.this_token_descr(); - let mut err = self.fatal(&format!("expected `;` or `{{`, found {}", token_str)); - err.span_label(self.token.span, "expected `;` or `{`"); - Err(err) - } - - pub(super) fn eat_incorrect_doc_comment_for_param_type(&mut self) { - if let token::DocComment(_) = self.token.kind { - self.struct_span_err( - self.token.span, - "documentation comments cannot be applied to a function parameter's type", - ) - .span_label(self.token.span, "doc comments are not allowed here") - .emit(); - self.bump(); - } else if self.token == token::Pound && self.look_ahead(1, |t| { - *t == token::OpenDelim(token::Bracket) - }) { - let lo = self.token.span; - // Skip every token until next possible arg. - while self.token != token::CloseDelim(token::Bracket) { - self.bump(); - } - let sp = lo.to(self.token.span); - self.bump(); - self.struct_span_err( - sp, - "attributes cannot be applied to a function parameter's type", - ) - .span_label(sp, "attributes are not allowed here") - .emit(); - } - } - - pub(super) fn parameter_without_type( - &mut self, - err: &mut DiagnosticBuilder<'_>, - pat: P<ast::Pat>, - require_name: bool, - is_self_allowed: bool, - is_trait_item: bool, - ) -> Option<Ident> { - // If we find a pattern followed by an identifier, it could be an (incorrect) - // C-style parameter declaration. - if self.check_ident() && self.look_ahead(1, |t| { - *t == token::Comma || *t == token::CloseDelim(token::Paren) - }) { // `fn foo(String s) {}` - let ident = self.parse_ident().unwrap(); - let span = pat.span.with_hi(ident.span.hi()); - - err.span_suggestion( - span, - "declare the type after the parameter binding", - String::from("<identifier>: <type>"), - Applicability::HasPlaceholders, - ); - return Some(ident); - } else if let PatKind::Ident(_, ident, _) = pat.kind { - if require_name && ( - is_trait_item || - self.token == token::Comma || - self.token == token::Lt || - self.token == token::CloseDelim(token::Paren) - ) { // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}` - if is_self_allowed { - err.span_suggestion( - pat.span, - "if this is a `self` type, give it a parameter name", - format!("self: {}", ident), - Applicability::MaybeIncorrect, - ); - } - // Avoid suggesting that `fn foo(HashMap<u32>)` is fixed with a change to - // `fn foo(HashMap: TypeName<u32>)`. - if self.token != token::Lt { - err.span_suggestion( - pat.span, - "if this was a parameter name, give it a type", - format!("{}: TypeName", ident), - Applicability::HasPlaceholders, - ); - } - err.span_suggestion( - pat.span, - "if this is a type, explicitly ignore the parameter name", - format!("_: {}", ident), - Applicability::MachineApplicable, - ); - err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)"); - - // Don't attempt to recover by using the `X` in `X<Y>` as the parameter name. - return if self.token == token::Lt { None } else { Some(ident) }; - } - } - None - } - - pub(super) fn recover_arg_parse(&mut self) -> PResult<'a, (P<ast::Pat>, P<ast::Ty>)> { - let pat = self.parse_pat(Some("argument name"))?; - self.expect(&token::Colon)?; - let ty = self.parse_ty()?; - - self.diagnostic() - .struct_span_err_with_code( - pat.span, - "patterns aren't allowed in methods without bodies", - DiagnosticId::Error("E0642".into()), - ) - .span_suggestion_short( - pat.span, - "give this argument a name or use an underscore to ignore it", - "_".to_owned(), - Applicability::MachineApplicable, - ) - .emit(); - - // Pretend the pattern is `_`, to avoid duplicate errors from AST validation. - let pat = P(Pat { - kind: PatKind::Wild, - span: pat.span, - id: ast::DUMMY_NODE_ID - }); - Ok((pat, ty)) - } - - pub(super) fn recover_bad_self_param( - &mut self, - mut param: ast::Param, - is_trait_item: bool, - ) -> PResult<'a, ast::Param> { - let sp = param.pat.span; - param.ty.kind = TyKind::Err; - let mut err = self.struct_span_err(sp, "unexpected `self` parameter in function"); - if is_trait_item { - err.span_label(sp, "must be the first associated function parameter"); - } else { - err.span_label(sp, "not valid as function parameter"); - err.note("`self` is only valid as the first parameter of an associated function"); - } - err.emit(); - Ok(param) - } - - pub(super) fn consume_block( - &mut self, - delim: token::DelimToken, - consume_close: ConsumeClosingDelim, - ) { - let mut brace_depth = 0; - loop { - if self.eat(&token::OpenDelim(delim)) { - brace_depth += 1; - } else if self.check(&token::CloseDelim(delim)) { - if brace_depth == 0 { - if let ConsumeClosingDelim::Yes = consume_close { - // Some of the callers of this method expect to be able to parse the - // closing delimiter themselves, so we leave it alone. Otherwise we advance - // the parser. - self.bump(); - } - return; - } else { - self.bump(); - brace_depth -= 1; - continue; - } - } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) { - return; - } else { - self.bump(); - } - } - } - - pub(super) fn expected_expression_found(&self) -> DiagnosticBuilder<'a> { - let (span, msg) = match (&self.token.kind, self.subparser_name) { - (&token::Eof, Some(origin)) => { - let sp = self.sess.source_map().next_point(self.token.span); - (sp, format!("expected expression, found end of {}", origin)) - } - _ => (self.token.span, format!( - "expected expression, found {}", - self.this_token_descr(), - )), - }; - let mut err = self.struct_span_err(span, &msg); - let sp = self.sess.source_map().start_point(self.token.span); - if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) { - self.sess.expr_parentheses_needed(&mut err, *sp, None); - } - err.span_label(span, "expected expression"); - err - } - - fn consume_tts( - &mut self, - mut acc: i64, // `i64` because malformed code can have more closing delims than opening. - // Not using `FxHashMap` due to `token::TokenKind: !Eq + !Hash`. - modifier: &[(token::TokenKind, i64)], - ) { - while acc > 0 { - if let Some((_, val)) = modifier.iter().find(|(t, _)| *t == self.token.kind) { - acc += *val; - } - if self.token.kind == token::Eof { - break; - } - self.bump(); - } - } - - /// Replace duplicated recovered parameters with `_` pattern to avoid unecessary errors. - /// - /// This is necessary because at this point we don't know whether we parsed a function with - /// anonymous parameters or a function with names but no types. In order to minimize - /// unecessary errors, we assume the parameters are in the shape of `fn foo(a, b, c)` where - /// the parameters are *names* (so we don't emit errors about not being able to find `b` in - /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`, - /// we deduplicate them to not complain about duplicated parameter names. - pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) { - let mut seen_inputs = FxHashSet::default(); - for input in fn_inputs.iter_mut() { - let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) = ( - &input.pat.kind, &input.ty.kind, - ) { - Some(*ident) - } else { - None - }; - if let Some(ident) = opt_ident { - if seen_inputs.contains(&ident) { - input.pat.kind = PatKind::Wild; - } - seen_inputs.insert(ident); - } - } - } -} diff --git a/src/libsyntax/parse/parser/expr.rs b/src/libsyntax/parse/parser/expr.rs deleted file mode 100644 index 800074035ce..00000000000 --- a/src/libsyntax/parse/parser/expr.rs +++ /dev/null @@ -1,1964 +0,0 @@ -use super::{Parser, Restrictions, PrevTokenKind, TokenType, PathStyle, BlockMode}; -use super::{SemiColonMode, SeqSep, TokenExpectType}; -use super::pat::{GateOr, PARAM_EXPECTED}; -use super::diagnostics::Error; - -use crate::ast::{ - self, DUMMY_NODE_ID, Attribute, AttrStyle, Ident, CaptureBy, BlockCheckMode, - Expr, ExprKind, RangeLimits, Label, Movability, IsAsync, Arm, Ty, TyKind, - FunctionRetTy, Param, FnDecl, BinOpKind, BinOp, UnOp, Mac, AnonConst, Field, Lit, -}; -use crate::maybe_recover_from_interpolated_ty_qpath; -use crate::token::{self, Token, TokenKind}; -use crate::print::pprust; -use crate::ptr::P; -use crate::source_map::{self, Span}; -use crate::util::classify; -use crate::util::literal::LitError; -use crate::util::parser::{AssocOp, Fixity, prec_let_scrutinee_needs_par}; - -use errors::{PResult, Applicability}; -use syntax_pos::symbol::{kw, sym}; -use syntax_pos::Symbol; -use std::mem; -use rustc_data_structures::thin_vec::ThinVec; - -/// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression -/// dropped into the token stream, which happens while parsing the result of -/// macro expansion). Placement of these is not as complex as I feared it would -/// be. The important thing is to make sure that lookahead doesn't balk at -/// `token::Interpolated` tokens. -macro_rules! maybe_whole_expr { - ($p:expr) => { - if let token::Interpolated(nt) = &$p.token.kind { - match &**nt { - token::NtExpr(e) | token::NtLiteral(e) => { - let e = e.clone(); - $p.bump(); - return Ok(e); - } - token::NtPath(path) => { - let path = path.clone(); - $p.bump(); - return Ok($p.mk_expr( - $p.token.span, ExprKind::Path(None, path), ThinVec::new() - )); - } - token::NtBlock(block) => { - let block = block.clone(); - $p.bump(); - return Ok($p.mk_expr( - $p.token.span, ExprKind::Block(block, None), ThinVec::new() - )); - } - // N.B., `NtIdent(ident)` is normalized to `Ident` in `fn bump`. - _ => {}, - }; - } - } -} - -#[derive(Debug)] -pub(super) enum LhsExpr { - NotYetParsed, - AttributesParsed(ThinVec<Attribute>), - AlreadyParsed(P<Expr>), -} - -impl From<Option<ThinVec<Attribute>>> for LhsExpr { - /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)` - /// and `None` into `LhsExpr::NotYetParsed`. - /// - /// This conversion does not allocate. - fn from(o: Option<ThinVec<Attribute>>) -> Self { - if let Some(attrs) = o { - LhsExpr::AttributesParsed(attrs) - } else { - LhsExpr::NotYetParsed - } - } -} - -impl From<P<Expr>> for LhsExpr { - /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`. - /// - /// This conversion does not allocate. - fn from(expr: P<Expr>) -> Self { - LhsExpr::AlreadyParsed(expr) - } -} - -impl<'a> Parser<'a> { - /// Parses an expression. - #[inline] - pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> { - self.parse_expr_res(Restrictions::empty(), None) - } - - fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> { - self.parse_paren_comma_seq(|p| { - match p.parse_expr() { - Ok(expr) => Ok(expr), - Err(mut err) => match p.token.kind { - token::Ident(name, false) - if name == kw::Underscore && p.look_ahead(1, |t| { - t == &token::Comma - }) => { - // Special-case handling of `foo(_, _, _)` - err.emit(); - let sp = p.token.span; - p.bump(); - Ok(p.mk_expr(sp, ExprKind::Err, ThinVec::new())) - } - _ => Err(err), - }, - } - }).map(|(r, _)| r) - } - - /// Parses an expression, subject to the given restrictions. - #[inline] - pub(super) fn parse_expr_res( - &mut self, - r: Restrictions, - already_parsed_attrs: Option<ThinVec<Attribute>> - ) -> PResult<'a, P<Expr>> { - self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs)) - } - - /// Parses an associative expression. - /// - /// This parses an expression accounting for associativity and precedence of the operators in - /// the expression. - #[inline] - fn parse_assoc_expr( - &mut self, - already_parsed_attrs: Option<ThinVec<Attribute>>, - ) -> PResult<'a, P<Expr>> { - self.parse_assoc_expr_with(0, already_parsed_attrs.into()) - } - - /// Parses an associative expression with operators of at least `min_prec` precedence. - pub(super) fn parse_assoc_expr_with( - &mut self, - min_prec: usize, - lhs: LhsExpr, - ) -> PResult<'a, P<Expr>> { - let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs { - expr - } else { - let attrs = match lhs { - LhsExpr::AttributesParsed(attrs) => Some(attrs), - _ => None, - }; - if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) { - return self.parse_prefix_range_expr(attrs); - } else { - self.parse_prefix_expr(attrs)? - } - }; - let last_type_ascription_set = self.last_type_ascription.is_some(); - - match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) { - (true, None) => { - self.last_type_ascription = None; - // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071 - return Ok(lhs); - } - (false, _) => {} // continue parsing the expression - // An exhaustive check is done in the following block, but these are checked first - // because they *are* ambiguous but also reasonable looking incorrect syntax, so we - // want to keep their span info to improve diagnostics in these cases in a later stage. - (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3` - (true, Some(AssocOp::Subtract)) | // `{ 42 } -5` - (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475) - (true, Some(AssocOp::Add)) // `{ 42 } + 42 - // If the next token is a keyword, then the tokens above *are* unambiguously incorrect: - // `if x { a } else { b } && if y { c } else { d }` - if !self.look_ahead(1, |t| t.is_reserved_ident()) => { - self.last_type_ascription = None; - // These cases are ambiguous and can't be identified in the parser alone - let sp = self.sess.source_map().start_point(self.token.span); - self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span); - return Ok(lhs); - } - (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => { - self.last_type_ascription = None; - return Ok(lhs); - } - (true, Some(_)) => { - // We've found an expression that would be parsed as a statement, but the next - // token implies this should be parsed as an expression. - // For example: `if let Some(x) = x { x } else { 0 } / 2` - let mut err = self.struct_span_err(self.token.span, &format!( - "expected expression, found `{}`", - pprust::token_to_string(&self.token), - )); - err.span_label(self.token.span, "expected expression"); - self.sess.expr_parentheses_needed( - &mut err, - lhs.span, - Some(pprust::expr_to_string(&lhs), - )); - err.emit(); - } - } - self.expected_tokens.push(TokenType::Operator); - while let Some(op) = AssocOp::from_token(&self.token) { - - // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what - // it refers to. Interpolated identifiers are unwrapped early and never show up here - // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process - // it as "interpolated", it doesn't change the answer for non-interpolated idents. - let lhs_span = match (self.prev_token_kind, &lhs.kind) { - (PrevTokenKind::Interpolated, _) => self.prev_span, - (PrevTokenKind::Ident, &ExprKind::Path(None, ref path)) - if path.segments.len() == 1 => self.prev_span, - _ => lhs.span, - }; - - let cur_op_span = self.token.span; - let restrictions = if op.is_assign_like() { - self.restrictions & Restrictions::NO_STRUCT_LITERAL - } else { - self.restrictions - }; - let prec = op.precedence(); - if prec < min_prec { - break; - } - // Check for deprecated `...` syntax - if self.token == token::DotDotDot && op == AssocOp::DotDotEq { - self.err_dotdotdot_syntax(self.token.span); - } - - if self.token == token::LArrow { - self.err_larrow_operator(self.token.span); - } - - self.bump(); - if op.is_comparison() { - if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? { - return Ok(expr); - } - } - // Special cases: - if op == AssocOp::As { - lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?; - continue - } else if op == AssocOp::Colon { - let maybe_path = self.could_ascription_be_path(&lhs.kind); - self.last_type_ascription = Some((self.prev_span, maybe_path)); - - lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?; - self.sess.gated_spans.gate(sym::type_ascription, lhs.span); - continue - } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq { - // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to - // generalise it to the Fixity::None code. - // - // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other - // two variants are handled with `parse_prefix_range_expr` call above. - let rhs = if self.is_at_start_of_range_notation_rhs() { - Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?) - } else { - None - }; - let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs { - x.span - } else { - cur_op_span - }); - let limits = if op == AssocOp::DotDot { - RangeLimits::HalfOpen - } else { - RangeLimits::Closed - }; - - let r = self.mk_range(Some(lhs), rhs, limits)?; - lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new()); - break - } - - let fixity = op.fixity(); - let prec_adjustment = match fixity { - Fixity::Right => 0, - Fixity::Left => 1, - // We currently have no non-associative operators that are not handled above by - // the special cases. The code is here only for future convenience. - Fixity::None => 1, - }; - let rhs = self.with_res( - restrictions - Restrictions::STMT_EXPR, - |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed) - )?; - - // Make sure that the span of the parent node is larger than the span of lhs and rhs, - // including the attributes. - let lhs_span = lhs - .attrs - .iter() - .filter(|a| a.style == AttrStyle::Outer) - .next() - .map_or(lhs_span, |a| a.span); - let span = lhs_span.to(rhs.span); - lhs = match op { - AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | - AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor | - AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight | - AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual | - AssocOp::Greater | AssocOp::GreaterEqual => { - let ast_op = op.to_ast_binop().unwrap(); - let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs); - self.mk_expr(span, binary, ThinVec::new()) - } - AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()), - AssocOp::AssignOp(k) => { - let aop = match k { - token::Plus => BinOpKind::Add, - token::Minus => BinOpKind::Sub, - token::Star => BinOpKind::Mul, - token::Slash => BinOpKind::Div, - token::Percent => BinOpKind::Rem, - token::Caret => BinOpKind::BitXor, - token::And => BinOpKind::BitAnd, - token::Or => BinOpKind::BitOr, - token::Shl => BinOpKind::Shl, - token::Shr => BinOpKind::Shr, - }; - let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs); - self.mk_expr(span, aopexpr, ThinVec::new()) - } - AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => { - self.bug("AssocOp should have been handled by special case") - } - }; - - if let Fixity::None = fixity { break } - } - if last_type_ascription_set { - self.last_type_ascription = None; - } - Ok(lhs) - } - - /// Checks if this expression is a successfully parsed statement. - fn expr_is_complete(&self, e: &Expr) -> bool { - self.restrictions.contains(Restrictions::STMT_EXPR) && - !classify::expr_requires_semi_to_be_stmt(e) - } - - fn is_at_start_of_range_notation_rhs(&self) -> bool { - if self.token.can_begin_expr() { - // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`. - if self.token == token::OpenDelim(token::Brace) { - return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL); - } - true - } else { - false - } - } - - /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`. - fn parse_prefix_range_expr( - &mut self, - already_parsed_attrs: Option<ThinVec<Attribute>> - ) -> PResult<'a, P<Expr>> { - // Check for deprecated `...` syntax. - if self.token == token::DotDotDot { - self.err_dotdotdot_syntax(self.token.span); - } - - debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind), - "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq", - self.token); - let tok = self.token.clone(); - let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?; - let lo = self.token.span; - let mut hi = self.token.span; - self.bump(); - let opt_end = if self.is_at_start_of_range_notation_rhs() { - // RHS must be parsed with more associativity than the dots. - let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1; - Some(self.parse_assoc_expr_with(next_prec, LhsExpr::NotYetParsed) - .map(|x| { - hi = x.span; - x - })?) - } else { - None - }; - let limits = if tok == token::DotDot { - RangeLimits::HalfOpen - } else { - RangeLimits::Closed - }; - - let r = self.mk_range(None, opt_end, limits)?; - Ok(self.mk_expr(lo.to(hi), r, attrs)) - } - - /// Parses a prefix-unary-operator expr. - fn parse_prefix_expr( - &mut self, - already_parsed_attrs: Option<ThinVec<Attribute>> - ) -> PResult<'a, P<Expr>> { - let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?; - let lo = self.token.span; - // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr() - let (hi, ex) = match self.token.kind { - token::Not => { - self.bump(); - let e = self.parse_prefix_expr(None); - let (span, e) = self.interpolated_or_expr_span(e)?; - (lo.to(span), self.mk_unary(UnOp::Not, e)) - } - // Suggest `!` for bitwise negation when encountering a `~` - token::Tilde => { - self.bump(); - let e = self.parse_prefix_expr(None); - let (span, e) = self.interpolated_or_expr_span(e)?; - let span_of_tilde = lo; - self.struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator") - .span_suggestion_short( - span_of_tilde, - "use `!` to perform bitwise not", - "!".to_owned(), - Applicability::MachineApplicable - ) - .emit(); - (lo.to(span), self.mk_unary(UnOp::Not, e)) - } - token::BinOp(token::Minus) => { - self.bump(); - let e = self.parse_prefix_expr(None); - let (span, e) = self.interpolated_or_expr_span(e)?; - (lo.to(span), self.mk_unary(UnOp::Neg, e)) - } - token::BinOp(token::Star) => { - self.bump(); - let e = self.parse_prefix_expr(None); - let (span, e) = self.interpolated_or_expr_span(e)?; - (lo.to(span), self.mk_unary(UnOp::Deref, e)) - } - token::BinOp(token::And) | token::AndAnd => { - self.expect_and()?; - let m = self.parse_mutability(); - let e = self.parse_prefix_expr(None); - let (span, e) = self.interpolated_or_expr_span(e)?; - (lo.to(span), ExprKind::AddrOf(m, e)) - } - token::Ident(..) if self.token.is_keyword(kw::Box) => { - self.bump(); - let e = self.parse_prefix_expr(None); - let (span, e) = self.interpolated_or_expr_span(e)?; - let span = lo.to(span); - self.sess.gated_spans.gate(sym::box_syntax, span); - (span, ExprKind::Box(e)) - } - token::Ident(..) if self.token.is_ident_named(sym::not) => { - // `not` is just an ordinary identifier in Rust-the-language, - // but as `rustc`-the-compiler, we can issue clever diagnostics - // for confused users who really want to say `!` - let token_cannot_continue_expr = |t: &Token| match t.kind { - // These tokens can start an expression after `!`, but - // can't continue an expression after an ident - token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw), - token::Literal(..) | token::Pound => true, - _ => t.is_whole_expr(), - }; - let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr); - if cannot_continue_expr { - self.bump(); - // Emit the error ... - self.struct_span_err( - self.token.span, - &format!("unexpected {} after identifier",self.this_token_descr()) - ) - .span_suggestion_short( - // Span the `not` plus trailing whitespace to avoid - // trailing whitespace after the `!` in our suggestion - self.sess.source_map() - .span_until_non_whitespace(lo.to(self.token.span)), - "use `!` to perform logical negation", - "!".to_owned(), - Applicability::MachineApplicable - ) - .emit(); - // —and recover! (just as if we were in the block - // for the `token::Not` arm) - let e = self.parse_prefix_expr(None); - let (span, e) = self.interpolated_or_expr_span(e)?; - (lo.to(span), self.mk_unary(UnOp::Not, e)) - } else { - return self.parse_dot_or_call_expr(Some(attrs)); - } - } - _ => { return self.parse_dot_or_call_expr(Some(attrs)); } - }; - return Ok(self.mk_expr(lo.to(hi), ex, attrs)); - } - - /// Returns the span of expr, if it was not interpolated or the span of the interpolated token. - fn interpolated_or_expr_span( - &self, - expr: PResult<'a, P<Expr>>, - ) -> PResult<'a, (Span, P<Expr>)> { - expr.map(|e| { - if self.prev_token_kind == PrevTokenKind::Interpolated { - (self.prev_span, e) - } else { - (e.span, e) - } - }) - } - - fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span, - expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind) - -> PResult<'a, P<Expr>> { - let mk_expr = |this: &mut Self, rhs: P<Ty>| { - this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new()) - }; - - // Save the state of the parser before parsing type normally, in case there is a - // LessThan comparison after this cast. - let parser_snapshot_before_type = self.clone(); - match self.parse_ty_no_plus() { - Ok(rhs) => { - Ok(mk_expr(self, rhs)) - } - Err(mut type_err) => { - // Rewind to before attempting to parse the type with generics, to recover - // from situations like `x as usize < y` in which we first tried to parse - // `usize < y` as a type with generic arguments. - let parser_snapshot_after_type = self.clone(); - mem::replace(self, parser_snapshot_before_type); - - match self.parse_path(PathStyle::Expr) { - Ok(path) => { - let (op_noun, op_verb) = match self.token.kind { - token::Lt => ("comparison", "comparing"), - token::BinOp(token::Shl) => ("shift", "shifting"), - _ => { - // We can end up here even without `<` being the next token, for - // example because `parse_ty_no_plus` returns `Err` on keywords, - // but `parse_path` returns `Ok` on them due to error recovery. - // Return original error and parser state. - mem::replace(self, parser_snapshot_after_type); - return Err(type_err); - } - }; - - // Successfully parsed the type path leaving a `<` yet to parse. - type_err.cancel(); - - // Report non-fatal diagnostics, keep `x as usize` as an expression - // in AST and continue parsing. - let msg = format!( - "`<` is interpreted as a start of generic arguments for `{}`, not a {}", - pprust::path_to_string(&path), - op_noun, - ); - let span_after_type = parser_snapshot_after_type.token.span; - let expr = mk_expr(self, P(Ty { - span: path.span, - kind: TyKind::Path(None, path), - id: DUMMY_NODE_ID, - })); - - let expr_str = self.span_to_snippet(expr.span) - .unwrap_or_else(|_| pprust::expr_to_string(&expr)); - - self.struct_span_err(self.token.span, &msg) - .span_label( - self.look_ahead(1, |t| t.span).to(span_after_type), - "interpreted as generic arguments" - ) - .span_label(self.token.span, format!("not interpreted as {}", op_noun)) - .span_suggestion( - expr.span, - &format!("try {} the cast value", op_verb), - format!("({})", expr_str), - Applicability::MachineApplicable, - ) - .emit(); - - Ok(expr) - } - Err(mut path_err) => { - // Couldn't parse as a path, return original error and parser state. - path_err.cancel(); - mem::replace(self, parser_snapshot_after_type); - Err(type_err) - } - } - } - } - } - - /// Parses `a.b` or `a(13)` or `a[4]` or just `a`. - fn parse_dot_or_call_expr( - &mut self, - already_parsed_attrs: Option<ThinVec<Attribute>>, - ) -> PResult<'a, P<Expr>> { - let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?; - - let b = self.parse_bottom_expr(); - let (span, b) = self.interpolated_or_expr_span(b)?; - self.parse_dot_or_call_expr_with(b, span, attrs) - } - - pub(super) fn parse_dot_or_call_expr_with( - &mut self, - e0: P<Expr>, - lo: Span, - mut attrs: ThinVec<Attribute>, - ) -> PResult<'a, P<Expr>> { - // Stitch the list of outer attributes onto the return value. - // A little bit ugly, but the best way given the current code - // structure - self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| - expr.map(|mut expr| { - attrs.extend::<Vec<_>>(expr.attrs.into()); - expr.attrs = attrs; - match expr.kind { - ExprKind::If(..) if !expr.attrs.is_empty() => { - // Just point to the first attribute in there... - let span = expr.attrs[0].span; - self.span_err(span, "attributes are not yet allowed on `if` expressions"); - } - _ => {} - } - expr - }) - ) - } - - fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> { - let mut e = e0; - let mut hi; - loop { - // expr? - while self.eat(&token::Question) { - let hi = self.prev_span; - e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new()); - } - - // expr.f - if self.eat(&token::Dot) { - match self.token.kind { - token::Ident(..) => { - e = self.parse_dot_suffix(e, lo)?; - } - token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => { - let span = self.token.span; - self.bump(); - let field = ExprKind::Field(e, Ident::new(symbol, span)); - e = self.mk_expr(lo.to(span), field, ThinVec::new()); - - self.expect_no_suffix(span, "a tuple index", suffix); - } - token::Literal(token::Lit { kind: token::Float, symbol, .. }) => { - self.bump(); - let fstr = symbol.as_str(); - let msg = format!("unexpected token: `{}`", symbol); - let mut err = self.diagnostic().struct_span_err(self.prev_span, &msg); - err.span_label(self.prev_span, "unexpected token"); - if fstr.chars().all(|x| "0123456789.".contains(x)) { - let float = match fstr.parse::<f64>().ok() { - Some(f) => f, - None => continue, - }; - let sugg = pprust::to_string(|s| { - s.popen(); - s.print_expr(&e); - s.s.word( "."); - s.print_usize(float.trunc() as usize); - s.pclose(); - s.s.word("."); - s.s.word(fstr.splitn(2, ".").last().unwrap().to_string()) - }); - err.span_suggestion( - lo.to(self.prev_span), - "try parenthesizing the first index", - sugg, - Applicability::MachineApplicable - ); - } - return Err(err); - - } - _ => { - // FIXME Could factor this out into non_fatal_unexpected or something. - let actual = self.this_token_to_string(); - self.span_err(self.token.span, &format!("unexpected token: `{}`", actual)); - } - } - continue; - } - if self.expr_is_complete(&e) { break; } - match self.token.kind { - // expr(...) - token::OpenDelim(token::Paren) => { - let seq = self.parse_paren_expr_seq().map(|es| { - let nd = self.mk_call(e, es); - let hi = self.prev_span; - self.mk_expr(lo.to(hi), nd, ThinVec::new()) - }); - e = self.recover_seq_parse_error(token::Paren, lo, seq); - } - - // expr[...] - // Could be either an index expression or a slicing expression. - token::OpenDelim(token::Bracket) => { - self.bump(); - let ix = self.parse_expr()?; - hi = self.token.span; - self.expect(&token::CloseDelim(token::Bracket))?; - let index = self.mk_index(e, ix); - e = self.mk_expr(lo.to(hi), index, ThinVec::new()) - } - _ => return Ok(e) - } - } - return Ok(e); - } - - /// Assuming we have just parsed `.`, continue parsing into an expression. - fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> { - if self.token.span.rust_2018() && self.eat_keyword(kw::Await) { - return self.mk_await_expr(self_arg, lo); - } - - let segment = self.parse_path_segment(PathStyle::Expr)?; - self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren)); - - Ok(match self.token.kind { - token::OpenDelim(token::Paren) => { - // Method call `expr.f()` - let mut args = self.parse_paren_expr_seq()?; - args.insert(0, self_arg); - - let span = lo.to(self.prev_span); - self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new()) - } - _ => { - // Field access `expr.f` - if let Some(args) = segment.args { - self.span_err(args.span(), - "field expressions may not have generic arguments"); - } - - let span = lo.to(self.prev_span); - self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new()) - } - }) - } - - /// At the bottom (top?) of the precedence hierarchy, - /// Parses things like parenthesized exprs, macros, `return`, etc. - /// - /// N.B., this does not parse outer attributes, and is private because it only works - /// correctly if called from `parse_dot_or_call_expr()`. - fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> { - maybe_recover_from_interpolated_ty_qpath!(self, true); - maybe_whole_expr!(self); - - // Outer attributes are already parsed and will be - // added to the return value after the fact. - // - // Therefore, prevent sub-parser from parsing - // attributes by giving them a empty "already-parsed" list. - let mut attrs = ThinVec::new(); - - let lo = self.token.span; - let mut hi = self.token.span; - - let ex: ExprKind; - - macro_rules! parse_lit { - () => { - match self.parse_lit() { - Ok(literal) => { - hi = self.prev_span; - ex = ExprKind::Lit(literal); - } - Err(mut err) => { - err.cancel(); - return Err(self.expected_expression_found()); - } - } - } - } - - // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`. - match self.token.kind { - // This match arm is a special-case of the `_` match arm below and - // could be removed without changing functionality, but it's faster - // to have it here, especially for programs with large constants. - token::Literal(_) => { - parse_lit!() - } - token::OpenDelim(token::Paren) => { - self.bump(); - - attrs.extend(self.parse_inner_attributes()?); - - // `(e)` is parenthesized `e`. - // `(e,)` is a tuple with only one field, `e`. - let mut es = vec![]; - let mut trailing_comma = false; - let mut recovered = false; - while self.token != token::CloseDelim(token::Paren) { - es.push(match self.parse_expr() { - Ok(es) => es, - Err(mut err) => { - // Recover from parse error in tuple list. - match self.token.kind { - token::Ident(name, false) - if name == kw::Underscore && self.look_ahead(1, |t| { - t == &token::Comma - }) => { - // Special-case handling of `Foo<(_, _, _)>` - err.emit(); - let sp = self.token.span; - self.bump(); - self.mk_expr(sp, ExprKind::Err, ThinVec::new()) - } - _ => return Ok( - self.recover_seq_parse_error(token::Paren, lo, Err(err)), - ), - } - } - }); - recovered = self.expect_one_of( - &[], - &[token::Comma, token::CloseDelim(token::Paren)], - )?; - if self.eat(&token::Comma) { - trailing_comma = true; - } else { - trailing_comma = false; - break; - } - } - if !recovered { - self.bump(); - } - - hi = self.prev_span; - ex = if es.len() == 1 && !trailing_comma { - ExprKind::Paren(es.into_iter().nth(0).unwrap()) - } else { - ExprKind::Tup(es) - }; - } - token::OpenDelim(token::Brace) => { - return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs); - } - token::BinOp(token::Or) | token::OrOr => { - return self.parse_closure_expr(attrs); - } - token::OpenDelim(token::Bracket) => { - self.bump(); - - attrs.extend(self.parse_inner_attributes()?); - - if self.eat(&token::CloseDelim(token::Bracket)) { - // Empty vector - ex = ExprKind::Array(Vec::new()); - } else { - // Non-empty vector - let first_expr = self.parse_expr()?; - if self.eat(&token::Semi) { - // Repeating array syntax: `[ 0; 512 ]` - let count = AnonConst { - id: DUMMY_NODE_ID, - value: self.parse_expr()?, - }; - self.expect(&token::CloseDelim(token::Bracket))?; - ex = ExprKind::Repeat(first_expr, count); - } else if self.eat(&token::Comma) { - // Vector with two or more elements - let remaining_exprs = self.parse_seq_to_end( - &token::CloseDelim(token::Bracket), - SeqSep::trailing_allowed(token::Comma), - |p| Ok(p.parse_expr()?) - )?; - let mut exprs = vec![first_expr]; - exprs.extend(remaining_exprs); - ex = ExprKind::Array(exprs); - } else { - // Vector with one element - self.expect(&token::CloseDelim(token::Bracket))?; - ex = ExprKind::Array(vec![first_expr]); - } - } - hi = self.prev_span; - } - _ => { - if self.eat_lt() { - let (qself, path) = self.parse_qpath(PathStyle::Expr)?; - hi = path.span; - return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs)); - } - if self.token.is_path_start() { - let path = self.parse_path(PathStyle::Expr)?; - - // `!`, as an operator, is prefix, so we know this isn't that. - if self.eat(&token::Not) { - // MACRO INVOCATION expression - let (delim, tts) = self.expect_delimited_token_tree()?; - hi = self.prev_span; - ex = ExprKind::Mac(Mac { - path, - tts, - delim, - span: lo.to(hi), - prior_type_ascription: self.last_type_ascription, - }); - } else if self.check(&token::OpenDelim(token::Brace)) { - if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) { - return expr; - } else { - hi = path.span; - ex = ExprKind::Path(None, path); - } - } else { - hi = path.span; - ex = ExprKind::Path(None, path); - } - - let expr = self.mk_expr(lo.to(hi), ex, attrs); - return self.maybe_recover_from_bad_qpath(expr, true); - } - if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) { - return self.parse_closure_expr(attrs); - } - if self.eat_keyword(kw::If) { - return self.parse_if_expr(attrs); - } - if self.eat_keyword(kw::For) { - let lo = self.prev_span; - return self.parse_for_expr(None, lo, attrs); - } - if self.eat_keyword(kw::While) { - let lo = self.prev_span; - return self.parse_while_expr(None, lo, attrs); - } - if let Some(label) = self.eat_label() { - let lo = label.ident.span; - self.expect(&token::Colon)?; - if self.eat_keyword(kw::While) { - return self.parse_while_expr(Some(label), lo, attrs) - } - if self.eat_keyword(kw::For) { - return self.parse_for_expr(Some(label), lo, attrs) - } - if self.eat_keyword(kw::Loop) { - return self.parse_loop_expr(Some(label), lo, attrs) - } - if self.token == token::OpenDelim(token::Brace) { - return self.parse_block_expr(Some(label), - lo, - BlockCheckMode::Default, - attrs); - } - let msg = "expected `while`, `for`, `loop` or `{` after a label"; - let mut err = self.fatal(msg); - err.span_label(self.token.span, msg); - return Err(err); - } - if self.eat_keyword(kw::Loop) { - let lo = self.prev_span; - return self.parse_loop_expr(None, lo, attrs); - } - if self.eat_keyword(kw::Continue) { - let label = self.eat_label(); - let ex = ExprKind::Continue(label); - let hi = self.prev_span; - return Ok(self.mk_expr(lo.to(hi), ex, attrs)); - } - if self.eat_keyword(kw::Match) { - let match_sp = self.prev_span; - return self.parse_match_expr(attrs).map_err(|mut err| { - err.span_label(match_sp, "while parsing this match expression"); - err - }); - } - if self.eat_keyword(kw::Unsafe) { - return self.parse_block_expr( - None, - lo, - BlockCheckMode::Unsafe(ast::UserProvided), - attrs); - } - if self.is_do_catch_block() { - let mut db = self.fatal("found removed `do catch` syntax"); - db.help("following RFC #2388, the new non-placeholder syntax is `try`"); - return Err(db); - } - if self.is_try_block() { - let lo = self.token.span; - assert!(self.eat_keyword(kw::Try)); - return self.parse_try_block(lo, attrs); - } - - // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly. - let is_span_rust_2018 = self.token.span.rust_2018(); - if is_span_rust_2018 && self.check_keyword(kw::Async) { - return if self.is_async_block() { // Check for `async {` and `async move {`. - self.parse_async_block(attrs) - } else { - self.parse_closure_expr(attrs) - }; - } - if self.eat_keyword(kw::Return) { - if self.token.can_begin_expr() { - let e = self.parse_expr()?; - hi = e.span; - ex = ExprKind::Ret(Some(e)); - } else { - ex = ExprKind::Ret(None); - } - } else if self.eat_keyword(kw::Break) { - let label = self.eat_label(); - let e = if self.token.can_begin_expr() - && !(self.token == token::OpenDelim(token::Brace) - && self.restrictions.contains( - Restrictions::NO_STRUCT_LITERAL)) { - Some(self.parse_expr()?) - } else { - None - }; - ex = ExprKind::Break(label, e); - hi = self.prev_span; - } else if self.eat_keyword(kw::Yield) { - if self.token.can_begin_expr() { - let e = self.parse_expr()?; - hi = e.span; - ex = ExprKind::Yield(Some(e)); - } else { - ex = ExprKind::Yield(None); - } - - let span = lo.to(hi); - self.sess.gated_spans.gate(sym::generators, span); - } else if self.eat_keyword(kw::Let) { - return self.parse_let_expr(attrs); - } else if is_span_rust_2018 && self.eat_keyword(kw::Await) { - let (await_hi, e_kind) = self.parse_incorrect_await_syntax(lo, self.prev_span)?; - hi = await_hi; - ex = e_kind; - } else { - if !self.unclosed_delims.is_empty() && self.check(&token::Semi) { - // Don't complain about bare semicolons after unclosed braces - // recovery in order to keep the error count down. Fixing the - // delimiters will possibly also fix the bare semicolon found in - // expression context. For example, silence the following error: - // - // error: expected expression, found `;` - // --> file.rs:2:13 - // | - // 2 | foo(bar(; - // | ^ expected expression - self.bump(); - return Ok(self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new())); - } - parse_lit!() - } - } - } - - let expr = self.mk_expr(lo.to(hi), ex, attrs); - self.maybe_recover_from_bad_qpath(expr, true) - } - - /// Matches `lit = true | false | token_lit`. - pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> { - let mut recovered = None; - if self.token == token::Dot { - // Attempt to recover `.4` as `0.4`. - recovered = self.look_ahead(1, |next_token| { - if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) - = next_token.kind { - if self.token.span.hi() == next_token.span.lo() { - let s = String::from("0.") + &symbol.as_str(); - let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix); - return Some(Token::new(kind, self.token.span.to(next_token.span))); - } - } - None - }); - if let Some(token) = &recovered { - self.bump(); - self.struct_span_err(token.span, "float literals must have an integer part") - .span_suggestion( - token.span, - "must have an integer part", - pprust::token_to_string(token), - Applicability::MachineApplicable, - ) - .emit(); - } - } - - let token = recovered.as_ref().unwrap_or(&self.token); - match Lit::from_token(token) { - Ok(lit) => { - self.bump(); - Ok(lit) - } - Err(LitError::NotLiteral) => { - let msg = format!("unexpected token: {}", self.this_token_descr()); - Err(self.span_fatal(token.span, &msg)) - } - Err(err) => { - let span = token.span; - let lit = match token.kind { - token::Literal(lit) => lit, - _ => unreachable!(), - }; - self.bump(); - self.error_literal_from_token(err, lit, span); - // Pack possible quotes and prefixes from the original literal into - // the error literal's symbol so they can be pretty-printed faithfully. - let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None); - let symbol = Symbol::intern(&suffixless_lit.to_string()); - let lit = token::Lit::new(token::Err, symbol, lit.suffix); - Lit::from_lit_token(lit, span).map_err(|_| unreachable!()) - } - } - } - - fn error_literal_from_token(&self, err: LitError, lit: token::Lit, span: Span) { - // Checks if `s` looks like i32 or u1234 etc. - fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool { - s.len() > 1 - && s.starts_with(first_chars) - && s[1..].chars().all(|c| c.is_ascii_digit()) - } - - let token::Lit { kind, suffix, .. } = lit; - match err { - // `NotLiteral` is not an error by itself, so we don't report - // it and give the parser opportunity to try something else. - LitError::NotLiteral => {} - // `LexerError` *is* an error, but it was already reported - // by lexer, so here we don't report it the second time. - LitError::LexerError => {} - LitError::InvalidSuffix => { - self.expect_no_suffix( - span, - &format!("{} {} literal", kind.article(), kind.descr()), - suffix, - ); - } - LitError::InvalidIntSuffix => { - let suf = suffix.expect("suffix error with no suffix").as_str(); - if looks_like_width_suffix(&['i', 'u'], &suf) { - // If it looks like a width, try to be helpful. - let msg = format!("invalid width `{}` for integer literal", &suf[1..]); - self.struct_span_err(span, &msg) - .help("valid widths are 8, 16, 32, 64 and 128") - .emit(); - } else { - let msg = format!("invalid suffix `{}` for integer literal", suf); - self.struct_span_err(span, &msg) - .span_label(span, format!("invalid suffix `{}`", suf)) - .help("the suffix must be one of the integral types (`u32`, `isize`, etc)") - .emit(); - } - } - LitError::InvalidFloatSuffix => { - let suf = suffix.expect("suffix error with no suffix").as_str(); - if looks_like_width_suffix(&['f'], &suf) { - // If it looks like a width, try to be helpful. - let msg = format!("invalid width `{}` for float literal", &suf[1..]); - self.struct_span_err(span, &msg) - .help("valid widths are 32 and 64") - .emit(); - } else { - let msg = format!("invalid suffix `{}` for float literal", suf); - self.struct_span_err(span, &msg) - .span_label(span, format!("invalid suffix `{}`", suf)) - .help("valid suffixes are `f32` and `f64`") - .emit(); - } - } - LitError::NonDecimalFloat(base) => { - let descr = match base { - 16 => "hexadecimal", - 8 => "octal", - 2 => "binary", - _ => unreachable!(), - }; - self.struct_span_err(span, &format!("{} float literal is not supported", descr)) - .span_label(span, "not supported") - .emit(); - } - LitError::IntTooLarge => { - self.struct_span_err(span, "integer literal is too large") - .emit(); - } - } - } - - pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) { - if let Some(suf) = suffix { - let mut err = if kind == "a tuple index" - && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf) - { - // #59553: warn instead of reject out of hand to allow the fix to percolate - // through the ecosystem when people fix their macros - let mut err = self.sess.span_diagnostic.struct_span_warn( - sp, - &format!("suffixes on {} are invalid", kind), - ); - err.note(&format!( - "`{}` is *temporarily* accepted on tuple index fields as it was \ - incorrectly accepted on stable for a few releases", - suf, - )); - err.help( - "on proc macros, you'll want to use `syn::Index::from` or \ - `proc_macro::Literal::*_unsuffixed` for code that will desugar \ - to tuple field access", - ); - err.note( - "for more context, see https://github.com/rust-lang/rust/issues/60210", - ); - err - } else { - self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind)) - }; - err.span_label(sp, format!("invalid suffix `{}`", suf)); - err.emit(); - } - } - - /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`). - pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> { - maybe_whole_expr!(self); - - let minus_lo = self.token.span; - let minus_present = self.eat(&token::BinOp(token::Minus)); - let lo = self.token.span; - let literal = self.parse_lit()?; - let hi = self.prev_span; - let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new()); - - if minus_present { - let minus_hi = self.prev_span; - let unary = self.mk_unary(UnOp::Neg, expr); - Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new())) - } else { - Ok(expr) - } - } - - /// Parses a block or unsafe block. - pub(super) fn parse_block_expr( - &mut self, - opt_label: Option<Label>, - lo: Span, - blk_mode: BlockCheckMode, - outer_attrs: ThinVec<Attribute>, - ) -> PResult<'a, P<Expr>> { - if let Some(label) = opt_label { - self.sess.gated_spans.gate(sym::label_break_value, label.ident.span); - } - - self.expect(&token::OpenDelim(token::Brace))?; - - let mut attrs = outer_attrs; - attrs.extend(self.parse_inner_attributes()?); - - let blk = self.parse_block_tail(lo, blk_mode)?; - Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs)) - } - - /// Parses a closure expression (e.g., `move |args| expr`). - fn parse_closure_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { - let lo = self.token.span; - - let movability = if self.eat_keyword(kw::Static) { - Movability::Static - } else { - Movability::Movable - }; - - let asyncness = if self.token.span.rust_2018() { - self.parse_asyncness() - } else { - IsAsync::NotAsync - }; - if asyncness.is_async() { - // Feature-gate `async ||` closures. - self.sess.gated_spans.gate(sym::async_closure, self.prev_span); - } - - let capture_clause = self.parse_capture_clause(); - let decl = self.parse_fn_block_decl()?; - let decl_hi = self.prev_span; - let body = match decl.output { - FunctionRetTy::Default(_) => { - let restrictions = self.restrictions - Restrictions::STMT_EXPR; - self.parse_expr_res(restrictions, None)? - }, - _ => { - // If an explicit return type is given, require a block to appear (RFC 968). - let body_lo = self.token.span; - self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())? - } - }; - - Ok(self.mk_expr( - lo.to(body.span), - ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)), - attrs)) - } - - /// Parses an optional `move` prefix to a closure lke construct. - fn parse_capture_clause(&mut self) -> CaptureBy { - if self.eat_keyword(kw::Move) { - CaptureBy::Value - } else { - CaptureBy::Ref - } - } - - /// Parses the `|arg, arg|` header of a closure. - fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> { - let inputs_captures = { - if self.eat(&token::OrOr) { - Vec::new() - } else { - self.expect(&token::BinOp(token::Or))?; - let args = self.parse_seq_to_before_tokens( - &[&token::BinOp(token::Or), &token::OrOr], - SeqSep::trailing_allowed(token::Comma), - TokenExpectType::NoExpect, - |p| p.parse_fn_block_param() - )?.0; - self.expect_or()?; - args - } - }; - let output = self.parse_ret_ty(true)?; - - Ok(P(FnDecl { - inputs: inputs_captures, - output, - })) - } - - /// Parses a parameter in a closure header (e.g., `|arg, arg|`). - fn parse_fn_block_param(&mut self) -> PResult<'a, Param> { - let lo = self.token.span; - let attrs = self.parse_outer_attributes()?; - let pat = self.parse_pat(PARAM_EXPECTED)?; - let t = if self.eat(&token::Colon) { - self.parse_ty()? - } else { - P(Ty { - id: DUMMY_NODE_ID, - kind: TyKind::Infer, - span: self.prev_span, - }) - }; - let span = lo.to(self.token.span); - Ok(Param { - attrs: attrs.into(), - ty: t, - pat, - span, - id: DUMMY_NODE_ID, - is_placeholder: false, - }) - } - - /// Parses an `if` expression (`if` token already eaten). - fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { - let lo = self.prev_span; - let cond = self.parse_cond_expr()?; - - // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then - // verify that the last statement is either an implicit return (no `;`) or an explicit - // return. This won't catch blocks with an explicit `return`, but that would be caught by - // the dead code lint. - if self.eat_keyword(kw::Else) || !cond.returns() { - let sp = self.sess.source_map().next_point(lo); - let mut err = self.diagnostic() - .struct_span_err(sp, "missing condition for `if` expression"); - err.span_label(sp, "expected if condition here"); - return Err(err) - } - let not_block = self.token != token::OpenDelim(token::Brace); - let thn = self.parse_block().map_err(|mut err| { - if not_block { - err.span_label(lo, "this `if` statement has a condition, but no block"); - } - err - })?; - let mut els: Option<P<Expr>> = None; - let mut hi = thn.span; - if self.eat_keyword(kw::Else) { - let elexpr = self.parse_else_expr()?; - hi = elexpr.span; - els = Some(elexpr); - } - Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs)) - } - - /// Parses the condition of a `if` or `while` expression. - fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> { - let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?; - - if let ExprKind::Let(..) = cond.kind { - // Remove the last feature gating of a `let` expression since it's stable. - self.sess.gated_spans.ungate_last(sym::let_chains, cond.span); - } - - Ok(cond) - } - - /// Parses a `let $pat = $expr` pseudo-expression. - /// The `let` token has already been eaten. - fn parse_let_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { - let lo = self.prev_span; - let pat = self.parse_top_pat(GateOr::No)?; - self.expect(&token::Eq)?; - let expr = self.with_res( - Restrictions::NO_STRUCT_LITERAL, - |this| this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into()) - )?; - let span = lo.to(expr.span); - self.sess.gated_spans.gate(sym::let_chains, span); - Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs)) - } - - /// Parses an `else { ... }` expression (`else` token already eaten). - fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> { - if self.eat_keyword(kw::If) { - return self.parse_if_expr(ThinVec::new()); - } else { - let blk = self.parse_block()?; - return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new())); - } - } - - /// Parses a `for ... in` expression (`for` token already eaten). - fn parse_for_expr( - &mut self, - opt_label: Option<Label>, - span_lo: Span, - mut attrs: ThinVec<Attribute> - ) -> PResult<'a, P<Expr>> { - // Parse: `for <src_pat> in <src_expr> <src_loop_block>` - - // Record whether we are about to parse `for (`. - // This is used below for recovery in case of `for ( $stuff ) $block` - // in which case we will suggest `for $stuff $block`. - let begin_paren = match self.token.kind { - token::OpenDelim(token::Paren) => Some(self.token.span), - _ => None, - }; - - let pat = self.parse_top_pat(GateOr::Yes)?; - if !self.eat_keyword(kw::In) { - let in_span = self.prev_span.between(self.token.span); - self.struct_span_err(in_span, "missing `in` in `for` loop") - .span_suggestion_short( - in_span, - "try adding `in` here", " in ".into(), - // has been misleading, at least in the past (closed Issue #48492) - Applicability::MaybeIncorrect - ) - .emit(); - } - let in_span = self.prev_span; - self.check_for_for_in_in_typo(in_span); - let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?; - - let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren); - - let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?; - attrs.extend(iattrs); - - let hi = self.prev_span; - Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs)) - } - - /// Parses a `while` or `while let` expression (`while` token already eaten). - fn parse_while_expr( - &mut self, - opt_label: Option<Label>, - span_lo: Span, - mut attrs: ThinVec<Attribute> - ) -> PResult<'a, P<Expr>> { - let cond = self.parse_cond_expr()?; - let (iattrs, body) = self.parse_inner_attrs_and_block()?; - attrs.extend(iattrs); - let span = span_lo.to(body.span); - Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs)) - } - - /// Parses `loop { ... }` (`loop` token already eaten). - fn parse_loop_expr( - &mut self, - opt_label: Option<Label>, - span_lo: Span, - mut attrs: ThinVec<Attribute> - ) -> PResult<'a, P<Expr>> { - let (iattrs, body) = self.parse_inner_attrs_and_block()?; - attrs.extend(iattrs); - let span = span_lo.to(body.span); - Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs)) - } - - fn eat_label(&mut self) -> Option<Label> { - if let Some(ident) = self.token.lifetime() { - let span = self.token.span; - self.bump(); - Some(Label { ident: Ident::new(ident.name, span) }) - } else { - None - } - } - - /// Parses a `match ... { ... }` expression (`match` token already eaten). - fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { - let match_span = self.prev_span; - let lo = self.prev_span; - let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?; - if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) { - if self.token == token::Semi { - e.span_suggestion_short( - match_span, - "try removing this `match`", - String::new(), - Applicability::MaybeIncorrect // speculative - ); - } - return Err(e) - } - attrs.extend(self.parse_inner_attributes()?); - - let mut arms: Vec<Arm> = Vec::new(); - while self.token != token::CloseDelim(token::Brace) { - match self.parse_arm() { - Ok(arm) => arms.push(arm), - Err(mut e) => { - // Recover by skipping to the end of the block. - e.emit(); - self.recover_stmt(); - let span = lo.to(self.token.span); - if self.token == token::CloseDelim(token::Brace) { - self.bump(); - } - return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs)); - } - } - } - let hi = self.token.span; - self.bump(); - return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs)); - } - - pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> { - let attrs = self.parse_outer_attributes()?; - let lo = self.token.span; - let pat = self.parse_top_pat(GateOr::No)?; - let guard = if self.eat_keyword(kw::If) { - Some(self.parse_expr()?) - } else { - None - }; - let arrow_span = self.token.span; - self.expect(&token::FatArrow)?; - let arm_start_span = self.token.span; - - let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None) - .map_err(|mut err| { - err.span_label(arrow_span, "while parsing the `match` arm starting here"); - err - })?; - - let require_comma = classify::expr_requires_semi_to_be_stmt(&expr) - && self.token != token::CloseDelim(token::Brace); - - let hi = self.token.span; - - if require_comma { - let cm = self.sess.source_map(); - self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]) - .map_err(|mut err| { - match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) { - (Ok(ref expr_lines), Ok(ref arm_start_lines)) - if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col - && expr_lines.lines.len() == 2 - && self.token == token::FatArrow => { - // We check whether there's any trailing code in the parse span, - // if there isn't, we very likely have the following: - // - // X | &Y => "y" - // | -- - missing comma - // | | - // | arrow_span - // X | &X => "x" - // | - ^^ self.token.span - // | | - // | parsed until here as `"y" & X` - err.span_suggestion_short( - cm.next_point(arm_start_span), - "missing a comma here to end this `match` arm", - ",".to_owned(), - Applicability::MachineApplicable - ); - } - _ => { - err.span_label(arrow_span, - "while parsing the `match` arm starting here"); - } - } - err - })?; - } else { - self.eat(&token::Comma); - } - - Ok(ast::Arm { - attrs, - pat, - guard, - body: expr, - span: lo.to(hi), - id: DUMMY_NODE_ID, - is_placeholder: false, - }) - } - - /// Parses a `try {...}` expression (`try` token already eaten). - fn parse_try_block( - &mut self, - span_lo: Span, - mut attrs: ThinVec<Attribute> - ) -> PResult<'a, P<Expr>> { - let (iattrs, body) = self.parse_inner_attrs_and_block()?; - attrs.extend(iattrs); - if self.eat_keyword(kw::Catch) { - let mut error = self.struct_span_err(self.prev_span, - "keyword `catch` cannot follow a `try` block"); - error.help("try using `match` on the result of the `try` block instead"); - error.emit(); - Err(error) - } else { - let span = span_lo.to(body.span); - self.sess.gated_spans.gate(sym::try_blocks, span); - Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs)) - } - } - - fn is_do_catch_block(&self) -> bool { - self.token.is_keyword(kw::Do) && - self.is_keyword_ahead(1, &[kw::Catch]) && - self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) && - !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL) - } - - fn is_try_block(&self) -> bool { - self.token.is_keyword(kw::Try) && - self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) && - self.token.span.rust_2018() && - // Prevent `while try {} {}`, `if try {} {} else {}`, etc. - !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL) - } - - /// Parses an `async move? {...}` expression. - fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> { - let span_lo = self.token.span; - self.expect_keyword(kw::Async)?; - let capture_clause = self.parse_capture_clause(); - let (iattrs, body) = self.parse_inner_attrs_and_block()?; - attrs.extend(iattrs); - Ok(self.mk_expr( - span_lo.to(body.span), - ExprKind::Async(capture_clause, DUMMY_NODE_ID, body), attrs)) - } - - fn is_async_block(&self) -> bool { - self.token.is_keyword(kw::Async) && - ( - ( // `async move {` - self.is_keyword_ahead(1, &[kw::Move]) && - self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) - ) || ( // `async {` - self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) - ) - ) - } - - fn maybe_parse_struct_expr( - &mut self, - lo: Span, - path: &ast::Path, - attrs: &ThinVec<Attribute>, - ) -> Option<PResult<'a, P<Expr>>> { - let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL); - let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && ( - // `{ ident, ` cannot start a block. - self.look_ahead(2, |t| t == &token::Comma) || - self.look_ahead(2, |t| t == &token::Colon) && ( - // `{ ident: token, ` cannot start a block. - self.look_ahead(4, |t| t == &token::Comma) || - // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`. - self.look_ahead(3, |t| !t.can_begin_type()) - ) - ); - - if struct_allowed || certainly_not_a_block() { - // This is a struct literal, but we don't can't accept them here. - let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone()); - if let (Ok(expr), false) = (&expr, struct_allowed) { - self.struct_span_err( - expr.span, - "struct literals are not allowed here", - ) - .multipart_suggestion( - "surround the struct literal with parentheses", - vec![ - (lo.shrink_to_lo(), "(".to_string()), - (expr.span.shrink_to_hi(), ")".to_string()), - ], - Applicability::MachineApplicable, - ) - .emit(); - } - return Some(expr); - } - None - } - - pub(super) fn parse_struct_expr( - &mut self, - lo: Span, - pth: ast::Path, - mut attrs: ThinVec<Attribute> - ) -> PResult<'a, P<Expr>> { - let struct_sp = lo.to(self.prev_span); - self.bump(); - let mut fields = Vec::new(); - let mut base = None; - - attrs.extend(self.parse_inner_attributes()?); - - while self.token != token::CloseDelim(token::Brace) { - if self.eat(&token::DotDot) { - let exp_span = self.prev_span; - match self.parse_expr() { - Ok(e) => { - base = Some(e); - } - Err(mut e) => { - e.emit(); - self.recover_stmt(); - } - } - if self.token == token::Comma { - self.struct_span_err( - exp_span.to(self.prev_span), - "cannot use a comma after the base struct", - ) - .span_suggestion_short( - self.token.span, - "remove this comma", - String::new(), - Applicability::MachineApplicable - ) - .note("the base struct must always be the last field") - .emit(); - self.recover_stmt(); - } - break; - } - - let mut recovery_field = None; - if let token::Ident(name, _) = self.token.kind { - if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) { - // Use in case of error after field-looking code: `S { foo: () with a }`. - recovery_field = Some(ast::Field { - ident: Ident::new(name, self.token.span), - span: self.token.span, - expr: self.mk_expr(self.token.span, ExprKind::Err, ThinVec::new()), - is_shorthand: false, - attrs: ThinVec::new(), - id: DUMMY_NODE_ID, - is_placeholder: false, - }); - } - } - let mut parsed_field = None; - match self.parse_field() { - Ok(f) => parsed_field = Some(f), - Err(mut e) => { - e.span_label(struct_sp, "while parsing this struct"); - e.emit(); - - // If the next token is a comma, then try to parse - // what comes next as additional fields, rather than - // bailing out until next `}`. - if self.token != token::Comma { - self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore); - if self.token != token::Comma { - break; - } - } - } - } - - match self.expect_one_of(&[token::Comma], - &[token::CloseDelim(token::Brace)]) { - Ok(_) => if let Some(f) = parsed_field.or(recovery_field) { - // Only include the field if there's no parse error for the field name. - fields.push(f); - } - Err(mut e) => { - if let Some(f) = recovery_field { - fields.push(f); - } - e.span_label(struct_sp, "while parsing this struct"); - e.emit(); - self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore); - self.eat(&token::Comma); - } - } - } - - let span = lo.to(self.token.span); - self.expect(&token::CloseDelim(token::Brace))?; - return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs)); - } - - /// Parses `ident (COLON expr)?`. - fn parse_field(&mut self) -> PResult<'a, Field> { - let attrs = self.parse_outer_attributes()?; - let lo = self.token.span; - - // Check if a colon exists one ahead. This means we're parsing a fieldname. - let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| { - t == &token::Colon || t == &token::Eq - }) { - let fieldname = self.parse_field_name()?; - - // Check for an equals token. This means the source incorrectly attempts to - // initialize a field with an eq rather than a colon. - if self.token == token::Eq { - self.diagnostic() - .struct_span_err(self.token.span, "expected `:`, found `=`") - .span_suggestion( - fieldname.span.shrink_to_hi().to(self.token.span), - "replace equals symbol with a colon", - ":".to_string(), - Applicability::MachineApplicable, - ) - .emit(); - } - self.bump(); // `:` - (fieldname, self.parse_expr()?, false) - } else { - let fieldname = self.parse_ident_common(false)?; - - // Mimic `x: x` for the `x` field shorthand. - let path = ast::Path::from_ident(fieldname); - let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new()); - (fieldname, expr, true) - }; - Ok(ast::Field { - ident: fieldname, - span: lo.to(expr.span), - expr, - is_shorthand, - attrs: attrs.into(), - id: DUMMY_NODE_ID, - is_placeholder: false, - }) - } - - fn err_dotdotdot_syntax(&self, span: Span) { - self.struct_span_err(span, "unexpected token: `...`") - .span_suggestion( - span, - "use `..` for an exclusive range", "..".to_owned(), - Applicability::MaybeIncorrect - ) - .span_suggestion( - span, - "or `..=` for an inclusive range", "..=".to_owned(), - Applicability::MaybeIncorrect - ) - .emit(); - } - - fn err_larrow_operator(&self, span: Span) { - self.struct_span_err( - span, - "unexpected token: `<-`" - ).span_suggestion( - span, - "if you meant to write a comparison against a negative value, add a \ - space in between `<` and `-`", - "< -".to_string(), - Applicability::MaybeIncorrect - ).emit(); - } - - fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind { - ExprKind::AssignOp(binop, lhs, rhs) - } - - fn mk_range( - &self, - start: Option<P<Expr>>, - end: Option<P<Expr>>, - limits: RangeLimits - ) -> PResult<'a, ExprKind> { - if end.is_none() && limits == RangeLimits::Closed { - Err(self.span_fatal_err(self.token.span, Error::InclusiveRangeWithNoEnd)) - } else { - Ok(ExprKind::Range(start, end, limits)) - } - } - - fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind { - ExprKind::Unary(unop, expr) - } - - fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind { - ExprKind::Binary(binop, lhs, rhs) - } - - fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind { - ExprKind::Index(expr, idx) - } - - fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind { - ExprKind::Call(f, args) - } - - fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> { - let span = lo.to(self.prev_span); - let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), ThinVec::new()); - self.recover_from_await_method_call(); - Ok(await_expr) - } - - crate fn mk_expr(&self, span: Span, kind: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> { - P(Expr { kind, span, attrs, id: DUMMY_NODE_ID }) - } - - pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> { - self.mk_expr(span, ExprKind::Err, ThinVec::new()) - } -} diff --git a/src/libsyntax/parse/parser/generics.rs b/src/libsyntax/parse/parser/generics.rs deleted file mode 100644 index ae9ecd8fe39..00000000000 --- a/src/libsyntax/parse/parser/generics.rs +++ /dev/null @@ -1,309 +0,0 @@ -use super::Parser; - -use crate::ast::{self, WhereClause, GenericParam, GenericParamKind, GenericBounds, Attribute}; -use crate::token; -use crate::source_map::DUMMY_SP; - -use syntax_pos::symbol::{kw, sym}; - -use errors::PResult; - -impl<'a> Parser<'a> { - /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`. - /// - /// ``` - /// BOUND = LT_BOUND (e.g., `'a`) - /// ``` - fn parse_lt_param_bounds(&mut self) -> GenericBounds { - let mut lifetimes = Vec::new(); - while self.check_lifetime() { - lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime())); - - if !self.eat_plus() { - break - } - } - lifetimes - } - - /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`. - fn parse_ty_param(&mut self, - preceding_attrs: Vec<Attribute>) - -> PResult<'a, GenericParam> { - let ident = self.parse_ident()?; - - // Parse optional colon and param bounds. - let bounds = if self.eat(&token::Colon) { - self.parse_generic_bounds(Some(self.prev_span))? - } else { - Vec::new() - }; - - let default = if self.eat(&token::Eq) { - Some(self.parse_ty()?) - } else { - None - }; - - Ok(GenericParam { - ident, - id: ast::DUMMY_NODE_ID, - attrs: preceding_attrs.into(), - bounds, - kind: GenericParamKind::Type { - default, - }, - is_placeholder: false - }) - } - - fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> { - let lo = self.token.span; - - self.expect_keyword(kw::Const)?; - let ident = self.parse_ident()?; - self.expect(&token::Colon)?; - let ty = self.parse_ty()?; - - self.sess.gated_spans.gate(sym::const_generics, lo.to(self.prev_span)); - - Ok(GenericParam { - ident, - id: ast::DUMMY_NODE_ID, - attrs: preceding_attrs.into(), - bounds: Vec::new(), - kind: GenericParamKind::Const { - ty, - }, - is_placeholder: false - }) - } - - /// Parses a (possibly empty) list of lifetime and type parameters, possibly including - /// a trailing comma and erroneous trailing attributes. - pub(super) fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> { - let mut params = Vec::new(); - loop { - let attrs = self.parse_outer_attributes()?; - if self.check_lifetime() { - let lifetime = self.expect_lifetime(); - // Parse lifetime parameter. - let bounds = if self.eat(&token::Colon) { - self.parse_lt_param_bounds() - } else { - Vec::new() - }; - params.push(ast::GenericParam { - ident: lifetime.ident, - id: lifetime.id, - attrs: attrs.into(), - bounds, - kind: ast::GenericParamKind::Lifetime, - is_placeholder: false - }); - } else if self.check_keyword(kw::Const) { - // Parse const parameter. - params.push(self.parse_const_param(attrs)?); - } else if self.check_ident() { - // Parse type parameter. - params.push(self.parse_ty_param(attrs)?); - } else if self.token.can_begin_type() { - // Trying to write an associated type bound? (#26271) - let snapshot = self.clone(); - match self.parse_ty_where_predicate() { - Ok(where_predicate) => { - self.struct_span_err( - where_predicate.span(), - "bounds on associated types do not belong here", - ) - .span_label(where_predicate.span(), "belongs in `where` clause") - .emit(); - } - Err(mut err) => { - err.cancel(); - std::mem::replace(self, snapshot); - break - } - } - } else { - // Check for trailing attributes and stop parsing. - if !attrs.is_empty() { - if !params.is_empty() { - self.struct_span_err( - attrs[0].span, - "trailing attribute after generic parameter", - ) - .span_label(attrs[0].span, "attributes must go before parameters") - .emit(); - } else { - self.struct_span_err( - attrs[0].span, - &format!("attribute without generic parameters"), - ) - .span_label( - attrs[0].span, - "attributes are only permitted when preceding parameters", - ) - .emit(); - } - } - break - } - - if !self.eat(&token::Comma) { - break - } - } - Ok(params) - } - - /// Parses a set of optional generic type parameter declarations. Where - /// clauses are not parsed here, and must be added later via - /// `parse_where_clause()`. - /// - /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > ) - /// | ( < lifetimes , typaramseq ( , )? > ) - /// where typaramseq = ( typaram ) | ( typaram , typaramseq ) - pub(super) fn parse_generics(&mut self) -> PResult<'a, ast::Generics> { - let span_lo = self.token.span; - let (params, span) = if self.eat_lt() { - let params = self.parse_generic_params()?; - self.expect_gt()?; - (params, span_lo.to(self.prev_span)) - } else { - (vec![], self.prev_span.between(self.token.span)) - }; - Ok(ast::Generics { - params, - where_clause: WhereClause { - predicates: Vec::new(), - span: DUMMY_SP, - }, - span, - }) - } - - /// Parses an optional where-clause and places it in `generics`. - /// - /// ```ignore (only-for-syntax-highlight) - /// where T : Trait<U, V> + 'b, 'a : 'b - /// ``` - pub(super) fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> { - let mut where_clause = WhereClause { - predicates: Vec::new(), - span: self.prev_span.to(self.prev_span), - }; - - if !self.eat_keyword(kw::Where) { - return Ok(where_clause); - } - let lo = self.prev_span; - - // We are considering adding generics to the `where` keyword as an alternative higher-rank - // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking - // change we parse those generics now, but report an error. - if self.choose_generics_over_qpath() { - let generics = self.parse_generics()?; - self.struct_span_err( - generics.span, - "generic parameters on `where` clauses are reserved for future use", - ) - .span_label(generics.span, "currently unsupported") - .emit(); - } - - loop { - let lo = self.token.span; - if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) { - let lifetime = self.expect_lifetime(); - // Bounds starting with a colon are mandatory, but possibly empty. - self.expect(&token::Colon)?; - let bounds = self.parse_lt_param_bounds(); - where_clause.predicates.push(ast::WherePredicate::RegionPredicate( - ast::WhereRegionPredicate { - span: lo.to(self.prev_span), - lifetime, - bounds, - } - )); - } else if self.check_type() { - where_clause.predicates.push(self.parse_ty_where_predicate()?); - } else { - break - } - - if !self.eat(&token::Comma) { - break - } - } - - where_clause.span = lo.to(self.prev_span); - Ok(where_clause) - } - - fn parse_ty_where_predicate(&mut self) -> PResult<'a, ast::WherePredicate> { - let lo = self.token.span; - // Parse optional `for<'a, 'b>`. - // This `for` is parsed greedily and applies to the whole predicate, - // the bounded type can have its own `for` applying only to it. - // Examples: - // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>` - // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>` - // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>` - let lifetime_defs = self.parse_late_bound_lifetime_defs()?; - - // Parse type with mandatory colon and (possibly empty) bounds, - // or with mandatory equality sign and the second type. - let ty = self.parse_ty()?; - if self.eat(&token::Colon) { - let bounds = self.parse_generic_bounds(Some(self.prev_span))?; - Ok(ast::WherePredicate::BoundPredicate( - ast::WhereBoundPredicate { - span: lo.to(self.prev_span), - bound_generic_params: lifetime_defs, - bounded_ty: ty, - bounds, - } - )) - // FIXME: Decide what should be used here, `=` or `==`. - // FIXME: We are just dropping the binders in lifetime_defs on the floor here. - } else if self.eat(&token::Eq) || self.eat(&token::EqEq) { - let rhs_ty = self.parse_ty()?; - Ok(ast::WherePredicate::EqPredicate( - ast::WhereEqPredicate { - span: lo.to(self.prev_span), - lhs_ty: ty, - rhs_ty, - id: ast::DUMMY_NODE_ID, - } - )) - } else { - self.unexpected() - } - } - - pub(super) fn choose_generics_over_qpath(&self) -> bool { - // There's an ambiguity between generic parameters and qualified paths in impls. - // If we see `<` it may start both, so we have to inspect some following tokens. - // The following combinations can only start generics, - // but not qualified paths (with one exception): - // `<` `>` - empty generic parameters - // `<` `#` - generic parameters with attributes - // `<` (LIFETIME|IDENT) `>` - single generic parameter - // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list - // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds - // `<` (LIFETIME|IDENT) `=` - generic parameter with a default - // `<` const - generic const parameter - // The only truly ambiguous case is - // `<` IDENT `>` `::` IDENT ... - // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`) - // because this is what almost always expected in practice, qualified paths in impls - // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment. - self.token == token::Lt && - (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) || - self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) && - self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma || - t == &token::Colon || t == &token::Eq) || - self.is_keyword_ahead(1, &[kw::Const])) - } -} diff --git a/src/libsyntax/parse/parser/item.rs b/src/libsyntax/parse/parser/item.rs deleted file mode 100644 index 531ad532a54..00000000000 --- a/src/libsyntax/parse/parser/item.rs +++ /dev/null @@ -1,2237 +0,0 @@ -use super::{Parser, PathStyle}; -use super::diagnostics::{Error, dummy_arg, ConsumeClosingDelim}; - -use crate::maybe_whole; -use crate::ptr::P; -use crate::ast::{self, Abi, DUMMY_NODE_ID, Ident, Attribute, AttrKind, AttrStyle, AnonConst, Item}; -use crate::ast::{ItemKind, ImplItem, ImplItemKind, TraitItem, TraitItemKind, UseTree, UseTreeKind}; -use crate::ast::{PathSegment, IsAuto, Constness, IsAsync, Unsafety, Defaultness}; -use crate::ast::{Visibility, VisibilityKind, Mutability, FnHeader, ForeignItem, ForeignItemKind}; -use crate::ast::{Ty, TyKind, Generics, GenericBounds, TraitRef, EnumDef, VariantData, StructField}; -use crate::ast::{Mac, MacDelimiter, Block, BindingMode, FnDecl, FnSig, SelfKind, Param}; -use crate::parse::token; -use crate::tokenstream::{TokenTree, TokenStream}; -use crate::symbol::{kw, sym}; -use crate::source_map::{self, respan, Span}; -use crate::ThinVec; - -use log::debug; -use std::mem; -use errors::{PResult, Applicability, DiagnosticBuilder, DiagnosticId, StashKey}; -use syntax_pos::BytePos; - -/// Whether the type alias or associated type is a concrete type or an opaque type. -#[derive(Debug)] -pub(super) enum AliasKind { - /// Just a new name for the same type. - Weak(P<Ty>), - /// Only trait impls of the type will be usable, not the actual type itself. - OpaqueTy(GenericBounds), -} - -pub(super) type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>); - -impl<'a> Parser<'a> { - pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> { - let attrs = self.parse_outer_attributes()?; - self.parse_item_(attrs, true, false) - } - - pub(super) fn parse_item_( - &mut self, - attrs: Vec<Attribute>, - macros_allowed: bool, - attributes_allowed: bool, - ) -> PResult<'a, Option<P<Item>>> { - let mut unclosed_delims = vec![]; - let (ret, tokens) = self.collect_tokens(|this| { - let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed); - unclosed_delims.append(&mut this.unclosed_delims); - item - })?; - self.unclosed_delims.append(&mut unclosed_delims); - - // Once we've parsed an item and recorded the tokens we got while - // parsing we may want to store `tokens` into the item we're about to - // return. Note, though, that we specifically didn't capture tokens - // related to outer attributes. The `tokens` field here may later be - // used with procedural macros to convert this item back into a token - // stream, but during expansion we may be removing attributes as we go - // along. - // - // If we've got inner attributes then the `tokens` we've got above holds - // these inner attributes. If an inner attribute is expanded we won't - // actually remove it from the token stream, so we'll just keep yielding - // it (bad!). To work around this case for now we just avoid recording - // `tokens` if we detect any inner attributes. This should help keep - // expansion correct, but we should fix this bug one day! - Ok(ret.map(|item| { - item.map(|mut i| { - if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) { - i.tokens = Some(tokens); - } - i - }) - })) - } - - /// Parses one of the items allowed by the flags. - fn parse_item_implementation( - &mut self, - attrs: Vec<Attribute>, - macros_allowed: bool, - attributes_allowed: bool, - ) -> PResult<'a, Option<P<Item>>> { - maybe_whole!(self, NtItem, |item| { - let mut item = item.into_inner(); - let mut attrs = attrs; - mem::swap(&mut item.attrs, &mut attrs); - item.attrs.extend(attrs); - Some(P(item)) - }); - - let lo = self.token.span; - - let vis = self.parse_visibility(false)?; - - if self.eat_keyword(kw::Use) { - // USE ITEM - let item_ = ItemKind::Use(P(self.parse_use_tree()?)); - self.expect_semi()?; - - let span = lo.to(self.prev_span); - let item = self.mk_item(span, Ident::invalid(), item_, vis, attrs); - return Ok(Some(item)); - } - - if self.eat_keyword(kw::Extern) { - let extern_sp = self.prev_span; - if self.eat_keyword(kw::Crate) { - return Ok(Some(self.parse_item_extern_crate(lo, vis, attrs)?)); - } - - let abi = self.parse_opt_abi()?; - - if self.eat_keyword(kw::Fn) { - // EXTERN FUNCTION ITEM - let fn_span = self.prev_span; - let header = FnHeader { - unsafety: Unsafety::Normal, - asyncness: respan(fn_span, IsAsync::NotAsync), - constness: respan(fn_span, Constness::NotConst), - abi, - }; - return self.parse_item_fn(lo, vis, attrs, header); - } else if self.check(&token::OpenDelim(token::Brace)) { - return Ok(Some( - self.parse_item_foreign_mod(lo, abi, vis, attrs, extern_sp)?, - )); - } - - self.unexpected()?; - } - - if self.is_static_global() { - self.bump(); - // STATIC ITEM - let m = self.parse_mutability(); - let info = self.parse_item_const(Some(m))?; - return self.mk_item_with_info(attrs, lo, vis, info); - } - - if self.eat_keyword(kw::Const) { - let const_span = self.prev_span; - if [kw::Fn, kw::Unsafe, kw::Extern].iter().any(|k| self.check_keyword(*k)) { - // CONST FUNCTION ITEM - let unsafety = self.parse_unsafety(); - - if self.check_keyword(kw::Extern) { - self.sess.gated_spans.gate(sym::const_extern_fn, lo.to(self.token.span)); - } - let abi = self.parse_extern_abi()?; - self.bump(); // `fn` - - let header = FnHeader { - unsafety, - asyncness: respan(const_span, IsAsync::NotAsync), - constness: respan(const_span, Constness::Const), - abi, - }; - return self.parse_item_fn(lo, vis, attrs, header); - } - - // CONST ITEM - if self.eat_keyword(kw::Mut) { - let prev_span = self.prev_span; - self.struct_span_err(prev_span, "const globals cannot be mutable") - .span_label(prev_span, "cannot be mutable") - .span_suggestion( - const_span, - "you might want to declare a static instead", - "static".to_owned(), - Applicability::MaybeIncorrect, - ) - .emit(); - } - - let info = self.parse_item_const(None)?; - return self.mk_item_with_info(attrs, lo, vis, info); - } - - // Parses `async unsafe? fn`. - if self.check_keyword(kw::Async) { - let async_span = self.token.span; - if self.is_keyword_ahead(1, &[kw::Fn]) - || self.is_keyword_ahead(2, &[kw::Fn]) - { - // ASYNC FUNCTION ITEM - self.bump(); // `async` - let unsafety = self.parse_unsafety(); // `unsafe`? - self.expect_keyword(kw::Fn)?; // `fn` - let fn_span = self.prev_span; - let asyncness = respan(async_span, IsAsync::Async { - closure_id: DUMMY_NODE_ID, - return_impl_trait_id: DUMMY_NODE_ID, - }); - self.ban_async_in_2015(async_span); - let header = FnHeader { - unsafety, - asyncness, - constness: respan(fn_span, Constness::NotConst), - abi: Abi::new(sym::Rust, fn_span), - }; - return self.parse_item_fn(lo, vis, attrs, header); - } - } - - if self.check_keyword(kw::Unsafe) && - self.is_keyword_ahead(1, &[kw::Trait, kw::Auto]) - { - // UNSAFE TRAIT ITEM - self.bump(); // `unsafe` - let info = self.parse_item_trait(lo, Unsafety::Unsafe)?; - return self.mk_item_with_info(attrs, lo, vis, info); - } - - if self.check_keyword(kw::Impl) || - self.check_keyword(kw::Unsafe) && - self.is_keyword_ahead(1, &[kw::Impl]) || - self.check_keyword(kw::Default) && - self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe]) - { - // IMPL ITEM - let defaultness = self.parse_defaultness(); - let unsafety = self.parse_unsafety(); - self.expect_keyword(kw::Impl)?; - let info = self.parse_item_impl(unsafety, defaultness)?; - return self.mk_item_with_info(attrs, lo, vis, info); - } - - if self.check_keyword(kw::Fn) { - // FUNCTION ITEM - self.bump(); - let fn_span = self.prev_span; - let header = FnHeader { - unsafety: Unsafety::Normal, - asyncness: respan(fn_span, IsAsync::NotAsync), - constness: respan(fn_span, Constness::NotConst), - abi: Abi::new(sym::Rust, fn_span), - }; - return self.parse_item_fn(lo, vis, attrs, header); - } - - if self.check_keyword(kw::Unsafe) - && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) - { - // UNSAFE FUNCTION ITEM - self.bump(); // `unsafe` - // `{` is also expected after `unsafe`; in case of error, include it in the diagnostic. - self.check(&token::OpenDelim(token::Brace)); - let abi = self.parse_extern_abi()?; - self.expect_keyword(kw::Fn)?; - let fn_span = self.prev_span; - let header = FnHeader { - unsafety: Unsafety::Unsafe, - asyncness: respan(fn_span, IsAsync::NotAsync), - constness: respan(fn_span, Constness::NotConst), - abi, - }; - return self.parse_item_fn(lo, vis, attrs, header); - } - - if self.eat_keyword(kw::Mod) { - // MODULE ITEM - let info = self.parse_item_mod(&attrs[..])?; - return self.mk_item_with_info(attrs, lo, vis, info); - } - - if let Some(type_) = self.eat_type() { - let (ident, alias, generics) = type_?; - // TYPE ITEM - let item_ = match alias { - AliasKind::Weak(ty) => ItemKind::TyAlias(ty, generics), - AliasKind::OpaqueTy(bounds) => ItemKind::OpaqueTy(bounds, generics), - }; - let span = lo.to(self.prev_span); - return Ok(Some(self.mk_item(span, ident, item_, vis, attrs))); - } - - if self.eat_keyword(kw::Enum) { - // ENUM ITEM - let info = self.parse_item_enum()?; - return self.mk_item_with_info(attrs, lo, vis, info); - } - - if self.check_keyword(kw::Trait) - || (self.check_keyword(kw::Auto) - && self.is_keyword_ahead(1, &[kw::Trait])) - { - // TRAIT ITEM - let info = self.parse_item_trait(lo, Unsafety::Normal)?; - return self.mk_item_with_info(attrs, lo, vis, info); - } - - if self.eat_keyword(kw::Struct) { - // STRUCT ITEM - let info = self.parse_item_struct()?; - return self.mk_item_with_info(attrs, lo, vis, info); - } - - if self.is_union_item() { - // UNION ITEM - self.bump(); - let info = self.parse_item_union()?; - return self.mk_item_with_info(attrs, lo, vis, info); - } - - if let Some(macro_def) = self.eat_macro_def(&attrs, &vis, lo)? { - return Ok(Some(macro_def)); - } - - // Verify whether we have encountered a struct or method definition where the user forgot to - // add the `struct` or `fn` keyword after writing `pub`: `pub S {}` - if vis.node.is_pub() && - self.check_ident() && - self.look_ahead(1, |t| *t != token::Not) - { - // Space between `pub` keyword and the identifier - // - // pub S {} - // ^^^ `sp` points here - let sp = self.prev_span.between(self.token.span); - let full_sp = self.prev_span.to(self.token.span); - let ident_sp = self.token.span; - if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) { - // possible public struct definition where `struct` was forgotten - let ident = self.parse_ident().unwrap(); - let msg = format!("add `struct` here to parse `{}` as a public struct", - ident); - let mut err = self.diagnostic() - .struct_span_err(sp, "missing `struct` for struct definition"); - err.span_suggestion_short( - sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative - ); - return Err(err); - } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) { - let ident = self.parse_ident().unwrap(); - self.bump(); // `(` - let kw_name = self.recover_first_param(); - self.consume_block(token::Paren, ConsumeClosingDelim::Yes); - let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) { - self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]); - self.bump(); // `{` - ("fn", kw_name, false) - } else if self.check(&token::OpenDelim(token::Brace)) { - self.bump(); // `{` - ("fn", kw_name, false) - } else if self.check(&token::Colon) { - let kw = "struct"; - (kw, kw, false) - } else { - ("fn` or `struct", "function or struct", true) - }; - - let msg = format!("missing `{}` for {} definition", kw, kw_name); - let mut err = self.diagnostic().struct_span_err(sp, &msg); - if !ambiguous { - self.consume_block(token::Brace, ConsumeClosingDelim::Yes); - let suggestion = format!("add `{}` here to parse `{}` as a public {}", - kw, - ident, - kw_name); - err.span_suggestion_short( - sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable - ); - } else { - if let Ok(snippet) = self.span_to_snippet(ident_sp) { - err.span_suggestion( - full_sp, - "if you meant to call a macro, try", - format!("{}!", snippet), - // this is the `ambiguous` conditional branch - Applicability::MaybeIncorrect - ); - } else { - err.help("if you meant to call a macro, remove the `pub` \ - and add a trailing `!` after the identifier"); - } - } - return Err(err); - } else if self.look_ahead(1, |t| *t == token::Lt) { - let ident = self.parse_ident().unwrap(); - self.eat_to_tokens(&[&token::Gt]); - self.bump(); // `>` - let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) { - ("fn", self.recover_first_param(), false) - } else if self.check(&token::OpenDelim(token::Brace)) { - ("struct", "struct", false) - } else { - ("fn` or `struct", "function or struct", true) - }; - let msg = format!("missing `{}` for {} definition", kw, kw_name); - let mut err = self.diagnostic().struct_span_err(sp, &msg); - if !ambiguous { - err.span_suggestion_short( - sp, - &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name), - format!(" {} ", kw), - Applicability::MachineApplicable, - ); - } - return Err(err); - } - } - self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, vis) - } - - pub(super) fn mk_item_with_info( - &self, - attrs: Vec<Attribute>, - lo: Span, - vis: Visibility, - info: ItemInfo, - ) -> PResult<'a, Option<P<Item>>> { - let (ident, item, extra_attrs) = info; - let span = lo.to(self.prev_span); - let attrs = Self::maybe_append(attrs, extra_attrs); - Ok(Some(self.mk_item(span, ident, item, vis, attrs))) - } - - fn maybe_append<T>(mut lhs: Vec<T>, mut rhs: Option<Vec<T>>) -> Vec<T> { - if let Some(ref mut rhs) = rhs { - lhs.append(rhs); - } - lhs - } - - /// This is the fall-through for parsing items. - fn parse_macro_use_or_failure( - &mut self, - attrs: Vec<Attribute> , - macros_allowed: bool, - attributes_allowed: bool, - lo: Span, - visibility: Visibility - ) -> PResult<'a, Option<P<Item>>> { - if macros_allowed && self.token.is_path_start() && - !(self.is_async_fn() && self.token.span.rust_2015()) { - // MACRO INVOCATION ITEM - - let prev_span = self.prev_span; - self.complain_if_pub_macro(&visibility.node, prev_span); - - let mac_lo = self.token.span; - - // Item macro - let path = self.parse_path(PathStyle::Mod)?; - self.expect(&token::Not)?; - let (delim, tts) = self.expect_delimited_token_tree()?; - if delim != MacDelimiter::Brace && !self.eat(&token::Semi) { - self.report_invalid_macro_expansion_item(); - } - - let hi = self.prev_span; - let mac = Mac { - path, - tts, - delim, - span: mac_lo.to(hi), - prior_type_ascription: self.last_type_ascription, - }; - let item = - self.mk_item(lo.to(hi), Ident::invalid(), ItemKind::Mac(mac), visibility, attrs); - return Ok(Some(item)); - } - - // FAILURE TO PARSE ITEM - match visibility.node { - VisibilityKind::Inherited => {} - _ => { - return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`")); - } - } - - if !attributes_allowed && !attrs.is_empty() { - self.expected_item_err(&attrs)?; - } - Ok(None) - } - - /// Emits an expected-item-after-attributes error. - fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> { - let message = match attrs.last() { - Some(&Attribute { kind: AttrKind::DocComment(_), .. }) => - "expected item after doc comment", - _ => - "expected item after attributes", - }; - - let mut err = self.diagnostic().struct_span_err(self.prev_span, message); - if attrs.last().unwrap().is_doc_comment() { - err.span_label(self.prev_span, "this doc comment doesn't document anything"); - } - Err(err) - } - - pub(super) fn is_async_fn(&self) -> bool { - self.token.is_keyword(kw::Async) && - self.is_keyword_ahead(1, &[kw::Fn]) - } - - /// Parses a macro invocation inside a `trait`, `impl` or `extern` block. - fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>, - at_end: &mut bool) -> PResult<'a, Option<Mac>> - { - if self.token.is_path_start() && - !(self.is_async_fn() && self.token.span.rust_2015()) { - let prev_span = self.prev_span; - let lo = self.token.span; - let path = self.parse_path(PathStyle::Mod)?; - - if path.segments.len() == 1 { - if !self.eat(&token::Not) { - return Err(self.missing_assoc_item_kind_err(item_kind, prev_span)); - } - } else { - self.expect(&token::Not)?; - } - - if let Some(vis) = vis { - self.complain_if_pub_macro(&vis.node, prev_span); - } - - *at_end = true; - - // eat a matched-delimiter token tree: - let (delim, tts) = self.expect_delimited_token_tree()?; - if delim != MacDelimiter::Brace { - self.expect_semi()?; - } - - Ok(Some(Mac { - path, - tts, - delim, - span: lo.to(self.prev_span), - prior_type_ascription: self.last_type_ascription, - })) - } else { - Ok(None) - } - } - - fn missing_assoc_item_kind_err(&self, item_type: &str, prev_span: Span) - -> DiagnosticBuilder<'a> - { - let expected_kinds = if item_type == "extern" { - "missing `fn`, `type`, or `static`" - } else { - "missing `fn`, `type`, or `const`" - }; - - // Given this code `path(`, it seems like this is not - // setting the visibility of a macro invocation, but rather - // a mistyped method declaration. - // Create a diagnostic pointing out that `fn` is missing. - // - // x | pub path(&self) { - // | ^ missing `fn`, `type`, or `const` - // pub path( - // ^^ `sp` below will point to this - let sp = prev_span.between(self.prev_span); - let mut err = self.diagnostic().struct_span_err( - sp, - &format!("{} for {}-item declaration", - expected_kinds, item_type)); - err.span_label(sp, expected_kinds); - err - } - - /// Parses an implementation item, `impl` keyword is already parsed. - /// - /// impl<'a, T> TYPE { /* impl items */ } - /// impl<'a, T> TRAIT for TYPE { /* impl items */ } - /// impl<'a, T> !TRAIT for TYPE { /* impl items */ } - /// - /// We actually parse slightly more relaxed grammar for better error reporting and recovery. - /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}` - /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}` - fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness) - -> PResult<'a, ItemInfo> { - // First, parse generic parameters if necessary. - let mut generics = if self.choose_generics_over_qpath() { - self.parse_generics()? - } else { - Generics::default() - }; - - // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type. - let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) { - self.bump(); // `!` - ast::ImplPolarity::Negative - } else { - ast::ImplPolarity::Positive - }; - - // Parse both types and traits as a type, then reinterpret if necessary. - let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span)); - let ty_first = if self.token.is_keyword(kw::For) && - self.look_ahead(1, |t| t != &token::Lt) { - let span = self.prev_span.between(self.token.span); - self.struct_span_err(span, "missing trait in a trait impl").emit(); - P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID }) - } else { - self.parse_ty()? - }; - - // If `for` is missing we try to recover. - let has_for = self.eat_keyword(kw::For); - let missing_for_span = self.prev_span.between(self.token.span); - - let ty_second = if self.token == token::DotDot { - // We need to report this error after `cfg` expansion for compatibility reasons - self.bump(); // `..`, do not add it to expected tokens - Some(self.mk_ty(self.prev_span, TyKind::Err)) - } else if has_for || self.token.can_begin_type() { - Some(self.parse_ty()?) - } else { - None - }; - - generics.where_clause = self.parse_where_clause()?; - - let (impl_items, attrs) = self.parse_impl_body()?; - - let item_kind = match ty_second { - Some(ty_second) => { - // impl Trait for Type - if !has_for { - self.struct_span_err(missing_for_span, "missing `for` in a trait impl") - .span_suggestion_short( - missing_for_span, - "add `for` here", - " for ".to_string(), - Applicability::MachineApplicable, - ).emit(); - } - - let ty_first = ty_first.into_inner(); - let path = match ty_first.kind { - // This notably includes paths passed through `ty` macro fragments (#46438). - TyKind::Path(None, path) => path, - _ => { - self.span_err(ty_first.span, "expected a trait, found type"); - err_path(ty_first.span) - } - }; - let trait_ref = TraitRef { path, ref_id: ty_first.id }; - - ItemKind::Impl(unsafety, polarity, defaultness, - generics, Some(trait_ref), ty_second, impl_items) - } - None => { - // impl Type - ItemKind::Impl(unsafety, polarity, defaultness, - generics, None, ty_first, impl_items) - } - }; - - Ok((Ident::invalid(), item_kind, Some(attrs))) - } - - fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> { - self.expect(&token::OpenDelim(token::Brace))?; - let attrs = self.parse_inner_attributes()?; - - let mut impl_items = Vec::new(); - while !self.eat(&token::CloseDelim(token::Brace)) { - let mut at_end = false; - match self.parse_impl_item(&mut at_end) { - Ok(impl_item) => impl_items.push(impl_item), - Err(mut err) => { - err.emit(); - if !at_end { - self.consume_block(token::Brace, ConsumeClosingDelim::Yes); - break; - } - } - } - } - Ok((impl_items, attrs)) - } - - /// Parses an impl item. - pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> { - maybe_whole!(self, NtImplItem, |x| x); - let attrs = self.parse_outer_attributes()?; - let mut unclosed_delims = vec![]; - let (mut item, tokens) = self.collect_tokens(|this| { - let item = this.parse_impl_item_(at_end, attrs); - unclosed_delims.append(&mut this.unclosed_delims); - item - })?; - self.unclosed_delims.append(&mut unclosed_delims); - - // See `parse_item` for why this clause is here. - if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) { - item.tokens = Some(tokens); - } - Ok(item) - } - - fn parse_impl_item_( - &mut self, - at_end: &mut bool, - mut attrs: Vec<Attribute>, - ) -> PResult<'a, ImplItem> { - let lo = self.token.span; - let vis = self.parse_visibility(false)?; - let defaultness = self.parse_defaultness(); - let (name, kind, generics) = if let Some(type_) = self.eat_type() { - let (name, alias, generics) = type_?; - let kind = match alias { - AliasKind::Weak(typ) => ast::ImplItemKind::TyAlias(typ), - AliasKind::OpaqueTy(bounds) => ast::ImplItemKind::OpaqueTy(bounds), - }; - (name, kind, generics) - } else if self.is_const_item() { - self.parse_impl_const()? - } else if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(&vis), at_end)? { - // FIXME: code copied from `parse_macro_use_or_failure` -- use abstraction! - (Ident::invalid(), ast::ImplItemKind::Macro(mac), Generics::default()) - } else { - let (name, inner_attrs, generics, kind) = self.parse_impl_method(at_end)?; - attrs.extend(inner_attrs); - (name, kind, generics) - }; - - Ok(ImplItem { - id: DUMMY_NODE_ID, - span: lo.to(self.prev_span), - ident: name, - vis, - defaultness, - attrs, - generics, - kind, - tokens: None, - }) - } - - /// Parses defaultness (i.e., `default` or nothing). - fn parse_defaultness(&mut self) -> Defaultness { - // `pub` is included for better error messages - if self.check_keyword(kw::Default) && - self.is_keyword_ahead(1, &[ - kw::Impl, - kw::Const, - kw::Async, - kw::Fn, - kw::Unsafe, - kw::Extern, - kw::Type, - kw::Pub, - ]) - { - self.bump(); // `default` - Defaultness::Default - } else { - Defaultness::Final - } - } - - /// Returns `true` if we are looking at `const ID` - /// (returns `false` for things like `const fn`, etc.). - fn is_const_item(&self) -> bool { - self.token.is_keyword(kw::Const) && - !self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe]) - } - - /// This parses the grammar: - /// ImplItemConst = "const" Ident ":" Ty "=" Expr ";" - fn parse_impl_const(&mut self) -> PResult<'a, (Ident, ImplItemKind, Generics)> { - self.expect_keyword(kw::Const)?; - let name = self.parse_ident()?; - self.expect(&token::Colon)?; - let typ = self.parse_ty()?; - self.expect(&token::Eq)?; - let expr = self.parse_expr()?; - self.expect_semi()?; - Ok((name, ImplItemKind::Const(typ, expr), Generics::default())) - } - - /// Parses `auto? trait Foo { ... }` or `trait Foo = Bar;`. - fn parse_item_trait(&mut self, lo: Span, unsafety: Unsafety) -> PResult<'a, ItemInfo> { - // Parse optional `auto` prefix. - let is_auto = if self.eat_keyword(kw::Auto) { - IsAuto::Yes - } else { - IsAuto::No - }; - - self.expect_keyword(kw::Trait)?; - let ident = self.parse_ident()?; - let mut tps = self.parse_generics()?; - - // Parse optional colon and supertrait bounds. - let had_colon = self.eat(&token::Colon); - let span_at_colon = self.prev_span; - let bounds = if had_colon { - self.parse_generic_bounds(Some(self.prev_span))? - } else { - Vec::new() - }; - - let span_before_eq = self.prev_span; - if self.eat(&token::Eq) { - // It's a trait alias. - if had_colon { - let span = span_at_colon.to(span_before_eq); - self.struct_span_err(span, "bounds are not allowed on trait aliases") - .emit(); - } - - let bounds = self.parse_generic_bounds(None)?; - tps.where_clause = self.parse_where_clause()?; - self.expect_semi()?; - - let whole_span = lo.to(self.prev_span); - if is_auto == IsAuto::Yes { - let msg = "trait aliases cannot be `auto`"; - self.struct_span_err(whole_span, msg) - .span_label(whole_span, msg) - .emit(); - } - if unsafety != Unsafety::Normal { - let msg = "trait aliases cannot be `unsafe`"; - self.struct_span_err(whole_span, msg) - .span_label(whole_span, msg) - .emit(); - } - - self.sess.gated_spans.gate(sym::trait_alias, whole_span); - - Ok((ident, ItemKind::TraitAlias(tps, bounds), None)) - } else { - // It's a normal trait. - tps.where_clause = self.parse_where_clause()?; - self.expect(&token::OpenDelim(token::Brace))?; - let mut trait_items = vec![]; - while !self.eat(&token::CloseDelim(token::Brace)) { - if let token::DocComment(_) = self.token.kind { - if self.look_ahead(1, - |tok| tok == &token::CloseDelim(token::Brace)) { - self.diagnostic().struct_span_err_with_code( - self.token.span, - "found a documentation comment that doesn't document anything", - DiagnosticId::Error("E0584".into()), - ) - .help( - "doc comments must come before what they document, maybe a \ - comment was intended with `//`?", - ) - .emit(); - self.bump(); - continue; - } - } - let mut at_end = false; - match self.parse_trait_item(&mut at_end) { - Ok(item) => trait_items.push(item), - Err(mut e) => { - e.emit(); - if !at_end { - self.consume_block(token::Brace, ConsumeClosingDelim::Yes); - break; - } - } - } - } - Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None)) - } - } - - /// Parses the items in a trait declaration. - pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> { - maybe_whole!(self, NtTraitItem, |x| x); - let attrs = self.parse_outer_attributes()?; - let mut unclosed_delims = vec![]; - let (mut item, tokens) = self.collect_tokens(|this| { - let item = this.parse_trait_item_(at_end, attrs); - unclosed_delims.append(&mut this.unclosed_delims); - item - })?; - self.unclosed_delims.append(&mut unclosed_delims); - // See `parse_item` for why this clause is here. - if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) { - item.tokens = Some(tokens); - } - Ok(item) - } - - fn parse_trait_item_( - &mut self, - at_end: &mut bool, - mut attrs: Vec<Attribute>, - ) -> PResult<'a, TraitItem> { - let lo = self.token.span; - self.eat_bad_pub(); - let (name, kind, generics) = if self.eat_keyword(kw::Type) { - self.parse_trait_item_assoc_ty()? - } else if self.is_const_item() { - self.parse_trait_item_const()? - } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? { - // trait item macro. - (Ident::invalid(), TraitItemKind::Macro(mac), Generics::default()) - } else { - self.parse_trait_item_method(at_end, &mut attrs)? - }; - - Ok(TraitItem { - id: DUMMY_NODE_ID, - ident: name, - attrs, - generics, - kind, - span: lo.to(self.prev_span), - tokens: None, - }) - } - - fn parse_trait_item_const(&mut self) -> PResult<'a, (Ident, TraitItemKind, Generics)> { - self.expect_keyword(kw::Const)?; - let ident = self.parse_ident()?; - self.expect(&token::Colon)?; - let ty = self.parse_ty()?; - let default = if self.eat(&token::Eq) { - Some(self.parse_expr()?) - } else { - None - }; - self.expect_semi()?; - Ok((ident, TraitItemKind::Const(ty, default), Generics::default())) - } - - /// Parses the following grammar: - /// - /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty] - fn parse_trait_item_assoc_ty(&mut self) -> PResult<'a, (Ident, TraitItemKind, Generics)> { - let ident = self.parse_ident()?; - let mut generics = self.parse_generics()?; - - // Parse optional colon and param bounds. - let bounds = if self.eat(&token::Colon) { - self.parse_generic_bounds(None)? - } else { - Vec::new() - }; - generics.where_clause = self.parse_where_clause()?; - - let default = if self.eat(&token::Eq) { - Some(self.parse_ty()?) - } else { - None - }; - self.expect_semi()?; - - Ok((ident, TraitItemKind::Type(bounds, default), generics)) - } - - /// Parses a `UseTree`. - /// - /// ``` - /// USE_TREE = [`::`] `*` | - /// [`::`] `{` USE_TREE_LIST `}` | - /// PATH `::` `*` | - /// PATH `::` `{` USE_TREE_LIST `}` | - /// PATH [`as` IDENT] - /// ``` - fn parse_use_tree(&mut self) -> PResult<'a, UseTree> { - let lo = self.token.span; - - let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() }; - let kind = if self.check(&token::OpenDelim(token::Brace)) || - self.check(&token::BinOp(token::Star)) || - self.is_import_coupler() { - // `use *;` or `use ::*;` or `use {...};` or `use ::{...};` - let mod_sep_ctxt = self.token.span.ctxt(); - if self.eat(&token::ModSep) { - prefix.segments.push( - PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)) - ); - } - - self.parse_use_tree_glob_or_nested()? - } else { - // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;` - prefix = self.parse_path(PathStyle::Mod)?; - - if self.eat(&token::ModSep) { - self.parse_use_tree_glob_or_nested()? - } else { - UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID) - } - }; - - Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) }) - } - - /// Parses `*` or `{...}`. - fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> { - Ok(if self.eat(&token::BinOp(token::Star)) { - UseTreeKind::Glob - } else { - UseTreeKind::Nested(self.parse_use_tree_list()?) - }) - } - - /// Parses a `UseTreeKind::Nested(list)`. - /// - /// ``` - /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`] - /// ``` - fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> { - self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID))) - .map(|(r, _)| r) - } - - fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> { - if self.eat_keyword(kw::As) { - self.parse_ident_or_underscore().map(Some) - } else { - Ok(None) - } - } - - fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> { - match self.token.kind { - token::Ident(name, false) if name == kw::Underscore => { - let span = self.token.span; - self.bump(); - Ok(Ident::new(name, span)) - } - _ => self.parse_ident(), - } - } - - /// Parses `extern crate` links. - /// - /// # Examples - /// - /// ``` - /// extern crate foo; - /// extern crate bar as foo; - /// ``` - fn parse_item_extern_crate( - &mut self, - lo: Span, - visibility: Visibility, - attrs: Vec<Attribute> - ) -> PResult<'a, P<Item>> { - // Accept `extern crate name-like-this` for better diagnostics - let orig_name = self.parse_crate_name_with_dashes()?; - let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? { - (rename, Some(orig_name.name)) - } else { - (orig_name, None) - }; - self.expect_semi()?; - - let span = lo.to(self.prev_span); - Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs)) - } - - fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> { - let error_msg = "crate name using dashes are not valid in `extern crate` statements"; - let suggestion_msg = "if the original crate name uses dashes you need to use underscores \ - in the code"; - let mut ident = if self.token.is_keyword(kw::SelfLower) { - self.parse_path_segment_ident() - } else { - self.parse_ident() - }?; - let mut idents = vec![]; - let mut replacement = vec![]; - let mut fixed_crate_name = false; - // Accept `extern crate name-like-this` for better diagnostics. - let dash = token::BinOp(token::BinOpToken::Minus); - if self.token == dash { // Do not include `-` as part of the expected tokens list. - while self.eat(&dash) { - fixed_crate_name = true; - replacement.push((self.prev_span, "_".to_string())); - idents.push(self.parse_ident()?); - } - } - if fixed_crate_name { - let fixed_name_sp = ident.span.to(idents.last().unwrap().span); - let mut fixed_name = format!("{}", ident.name); - for part in idents { - fixed_name.push_str(&format!("_{}", part.name)); - } - ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp); - - self.struct_span_err(fixed_name_sp, error_msg) - .span_label(fixed_name_sp, "dash-separated idents are not valid") - .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable) - .emit(); - } - Ok(ident) - } - - /// Parses `extern` for foreign ABIs modules. - /// - /// `extern` is expected to have been - /// consumed before calling this method. - /// - /// # Examples - /// - /// ```ignore (only-for-syntax-highlight) - /// extern "C" {} - /// extern {} - /// ``` - fn parse_item_foreign_mod( - &mut self, - lo: Span, - abi: Abi, - visibility: Visibility, - mut attrs: Vec<Attribute>, - extern_sp: Span, - ) -> PResult<'a, P<Item>> { - self.expect(&token::OpenDelim(token::Brace))?; - - attrs.extend(self.parse_inner_attributes()?); - - let mut foreign_items = vec![]; - while !self.eat(&token::CloseDelim(token::Brace)) { - foreign_items.push(self.parse_foreign_item(extern_sp)?); - } - - let prev_span = self.prev_span; - let m = ast::ForeignMod { - abi, - items: foreign_items - }; - let invalid = Ident::invalid(); - Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs)) - } - - /// Parses a foreign item. - pub fn parse_foreign_item(&mut self, extern_sp: Span) -> PResult<'a, ForeignItem> { - maybe_whole!(self, NtForeignItem, |ni| ni); - - let attrs = self.parse_outer_attributes()?; - let lo = self.token.span; - let visibility = self.parse_visibility(false)?; - - // FOREIGN STATIC ITEM - // Treat `const` as `static` for error recovery, but don't add it to expected tokens. - if self.check_keyword(kw::Static) || self.token.is_keyword(kw::Const) { - if self.token.is_keyword(kw::Const) { - let mut err = self - .struct_span_err(self.token.span, "extern items cannot be `const`"); - - - // The user wrote 'const fn' - if self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe]) { - err.emit(); - // Consume `const` - self.bump(); - // Consume `unsafe` if present, since `extern` blocks - // don't allow it. This will leave behind a plain 'fn' - self.eat_keyword(kw::Unsafe); - // Treat 'const fn` as a plain `fn` for error recovery purposes. - // We've already emitted an error, so compilation is guaranteed - // to fail - return Ok(self.parse_item_foreign_fn(visibility, lo, attrs, extern_sp)?); - } - err.span_suggestion( - self.token.span, - "try using a static value", - "static".to_owned(), - Applicability::MachineApplicable - ); - err.emit(); - } - self.bump(); // `static` or `const` - return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?); - } - // FOREIGN FUNCTION ITEM - if self.check_keyword(kw::Fn) { - return Ok(self.parse_item_foreign_fn(visibility, lo, attrs, extern_sp)?); - } - // FOREIGN TYPE ITEM - if self.check_keyword(kw::Type) { - return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?); - } - - match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? { - Some(mac) => { - Ok( - ForeignItem { - ident: Ident::invalid(), - span: lo.to(self.prev_span), - id: DUMMY_NODE_ID, - attrs, - vis: visibility, - kind: ForeignItemKind::Macro(mac), - } - ) - } - None => { - if !attrs.is_empty() { - self.expected_item_err(&attrs)?; - } - - self.unexpected() - } - } - } - - /// Parses a static item from a foreign module. - /// Assumes that the `static` keyword is already parsed. - fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>) - -> PResult<'a, ForeignItem> { - let mutbl = self.parse_mutability(); - let ident = self.parse_ident()?; - self.expect(&token::Colon)?; - let ty = self.parse_ty()?; - let hi = self.token.span; - self.expect_semi()?; - Ok(ForeignItem { - ident, - attrs, - kind: ForeignItemKind::Static(ty, mutbl), - id: DUMMY_NODE_ID, - span: lo.to(hi), - vis, - }) - } - - /// Parses a type from a foreign module. - fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>) - -> PResult<'a, ForeignItem> { - self.expect_keyword(kw::Type)?; - - let ident = self.parse_ident()?; - let hi = self.token.span; - self.expect_semi()?; - Ok(ast::ForeignItem { - ident, - attrs, - kind: ForeignItemKind::Ty, - id: DUMMY_NODE_ID, - span: lo.to(hi), - vis - }) - } - - fn is_static_global(&mut self) -> bool { - if self.check_keyword(kw::Static) { - // Check if this could be a closure. - !self.look_ahead(1, |token| { - if token.is_keyword(kw::Move) { - return true; - } - match token.kind { - token::BinOp(token::Or) | token::OrOr => true, - _ => false, - } - }) - } else { - false - } - } - - /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty = $expr` with - /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`. - /// - /// When `m` is `"const"`, `$ident` may also be `"_"`. - fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> { - let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?; - - // Parse the type of a `const` or `static mut?` item. - // That is, the `":" $ty` fragment. - let ty = if self.token == token::Eq { - self.recover_missing_const_type(id, m) - } else { - // Not `=` so expect `":"" $ty` as usual. - self.expect(&token::Colon)?; - self.parse_ty()? - }; - - self.expect(&token::Eq)?; - let e = self.parse_expr()?; - self.expect_semi()?; - let item = match m { - Some(m) => ItemKind::Static(ty, m, e), - None => ItemKind::Const(ty, e), - }; - Ok((id, item, None)) - } - - /// We were supposed to parse `:` but instead, we're already at `=`. - /// This means that the type is missing. - fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> { - // Construct the error and stash it away with the hope - // that typeck will later enrich the error with a type. - let kind = match m { - Some(Mutability::Mutable) => "static mut", - Some(Mutability::Immutable) => "static", - None => "const", - }; - let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind)); - err.span_suggestion( - id.span, - "provide a type for the item", - format!("{}: <type>", id), - Applicability::HasPlaceholders, - ); - err.stash(id.span, StashKey::ItemNoType); - - // The user intended that the type be inferred, - // so treat this as if the user wrote e.g. `const A: _ = expr;`. - P(Ty { - kind: TyKind::Infer, - span: id.span, - id: ast::DUMMY_NODE_ID, - }) - } - - /// Parses `type Foo = Bar;` or returns `None` - /// without modifying the parser state. - fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, Generics)>> { - // This parses the grammar: - // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";" - if self.eat_keyword(kw::Type) { - Some(self.parse_type_alias()) - } else { - None - } - } - - /// Parses a type alias or opaque type. - fn parse_type_alias(&mut self) -> PResult<'a, (Ident, AliasKind, Generics)> { - let ident = self.parse_ident()?; - let mut tps = self.parse_generics()?; - tps.where_clause = self.parse_where_clause()?; - self.expect(&token::Eq)?; - let alias = if self.check_keyword(kw::Impl) { - self.bump(); - let bounds = self.parse_generic_bounds(Some(self.prev_span))?; - AliasKind::OpaqueTy(bounds) - } else { - let ty = self.parse_ty()?; - AliasKind::Weak(ty) - }; - self.expect_semi()?; - Ok((ident, alias, tps)) - } - - /// Parses an enum declaration. - fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> { - let id = self.parse_ident()?; - let mut generics = self.parse_generics()?; - generics.where_clause = self.parse_where_clause()?; - self.expect(&token::OpenDelim(token::Brace))?; - - let enum_definition = self.parse_enum_def(&generics).map_err(|e| { - self.recover_stmt(); - self.eat(&token::CloseDelim(token::Brace)); - e - })?; - Ok((id, ItemKind::Enum(enum_definition, generics), None)) - } - - /// Parses the part of an enum declaration following the `{`. - fn parse_enum_def(&mut self, _generics: &Generics) -> PResult<'a, EnumDef> { - let mut variants = Vec::new(); - while self.token != token::CloseDelim(token::Brace) { - let variant_attrs = self.parse_outer_attributes()?; - let vlo = self.token.span; - - self.eat_bad_pub(); - let ident = self.parse_ident()?; - - let struct_def = if self.check(&token::OpenDelim(token::Brace)) { - // Parse a struct variant. - let (fields, recovered) = self.parse_record_struct_body()?; - VariantData::Struct(fields, recovered) - } else if self.check(&token::OpenDelim(token::Paren)) { - VariantData::Tuple( - self.parse_tuple_struct_body()?, - DUMMY_NODE_ID, - ) - } else { - VariantData::Unit(DUMMY_NODE_ID) - }; - - let disr_expr = if self.eat(&token::Eq) { - Some(AnonConst { - id: DUMMY_NODE_ID, - value: self.parse_expr()?, - }) - } else { - None - }; - - let vr = ast::Variant { - ident, - id: DUMMY_NODE_ID, - attrs: variant_attrs, - data: struct_def, - disr_expr, - span: vlo.to(self.prev_span), - is_placeholder: false, - }; - variants.push(vr); - - if !self.eat(&token::Comma) { - if self.token.is_ident() && !self.token.is_reserved_ident() { - let sp = self.sess.source_map().next_point(self.prev_span); - self.struct_span_err(sp, "missing comma") - .span_suggestion_short( - sp, - "missing comma", - ",".to_owned(), - Applicability::MaybeIncorrect, - ) - .emit(); - } else { - break; - } - } - } - self.expect(&token::CloseDelim(token::Brace))?; - - Ok(ast::EnumDef { variants }) - } - - /// Parses `struct Foo { ... }`. - fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> { - let class_name = self.parse_ident()?; - - let mut generics = self.parse_generics()?; - - // There is a special case worth noting here, as reported in issue #17904. - // If we are parsing a tuple struct it is the case that the where clause - // should follow the field list. Like so: - // - // struct Foo<T>(T) where T: Copy; - // - // If we are parsing a normal record-style struct it is the case - // that the where clause comes before the body, and after the generics. - // So if we look ahead and see a brace or a where-clause we begin - // parsing a record style struct. - // - // Otherwise if we look ahead and see a paren we parse a tuple-style - // struct. - - let vdata = if self.token.is_keyword(kw::Where) { - generics.where_clause = self.parse_where_clause()?; - if self.eat(&token::Semi) { - // If we see a: `struct Foo<T> where T: Copy;` style decl. - VariantData::Unit(DUMMY_NODE_ID) - } else { - // If we see: `struct Foo<T> where T: Copy { ... }` - let (fields, recovered) = self.parse_record_struct_body()?; - VariantData::Struct(fields, recovered) - } - // No `where` so: `struct Foo<T>;` - } else if self.eat(&token::Semi) { - VariantData::Unit(DUMMY_NODE_ID) - // Record-style struct definition - } else if self.token == token::OpenDelim(token::Brace) { - let (fields, recovered) = self.parse_record_struct_body()?; - VariantData::Struct(fields, recovered) - // Tuple-style struct definition with optional where-clause. - } else if self.token == token::OpenDelim(token::Paren) { - let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID); - generics.where_clause = self.parse_where_clause()?; - self.expect_semi()?; - body - } else { - let token_str = self.this_token_descr(); - let mut err = self.fatal(&format!( - "expected `where`, `{{`, `(`, or `;` after struct name, found {}", - token_str - )); - err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name"); - return Err(err); - }; - - Ok((class_name, ItemKind::Struct(vdata, generics), None)) - } - - /// Parses `union Foo { ... }`. - fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> { - let class_name = self.parse_ident()?; - - let mut generics = self.parse_generics()?; - - let vdata = if self.token.is_keyword(kw::Where) { - generics.where_clause = self.parse_where_clause()?; - let (fields, recovered) = self.parse_record_struct_body()?; - VariantData::Struct(fields, recovered) - } else if self.token == token::OpenDelim(token::Brace) { - let (fields, recovered) = self.parse_record_struct_body()?; - VariantData::Struct(fields, recovered) - } else { - let token_str = self.this_token_descr(); - let mut err = self.fatal(&format!( - "expected `where` or `{{` after union name, found {}", token_str)); - err.span_label(self.token.span, "expected `where` or `{` after union name"); - return Err(err); - }; - - Ok((class_name, ItemKind::Union(vdata, generics), None)) - } - - pub(super) fn is_union_item(&self) -> bool { - self.token.is_keyword(kw::Union) && - self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) - } - - fn parse_record_struct_body( - &mut self, - ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> { - let mut fields = Vec::new(); - let mut recovered = false; - if self.eat(&token::OpenDelim(token::Brace)) { - while self.token != token::CloseDelim(token::Brace) { - let field = self.parse_struct_decl_field().map_err(|e| { - self.consume_block(token::Brace, ConsumeClosingDelim::No); - recovered = true; - e - }); - match field { - Ok(field) => fields.push(field), - Err(mut err) => { - err.emit(); - break; - } - } - } - self.eat(&token::CloseDelim(token::Brace)); - } else { - let token_str = self.this_token_descr(); - let mut err = self.fatal(&format!( - "expected `where`, or `{{` after struct name, found {}", token_str)); - err.span_label(self.token.span, "expected `where`, or `{` after struct name"); - return Err(err); - } - - Ok((fields, recovered)) - } - - fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> { - // This is the case where we find `struct Foo<T>(T) where T: Copy;` - // Unit like structs are handled in parse_item_struct function - self.parse_paren_comma_seq(|p| { - let attrs = p.parse_outer_attributes()?; - let lo = p.token.span; - let vis = p.parse_visibility(true)?; - let ty = p.parse_ty()?; - Ok(StructField { - span: lo.to(ty.span), - vis, - ident: None, - id: DUMMY_NODE_ID, - ty, - attrs, - is_placeholder: false, - }) - }).map(|(r, _)| r) - } - - /// Parses an element of a struct declaration. - fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> { - let attrs = self.parse_outer_attributes()?; - let lo = self.token.span; - let vis = self.parse_visibility(false)?; - self.parse_single_struct_field(lo, vis, attrs) - } - - /// Parses a structure field declaration. - fn parse_single_struct_field(&mut self, - lo: Span, - vis: Visibility, - attrs: Vec<Attribute> ) - -> PResult<'a, StructField> { - let mut seen_comma: bool = false; - let a_var = self.parse_name_and_ty(lo, vis, attrs)?; - if self.token == token::Comma { - seen_comma = true; - } - match self.token.kind { - token::Comma => { - self.bump(); - } - token::CloseDelim(token::Brace) => {} - token::DocComment(_) => { - let previous_span = self.prev_span; - let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment); - self.bump(); // consume the doc comment - let comma_after_doc_seen = self.eat(&token::Comma); - // `seen_comma` is always false, because we are inside doc block - // condition is here to make code more readable - if seen_comma == false && comma_after_doc_seen == true { - seen_comma = true; - } - if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) { - err.emit(); - } else { - if seen_comma == false { - let sp = self.sess.source_map().next_point(previous_span); - err.span_suggestion( - sp, - "missing comma here", - ",".into(), - Applicability::MachineApplicable - ); - } - return Err(err); - } - } - _ => { - let sp = self.sess.source_map().next_point(self.prev_span); - let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}", - self.this_token_descr())); - if self.token.is_ident() { - // This is likely another field; emit the diagnostic and keep going - err.span_suggestion( - sp, - "try adding a comma", - ",".into(), - Applicability::MachineApplicable, - ); - err.emit(); - } else { - return Err(err) - } - } - } - Ok(a_var) - } - - /// Parses a structure field. - fn parse_name_and_ty( - &mut self, - lo: Span, - vis: Visibility, - attrs: Vec<Attribute> - ) -> PResult<'a, StructField> { - let name = self.parse_ident()?; - self.expect(&token::Colon)?; - let ty = self.parse_ty()?; - Ok(StructField { - span: lo.to(self.prev_span), - ident: Some(name), - vis, - id: DUMMY_NODE_ID, - ty, - attrs, - is_placeholder: false, - }) - } - - pub(super) fn eat_macro_def( - &mut self, - attrs: &[Attribute], - vis: &Visibility, - lo: Span - ) -> PResult<'a, Option<P<Item>>> { - let token_lo = self.token.span; - let (ident, def) = if self.eat_keyword(kw::Macro) { - let ident = self.parse_ident()?; - let tokens = if self.check(&token::OpenDelim(token::Brace)) { - match self.parse_token_tree() { - TokenTree::Delimited(_, _, tts) => tts, - _ => unreachable!(), - } - } else if self.check(&token::OpenDelim(token::Paren)) { - let args = self.parse_token_tree(); - let body = if self.check(&token::OpenDelim(token::Brace)) { - self.parse_token_tree() - } else { - self.unexpected()?; - unreachable!() - }; - TokenStream::new(vec![ - args.into(), - TokenTree::token(token::FatArrow, token_lo.to(self.prev_span)).into(), - body.into(), - ]) - } else { - self.unexpected()?; - unreachable!() - }; - - (ident, ast::MacroDef { tokens: tokens.into(), legacy: false }) - } else if self.check_keyword(sym::macro_rules) && - self.look_ahead(1, |t| *t == token::Not) && - self.look_ahead(2, |t| t.is_ident()) { - let prev_span = self.prev_span; - self.complain_if_pub_macro(&vis.node, prev_span); - self.bump(); - self.bump(); - - let ident = self.parse_ident()?; - let (delim, tokens) = self.expect_delimited_token_tree()?; - if delim != MacDelimiter::Brace && !self.eat(&token::Semi) { - self.report_invalid_macro_expansion_item(); - } - - (ident, ast::MacroDef { tokens, legacy: true }) - } else { - return Ok(None); - }; - - let span = lo.to(self.prev_span); - - if !def.legacy { - self.sess.gated_spans.gate(sym::decl_macro, span); - } - - Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec()))) - } - - fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) { - match *vis { - VisibilityKind::Inherited => {} - _ => { - let mut err = if self.token.is_keyword(sym::macro_rules) { - let mut err = self.diagnostic() - .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`"); - err.span_suggestion( - sp, - "try exporting the macro", - "#[macro_export]".to_owned(), - Applicability::MaybeIncorrect // speculative - ); - err - } else { - let mut err = self.diagnostic() - .struct_span_err(sp, "can't qualify macro invocation with `pub`"); - err.help("try adjusting the macro to put `pub` inside the invocation"); - err - }; - err.emit(); - } - } - } - - fn report_invalid_macro_expansion_item(&self) { - self.struct_span_err( - self.prev_span, - "macros that expand to items must be delimited with braces or followed by a semicolon", - ).multipart_suggestion( - "change the delimiters to curly braces", - vec![ - (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")), - (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()), - ], - Applicability::MaybeIncorrect, - ).span_suggestion( - self.sess.source_map().next_point(self.prev_span), - "add a semicolon", - ';'.to_string(), - Applicability::MaybeIncorrect, - ).emit(); - } - - fn mk_item(&self, span: Span, ident: Ident, kind: ItemKind, vis: Visibility, - attrs: Vec<Attribute>) -> P<Item> { - P(Item { - ident, - attrs, - id: DUMMY_NODE_ID, - kind, - vis, - span, - tokens: None, - }) - } -} - -/// The parsing configuration used to parse a parameter list (see `parse_fn_params`). -pub(super) struct ParamCfg { - /// Is `self` is allowed as the first parameter? - pub is_self_allowed: bool, - /// Is `...` allowed as the tail of the parameter list? - pub allow_c_variadic: bool, - /// `is_name_required` decides if, per-parameter, - /// the parameter must have a pattern or just a type. - pub is_name_required: fn(&token::Token) -> bool, -} - -/// Parsing of functions and methods. -impl<'a> Parser<'a> { - /// Parses an item-position function declaration. - fn parse_item_fn( - &mut self, - lo: Span, - vis: Visibility, - attrs: Vec<Attribute>, - header: FnHeader, - ) -> PResult<'a, Option<P<Item>>> { - let (ident, decl, generics) = self.parse_fn_sig(ParamCfg { - is_self_allowed: false, - allow_c_variadic: header.abi.symbol == sym::C && header.unsafety == Unsafety::Unsafe, - is_name_required: |_| true, - })?; - let (inner_attrs, body) = self.parse_inner_attrs_and_block()?; - let kind = ItemKind::Fn(FnSig { decl, header }, generics, body); - self.mk_item_with_info(attrs, lo, vis, (ident, kind, Some(inner_attrs))) - } - - /// Parses a function declaration from a foreign module. - fn parse_item_foreign_fn( - &mut self, - vis: ast::Visibility, - lo: Span, - attrs: Vec<Attribute>, - extern_sp: Span, - ) -> PResult<'a, ForeignItem> { - self.expect_keyword(kw::Fn)?; - let (ident, decl, generics) = self.parse_fn_sig(ParamCfg { - is_self_allowed: false, - allow_c_variadic: true, - is_name_required: |_| true, - })?; - let span = lo.to(self.token.span); - self.parse_semi_or_incorrect_foreign_fn_body(&ident, extern_sp)?; - Ok(ast::ForeignItem { - ident, - attrs, - kind: ForeignItemKind::Fn(decl, generics), - id: DUMMY_NODE_ID, - span, - vis, - }) - } - - /// Parses a method or a macro invocation in a trait impl. - fn parse_impl_method( - &mut self, - at_end: &mut bool, - ) -> PResult<'a, (Ident, Vec<Attribute>, Generics, ImplItemKind)> { - let (ident, sig, generics) = self.parse_method_sig(|_| true)?; - *at_end = true; - let (inner_attrs, body) = self.parse_inner_attrs_and_block()?; - Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(sig, body))) - } - - fn parse_trait_item_method( - &mut self, - at_end: &mut bool, - attrs: &mut Vec<Attribute>, - ) -> PResult<'a, (Ident, TraitItemKind, Generics)> { - // This is somewhat dubious; We don't want to allow - // argument names to be left off if there is a definition... - // - // We don't allow argument names to be left off in edition 2018. - let (ident, sig, generics) = self.parse_method_sig(|t| t.span.rust_2018())?; - let body = self.parse_trait_method_body(at_end, attrs)?; - Ok((ident, TraitItemKind::Method(sig, body), generics)) - } - - /// Parse the "body" of a method in a trait item definition. - /// This can either be `;` when there's no body, - /// or e.g. a block when the method is a provided one. - fn parse_trait_method_body( - &mut self, - at_end: &mut bool, - attrs: &mut Vec<Attribute>, - ) -> PResult<'a, Option<P<Block>>> { - Ok(match self.token.kind { - token::Semi => { - debug!("parse_trait_method_body(): parsing required method"); - self.bump(); - *at_end = true; - None - } - token::OpenDelim(token::Brace) => { - debug!("parse_trait_method_body(): parsing provided method"); - *at_end = true; - let (inner_attrs, body) = self.parse_inner_attrs_and_block()?; - attrs.extend(inner_attrs.iter().cloned()); - Some(body) - } - token::Interpolated(ref nt) => { - match **nt { - token::NtBlock(..) => { - *at_end = true; - let (inner_attrs, body) = self.parse_inner_attrs_and_block()?; - attrs.extend(inner_attrs.iter().cloned()); - Some(body) - } - _ => return self.expected_semi_or_open_brace(), - } - } - _ => return self.expected_semi_or_open_brace(), - }) - } - - /// Parse the "signature", including the identifier, parameters, and generics - /// of a method. The body is not parsed as that differs between `trait`s and `impl`s. - fn parse_method_sig( - &mut self, - is_name_required: fn(&token::Token) -> bool, - ) -> PResult<'a, (Ident, FnSig, Generics)> { - let header = self.parse_fn_front_matter()?; - let (ident, decl, generics) = self.parse_fn_sig(ParamCfg { - is_self_allowed: true, - allow_c_variadic: false, - is_name_required, - })?; - Ok((ident, FnSig { header, decl }, generics)) - } - - /// Parses all the "front matter" for a `fn` declaration, up to - /// and including the `fn` keyword: - /// - /// - `const fn` - /// - `unsafe fn` - /// - `const unsafe fn` - /// - `extern fn` - /// - etc. - fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> { - let is_const_fn = self.eat_keyword(kw::Const); - let const_span = self.prev_span; - let asyncness = self.parse_asyncness(); - if let IsAsync::Async { .. } = asyncness { - self.ban_async_in_2015(self.prev_span); - } - let asyncness = respan(self.prev_span, asyncness); - let unsafety = self.parse_unsafety(); - let (constness, unsafety, abi) = if is_const_fn { - (respan(const_span, Constness::Const), unsafety, Abi::default()) - } else { - let abi = self.parse_extern_abi()?; - (respan(self.prev_span, Constness::NotConst), unsafety, abi) - }; - if !self.eat_keyword(kw::Fn) { - // It is possible for `expect_one_of` to recover given the contents of - // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't - // account for this. - if !self.expect_one_of(&[], &[])? { unreachable!() } - } - Ok(FnHeader { constness, unsafety, asyncness, abi }) - } - - /// Parse the "signature", including the identifier, parameters, and generics of a function. - fn parse_fn_sig(&mut self, cfg: ParamCfg) -> PResult<'a, (Ident, P<FnDecl>, Generics)> { - let ident = self.parse_ident()?; - let mut generics = self.parse_generics()?; - let decl = self.parse_fn_decl(cfg, true)?; - generics.where_clause = self.parse_where_clause()?; - Ok((ident, decl, generics)) - } - - /// Parses the parameter list and result type of a function declaration. - pub(super) fn parse_fn_decl( - &mut self, - cfg: ParamCfg, - ret_allow_plus: bool, - ) -> PResult<'a, P<FnDecl>> { - Ok(P(FnDecl { - inputs: self.parse_fn_params(cfg)?, - output: self.parse_ret_ty(ret_allow_plus)?, - })) - } - - /// Parses the parameter list of a function, including the `(` and `)` delimiters. - fn parse_fn_params(&mut self, mut cfg: ParamCfg) -> PResult<'a, Vec<Param>> { - let sp = self.token.span; - let is_trait_item = cfg.is_self_allowed; - let mut c_variadic = false; - // Parse the arguments, starting out with `self` being possibly allowed... - let (params, _) = self.parse_paren_comma_seq(|p| { - let param = p.parse_param_general(&cfg, is_trait_item); - // ...now that we've parsed the first argument, `self` is no longer allowed. - cfg.is_self_allowed = false; - - match param { - Ok(param) => Ok( - if let TyKind::CVarArgs = param.ty.kind { - c_variadic = true; - if p.token != token::CloseDelim(token::Paren) { - p.span_err( - p.token.span, - "`...` must be the last argument of a C-variadic function", - ); - // FIXME(eddyb) this should probably still push `CVarArgs`. - // Maybe AST validation/HIR lowering should emit the above error? - None - } else { - Some(param) - } - } else { - Some(param) - } - ), - Err(mut e) => { - e.emit(); - let lo = p.prev_span; - // Skip every token until next possible arg or end. - p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]); - // Create a placeholder argument for proper arg count (issue #34264). - let span = lo.to(p.prev_span); - Ok(Some(dummy_arg(Ident::new(kw::Invalid, span)))) - } - } - })?; - - let mut params: Vec<_> = params.into_iter().filter_map(|x| x).collect(); - - // Replace duplicated recovered params with `_` pattern to avoid unecessary errors. - self.deduplicate_recovered_params_names(&mut params); - - if c_variadic && params.len() <= 1 { - self.span_err( - sp, - "C-variadic function must be declared with at least one named argument", - ); - } - - Ok(params) - } - - /// Skips unexpected attributes and doc comments in this position and emits an appropriate - /// error. - /// This version of parse param doesn't necessarily require identifier names. - fn parse_param_general(&mut self, cfg: &ParamCfg, is_trait_item: bool) -> PResult<'a, Param> { - let lo = self.token.span; - let attrs = self.parse_outer_attributes()?; - - // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here. - if let Some(mut param) = self.parse_self_param()? { - param.attrs = attrs.into(); - return if cfg.is_self_allowed { - Ok(param) - } else { - self.recover_bad_self_param(param, is_trait_item) - }; - } - - let is_name_required = match self.token.kind { - token::DotDotDot => false, - _ => (cfg.is_name_required)(&self.token), - }; - let (pat, ty) = if is_name_required || self.is_named_param() { - debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required); - - let pat = self.parse_fn_param_pat()?; - if let Err(mut err) = self.expect(&token::Colon) { - return if let Some(ident) = self.parameter_without_type( - &mut err, - pat, - is_name_required, - cfg.is_self_allowed, - is_trait_item, - ) { - err.emit(); - Ok(dummy_arg(ident)) - } else { - Err(err) - }; - } - - self.eat_incorrect_doc_comment_for_param_type(); - (pat, self.parse_ty_common(true, true, cfg.allow_c_variadic)?) - } else { - debug!("parse_param_general ident_to_pat"); - let parser_snapshot_before_ty = self.clone(); - self.eat_incorrect_doc_comment_for_param_type(); - let mut ty = self.parse_ty_common(true, true, cfg.allow_c_variadic); - if ty.is_ok() && self.token != token::Comma && - self.token != token::CloseDelim(token::Paren) { - // This wasn't actually a type, but a pattern looking like a type, - // so we are going to rollback and re-parse for recovery. - ty = self.unexpected(); - } - match ty { - Ok(ty) => { - let ident = Ident::new(kw::Invalid, self.prev_span); - let bm = BindingMode::ByValue(Mutability::Immutable); - let pat = self.mk_pat_ident(ty.span, bm, ident); - (pat, ty) - } - // If this is a C-variadic argument and we hit an error, return the error. - Err(err) if self.token == token::DotDotDot => return Err(err), - // Recover from attempting to parse the argument as a type without pattern. - Err(mut err) => { - err.cancel(); - mem::replace(self, parser_snapshot_before_ty); - self.recover_arg_parse()? - } - } - }; - - let span = lo.to(self.token.span); - - Ok(Param { - attrs: attrs.into(), - id: ast::DUMMY_NODE_ID, - is_placeholder: false, - pat, - span, - ty, - }) - } - - /// Returns the parsed optional self parameter and whether a self shortcut was used. - /// - /// See `parse_self_param_with_attrs` to collect attributes. - fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> { - // Extract an identifier *after* having confirmed that the token is one. - let expect_self_ident = |this: &mut Self| { - match this.token.kind { - // Preserve hygienic context. - token::Ident(name, _) => { - let span = this.token.span; - this.bump(); - Ident::new(name, span) - } - _ => unreachable!(), - } - }; - // Is `self` `n` tokens ahead? - let is_isolated_self = |this: &Self, n| { - this.is_keyword_ahead(n, &[kw::SelfLower]) - && this.look_ahead(n + 1, |t| t != &token::ModSep) - }; - // Is `mut self` `n` tokens ahead? - let is_isolated_mut_self = |this: &Self, n| { - this.is_keyword_ahead(n, &[kw::Mut]) - && is_isolated_self(this, n + 1) - }; - // Parse `self` or `self: TYPE`. We already know the current token is `self`. - let parse_self_possibly_typed = |this: &mut Self, m| { - let eself_ident = expect_self_ident(this); - let eself_hi = this.prev_span; - let eself = if this.eat(&token::Colon) { - SelfKind::Explicit(this.parse_ty()?, m) - } else { - SelfKind::Value(m) - }; - Ok((eself, eself_ident, eself_hi)) - }; - // Recover for the grammar `*self`, `*const self`, and `*mut self`. - let recover_self_ptr = |this: &mut Self| { - let msg = "cannot pass `self` by raw pointer"; - let span = this.token.span; - this.struct_span_err(span, msg) - .span_label(span, msg) - .emit(); - - Ok((SelfKind::Value(Mutability::Immutable), expect_self_ident(this), this.prev_span)) - }; - - // Parse optional `self` parameter of a method. - // Only a limited set of initial token sequences is considered `self` parameters; anything - // else is parsed as a normal function parameter list, so some lookahead is required. - let eself_lo = self.token.span; - let (eself, eself_ident, eself_hi) = match self.token.kind { - token::BinOp(token::And) => { - let eself = if is_isolated_self(self, 1) { - // `&self` - self.bump(); - SelfKind::Region(None, Mutability::Immutable) - } else if is_isolated_mut_self(self, 1) { - // `&mut self` - self.bump(); - self.bump(); - SelfKind::Region(None, Mutability::Mutable) - } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) { - // `&'lt self` - self.bump(); - let lt = self.expect_lifetime(); - SelfKind::Region(Some(lt), Mutability::Immutable) - } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) { - // `&'lt mut self` - self.bump(); - let lt = self.expect_lifetime(); - self.bump(); - SelfKind::Region(Some(lt), Mutability::Mutable) - } else { - // `¬_self` - return Ok(None); - }; - (eself, expect_self_ident(self), self.prev_span) - } - // `*self` - token::BinOp(token::Star) if is_isolated_self(self, 1) => { - self.bump(); - recover_self_ptr(self)? - } - // `*mut self` and `*const self` - token::BinOp(token::Star) if - self.look_ahead(1, |t| t.is_mutability()) - && is_isolated_self(self, 2) => - { - self.bump(); - self.bump(); - recover_self_ptr(self)? - } - // `self` and `self: TYPE` - token::Ident(..) if is_isolated_self(self, 0) => { - parse_self_possibly_typed(self, Mutability::Immutable)? - } - // `mut self` and `mut self: TYPE` - token::Ident(..) if is_isolated_mut_self(self, 0) => { - self.bump(); - parse_self_possibly_typed(self, Mutability::Mutable)? - } - _ => return Ok(None), - }; - - let eself = source_map::respan(eself_lo.to(eself_hi), eself); - Ok(Some(Param::from_self(ThinVec::default(), eself, eself_ident))) - } - - fn is_named_param(&self) -> bool { - let offset = match self.token.kind { - token::Interpolated(ref nt) => match **nt { - token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon), - _ => 0, - } - token::BinOp(token::And) | token::AndAnd => 1, - _ if self.token.is_keyword(kw::Mut) => 1, - _ => 0, - }; - - self.look_ahead(offset, |t| t.is_ident()) && - self.look_ahead(offset + 1, |t| t == &token::Colon) - } - - fn recover_first_param(&mut self) -> &'static str { - match self.parse_outer_attributes() - .and_then(|_| self.parse_self_param()) - .map_err(|mut e| e.cancel()) - { - Ok(Some(_)) => "method", - _ => "function", - } - } -} diff --git a/src/libsyntax/parse/parser/mod.rs b/src/libsyntax/parse/parser/mod.rs deleted file mode 100644 index 455f4172f5f..00000000000 --- a/src/libsyntax/parse/parser/mod.rs +++ /dev/null @@ -1,1391 +0,0 @@ -pub mod attr; -mod expr; -mod pat; -mod item; -mod module; -mod ty; -mod path; -pub use path::PathStyle; -mod stmt; -mod generics; -mod diagnostics; -use diagnostics::Error; - -use crate::ast::{ - self, Abi, DUMMY_NODE_ID, AttrStyle, Attribute, CrateSugar, Ident, - IsAsync, MacDelimiter, Mutability, StrStyle, Visibility, VisibilityKind, Unsafety, -}; -use crate::parse::{Directory, DirectoryOwnership}; -use crate::parse::lexer::UnmatchedBrace; -use crate::util::comments::{doc_comment_style, strip_doc_comment_decoration}; -use crate::token::{self, Token, TokenKind, DelimToken}; -use crate::print::pprust; -use crate::ptr::P; -use crate::sess::ParseSess; -use crate::source_map::respan; -use crate::symbol::{kw, sym, Symbol}; -use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint}; -use crate::ThinVec; - -use errors::{PResult, Applicability, DiagnosticBuilder, DiagnosticId, FatalError}; -use syntax_pos::{Span, BytePos, DUMMY_SP, FileName}; -use log::debug; - -use std::borrow::Cow; -use std::{cmp, mem, slice}; -use std::path::PathBuf; - -bitflags::bitflags! { - struct Restrictions: u8 { - const STMT_EXPR = 1 << 0; - const NO_STRUCT_LITERAL = 1 << 1; - } -} - -#[derive(Clone, Copy, PartialEq, Debug)] -enum SemiColonMode { - Break, - Ignore, - Comma, -} - -#[derive(Clone, Copy, PartialEq, Debug)] -enum BlockMode { - Break, - Ignore, -} - -/// Like `maybe_whole_expr`, but for things other than expressions. -#[macro_export] -macro_rules! maybe_whole { - ($p:expr, $constructor:ident, |$x:ident| $e:expr) => { - if let token::Interpolated(nt) = &$p.token.kind { - if let token::$constructor(x) = &**nt { - let $x = x.clone(); - $p.bump(); - return Ok($e); - } - } - }; -} - -/// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`. -#[macro_export] -macro_rules! maybe_recover_from_interpolated_ty_qpath { - ($self: expr, $allow_qpath_recovery: expr) => { - if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) { - if let token::Interpolated(nt) = &$self.token.kind { - if let token::NtTy(ty) = &**nt { - let ty = ty.clone(); - $self.bump(); - return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty); - } - } - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq)] -enum PrevTokenKind { - DocComment, - Comma, - Plus, - Interpolated, - Eof, - Ident, - BitOr, - Other, -} - -// NOTE: `Ident`s are handled by `common.rs`. - -#[derive(Clone)] -pub struct Parser<'a> { - pub sess: &'a ParseSess, - /// The current normalized token. - /// "Normalized" means that some interpolated tokens - /// (`$i: ident` and `$l: lifetime` meta-variables) are replaced - /// with non-interpolated identifier and lifetime tokens they refer to. - /// Perhaps the normalized / non-normalized setup can be simplified somehow. - pub token: Token, - /// The span of the current non-normalized token. - meta_var_span: Option<Span>, - /// The span of the previous non-normalized token. - pub prev_span: Span, - /// The kind of the previous normalized token (in simplified form). - prev_token_kind: PrevTokenKind, - restrictions: Restrictions, - /// Used to determine the path to externally loaded source files. - pub(super) directory: Directory<'a>, - /// `true` to parse sub-modules in other files. - pub(super) recurse_into_file_modules: bool, - /// Name of the root module this parser originated from. If `None`, then the - /// name is not known. This does not change while the parser is descending - /// into modules, and sub-parsers have new values for this name. - pub root_module_name: Option<String>, - expected_tokens: Vec<TokenType>, - token_cursor: TokenCursor, - desugar_doc_comments: bool, - /// `true` we should configure out of line modules as we parse. - cfg_mods: bool, - /// This field is used to keep track of how many left angle brackets we have seen. This is - /// required in order to detect extra leading left angle brackets (`<` characters) and error - /// appropriately. - /// - /// See the comments in the `parse_path_segment` function for more details. - unmatched_angle_bracket_count: u32, - max_angle_bracket_count: u32, - /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery - /// it gets removed from here. Every entry left at the end gets emitted as an independent - /// error. - pub(super) unclosed_delims: Vec<UnmatchedBrace>, - last_unexpected_token_span: Option<Span>, - pub last_type_ascription: Option<(Span, bool /* likely path typo */)>, - /// If present, this `Parser` is not parsing Rust code but rather a macro call. - subparser_name: Option<&'static str>, -} - -impl<'a> Drop for Parser<'a> { - fn drop(&mut self) { - emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); - } -} - -#[derive(Clone)] -struct TokenCursor { - frame: TokenCursorFrame, - stack: Vec<TokenCursorFrame>, -} - -#[derive(Clone)] -struct TokenCursorFrame { - delim: token::DelimToken, - span: DelimSpan, - open_delim: bool, - tree_cursor: tokenstream::Cursor, - close_delim: bool, - last_token: LastToken, -} - -/// This is used in `TokenCursorFrame` above to track tokens that are consumed -/// by the parser, and then that's transitively used to record the tokens that -/// each parse AST item is created with. -/// -/// Right now this has two states, either collecting tokens or not collecting -/// tokens. If we're collecting tokens we just save everything off into a local -/// `Vec`. This should eventually though likely save tokens from the original -/// token stream and just use slicing of token streams to avoid creation of a -/// whole new vector. -/// -/// The second state is where we're passively not recording tokens, but the last -/// token is still tracked for when we want to start recording tokens. This -/// "last token" means that when we start recording tokens we'll want to ensure -/// that this, the first token, is included in the output. -/// -/// You can find some more example usage of this in the `collect_tokens` method -/// on the parser. -#[derive(Clone)] -enum LastToken { - Collecting(Vec<TreeAndJoint>), - Was(Option<TreeAndJoint>), -} - -impl TokenCursorFrame { - fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self { - TokenCursorFrame { - delim, - span, - open_delim: delim == token::NoDelim, - tree_cursor: tts.clone().into_trees(), - close_delim: delim == token::NoDelim, - last_token: LastToken::Was(None), - } - } -} - -impl TokenCursor { - fn next(&mut self) -> Token { - loop { - let tree = if !self.frame.open_delim { - self.frame.open_delim = true; - TokenTree::open_tt(self.frame.span, self.frame.delim) - } else if let Some(tree) = self.frame.tree_cursor.next() { - tree - } else if !self.frame.close_delim { - self.frame.close_delim = true; - TokenTree::close_tt(self.frame.span, self.frame.delim) - } else if let Some(frame) = self.stack.pop() { - self.frame = frame; - continue - } else { - return Token::new(token::Eof, DUMMY_SP); - }; - - match self.frame.last_token { - LastToken::Collecting(ref mut v) => v.push(tree.clone().into()), - LastToken::Was(ref mut t) => *t = Some(tree.clone().into()), - } - - match tree { - TokenTree::Token(token) => return token, - TokenTree::Delimited(sp, delim, tts) => { - let frame = TokenCursorFrame::new(sp, delim, &tts); - self.stack.push(mem::replace(&mut self.frame, frame)); - } - } - } - } - - fn next_desugared(&mut self) -> Token { - let (name, sp) = match self.next() { - Token { kind: token::DocComment(name), span } => (name, span), - tok => return tok, - }; - - let stripped = strip_doc_comment_decoration(&name.as_str()); - - // Searches for the occurrences of `"#*` and returns the minimum number of `#`s - // required to wrap the text. - let mut num_of_hashes = 0; - let mut count = 0; - for ch in stripped.chars() { - count = match ch { - '"' => 1, - '#' if count > 0 => count + 1, - _ => 0, - }; - num_of_hashes = cmp::max(num_of_hashes, count); - } - - let delim_span = DelimSpan::from_single(sp); - let body = TokenTree::Delimited( - delim_span, - token::Bracket, - [ - TokenTree::token(token::Ident(sym::doc, false), sp), - TokenTree::token(token::Eq, sp), - TokenTree::token(TokenKind::lit( - token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None - ), sp), - ] - .iter().cloned().collect::<TokenStream>().into(), - ); - - self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new( - delim_span, - token::NoDelim, - &if doc_comment_style(&name.as_str()) == AttrStyle::Inner { - [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body] - .iter().cloned().collect::<TokenStream>() - } else { - [TokenTree::token(token::Pound, sp), body] - .iter().cloned().collect::<TokenStream>() - }, - ))); - - self.next() - } -} - -#[derive(Clone, PartialEq)] -enum TokenType { - Token(TokenKind), - Keyword(Symbol), - Operator, - Lifetime, - Ident, - Path, - Type, - Const, -} - -impl TokenType { - fn to_string(&self) -> String { - match *self { - TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)), - TokenType::Keyword(kw) => format!("`{}`", kw), - TokenType::Operator => "an operator".to_string(), - TokenType::Lifetime => "lifetime".to_string(), - TokenType::Ident => "identifier".to_string(), - TokenType::Path => "path".to_string(), - TokenType::Type => "type".to_string(), - TokenType::Const => "const".to_string(), - } - } -} - -#[derive(Copy, Clone, Debug)] -enum TokenExpectType { - Expect, - NoExpect, -} - -/// A sequence separator. -struct SeqSep { - /// The separator token. - sep: Option<TokenKind>, - /// `true` if a trailing separator is allowed. - trailing_sep_allowed: bool, -} - -impl SeqSep { - fn trailing_allowed(t: TokenKind) -> SeqSep { - SeqSep { - sep: Some(t), - trailing_sep_allowed: true, - } - } - - fn none() -> SeqSep { - SeqSep { - sep: None, - trailing_sep_allowed: false, - } - } -} - -impl<'a> Parser<'a> { - pub fn new( - sess: &'a ParseSess, - tokens: TokenStream, - directory: Option<Directory<'a>>, - recurse_into_file_modules: bool, - desugar_doc_comments: bool, - subparser_name: Option<&'static str>, - ) -> Self { - let mut parser = Parser { - sess, - token: Token::dummy(), - prev_span: DUMMY_SP, - meta_var_span: None, - prev_token_kind: PrevTokenKind::Other, - restrictions: Restrictions::empty(), - recurse_into_file_modules, - directory: Directory { - path: Cow::from(PathBuf::new()), - ownership: DirectoryOwnership::Owned { relative: None } - }, - root_module_name: None, - expected_tokens: Vec::new(), - token_cursor: TokenCursor { - frame: TokenCursorFrame::new( - DelimSpan::dummy(), - token::NoDelim, - &tokens.into(), - ), - stack: Vec::new(), - }, - desugar_doc_comments, - cfg_mods: true, - unmatched_angle_bracket_count: 0, - max_angle_bracket_count: 0, - unclosed_delims: Vec::new(), - last_unexpected_token_span: None, - last_type_ascription: None, - subparser_name, - }; - - parser.token = parser.next_tok(); - - if let Some(directory) = directory { - parser.directory = directory; - } else if !parser.token.span.is_dummy() { - if let Some(FileName::Real(path)) = - &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path { - if let Some(directory_path) = path.parent() { - parser.directory.path = Cow::from(directory_path.to_path_buf()); - } - } - } - - parser.process_potential_macro_variable(); - parser - } - - fn next_tok(&mut self) -> Token { - let mut next = if self.desugar_doc_comments { - self.token_cursor.next_desugared() - } else { - self.token_cursor.next() - }; - if next.span.is_dummy() { - // Tweak the location for better diagnostics, but keep syntactic context intact. - next.span = self.prev_span.with_ctxt(next.span.ctxt()); - } - next - } - - /// Converts the current token to a string using `self`'s reader. - pub fn this_token_to_string(&self) -> String { - pprust::token_to_string(&self.token) - } - - fn token_descr(&self) -> Option<&'static str> { - Some(match &self.token.kind { - _ if self.token.is_special_ident() => "reserved identifier", - _ if self.token.is_used_keyword() => "keyword", - _ if self.token.is_unused_keyword() => "reserved keyword", - token::DocComment(..) => "doc comment", - _ => return None, - }) - } - - pub(super) fn this_token_descr(&self) -> String { - if let Some(prefix) = self.token_descr() { - format!("{} `{}`", prefix, self.this_token_to_string()) - } else { - format!("`{}`", self.this_token_to_string()) - } - } - - crate fn unexpected<T>(&mut self) -> PResult<'a, T> { - match self.expect_one_of(&[], &[]) { - Err(e) => Err(e), - Ok(_) => unreachable!(), - } - } - - /// Expects and consumes the token `t`. Signals an error if the next token is not `t`. - pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { - if self.expected_tokens.is_empty() { - if self.token == *t { - self.bump(); - Ok(false) - } else { - self.unexpected_try_recover(t) - } - } else { - self.expect_one_of(slice::from_ref(t), &[]) - } - } - - /// Expect next token to be edible or inedible token. If edible, - /// then consume it; if inedible, then return without consuming - /// anything. Signal a fatal error if next token is unexpected. - pub fn expect_one_of( - &mut self, - edible: &[TokenKind], - inedible: &[TokenKind], - ) -> PResult<'a, bool /* recovered */> { - if edible.contains(&self.token.kind) { - self.bump(); - Ok(false) - } else if inedible.contains(&self.token.kind) { - // leave it in the input - Ok(false) - } else if self.last_unexpected_token_span == Some(self.token.span) { - FatalError.raise(); - } else { - self.expected_one_of_not_found(edible, inedible) - } - } - - fn parse_ident(&mut self) -> PResult<'a, ast::Ident> { - self.parse_ident_common(true) - } - - fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> { - match self.token.kind { - token::Ident(name, _) => { - if self.token.is_reserved_ident() { - let mut err = self.expected_ident_found(); - if recover { - err.emit(); - } else { - return Err(err); - } - } - let span = self.token.span; - self.bump(); - Ok(Ident::new(name, span)) - } - _ => { - Err(if self.prev_token_kind == PrevTokenKind::DocComment { - self.span_fatal_err(self.prev_span, Error::UselessDocComment) - } else { - self.expected_ident_found() - }) - } - } - } - - /// Checks if the next token is `tok`, and returns `true` if so. - /// - /// This method will automatically add `tok` to `expected_tokens` if `tok` is not - /// encountered. - fn check(&mut self, tok: &TokenKind) -> bool { - let is_present = self.token == *tok; - if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); } - is_present - } - - /// Consumes a token 'tok' if it exists. Returns whether the given token was present. - pub fn eat(&mut self, tok: &TokenKind) -> bool { - let is_present = self.check(tok); - if is_present { self.bump() } - is_present - } - - /// If the next token is the given keyword, returns `true` without eating it. - /// An expectation is also added for diagnostics purposes. - fn check_keyword(&mut self, kw: Symbol) -> bool { - self.expected_tokens.push(TokenType::Keyword(kw)); - self.token.is_keyword(kw) - } - - /// If the next token is the given keyword, eats it and returns `true`. - /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes. - fn eat_keyword(&mut self, kw: Symbol) -> bool { - if self.check_keyword(kw) { - self.bump(); - true - } else { - false - } - } - - fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { - if self.token.is_keyword(kw) { - self.bump(); - true - } else { - false - } - } - - /// If the given word is not a keyword, signals an error. - /// If the next token is not the given word, signals an error. - /// Otherwise, eats it. - fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { - if !self.eat_keyword(kw) { - self.unexpected() - } else { - Ok(()) - } - } - - fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { - if ok { - true - } else { - self.expected_tokens.push(typ); - false - } - } - - fn check_ident(&mut self) -> bool { - self.check_or_expected(self.token.is_ident(), TokenType::Ident) - } - - fn check_path(&mut self) -> bool { - self.check_or_expected(self.token.is_path_start(), TokenType::Path) - } - - fn check_type(&mut self) -> bool { - self.check_or_expected(self.token.can_begin_type(), TokenType::Type) - } - - fn check_const_arg(&mut self) -> bool { - self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) - } - - /// Checks to see if the next token is either `+` or `+=`. - /// Otherwise returns `false`. - fn check_plus(&mut self) -> bool { - self.check_or_expected( - self.token.is_like_plus(), - TokenType::Token(token::BinOp(token::Plus)), - ) - } - - /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=` - /// and continues. If a `+` is not seen, returns `false`. - /// - /// This is used when token-splitting `+=` into `+`. - /// See issue #47856 for an example of when this may occur. - fn eat_plus(&mut self) -> bool { - self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus))); - match self.token.kind { - token::BinOp(token::Plus) => { - self.bump(); - true - } - token::BinOpEq(token::Plus) => { - let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1)); - self.bump_with(token::Eq, span); - true - } - _ => false, - } - } - - /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single - /// `&` and continues. If an `&` is not seen, signals an error. - fn expect_and(&mut self) -> PResult<'a, ()> { - self.expected_tokens.push(TokenType::Token(token::BinOp(token::And))); - match self.token.kind { - token::BinOp(token::And) => { - self.bump(); - Ok(()) - } - token::AndAnd => { - let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1)); - Ok(self.bump_with(token::BinOp(token::And), span)) - } - _ => self.unexpected() - } - } - - /// Expects and consumes an `|`. If `||` is seen, replaces it with a single - /// `|` and continues. If an `|` is not seen, signals an error. - fn expect_or(&mut self) -> PResult<'a, ()> { - self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or))); - match self.token.kind { - token::BinOp(token::Or) => { - self.bump(); - Ok(()) - } - token::OrOr => { - let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1)); - Ok(self.bump_with(token::BinOp(token::Or), span)) - } - _ => self.unexpected() - } - } - - /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single - /// `<` and continue. If `<-` is seen, replaces it with a single `<` - /// and continue. If a `<` is not seen, returns false. - /// - /// This is meant to be used when parsing generics on a path to get the - /// starting token. - fn eat_lt(&mut self) -> bool { - self.expected_tokens.push(TokenType::Token(token::Lt)); - let ate = match self.token.kind { - token::Lt => { - self.bump(); - true - } - token::BinOp(token::Shl) => { - let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1)); - self.bump_with(token::Lt, span); - true - } - token::LArrow => { - let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1)); - self.bump_with(token::BinOp(token::Minus), span); - true - } - _ => false, - }; - - if ate { - // See doc comment for `unmatched_angle_bracket_count`. - self.unmatched_angle_bracket_count += 1; - self.max_angle_bracket_count += 1; - debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); - } - - ate - } - - fn expect_lt(&mut self) -> PResult<'a, ()> { - if !self.eat_lt() { - self.unexpected() - } else { - Ok(()) - } - } - - /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it - /// with a single `>` and continues. If a `>` is not seen, signals an error. - fn expect_gt(&mut self) -> PResult<'a, ()> { - self.expected_tokens.push(TokenType::Token(token::Gt)); - let ate = match self.token.kind { - token::Gt => { - self.bump(); - Some(()) - } - token::BinOp(token::Shr) => { - let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1)); - Some(self.bump_with(token::Gt, span)) - } - token::BinOpEq(token::Shr) => { - let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1)); - Some(self.bump_with(token::Ge, span)) - } - token::Ge => { - let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1)); - Some(self.bump_with(token::Eq, span)) - } - _ => None, - }; - - match ate { - Some(_) => { - // See doc comment for `unmatched_angle_bracket_count`. - if self.unmatched_angle_bracket_count > 0 { - self.unmatched_angle_bracket_count -= 1; - debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count); - } - - Ok(()) - }, - None => self.unexpected(), - } - } - - /// Parses a sequence, including the closing delimiter. The function - /// `f` must consume tokens until reaching the next separator or - /// closing bracket. - fn parse_seq_to_end<T>( - &mut self, - ket: &TokenKind, - sep: SeqSep, - f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, Vec<T>> { - let (val, _, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; - if !recovered { - self.bump(); - } - Ok(val) - } - - /// Parses a sequence, not including the closing delimiter. The function - /// `f` must consume tokens until reaching the next separator or - /// closing bracket. - fn parse_seq_to_before_end<T>( - &mut self, - ket: &TokenKind, - sep: SeqSep, - f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec<T>, bool, bool)> { - self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f) - } - - fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool { - kets.iter().any(|k| { - match expect { - TokenExpectType::Expect => self.check(k), - TokenExpectType::NoExpect => self.token == **k, - } - }) - } - - fn parse_seq_to_before_tokens<T>( - &mut self, - kets: &[&TokenKind], - sep: SeqSep, - expect: TokenExpectType, - mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> { - let mut first = true; - let mut recovered = false; - let mut trailing = false; - let mut v = vec![]; - while !self.expect_any_with_type(kets, expect) { - if let token::CloseDelim(..) | token::Eof = self.token.kind { - break - } - if let Some(ref t) = sep.sep { - if first { - first = false; - } else { - match self.expect(t) { - Ok(false) => {} - Ok(true) => { - recovered = true; - break; - } - Err(mut e) => { - // Attempt to keep parsing if it was a similar separator. - if let Some(ref tokens) = t.similar_tokens() { - if tokens.contains(&self.token.kind) { - self.bump(); - } - } - e.emit(); - // Attempt to keep parsing if it was an omitted separator. - match f(self) { - Ok(t) => { - v.push(t); - continue; - }, - Err(mut e) => { - e.cancel(); - break; - } - } - } - } - } - } - if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { - trailing = true; - break; - } - - let t = f(self)?; - v.push(t); - } - - Ok((v, trailing, recovered)) - } - - /// Parses a sequence, including the closing delimiter. The function - /// `f` must consume tokens until reaching the next separator or - /// closing bracket. - fn parse_unspanned_seq<T>( - &mut self, - bra: &TokenKind, - ket: &TokenKind, - sep: SeqSep, - f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec<T>, bool)> { - self.expect(bra)?; - let (result, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; - if !recovered { - self.eat(ket); - } - Ok((result, trailing)) - } - - fn parse_delim_comma_seq<T>( - &mut self, - delim: DelimToken, - f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec<T>, bool)> { - self.parse_unspanned_seq( - &token::OpenDelim(delim), - &token::CloseDelim(delim), - SeqSep::trailing_allowed(token::Comma), - f, - ) - } - - fn parse_paren_comma_seq<T>( - &mut self, - f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec<T>, bool)> { - self.parse_delim_comma_seq(token::Paren, f) - } - - /// Advance the parser by one token. - pub fn bump(&mut self) { - if self.prev_token_kind == PrevTokenKind::Eof { - // Bumping after EOF is a bad sign, usually an infinite loop. - self.bug("attempted to bump the parser past EOF (may be stuck in a loop)"); - } - - self.prev_span = self.meta_var_span.take().unwrap_or(self.token.span); - - // Record last token kind for possible error recovery. - self.prev_token_kind = match self.token.kind { - token::DocComment(..) => PrevTokenKind::DocComment, - token::Comma => PrevTokenKind::Comma, - token::BinOp(token::Plus) => PrevTokenKind::Plus, - token::BinOp(token::Or) => PrevTokenKind::BitOr, - token::Interpolated(..) => PrevTokenKind::Interpolated, - token::Eof => PrevTokenKind::Eof, - token::Ident(..) => PrevTokenKind::Ident, - _ => PrevTokenKind::Other, - }; - - self.token = self.next_tok(); - self.expected_tokens.clear(); - // Check after each token. - self.process_potential_macro_variable(); - } - - /// Advances the parser using provided token as a next one. Use this when - /// consuming a part of a token. For example a single `<` from `<<`. - fn bump_with(&mut self, next: TokenKind, span: Span) { - self.prev_span = self.token.span.with_hi(span.lo()); - // It would be incorrect to record the kind of the current token, but - // fortunately for tokens currently using `bump_with`, the - // `prev_token_kind` will be of no use anyway. - self.prev_token_kind = PrevTokenKind::Other; - self.token = Token::new(next, span); - self.expected_tokens.clear(); - } - - /// Look-ahead `dist` tokens of `self.token` and get access to that token there. - /// When `dist == 0` then the current token is looked at. - pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { - if dist == 0 { - return looker(&self.token); - } - - let frame = &self.token_cursor.frame; - looker(&match frame.tree_cursor.look_ahead(dist - 1) { - Some(tree) => match tree { - TokenTree::Token(token) => token, - TokenTree::Delimited(dspan, delim, _) => - Token::new(token::OpenDelim(delim), dspan.open), - } - None => Token::new(token::CloseDelim(frame.delim), frame.span.close) - }) - } - - /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. - fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { - self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) - } - - /// Parses asyncness: `async` or nothing. - fn parse_asyncness(&mut self) -> IsAsync { - if self.eat_keyword(kw::Async) { - IsAsync::Async { - closure_id: DUMMY_NODE_ID, - return_impl_trait_id: DUMMY_NODE_ID, - } - } else { - IsAsync::NotAsync - } - } - - /// Parses unsafety: `unsafe` or nothing. - fn parse_unsafety(&mut self) -> Unsafety { - if self.eat_keyword(kw::Unsafe) { - Unsafety::Unsafe - } else { - Unsafety::Normal - } - } - - /// Parses mutability (`mut` or nothing). - fn parse_mutability(&mut self) -> Mutability { - if self.eat_keyword(kw::Mut) { - Mutability::Mutable - } else { - Mutability::Immutable - } - } - - /// Possibly parses mutability (`const` or `mut`). - fn parse_const_or_mut(&mut self) -> Option<Mutability> { - if self.eat_keyword(kw::Mut) { - Some(Mutability::Mutable) - } else if self.eat_keyword(kw::Const) { - Some(Mutability::Immutable) - } else { - None - } - } - - fn parse_field_name(&mut self) -> PResult<'a, Ident> { - if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = - self.token.kind { - self.expect_no_suffix(self.token.span, "a tuple index", suffix); - self.bump(); - Ok(Ident::new(symbol, self.prev_span)) - } else { - self.parse_ident_common(false) - } - } - - fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> { - let delim = match self.token.kind { - token::OpenDelim(delim) => delim, - _ => { - let msg = "expected open delimiter"; - let mut err = self.fatal(msg); - err.span_label(self.token.span, msg); - return Err(err) - } - }; - let tts = match self.parse_token_tree() { - TokenTree::Delimited(_, _, tts) => tts, - _ => unreachable!(), - }; - let delim = match delim { - token::Paren => MacDelimiter::Parenthesis, - token::Bracket => MacDelimiter::Bracket, - token::Brace => MacDelimiter::Brace, - token::NoDelim => self.bug("unexpected no delimiter"), - }; - Ok((delim, tts.into())) - } - - fn parse_or_use_outer_attributes( - &mut self, - already_parsed_attrs: Option<ThinVec<Attribute>>, - ) -> PResult<'a, ThinVec<Attribute>> { - if let Some(attrs) = already_parsed_attrs { - Ok(attrs) - } else { - self.parse_outer_attributes().map(|a| a.into()) - } - } - - pub fn process_potential_macro_variable(&mut self) { - self.token = match self.token.kind { - token::Dollar if self.token.span.from_expansion() && - self.look_ahead(1, |t| t.is_ident()) => { - self.bump(); - let name = match self.token.kind { - token::Ident(name, _) => name, - _ => unreachable!() - }; - let span = self.prev_span.to(self.token.span); - self.diagnostic() - .struct_span_fatal(span, &format!("unknown macro variable `{}`", name)) - .span_label(span, "unknown macro variable") - .emit(); - self.bump(); - return - } - token::Interpolated(ref nt) => { - self.meta_var_span = Some(self.token.span); - // Interpolated identifier and lifetime tokens are replaced with usual identifier - // and lifetime tokens, so the former are never encountered during normal parsing. - match **nt { - token::NtIdent(ident, is_raw) => - Token::new(token::Ident(ident.name, is_raw), ident.span), - token::NtLifetime(ident) => - Token::new(token::Lifetime(ident.name), ident.span), - _ => return, - } - } - _ => return, - }; - } - - /// Parses a single token tree from the input. - pub fn parse_token_tree(&mut self) -> TokenTree { - match self.token.kind { - token::OpenDelim(..) => { - let frame = mem::replace(&mut self.token_cursor.frame, - self.token_cursor.stack.pop().unwrap()); - self.token.span = frame.span.entire(); - self.bump(); - TokenTree::Delimited( - frame.span, - frame.delim, - frame.tree_cursor.stream.into(), - ) - }, - token::CloseDelim(_) | token::Eof => unreachable!(), - _ => { - let token = self.token.take(); - self.bump(); - TokenTree::Token(token) - } - } - } - - /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF. - pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> { - let mut tts = Vec::new(); - while self.token != token::Eof { - tts.push(self.parse_token_tree()); - } - Ok(tts) - } - - pub fn parse_tokens(&mut self) -> TokenStream { - let mut result = Vec::new(); - loop { - match self.token.kind { - token::Eof | token::CloseDelim(..) => break, - _ => result.push(self.parse_token_tree().into()), - } - } - TokenStream::new(result) - } - - /// Evaluates the closure with restrictions in place. - /// - /// Afters the closure is evaluated, restrictions are reset. - fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T { - let old = self.restrictions; - self.restrictions = res; - let res = f(self); - self.restrictions = old; - res - } - - fn is_crate_vis(&self) -> bool { - self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) - } - - /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`, - /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`. - /// If the following element can't be a tuple (i.e., it's a function definition), then - /// it's not a tuple struct field), and the contents within the parentheses isn't valid, - /// so emit a proper diagnostic. - pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> { - maybe_whole!(self, NtVis, |x| x); - - self.expected_tokens.push(TokenType::Keyword(kw::Crate)); - if self.is_crate_vis() { - self.bump(); // `crate` - self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_span); - return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate))); - } - - if !self.eat_keyword(kw::Pub) { - // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no - // keyword to grab a span from for inherited visibility; an empty span at the - // beginning of the current token would seem to be the "Schelling span". - return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited)) - } - let lo = self.prev_span; - - if self.check(&token::OpenDelim(token::Paren)) { - // We don't `self.bump()` the `(` yet because this might be a struct definition where - // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`. - // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so - // by the following tokens. - if self.is_keyword_ahead(1, &[kw::Crate]) - && self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)` - { - // Parse `pub(crate)`. - self.bump(); // `(` - self.bump(); // `crate` - self.expect(&token::CloseDelim(token::Paren))?; // `)` - let vis = VisibilityKind::Crate(CrateSugar::PubCrate); - return Ok(respan(lo.to(self.prev_span), vis)); - } else if self.is_keyword_ahead(1, &[kw::In]) { - // Parse `pub(in path)`. - self.bump(); // `(` - self.bump(); // `in` - let path = self.parse_path(PathStyle::Mod)?; // `path` - self.expect(&token::CloseDelim(token::Paren))?; // `)` - let vis = VisibilityKind::Restricted { - path: P(path), - id: ast::DUMMY_NODE_ID, - }; - return Ok(respan(lo.to(self.prev_span), vis)); - } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) - && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower]) - { - // Parse `pub(self)` or `pub(super)`. - self.bump(); // `(` - let path = self.parse_path(PathStyle::Mod)?; // `super`/`self` - self.expect(&token::CloseDelim(token::Paren))?; // `)` - let vis = VisibilityKind::Restricted { - path: P(path), - id: ast::DUMMY_NODE_ID, - }; - return Ok(respan(lo.to(self.prev_span), vis)); - } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct. - self.recover_incorrect_vis_restriction()?; - // Emit diagnostic, but continue with public visibility. - } - } - - Ok(respan(lo, VisibilityKind::Public)) - } - - /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }` - fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> { - self.bump(); // `(` - let path = self.parse_path(PathStyle::Mod)?; - self.expect(&token::CloseDelim(token::Paren))?; // `)` - - let msg = "incorrect visibility restriction"; - let suggestion = r##"some possible visibility restrictions are: -`pub(crate)`: visible only on the current crate -`pub(super)`: visible only in the current module's parent -`pub(in path::to::module)`: visible only on the specified path"##; - - let path_str = pprust::path_to_string(&path); - - struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg) - .help(suggestion) - .span_suggestion( - path.span, - &format!("make this visible only to module `{}` with `in`", path_str), - format!("in {}", path_str), - Applicability::MachineApplicable, - ) - .emit(); - - Ok(()) - } - - /// Parses `extern string_literal?`. - /// If `extern` is not found, the Rust ABI is used. - /// If `extern` is found and a `string_literal` does not follow, the C ABI is used. - fn parse_extern_abi(&mut self) -> PResult<'a, Abi> { - Ok(if self.eat_keyword(kw::Extern) { - self.parse_opt_abi()? - } else { - Abi::default() - }) - } - - /// Parses a string literal as an ABI spec. - /// If one is not found, the "C" ABI is used. - fn parse_opt_abi(&mut self) -> PResult<'a, Abi> { - let span = if self.token.can_begin_literal_or_bool() { - let ast::Lit { span, kind, .. } = self.parse_lit()?; - match kind { - ast::LitKind::Str(symbol, _) => return Ok(Abi::new(symbol, span)), - ast::LitKind::Err(_) => {} - _ => { - self.struct_span_err(span, "non-string ABI literal") - .span_suggestion( - span, - "specify the ABI with a string literal", - "\"C\"".to_string(), - Applicability::MaybeIncorrect, - ) - .emit(); - } - } - span - } else { - self.prev_span - }; - Ok(Abi::new(sym::C, span)) - } - - /// We are parsing `async fn`. If we are on Rust 2015, emit an error. - fn ban_async_in_2015(&self, async_span: Span) { - if async_span.rust_2015() { - self.diagnostic() - .struct_span_err_with_code( - async_span, - "`async fn` is not permitted in the 2015 edition", - DiagnosticId::Error("E0670".into()) - ) - .emit(); - } - } - - fn collect_tokens<R>( - &mut self, - f: impl FnOnce(&mut Self) -> PResult<'a, R>, - ) -> PResult<'a, (R, TokenStream)> { - // Record all tokens we parse when parsing this item. - let mut tokens = Vec::new(); - let prev_collecting = match self.token_cursor.frame.last_token { - LastToken::Collecting(ref mut list) => { - Some(mem::take(list)) - } - LastToken::Was(ref mut last) => { - tokens.extend(last.take()); - None - } - }; - self.token_cursor.frame.last_token = LastToken::Collecting(tokens); - let prev = self.token_cursor.stack.len(); - let ret = f(self); - let last_token = if self.token_cursor.stack.len() == prev { - &mut self.token_cursor.frame.last_token - } else if self.token_cursor.stack.get(prev).is_none() { - // This can happen due to a bad interaction of two unrelated recovery mechanisms with - // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(` - // (#62881). - return Ok((ret?, TokenStream::default())); - } else { - &mut self.token_cursor.stack[prev].last_token - }; - - // Pull out the tokens that we've collected from the call to `f` above. - let mut collected_tokens = match *last_token { - LastToken::Collecting(ref mut v) => mem::take(v), - LastToken::Was(ref was) => { - let msg = format!("our vector went away? - found Was({:?})", was); - debug!("collect_tokens: {}", msg); - self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg); - // This can happen due to a bad interaction of two unrelated recovery mechanisms - // with mismatched delimiters *and* recovery lookahead on the likely typo - // `pub ident(` (#62895, different but similar to the case above). - return Ok((ret?, TokenStream::default())); - } - }; - - // If we're not at EOF our current token wasn't actually consumed by - // `f`, but it'll still be in our list that we pulled out. In that case - // put it back. - let extra_token = if self.token != token::Eof { - collected_tokens.pop() - } else { - None - }; - - // If we were previously collecting tokens, then this was a recursive - // call. In that case we need to record all the tokens we collected in - // our parent list as well. To do that we push a clone of our stream - // onto the previous list. - match prev_collecting { - Some(mut list) => { - list.extend(collected_tokens.iter().cloned()); - list.extend(extra_token); - *last_token = LastToken::Collecting(list); - } - None => { - *last_token = LastToken::Was(extra_token); - } - } - - Ok((ret?, TokenStream::new(collected_tokens))) - } - - /// `::{` or `::*` - fn is_import_coupler(&mut self) -> bool { - self.check(&token::ModSep) && - self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) || - *t == token::BinOp(token::Star)) - } - - fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> { - let ret = match self.token.kind { - token::Literal(token::Lit { kind: token::Str, symbol, suffix }) => - (symbol, ast::StrStyle::Cooked, suffix), - token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) => - (symbol, ast::StrStyle::Raw(n), suffix), - _ => return None - }; - self.bump(); - Some(ret) - } - - pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> { - match self.parse_optional_str() { - Some((s, style, suf)) => { - let sp = self.prev_span; - self.expect_no_suffix(sp, "a string literal", suf); - Ok((s, style)) - } - _ => { - let msg = "expected string literal"; - let mut err = self.fatal(msg); - err.span_label(self.token.span, msg); - Err(err) - } - } - } -} - -crate fn make_unclosed_delims_error( - unmatched: UnmatchedBrace, - sess: &ParseSess, -) -> Option<DiagnosticBuilder<'_>> { - // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to - // `unmatched_braces` only for error recovery in the `Parser`. - let found_delim = unmatched.found_delim?; - let mut err = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!( - "incorrect close delimiter: `{}`", - pprust::token_kind_to_string(&token::CloseDelim(found_delim)), - )); - err.span_label(unmatched.found_span, "incorrect close delimiter"); - if let Some(sp) = unmatched.candidate_span { - err.span_label(sp, "close delimiter possibly meant for this"); - } - if let Some(sp) = unmatched.unclosed_span { - err.span_label(sp, "un-closed delimiter"); - } - Some(err) -} - -pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) { - *sess.reached_eof.borrow_mut() |= unclosed_delims.iter() - .any(|unmatched_delim| unmatched_delim.found_delim.is_none()); - for unmatched in unclosed_delims.drain(..) { - make_unclosed_delims_error(unmatched, sess).map(|mut e| e.emit()); - } -} diff --git a/src/libsyntax/parse/parser/module.rs b/src/libsyntax/parse/parser/module.rs deleted file mode 100644 index 3e5974c2eee..00000000000 --- a/src/libsyntax/parse/parser/module.rs +++ /dev/null @@ -1,320 +0,0 @@ -use super::Parser; -use super::item::ItemInfo; -use super::diagnostics::Error; - -use crate::attr; -use crate::ast::{self, Ident, Attribute, ItemKind, Mod, Crate}; -use crate::parse::{new_sub_parser_from_file, DirectoryOwnership}; -use crate::token::{self, TokenKind}; -use crate::source_map::{SourceMap, Span, DUMMY_SP, FileName}; -use crate::symbol::sym; - -use errors::PResult; - -use std::path::{self, Path, PathBuf}; - -/// Information about the path to a module. -pub(super) struct ModulePath { - name: String, - path_exists: bool, - pub result: Result<ModulePathSuccess, Error>, -} - -pub(super) struct ModulePathSuccess { - pub path: PathBuf, - pub directory_ownership: DirectoryOwnership, -} - -impl<'a> Parser<'a> { - /// Parses a source module as a crate. This is the main entry point for the parser. - pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> { - let lo = self.token.span; - let krate = Ok(ast::Crate { - attrs: self.parse_inner_attributes()?, - module: self.parse_mod_items(&token::Eof, lo)?, - span: lo.to(self.token.span), - }); - krate - } - - /// Parses a `mod <foo> { ... }` or `mod <foo>;` item. - pub(super) fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> { - let (in_cfg, outer_attrs) = { - // FIXME(Centril): This results in a cycle between config and parsing. - // Consider using dynamic dispatch via `self.sess` to disentangle the knot. - let mut strip_unconfigured = crate::config::StripUnconfigured { - sess: self.sess, - features: None, // Don't perform gated feature checking. - }; - let mut outer_attrs = outer_attrs.to_owned(); - strip_unconfigured.process_cfg_attrs(&mut outer_attrs); - (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs) - }; - - let id_span = self.token.span; - let id = self.parse_ident()?; - if self.eat(&token::Semi) { - if in_cfg && self.recurse_into_file_modules { - // This mod is in an external file. Let's go get it! - let ModulePathSuccess { path, directory_ownership } = - self.submod_path(id, &outer_attrs, id_span)?; - let (module, attrs) = - self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?; - Ok((id, ItemKind::Mod(module), Some(attrs))) - } else { - let placeholder = ast::Mod { - inner: DUMMY_SP, - items: Vec::new(), - inline: false - }; - Ok((id, ItemKind::Mod(placeholder), None)) - } - } else { - let old_directory = self.directory.clone(); - self.push_directory(id, &outer_attrs); - - self.expect(&token::OpenDelim(token::Brace))?; - let mod_inner_lo = self.token.span; - let attrs = self.parse_inner_attributes()?; - let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?; - - self.directory = old_directory; - Ok((id, ItemKind::Mod(module), Some(attrs))) - } - } - - /// Given a termination token, parses all of the items in a module. - fn parse_mod_items(&mut self, term: &TokenKind, inner_lo: Span) -> PResult<'a, Mod> { - let mut items = vec![]; - while let Some(item) = self.parse_item()? { - items.push(item); - self.maybe_consume_incorrect_semicolon(&items); - } - - if !self.eat(term) { - let token_str = self.this_token_descr(); - if !self.maybe_consume_incorrect_semicolon(&items) { - let mut err = self.fatal(&format!("expected item, found {}", token_str)); - err.span_label(self.token.span, "expected item"); - return Err(err); - } - } - - let hi = if self.token.span.is_dummy() { - inner_lo - } else { - self.prev_span - }; - - Ok(Mod { - inner: inner_lo.to(hi), - items, - inline: true - }) - } - - fn submod_path( - &mut self, - id: ast::Ident, - outer_attrs: &[Attribute], - id_sp: Span - ) -> PResult<'a, ModulePathSuccess> { - if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) { - return Ok(ModulePathSuccess { - directory_ownership: match path.file_name().and_then(|s| s.to_str()) { - // All `#[path]` files are treated as though they are a `mod.rs` file. - // This means that `mod foo;` declarations inside `#[path]`-included - // files are siblings, - // - // Note that this will produce weirdness when a file named `foo.rs` is - // `#[path]` included and contains a `mod foo;` declaration. - // If you encounter this, it's your own darn fault :P - Some(_) => DirectoryOwnership::Owned { relative: None }, - _ => DirectoryOwnership::UnownedViaMod, - }, - path, - }); - } - - let relative = match self.directory.ownership { - DirectoryOwnership::Owned { relative } => relative, - DirectoryOwnership::UnownedViaBlock | - DirectoryOwnership::UnownedViaMod => None, - }; - let paths = Parser::default_submod_path( - id, relative, &self.directory.path, self.sess.source_map()); - - match self.directory.ownership { - DirectoryOwnership::Owned { .. } => { - paths.result.map_err(|err| self.span_fatal_err(id_sp, err)) - }, - DirectoryOwnership::UnownedViaBlock => { - let msg = - "Cannot declare a non-inline module inside a block \ - unless it has a path attribute"; - let mut err = self.diagnostic().struct_span_err(id_sp, msg); - if paths.path_exists { - let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", - paths.name); - err.span_note(id_sp, &msg); - } - Err(err) - } - DirectoryOwnership::UnownedViaMod => { - let mut err = self.diagnostic().struct_span_err(id_sp, - "cannot declare a new module at this location"); - if !id_sp.is_dummy() { - let src_path = self.sess.source_map().span_to_filename(id_sp); - if let FileName::Real(src_path) = src_path { - if let Some(stem) = src_path.file_stem() { - let mut dest_path = src_path.clone(); - dest_path.set_file_name(stem); - dest_path.push("mod.rs"); - err.span_note(id_sp, - &format!("maybe move this module `{}` to its own \ - directory via `{}`", src_path.display(), - dest_path.display())); - } - } - } - if paths.path_exists { - err.span_note(id_sp, - &format!("... or maybe `use` the module `{}` instead \ - of possibly redeclaring it", - paths.name)); - } - Err(err) - } - } - } - - pub(super) fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> { - if let Some(s) = attr::first_attr_value_str_by_name(attrs, sym::path) { - let s = s.as_str(); - - // On windows, the base path might have the form - // `\\?\foo\bar` in which case it does not tolerate - // mixed `/` and `\` separators, so canonicalize - // `/` to `\`. - #[cfg(windows)] - let s = s.replace("/", "\\"); - Some(dir_path.join(&*s)) - } else { - None - } - } - - /// Returns a path to a module. - pub(super) fn default_submod_path( - id: ast::Ident, - relative: Option<ast::Ident>, - dir_path: &Path, - source_map: &SourceMap) -> ModulePath - { - // If we're in a foo.rs file instead of a mod.rs file, - // we need to look for submodules in - // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than - // `./<id>.rs` and `./<id>/mod.rs`. - let relative_prefix_string; - let relative_prefix = if let Some(ident) = relative { - relative_prefix_string = format!("{}{}", ident, path::MAIN_SEPARATOR); - &relative_prefix_string - } else { - "" - }; - - let mod_name = id.to_string(); - let default_path_str = format!("{}{}.rs", relative_prefix, mod_name); - let secondary_path_str = format!("{}{}{}mod.rs", - relative_prefix, mod_name, path::MAIN_SEPARATOR); - let default_path = dir_path.join(&default_path_str); - let secondary_path = dir_path.join(&secondary_path_str); - let default_exists = source_map.file_exists(&default_path); - let secondary_exists = source_map.file_exists(&secondary_path); - - let result = match (default_exists, secondary_exists) { - (true, false) => Ok(ModulePathSuccess { - path: default_path, - directory_ownership: DirectoryOwnership::Owned { - relative: Some(id), - }, - }), - (false, true) => Ok(ModulePathSuccess { - path: secondary_path, - directory_ownership: DirectoryOwnership::Owned { - relative: None, - }, - }), - (false, false) => Err(Error::FileNotFoundForModule { - mod_name: mod_name.clone(), - default_path: default_path_str, - secondary_path: secondary_path_str, - dir_path: dir_path.display().to_string(), - }), - (true, true) => Err(Error::DuplicatePaths { - mod_name: mod_name.clone(), - default_path: default_path_str, - secondary_path: secondary_path_str, - }), - }; - - ModulePath { - name: mod_name, - path_exists: default_exists || secondary_exists, - result, - } - } - - /// Reads a module from a source file. - fn eval_src_mod( - &mut self, - path: PathBuf, - directory_ownership: DirectoryOwnership, - name: String, - id_sp: Span, - ) -> PResult<'a, (Mod, Vec<Attribute>)> { - let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut(); - if let Some(i) = included_mod_stack.iter().position(|p| *p == path) { - let mut err = String::from("circular modules: "); - let len = included_mod_stack.len(); - for p in &included_mod_stack[i.. len] { - err.push_str(&p.to_string_lossy()); - err.push_str(" -> "); - } - err.push_str(&path.to_string_lossy()); - return Err(self.span_fatal(id_sp, &err[..])); - } - included_mod_stack.push(path.clone()); - drop(included_mod_stack); - - let mut p0 = - new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp); - p0.cfg_mods = self.cfg_mods; - let mod_inner_lo = p0.token.span; - let mod_attrs = p0.parse_inner_attributes()?; - let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?; - m0.inline = false; - self.sess.included_mod_stack.borrow_mut().pop(); - Ok((m0, mod_attrs)) - } - - fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) { - if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) { - self.directory.path.to_mut().push(&*path.as_str()); - self.directory.ownership = DirectoryOwnership::Owned { relative: None }; - } else { - // We have to push on the current module name in the case of relative - // paths in order to ensure that any additional module paths from inline - // `mod x { ... }` come after the relative extension. - // - // For example, a `mod z { ... }` inside `x/y.rs` should set the current - // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`. - if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership { - if let Some(ident) = relative.take() { // remove the relative offset - self.directory.path.to_mut().push(&*ident.as_str()); - } - } - self.directory.path.to_mut().push(&*id.as_str()); - } - } -} diff --git a/src/libsyntax/parse/parser/pat.rs b/src/libsyntax/parse/parser/pat.rs deleted file mode 100644 index f347300da71..00000000000 --- a/src/libsyntax/parse/parser/pat.rs +++ /dev/null @@ -1,1016 +0,0 @@ -use super::{Parser, PathStyle}; - -use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole}; -use crate::ptr::P; -use crate::ast::{self, Attribute, Pat, PatKind, FieldPat, RangeEnd, RangeSyntax, Mac}; -use crate::ast::{BindingMode, Ident, Mutability, Path, QSelf, Expr, ExprKind}; -use crate::mut_visit::{noop_visit_pat, noop_visit_mac, MutVisitor}; -use crate::token; -use crate::print::pprust; -use crate::source_map::{respan, Span, Spanned}; -use crate::ThinVec; -use syntax_pos::symbol::{kw, sym}; -use errors::{PResult, Applicability, DiagnosticBuilder}; - -type Expected = Option<&'static str>; - -/// `Expected` for function and lambda parameter patterns. -pub(super) const PARAM_EXPECTED: Expected = Some("parameter name"); - -const WHILE_PARSING_OR_MSG: &str = "while parsing this or-pattern starting here"; - -/// Whether or not an or-pattern should be gated when occurring in the current context. -#[derive(PartialEq)] -pub(super) enum GateOr { Yes, No } - -/// Whether or not to recover a `,` when parsing or-patterns. -#[derive(PartialEq, Copy, Clone)] -enum RecoverComma { Yes, No } - -impl<'a> Parser<'a> { - /// Parses a pattern. - /// - /// Corresponds to `pat<no_top_alt>` in RFC 2535 and does not admit or-patterns - /// at the top level. Used when parsing the parameters of lambda expressions, - /// functions, function pointers, and `pat` macro fragments. - pub fn parse_pat(&mut self, expected: Expected) -> PResult<'a, P<Pat>> { - self.parse_pat_with_range_pat(true, expected) - } - - /// Entry point to the main pattern parser. - /// Corresponds to `top_pat` in RFC 2535 and allows or-pattern at the top level. - pub(super) fn parse_top_pat(&mut self, gate_or: GateOr) -> PResult<'a, P<Pat>> { - // Allow a '|' before the pats (RFCs 1925, 2530, and 2535). - let gated_leading_vert = self.eat_or_separator(None) && gate_or == GateOr::Yes; - let leading_vert_span = self.prev_span; - - // Parse the possibly-or-pattern. - let pat = self.parse_pat_with_or(None, gate_or, RecoverComma::Yes)?; - - // If we parsed a leading `|` which should be gated, - // and no other gated or-pattern has been parsed thus far, - // then we should really gate the leading `|`. - // This complicated procedure is done purely for diagnostics UX. - if gated_leading_vert && self.sess.gated_spans.is_ungated(sym::or_patterns) { - self.sess.gated_spans.gate(sym::or_patterns, leading_vert_span); - } - - Ok(pat) - } - - /// Parse the pattern for a function or function pointer parameter. - /// Special recovery is provided for or-patterns and leading `|`. - pub(super) fn parse_fn_param_pat(&mut self) -> PResult<'a, P<Pat>> { - self.recover_leading_vert(None, "not allowed in a parameter pattern"); - let pat = self.parse_pat_with_or(PARAM_EXPECTED, GateOr::No, RecoverComma::No)?; - - if let PatKind::Or(..) = &pat.kind { - self.ban_illegal_fn_param_or_pat(&pat); - } - - Ok(pat) - } - - /// Ban `A | B` immediately in a parameter pattern and suggest wrapping in parens. - fn ban_illegal_fn_param_or_pat(&self, pat: &Pat) { - let msg = "wrap the pattern in parenthesis"; - let fix = format!("({})", pprust::pat_to_string(pat)); - self.struct_span_err(pat.span, "an or-pattern parameter must be wrapped in parenthesis") - .span_suggestion(pat.span, msg, fix, Applicability::MachineApplicable) - .emit(); - } - - /// Parses a pattern, that may be a or-pattern (e.g. `Foo | Bar` in `Some(Foo | Bar)`). - /// Corresponds to `pat<allow_top_alt>` in RFC 2535. - fn parse_pat_with_or( - &mut self, - expected: Expected, - gate_or: GateOr, - rc: RecoverComma, - ) -> PResult<'a, P<Pat>> { - // Parse the first pattern (`p_0`). - let first_pat = self.parse_pat(expected)?; - self.maybe_recover_unexpected_comma(first_pat.span, rc)?; - - // If the next token is not a `|`, - // this is not an or-pattern and we should exit here. - if !self.check(&token::BinOp(token::Or)) && self.token != token::OrOr { - return Ok(first_pat) - } - - // Parse the patterns `p_1 | ... | p_n` where `n > 0`. - let lo = first_pat.span; - let mut pats = vec![first_pat]; - while self.eat_or_separator(Some(lo)) { - let pat = self.parse_pat(expected).map_err(|mut err| { - err.span_label(lo, WHILE_PARSING_OR_MSG); - err - })?; - self.maybe_recover_unexpected_comma(pat.span, rc)?; - pats.push(pat); - } - let or_pattern_span = lo.to(self.prev_span); - - // Feature gate the or-pattern if instructed: - if gate_or == GateOr::Yes { - self.sess.gated_spans.gate(sym::or_patterns, or_pattern_span); - } - - Ok(self.mk_pat(or_pattern_span, PatKind::Or(pats))) - } - - /// Eat the or-pattern `|` separator. - /// If instead a `||` token is encountered, recover and pretend we parsed `|`. - fn eat_or_separator(&mut self, lo: Option<Span>) -> bool { - if self.recover_trailing_vert(lo) { - return false; - } - - match self.token.kind { - token::OrOr => { - // Found `||`; Recover and pretend we parsed `|`. - self.ban_unexpected_or_or(lo); - self.bump(); - true - } - _ => self.eat(&token::BinOp(token::Or)), - } - } - - /// Recover if `|` or `||` is the current token and we have one of the - /// tokens `=>`, `if`, `=`, `:`, `;`, `,`, `]`, `)`, or `}` ahead of us. - /// - /// These tokens all indicate that we reached the end of the or-pattern - /// list and can now reliably say that the `|` was an illegal trailing vert. - /// Note that there are more tokens such as `@` for which we know that the `|` - /// is an illegal parse. However, the user's intent is less clear in that case. - fn recover_trailing_vert(&mut self, lo: Option<Span>) -> bool { - let is_end_ahead = self.look_ahead(1, |token| match &token.kind { - token::FatArrow // e.g. `a | => 0,`. - | token::Ident(kw::If, false) // e.g. `a | if expr`. - | token::Eq // e.g. `let a | = 0`. - | token::Semi // e.g. `let a |;`. - | token::Colon // e.g. `let a | :`. - | token::Comma // e.g. `let (a |,)`. - | token::CloseDelim(token::Bracket) // e.g. `let [a | ]`. - | token::CloseDelim(token::Paren) // e.g. `let (a | )`. - | token::CloseDelim(token::Brace) => true, // e.g. `let A { f: a | }`. - _ => false, - }); - match (is_end_ahead, &self.token.kind) { - (true, token::BinOp(token::Or)) | (true, token::OrOr) => { - self.ban_illegal_vert(lo, "trailing", "not allowed in an or-pattern"); - self.bump(); - true - } - _ => false, - } - } - - /// We have parsed `||` instead of `|`. Error and suggest `|` instead. - fn ban_unexpected_or_or(&mut self, lo: Option<Span>) { - let mut err = self.struct_span_err(self.token.span, "unexpected token `||` after pattern"); - err.span_suggestion( - self.token.span, - "use a single `|` to separate multiple alternative patterns", - "|".to_owned(), - Applicability::MachineApplicable - ); - if let Some(lo) = lo { - err.span_label(lo, WHILE_PARSING_OR_MSG); - } - err.emit(); - } - - /// Some special error handling for the "top-level" patterns in a match arm, - /// `for` loop, `let`, &c. (in contrast to subpatterns within such). - fn maybe_recover_unexpected_comma(&mut self, lo: Span, rc: RecoverComma) -> PResult<'a, ()> { - if rc == RecoverComma::No || self.token != token::Comma { - return Ok(()); - } - - // An unexpected comma after a top-level pattern is a clue that the - // user (perhaps more accustomed to some other language) forgot the - // parentheses in what should have been a tuple pattern; return a - // suggestion-enhanced error here rather than choking on the comma later. - let comma_span = self.token.span; - self.bump(); - if let Err(mut err) = self.skip_pat_list() { - // We didn't expect this to work anyway; we just wanted to advance to the - // end of the comma-sequence so we know the span to suggest parenthesizing. - err.cancel(); - } - let seq_span = lo.to(self.prev_span); - let mut err = self.struct_span_err(comma_span, "unexpected `,` in pattern"); - if let Ok(seq_snippet) = self.span_to_snippet(seq_span) { - err.span_suggestion( - seq_span, - "try adding parentheses to match on a tuple..", - format!("({})", seq_snippet), - Applicability::MachineApplicable - ) - .span_suggestion( - seq_span, - "..or a vertical bar to match on multiple alternatives", - format!("{}", seq_snippet.replace(",", " |")), - Applicability::MachineApplicable - ); - } - Err(err) - } - - /// Parse and throw away a parentesized comma separated - /// sequence of patterns until `)` is reached. - fn skip_pat_list(&mut self) -> PResult<'a, ()> { - while !self.check(&token::CloseDelim(token::Paren)) { - self.parse_pat(None)?; - if !self.eat(&token::Comma) { - return Ok(()) - } - } - Ok(()) - } - - /// Recursive possibly-or-pattern parser with recovery for an erroneous leading `|`. - /// See `parse_pat_with_or` for details on parsing or-patterns. - fn parse_pat_with_or_inner(&mut self) -> PResult<'a, P<Pat>> { - self.recover_leading_vert(None, "only allowed in a top-level pattern"); - self.parse_pat_with_or(None, GateOr::Yes, RecoverComma::No) - } - - /// Recover if `|` or `||` is here. - /// The user is thinking that a leading `|` is allowed in this position. - fn recover_leading_vert(&mut self, lo: Option<Span>, ctx: &str) { - if let token::BinOp(token::Or) | token::OrOr = self.token.kind { - self.ban_illegal_vert(lo, "leading", ctx); - self.bump(); - } - } - - /// A `|` or possibly `||` token shouldn't be here. Ban it. - fn ban_illegal_vert(&mut self, lo: Option<Span>, pos: &str, ctx: &str) { - let span = self.token.span; - let mut err = self.struct_span_err(span, &format!("a {} `|` is {}", pos, ctx)); - err.span_suggestion( - span, - &format!("remove the `{}`", pprust::token_to_string(&self.token)), - String::new(), - Applicability::MachineApplicable, - ); - if let Some(lo) = lo { - err.span_label(lo, WHILE_PARSING_OR_MSG); - } - if let token::OrOr = self.token.kind { - err.note("alternatives in or-patterns are separated with `|`, not `||`"); - } - err.emit(); - } - - /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are - /// allowed). - fn parse_pat_with_range_pat( - &mut self, - allow_range_pat: bool, - expected: Expected, - ) -> PResult<'a, P<Pat>> { - maybe_recover_from_interpolated_ty_qpath!(self, true); - maybe_whole!(self, NtPat, |x| x); - - let lo = self.token.span; - let pat = match self.token.kind { - token::BinOp(token::And) | token::AndAnd => self.parse_pat_deref(expected)?, - token::OpenDelim(token::Paren) => self.parse_pat_tuple_or_parens()?, - token::OpenDelim(token::Bracket) => { - // Parse `[pat, pat,...]` as a slice pattern. - let (pats, _) = self.parse_delim_comma_seq( - token::Bracket, - |p| p.parse_pat_with_or_inner(), - )?; - PatKind::Slice(pats) - } - token::DotDot => { - self.bump(); - if self.is_pat_range_end_start() { - // Parse `..42` for recovery. - self.parse_pat_range_to(RangeEnd::Excluded, "..")? - } else { - // A rest pattern `..`. - PatKind::Rest - } - } - token::DotDotEq => { - // Parse `..=42` for recovery. - self.bump(); - self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotEq), "..=")? - } - token::DotDotDot => { - // Parse `...42` for recovery. - self.bump(); - self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotDot), "...")? - } - // At this point, token != `&`, `&&`, `(`, `[`, `..`, `..=`, or `...`. - _ => if self.eat_keyword(kw::Underscore) { - // Parse _ - PatKind::Wild - } else if self.eat_keyword(kw::Mut) { - self.parse_pat_ident_mut()? - } else if self.eat_keyword(kw::Ref) { - // Parse ref ident @ pat / ref mut ident @ pat - let mutbl = self.parse_mutability(); - self.parse_pat_ident(BindingMode::ByRef(mutbl))? - } else if self.eat_keyword(kw::Box) { - // Parse `box pat` - let pat = self.parse_pat_with_range_pat(false, None)?; - self.sess.gated_spans.gate(sym::box_patterns, lo.to(self.prev_span)); - PatKind::Box(pat) - } else if self.can_be_ident_pat() { - // Parse `ident @ pat` - // This can give false positives and parse nullary enums, - // they are dealt with later in resolve. - self.parse_pat_ident(BindingMode::ByValue(Mutability::Immutable))? - } else if self.is_start_of_pat_with_path() { - // Parse pattern starting with a path - let (qself, path) = if self.eat_lt() { - // Parse a qualified path - let (qself, path) = self.parse_qpath(PathStyle::Expr)?; - (Some(qself), path) - } else { - // Parse an unqualified path - (None, self.parse_path(PathStyle::Expr)?) - }; - match self.token.kind { - token::Not if qself.is_none() => self.parse_pat_mac_invoc(lo, path)?, - token::DotDotDot | token::DotDotEq | token::DotDot => { - self.parse_pat_range_starting_with_path(lo, qself, path)? - } - token::OpenDelim(token::Brace) => self.parse_pat_struct(qself, path)?, - token::OpenDelim(token::Paren) => self.parse_pat_tuple_struct(qself, path)?, - _ => PatKind::Path(qself, path), - } - } else { - // Try to parse everything else as literal with optional minus - match self.parse_literal_maybe_minus() { - Ok(begin) - if self.check(&token::DotDot) - || self.check(&token::DotDotEq) - || self.check(&token::DotDotDot) => - { - self.parse_pat_range_starting_with_lit(begin)? - } - Ok(begin) => PatKind::Lit(begin), - Err(err) => return self.fatal_unexpected_non_pat(err, expected), - } - } - }; - - let pat = self.mk_pat(lo.to(self.prev_span), pat); - let pat = self.maybe_recover_from_bad_qpath(pat, true)?; - let pat = self.recover_intersection_pat(pat)?; - - if !allow_range_pat { - self.ban_pat_range_if_ambiguous(&pat)? - } - - Ok(pat) - } - - /// Try to recover the more general form `intersect ::= $pat_lhs @ $pat_rhs`. - /// - /// Allowed binding patterns generated by `binding ::= ref? mut? $ident @ $pat_rhs` - /// should already have been parsed by now at this point, - /// if the next token is `@` then we can try to parse the more general form. - /// - /// Consult `parse_pat_ident` for the `binding` grammar. - /// - /// The notion of intersection patterns are found in - /// e.g. [F#][and] where they are called AND-patterns. - /// - /// [and]: https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching - fn recover_intersection_pat(&mut self, lhs: P<Pat>) -> PResult<'a, P<Pat>> { - if self.token.kind != token::At { - // Next token is not `@` so it's not going to be an intersection pattern. - return Ok(lhs); - } - - // At this point we attempt to parse `@ $pat_rhs` and emit an error. - self.bump(); // `@` - let mut rhs = self.parse_pat(None)?; - let sp = lhs.span.to(rhs.span); - - if let PatKind::Ident(_, _, ref mut sub @ None) = rhs.kind { - // The user inverted the order, so help them fix that. - let mut applicability = Applicability::MachineApplicable; - lhs.walk(&mut |p| match p.kind { - // `check_match` is unhappy if the subpattern has a binding anywhere. - PatKind::Ident(..) => { - applicability = Applicability::MaybeIncorrect; - false // Short-circuit. - }, - _ => true, - }); - - let lhs_span = lhs.span; - // Move the LHS into the RHS as a subpattern. - // The RHS is now the full pattern. - *sub = Some(lhs); - - self.struct_span_err(sp, "pattern on wrong side of `@`") - .span_label(lhs_span, "pattern on the left, should be on the right") - .span_label(rhs.span, "binding on the right, should be on the left") - .span_suggestion(sp, "switch the order", pprust::pat_to_string(&rhs), applicability) - .emit(); - } else { - // The special case above doesn't apply so we may have e.g. `A(x) @ B(y)`. - rhs.kind = PatKind::Wild; - self.struct_span_err(sp, "left-hand side of `@` must be a binding") - .span_label(lhs.span, "interpreted as a pattern, not a binding") - .span_label(rhs.span, "also a pattern") - .note("bindings are `x`, `mut x`, `ref x`, and `ref mut x`") - .emit(); - } - - rhs.span = sp; - Ok(rhs) - } - - /// Ban a range pattern if it has an ambiguous interpretation. - fn ban_pat_range_if_ambiguous(&self, pat: &Pat) -> PResult<'a, ()> { - match pat.kind { - PatKind::Range( - .., Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. } - ) => return Ok(()), - PatKind::Range(..) => {} - _ => return Ok(()), - } - - let mut err = self.struct_span_err( - pat.span, - "the range pattern here has ambiguous interpretation", - ); - err.span_suggestion( - pat.span, - "add parentheses to clarify the precedence", - format!("({})", pprust::pat_to_string(&pat)), - // "ambiguous interpretation" implies that we have to be guessing - Applicability::MaybeIncorrect - ); - Err(err) - } - - /// Parse `&pat` / `&mut pat`. - fn parse_pat_deref(&mut self, expected: Expected) -> PResult<'a, PatKind> { - self.expect_and()?; - let mutbl = self.parse_mutability(); - - if let token::Lifetime(name) = self.token.kind { - let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern", name)); - err.span_label(self.token.span, "unexpected lifetime"); - return Err(err); - } - - let subpat = self.parse_pat_with_range_pat(false, expected)?; - Ok(PatKind::Ref(subpat, mutbl)) - } - - /// Parse a tuple or parenthesis pattern. - fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> { - let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?; - - // Here, `(pat,)` is a tuple pattern. - // For backward compatibility, `(..)` is a tuple pattern as well. - Ok(if fields.len() == 1 && !(trailing_comma || fields[0].is_rest()) { - PatKind::Paren(fields.into_iter().nth(0).unwrap()) - } else { - PatKind::Tuple(fields) - }) - } - - /// Parse a mutable binding with the `mut` token already eaten. - fn parse_pat_ident_mut(&mut self) -> PResult<'a, PatKind> { - let mut_span = self.prev_span; - - if self.eat_keyword(kw::Ref) { - return self.recover_mut_ref_ident(mut_span) - } - - self.recover_additional_muts(); - - // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`. - if let token::Interpolated(ref nt) = self.token.kind { - if let token::NtPat(_) = **nt { - self.expected_ident_found().emit(); - } - } - - // Parse the pattern we hope to be an identifier. - let mut pat = self.parse_pat(Some("identifier"))?; - - // Add `mut` to any binding in the parsed pattern. - let changed_any_binding = Self::make_all_value_bindings_mutable(&mut pat); - - // Unwrap; If we don't have `mut $ident`, error. - let pat = pat.into_inner(); - match &pat.kind { - PatKind::Ident(..) => {} - _ => self.ban_mut_general_pat(mut_span, &pat, changed_any_binding), - } - - Ok(pat.kind) - } - - /// Recover on `mut ref? ident @ pat` and suggest - /// that the order of `mut` and `ref` is incorrect. - fn recover_mut_ref_ident(&mut self, lo: Span) -> PResult<'a, PatKind> { - let mutref_span = lo.to(self.prev_span); - self.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect") - .span_suggestion( - mutref_span, - "try switching the order", - "ref mut".into(), - Applicability::MachineApplicable - ) - .emit(); - - self.parse_pat_ident(BindingMode::ByRef(Mutability::Mutable)) - } - - /// Turn all by-value immutable bindings in a pattern into mutable bindings. - /// Returns `true` if any change was made. - fn make_all_value_bindings_mutable(pat: &mut P<Pat>) -> bool { - struct AddMut(bool); - impl MutVisitor for AddMut { - fn visit_mac(&mut self, mac: &mut Mac) { - noop_visit_mac(mac, self); - } - - fn visit_pat(&mut self, pat: &mut P<Pat>) { - if let PatKind::Ident(BindingMode::ByValue(ref mut m @ Mutability::Immutable), ..) - = pat.kind - { - *m = Mutability::Mutable; - self.0 = true; - } - noop_visit_pat(pat, self); - } - } - - let mut add_mut = AddMut(false); - add_mut.visit_pat(pat); - add_mut.0 - } - - /// Error on `mut $pat` where `$pat` is not an ident. - fn ban_mut_general_pat(&self, lo: Span, pat: &Pat, changed_any_binding: bool) { - let span = lo.to(pat.span); - let fix = pprust::pat_to_string(&pat); - let (problem, suggestion) = if changed_any_binding { - ("`mut` must be attached to each individual binding", "add `mut` to each binding") - } else { - ("`mut` must be followed by a named binding", "remove the `mut` prefix") - }; - self.struct_span_err(span, problem) - .span_suggestion(span, suggestion, fix, Applicability::MachineApplicable) - .note("`mut` may be followed by `variable` and `variable @ pattern`") - .emit() - } - - /// Eat any extraneous `mut`s and error + recover if we ate any. - fn recover_additional_muts(&mut self) { - let lo = self.token.span; - while self.eat_keyword(kw::Mut) {} - if lo == self.token.span { - return; - } - - let span = lo.to(self.prev_span); - self.struct_span_err(span, "`mut` on a binding may not be repeated") - .span_suggestion( - span, - "remove the additional `mut`s", - String::new(), - Applicability::MachineApplicable, - ) - .emit(); - } - - /// Parse macro invocation - fn parse_pat_mac_invoc(&mut self, lo: Span, path: Path) -> PResult<'a, PatKind> { - self.bump(); - let (delim, tts) = self.expect_delimited_token_tree()?; - let mac = Mac { - path, - tts, - delim, - span: lo.to(self.prev_span), - prior_type_ascription: self.last_type_ascription, - }; - Ok(PatKind::Mac(mac)) - } - - fn excluded_range_end(&self, span: Span) -> RangeEnd { - self.sess.gated_spans.gate(sym::exclusive_range_pattern, span); - RangeEnd::Excluded - } - - /// Parse a range pattern `$path $form $end?` where `$form = ".." | "..." | "..=" ;`. - /// The `$path` has already been parsed and the next token is the `$form`. - fn parse_pat_range_starting_with_path( - &mut self, - lo: Span, - qself: Option<QSelf>, - path: Path - ) -> PResult<'a, PatKind> { - let (end_kind, form) = match self.token.kind { - token::DotDot => (self.excluded_range_end(self.token.span), ".."), - token::DotDotDot => (RangeEnd::Included(RangeSyntax::DotDotDot), "..."), - token::DotDotEq => (RangeEnd::Included(RangeSyntax::DotDotEq), "..="), - _ => panic!("can only parse `..`/`...`/`..=` for ranges (checked above)"), - }; - let op_span = self.token.span; - // Parse range - let span = lo.to(self.prev_span); - let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new()); - self.bump(); - let end = self.parse_pat_range_end_opt(&begin, form)?; - Ok(PatKind::Range(begin, end, respan(op_span, end_kind))) - } - - /// Parse a range pattern `$literal $form $end?` where `$form = ".." | "..." | "..=" ;`. - /// The `$path` has already been parsed and the next token is the `$form`. - fn parse_pat_range_starting_with_lit(&mut self, begin: P<Expr>) -> PResult<'a, PatKind> { - let op_span = self.token.span; - let (end_kind, form) = if self.eat(&token::DotDotDot) { - (RangeEnd::Included(RangeSyntax::DotDotDot), "...") - } else if self.eat(&token::DotDotEq) { - (RangeEnd::Included(RangeSyntax::DotDotEq), "..=") - } else if self.eat(&token::DotDot) { - (self.excluded_range_end(op_span), "..") - } else { - panic!("impossible case: we already matched on a range-operator token") - }; - let end = self.parse_pat_range_end_opt(&begin, form)?; - Ok(PatKind::Range(begin, end, respan(op_span, end_kind))) - } - - fn fatal_unexpected_non_pat( - &mut self, - mut err: DiagnosticBuilder<'a>, - expected: Expected, - ) -> PResult<'a, P<Pat>> { - err.cancel(); - - let expected = expected.unwrap_or("pattern"); - let msg = format!("expected {}, found {}", expected, self.this_token_descr()); - - let mut err = self.fatal(&msg); - err.span_label(self.token.span, format!("expected {}", expected)); - - let sp = self.sess.source_map().start_point(self.token.span); - if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) { - self.sess.expr_parentheses_needed(&mut err, *sp, None); - } - - Err(err) - } - - /// Is the current token suitable as the start of a range patterns end? - fn is_pat_range_end_start(&self) -> bool { - self.token.is_path_start() // e.g. `MY_CONST`; - || self.token == token::Dot // e.g. `.5` for recovery; - || self.token.can_begin_literal_or_bool() // e.g. `42`. - || self.token.is_whole_expr() - } - - /// Parse a range-to pattern, e.g. `..X` and `..=X` for recovery. - fn parse_pat_range_to(&mut self, re: RangeEnd, form: &str) -> PResult<'a, PatKind> { - let lo = self.prev_span; - let end = self.parse_pat_range_end()?; - let range_span = lo.to(end.span); - let begin = self.mk_expr(range_span, ExprKind::Err, ThinVec::new()); - - self.diagnostic() - .struct_span_err(range_span, &format!("`{}X` range patterns are not supported", form)) - .span_suggestion( - range_span, - "try using the minimum value for the type", - format!("MIN{}{}", form, pprust::expr_to_string(&end)), - Applicability::HasPlaceholders, - ) - .emit(); - - Ok(PatKind::Range(begin, end, respan(lo, re))) - } - - /// Parse the end of a `X..Y`, `X..=Y`, or `X...Y` range pattern or recover - /// if that end is missing treating it as `X..`, `X..=`, or `X...` respectively. - fn parse_pat_range_end_opt(&mut self, begin: &Expr, form: &str) -> PResult<'a, P<Expr>> { - if self.is_pat_range_end_start() { - // Parsing e.g. `X..=Y`. - self.parse_pat_range_end() - } else { - // Parsing e.g. `X..`. - let range_span = begin.span.to(self.prev_span); - - self.diagnostic() - .struct_span_err( - range_span, - &format!("`X{}` range patterns are not supported", form), - ) - .span_suggestion( - range_span, - "try using the maximum value for the type", - format!("{}{}MAX", pprust::expr_to_string(&begin), form), - Applicability::HasPlaceholders, - ) - .emit(); - - Ok(self.mk_expr(range_span, ExprKind::Err, ThinVec::new())) - } - } - - fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> { - if self.token.is_path_start() { - let lo = self.token.span; - let (qself, path) = if self.eat_lt() { - // Parse a qualified path - let (qself, path) = self.parse_qpath(PathStyle::Expr)?; - (Some(qself), path) - } else { - // Parse an unqualified path - (None, self.parse_path(PathStyle::Expr)?) - }; - let hi = self.prev_span; - Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new())) - } else { - self.parse_literal_maybe_minus() - } - } - - /// Is this the start of a pattern beginning with a path? - fn is_start_of_pat_with_path(&mut self) -> bool { - self.check_path() - // Just for recovery (see `can_be_ident`). - || self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In) - } - - /// Would `parse_pat_ident` be appropriate here? - fn can_be_ident_pat(&mut self) -> bool { - self.check_ident() - && !self.token.is_bool_lit() // Avoid `true` or `false` as a binding as it is a literal. - && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path. - // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`. - && !self.token.is_keyword(kw::In) - && self.look_ahead(1, |t| match t.kind { // Try to do something more complex? - token::OpenDelim(token::Paren) // A tuple struct pattern. - | token::OpenDelim(token::Brace) // A struct pattern. - | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern. - | token::ModSep // A tuple / struct variant pattern. - | token::Not => false, // A macro expanding to a pattern. - _ => true, - }) - } - - /// Parses `ident` or `ident @ pat`. - /// Used by the copy foo and ref foo patterns to give a good - /// error message when parsing mistakes like `ref foo(a, b)`. - fn parse_pat_ident(&mut self, binding_mode: BindingMode) -> PResult<'a, PatKind> { - let ident = self.parse_ident()?; - let sub = if self.eat(&token::At) { - Some(self.parse_pat(Some("binding pattern"))?) - } else { - None - }; - - // Just to be friendly, if they write something like `ref Some(i)`, - // we end up here with `(` as the current token. - // This shortly leads to a parse error. Note that if there is no explicit - // binding mode then we do not end up here, because the lookahead - // will direct us over to `parse_enum_variant()`. - if self.token == token::OpenDelim(token::Paren) { - return Err(self.span_fatal( - self.prev_span, - "expected identifier, found enum pattern", - )) - } - - Ok(PatKind::Ident(binding_mode, ident, sub)) - } - - /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`). - fn parse_pat_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> { - if qself.is_some() { - let msg = "unexpected `{` after qualified path"; - let mut err = self.fatal(msg); - err.span_label(self.token.span, msg); - return Err(err); - } - - self.bump(); - let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| { - e.emit(); - self.recover_stmt(); - (vec![], true) - }); - self.bump(); - Ok(PatKind::Struct(path, fields, etc)) - } - - /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`). - fn parse_pat_tuple_struct(&mut self, qself: Option<QSelf>, path: Path) -> PResult<'a, PatKind> { - if qself.is_some() { - let msg = "unexpected `(` after qualified path"; - let mut err = self.fatal(msg); - err.span_label(self.token.span, msg); - return Err(err); - } - let (fields, _) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?; - Ok(PatKind::TupleStruct(path, fields)) - } - - /// Parses the fields of a struct-like pattern. - fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<FieldPat>, bool)> { - let mut fields = Vec::new(); - let mut etc = false; - let mut ate_comma = true; - let mut delayed_err: Option<DiagnosticBuilder<'a>> = None; - let mut etc_span = None; - - while self.token != token::CloseDelim(token::Brace) { - let attrs = match self.parse_outer_attributes() { - Ok(attrs) => attrs, - Err(err) => { - if let Some(mut delayed) = delayed_err { - delayed.emit(); - } - return Err(err); - }, - }; - let lo = self.token.span; - - // check that a comma comes after every field - if !ate_comma { - let err = self.struct_span_err(self.prev_span, "expected `,`"); - if let Some(mut delayed) = delayed_err { - delayed.emit(); - } - return Err(err); - } - ate_comma = false; - - if self.check(&token::DotDot) || self.token == token::DotDotDot { - etc = true; - let mut etc_sp = self.token.span; - - self.recover_one_fewer_dotdot(); - self.bump(); // `..` || `...` - - if self.token == token::CloseDelim(token::Brace) { - etc_span = Some(etc_sp); - break; - } - let token_str = self.this_token_descr(); - let mut err = self.fatal(&format!("expected `}}`, found {}", token_str)); - - err.span_label(self.token.span, "expected `}`"); - let mut comma_sp = None; - if self.token == token::Comma { // Issue #49257 - let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span); - etc_sp = etc_sp.to(nw_span); - err.span_label(etc_sp, - "`..` must be at the end and cannot have a trailing comma"); - comma_sp = Some(self.token.span); - self.bump(); - ate_comma = true; - } - - etc_span = Some(etc_sp.until(self.token.span)); - if self.token == token::CloseDelim(token::Brace) { - // If the struct looks otherwise well formed, recover and continue. - if let Some(sp) = comma_sp { - err.span_suggestion_short( - sp, - "remove this comma", - String::new(), - Applicability::MachineApplicable, - ); - } - err.emit(); - break; - } else if self.token.is_ident() && ate_comma { - // Accept fields coming after `..,`. - // This way we avoid "pattern missing fields" errors afterwards. - // We delay this error until the end in order to have a span for a - // suggested fix. - if let Some(mut delayed_err) = delayed_err { - delayed_err.emit(); - return Err(err); - } else { - delayed_err = Some(err); - } - } else { - if let Some(mut err) = delayed_err { - err.emit(); - } - return Err(err); - } - } - - fields.push(match self.parse_pat_field(lo, attrs) { - Ok(field) => field, - Err(err) => { - if let Some(mut delayed_err) = delayed_err { - delayed_err.emit(); - } - return Err(err); - } - }); - ate_comma = self.eat(&token::Comma); - } - - if let Some(mut err) = delayed_err { - if let Some(etc_span) = etc_span { - err.multipart_suggestion( - "move the `..` to the end of the field list", - vec![ - (etc_span, String::new()), - (self.token.span, format!("{}.. }}", if ate_comma { "" } else { ", " })), - ], - Applicability::MachineApplicable, - ); - } - err.emit(); - } - return Ok((fields, etc)); - } - - /// Recover on `...` as if it were `..` to avoid further errors. - /// See issue #46718. - fn recover_one_fewer_dotdot(&self) { - if self.token != token::DotDotDot { - return; - } - - self.struct_span_err(self.token.span, "expected field pattern, found `...`") - .span_suggestion( - self.token.span, - "to omit remaining fields, use one fewer `.`", - "..".to_owned(), - Applicability::MachineApplicable - ) - .emit(); - } - - fn parse_pat_field(&mut self, lo: Span, attrs: Vec<Attribute>) -> PResult<'a, FieldPat> { - // Check if a colon exists one ahead. This means we're parsing a fieldname. - let hi; - let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) { - // Parsing a pattern of the form `fieldname: pat`. - let fieldname = self.parse_field_name()?; - self.bump(); - let pat = self.parse_pat_with_or_inner()?; - hi = pat.span; - (pat, fieldname, false) - } else { - // Parsing a pattern of the form `(box) (ref) (mut) fieldname`. - let is_box = self.eat_keyword(kw::Box); - let boxed_span = self.token.span; - let is_ref = self.eat_keyword(kw::Ref); - let is_mut = self.eat_keyword(kw::Mut); - let fieldname = self.parse_ident()?; - hi = self.prev_span; - - let bind_type = match (is_ref, is_mut) { - (true, true) => BindingMode::ByRef(Mutability::Mutable), - (true, false) => BindingMode::ByRef(Mutability::Immutable), - (false, true) => BindingMode::ByValue(Mutability::Mutable), - (false, false) => BindingMode::ByValue(Mutability::Immutable), - }; - - let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname); - let subpat = if is_box { - self.mk_pat(lo.to(hi), PatKind::Box(fieldpat)) - } else { - fieldpat - }; - (subpat, fieldname, true) - }; - - Ok(FieldPat { - ident: fieldname, - pat: subpat, - is_shorthand, - attrs: attrs.into(), - id: ast::DUMMY_NODE_ID, - span: lo.to(hi), - is_placeholder: false, - }) - } - - pub(super) fn mk_pat_ident(&self, span: Span, bm: BindingMode, ident: Ident) -> P<Pat> { - self.mk_pat(span, PatKind::Ident(bm, ident, None)) - } - - fn mk_pat(&self, span: Span, kind: PatKind) -> P<Pat> { - P(Pat { kind, span, id: ast::DUMMY_NODE_ID }) - } -} diff --git a/src/libsyntax/parse/parser/path.rs b/src/libsyntax/parse/parser/path.rs deleted file mode 100644 index 9ceb3ba1eb4..00000000000 --- a/src/libsyntax/parse/parser/path.rs +++ /dev/null @@ -1,497 +0,0 @@ -use super::{Parser, TokenType}; - -use crate::{maybe_whole, ThinVec}; -use crate::ast::{self, QSelf, Path, PathSegment, Ident, ParenthesizedArgs, AngleBracketedArgs}; -use crate::ast::{AnonConst, GenericArg, AssocTyConstraint, AssocTyConstraintKind, BlockCheckMode}; -use crate::token::{self, Token}; -use crate::source_map::{Span, BytePos}; -use syntax_pos::symbol::{kw, sym}; - -use std::mem; -use log::debug; -use errors::{PResult, Applicability, pluralize}; - -/// Specifies how to parse a path. -#[derive(Copy, Clone, PartialEq)] -pub enum PathStyle { - /// In some contexts, notably in expressions, paths with generic arguments are ambiguous - /// with something else. For example, in expressions `segment < ....` can be interpreted - /// as a comparison and `segment ( ....` can be interpreted as a function call. - /// In all such contexts the non-path interpretation is preferred by default for practical - /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g. - /// `x<y>` - comparisons, `x::<y>` - unambiguously a path. - Expr, - /// In other contexts, notably in types, no ambiguity exists and paths can be written - /// without the disambiguator, e.g., `x<y>` - unambiguously a path. - /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too. - Type, - /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports, - /// visibilities or attributes. - /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead - /// (paths in "mod" contexts have to be checked later for absence of generic arguments - /// anyway, due to macros), but it is used to avoid weird suggestions about expected - /// tokens when something goes wrong. - Mod, -} - -impl<'a> Parser<'a> { - /// Parses a qualified path. - /// Assumes that the leading `<` has been parsed already. - /// - /// `qualified_path = <type [as trait_ref]>::path` - /// - /// # Examples - /// `<T>::default` - /// `<T as U>::a` - /// `<T as U>::F::a<S>` (without disambiguator) - /// `<T as U>::F::a::<S>` (with disambiguator) - pub(super) fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, Path)> { - let lo = self.prev_span; - let ty = self.parse_ty()?; - - // `path` will contain the prefix of the path up to the `>`, - // if any (e.g., `U` in the `<T as U>::*` examples - // above). `path_span` has the span of that path, or an empty - // span in the case of something like `<T>::Bar`. - let (mut path, path_span); - if self.eat_keyword(kw::As) { - let path_lo = self.token.span; - path = self.parse_path(PathStyle::Type)?; - path_span = path_lo.to(self.prev_span); - } else { - path_span = self.token.span.to(self.token.span); - path = ast::Path { segments: Vec::new(), span: path_span }; - } - - // See doc comment for `unmatched_angle_bracket_count`. - self.expect(&token::Gt)?; - if self.unmatched_angle_bracket_count > 0 { - self.unmatched_angle_bracket_count -= 1; - debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count); - } - - self.expect(&token::ModSep)?; - - let qself = QSelf { ty, path_span, position: path.segments.len() }; - self.parse_path_segments(&mut path.segments, style)?; - - Ok((qself, Path { segments: path.segments, span: lo.to(self.prev_span) })) - } - - /// Parses simple paths. - /// - /// `path = [::] segment+` - /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]` - /// - /// # Examples - /// `a::b::C<D>` (without disambiguator) - /// `a::b::C::<D>` (with disambiguator) - /// `Fn(Args)` (without disambiguator) - /// `Fn::(Args)` (with disambiguator) - pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, Path> { - maybe_whole!(self, NtPath, |path| { - if style == PathStyle::Mod && - path.segments.iter().any(|segment| segment.args.is_some()) { - self.diagnostic().span_err(path.span, "unexpected generic arguments in path"); - } - path - }); - - let lo = self.meta_var_span.unwrap_or(self.token.span); - let mut segments = Vec::new(); - let mod_sep_ctxt = self.token.span.ctxt(); - if self.eat(&token::ModSep) { - segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))); - } - self.parse_path_segments(&mut segments, style)?; - - Ok(Path { segments, span: lo.to(self.prev_span) }) - } - - /// Like `parse_path`, but also supports parsing `Word` meta items into paths for - /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]` - /// attributes. - fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, Path> { - let meta_ident = match self.token.kind { - token::Interpolated(ref nt) => match **nt { - token::NtMeta(ref item) => match item.tokens.is_empty() { - true => Some(item.path.clone()), - false => None, - }, - _ => None, - }, - _ => None, - }; - if let Some(path) = meta_ident { - self.bump(); - return Ok(path); - } - self.parse_path(style) - } - - /// Parse a list of paths inside `#[derive(path_0, ..., path_n)]`. - pub fn parse_derive_paths(&mut self) -> PResult<'a, Vec<Path>> { - self.expect(&token::OpenDelim(token::Paren))?; - let mut list = Vec::new(); - while !self.eat(&token::CloseDelim(token::Paren)) { - let path = self.parse_path_allowing_meta(PathStyle::Mod)?; - list.push(path); - if !self.eat(&token::Comma) { - self.expect(&token::CloseDelim(token::Paren))?; - break - } - } - Ok(list) - } - - pub(super) fn parse_path_segments( - &mut self, - segments: &mut Vec<PathSegment>, - style: PathStyle, - ) -> PResult<'a, ()> { - loop { - let segment = self.parse_path_segment(style)?; - if style == PathStyle::Expr { - // In order to check for trailing angle brackets, we must have finished - // recursing (`parse_path_segment` can indirectly call this function), - // that is, the next token must be the highlighted part of the below example: - // - // `Foo::<Bar as Baz<T>>::Qux` - // ^ here - // - // As opposed to the below highlight (if we had only finished the first - // recursion): - // - // `Foo::<Bar as Baz<T>>::Qux` - // ^ here - // - // `PathStyle::Expr` is only provided at the root invocation and never in - // `parse_path_segment` to recurse and therefore can be checked to maintain - // this invariant. - self.check_trailing_angle_brackets(&segment, token::ModSep); - } - segments.push(segment); - - if self.is_import_coupler() || !self.eat(&token::ModSep) { - return Ok(()); - } - } - } - - pub(super) fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> { - let ident = self.parse_path_segment_ident()?; - - let is_args_start = |token: &Token| match token.kind { - token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) - | token::LArrow => true, - _ => false, - }; - let check_args_start = |this: &mut Self| { - this.expected_tokens.extend_from_slice( - &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))] - ); - is_args_start(&this.token) - }; - - Ok(if style == PathStyle::Type && check_args_start(self) || - style != PathStyle::Mod && self.check(&token::ModSep) - && self.look_ahead(1, |t| is_args_start(t)) { - // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If - // it isn't, then we reset the unmatched angle bracket count as we're about to start - // parsing a new path. - if style == PathStyle::Expr { - self.unmatched_angle_bracket_count = 0; - self.max_angle_bracket_count = 0; - } - - // Generic arguments are found - `<`, `(`, `::<` or `::(`. - self.eat(&token::ModSep); - let lo = self.token.span; - let args = if self.eat_lt() { - // `<'a, T, A = U>` - let (args, constraints) = - self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?; - self.expect_gt()?; - let span = lo.to(self.prev_span); - AngleBracketedArgs { args, constraints, span }.into() - } else { - // `(T, U) -> R` - let (inputs, _) = self.parse_paren_comma_seq(|p| p.parse_ty())?; - let span = ident.span.to(self.prev_span); - let output = if self.eat(&token::RArrow) { - Some(self.parse_ty_common(false, false, false)?) - } else { - None - }; - ParenthesizedArgs { inputs, output, span }.into() - }; - - PathSegment { ident, args, id: ast::DUMMY_NODE_ID } - } else { - // Generic arguments are not found. - PathSegment::from_ident(ident) - }) - } - - pub(super) fn parse_path_segment_ident(&mut self) -> PResult<'a, Ident> { - match self.token.kind { - token::Ident(name, _) if name.is_path_segment_keyword() => { - let span = self.token.span; - self.bump(); - Ok(Ident::new(name, span)) - } - _ => self.parse_ident(), - } - } - - /// Parses generic args (within a path segment) with recovery for extra leading angle brackets. - /// For the purposes of understanding the parsing logic of generic arguments, this function - /// can be thought of being the same as just calling `self.parse_generic_args()` if the source - /// had the correct amount of leading angle brackets. - /// - /// ```ignore (diagnostics) - /// bar::<<<<T as Foo>::Output>(); - /// ^^ help: remove extra angle brackets - /// ``` - fn parse_generic_args_with_leaning_angle_bracket_recovery( - &mut self, - style: PathStyle, - lo: Span, - ) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> { - // We need to detect whether there are extra leading left angle brackets and produce an - // appropriate error and suggestion. This cannot be implemented by looking ahead at - // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens - // then there won't be matching `>` tokens to find. - // - // To explain how this detection works, consider the following example: - // - // ```ignore (diagnostics) - // bar::<<<<T as Foo>::Output>(); - // ^^ help: remove extra angle brackets - // ``` - // - // Parsing of the left angle brackets starts in this function. We start by parsing the - // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via - // `eat_lt`): - // - // *Upcoming tokens:* `<<<<T as Foo>::Output>;` - // *Unmatched count:* 1 - // *`parse_path_segment` calls deep:* 0 - // - // This has the effect of recursing as this function is called if a `<` character - // is found within the expected generic arguments: - // - // *Upcoming tokens:* `<<<T as Foo>::Output>;` - // *Unmatched count:* 2 - // *`parse_path_segment` calls deep:* 1 - // - // Eventually we will have recursed until having consumed all of the `<` tokens and - // this will be reflected in the count: - // - // *Upcoming tokens:* `T as Foo>::Output>;` - // *Unmatched count:* 4 - // `parse_path_segment` calls deep:* 3 - // - // The parser will continue until reaching the first `>` - this will decrement the - // unmatched angle bracket count and return to the parent invocation of this function - // having succeeded in parsing: - // - // *Upcoming tokens:* `::Output>;` - // *Unmatched count:* 3 - // *`parse_path_segment` calls deep:* 2 - // - // This will continue until the next `>` character which will also return successfully - // to the parent invocation of this function and decrement the count: - // - // *Upcoming tokens:* `;` - // *Unmatched count:* 2 - // *`parse_path_segment` calls deep:* 1 - // - // At this point, this function will expect to find another matching `>` character but - // won't be able to and will return an error. This will continue all the way up the - // call stack until the first invocation: - // - // *Upcoming tokens:* `;` - // *Unmatched count:* 2 - // *`parse_path_segment` calls deep:* 0 - // - // In doing this, we have managed to work out how many unmatched leading left angle - // brackets there are, but we cannot recover as the unmatched angle brackets have - // already been consumed. To remedy this, we keep a snapshot of the parser state - // before we do the above. We can then inspect whether we ended up with a parsing error - // and unmatched left angle brackets and if so, restore the parser state before we - // consumed any `<` characters to emit an error and consume the erroneous tokens to - // recover by attempting to parse again. - // - // In practice, the recursion of this function is indirect and there will be other - // locations that consume some `<` characters - as long as we update the count when - // this happens, it isn't an issue. - - let is_first_invocation = style == PathStyle::Expr; - // Take a snapshot before attempting to parse - we can restore this later. - let snapshot = if is_first_invocation { - Some(self.clone()) - } else { - None - }; - - debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)"); - match self.parse_generic_args() { - Ok(value) => Ok(value), - Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => { - // Cancel error from being unable to find `>`. We know the error - // must have been this due to a non-zero unmatched angle bracket - // count. - e.cancel(); - - // Swap `self` with our backup of the parser state before attempting to parse - // generic arguments. - let snapshot = mem::replace(self, snapshot.unwrap()); - - debug!( - "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \ - snapshot.count={:?}", - snapshot.unmatched_angle_bracket_count, - ); - - // Eat the unmatched angle brackets. - for _ in 0..snapshot.unmatched_angle_bracket_count { - self.eat_lt(); - } - - // Make a span over ${unmatched angle bracket count} characters. - let span = lo.with_hi( - lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count) - ); - self.diagnostic() - .struct_span_err( - span, - &format!( - "unmatched angle bracket{}", - pluralize!(snapshot.unmatched_angle_bracket_count) - ), - ) - .span_suggestion( - span, - &format!( - "remove extra angle bracket{}", - pluralize!(snapshot.unmatched_angle_bracket_count) - ), - String::new(), - Applicability::MachineApplicable, - ) - .emit(); - - // Try again without unmatched angle bracket characters. - self.parse_generic_args() - }, - Err(e) => Err(e), - } - } - - /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings, - /// possibly including trailing comma. - fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> { - let mut args = Vec::new(); - let mut constraints = Vec::new(); - let mut misplaced_assoc_ty_constraints: Vec<Span> = Vec::new(); - let mut assoc_ty_constraints: Vec<Span> = Vec::new(); - - let args_lo = self.token.span; - - loop { - if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) { - // Parse lifetime argument. - args.push(GenericArg::Lifetime(self.expect_lifetime())); - misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints); - } else if self.check_ident() - && self.look_ahead(1, |t| t == &token::Eq || t == &token::Colon) - { - // Parse associated type constraint. - let lo = self.token.span; - let ident = self.parse_ident()?; - let kind = if self.eat(&token::Eq) { - AssocTyConstraintKind::Equality { - ty: self.parse_ty()?, - } - } else if self.eat(&token::Colon) { - AssocTyConstraintKind::Bound { - bounds: self.parse_generic_bounds(Some(self.prev_span))?, - } - } else { - unreachable!(); - }; - - let span = lo.to(self.prev_span); - - // Gate associated type bounds, e.g., `Iterator<Item: Ord>`. - if let AssocTyConstraintKind::Bound { .. } = kind { - self.sess.gated_spans.gate(sym::associated_type_bounds, span); - } - - constraints.push(AssocTyConstraint { - id: ast::DUMMY_NODE_ID, - ident, - kind, - span, - }); - assoc_ty_constraints.push(span); - } else if self.check_const_arg() { - // Parse const argument. - let expr = if let token::OpenDelim(token::Brace) = self.token.kind { - self.parse_block_expr( - None, self.token.span, BlockCheckMode::Default, ThinVec::new() - )? - } else if self.token.is_ident() { - // FIXME(const_generics): to distinguish between idents for types and consts, - // we should introduce a GenericArg::Ident in the AST and distinguish when - // lowering to the HIR. For now, idents for const args are not permitted. - if self.token.is_bool_lit() { - self.parse_literal_maybe_minus()? - } else { - return Err( - self.fatal("identifiers may currently not be used for const generics") - ); - } - } else { - self.parse_literal_maybe_minus()? - }; - let value = AnonConst { - id: ast::DUMMY_NODE_ID, - value: expr, - }; - args.push(GenericArg::Const(value)); - misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints); - } else if self.check_type() { - // Parse type argument. - args.push(GenericArg::Type(self.parse_ty()?)); - misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints); - } else { - break - } - - if !self.eat(&token::Comma) { - break - } - } - - // FIXME: we would like to report this in ast_validation instead, but we currently do not - // preserve ordering of generic parameters with respect to associated type binding, so we - // lose that information after parsing. - if misplaced_assoc_ty_constraints.len() > 0 { - let mut err = self.struct_span_err( - args_lo.to(self.prev_span), - "associated type bindings must be declared after generic parameters", - ); - for span in misplaced_assoc_ty_constraints { - err.span_label( - span, - "this associated type binding should be moved after the generic parameters", - ); - } - err.emit(); - } - - Ok((args, constraints)) - } -} diff --git a/src/libsyntax/parse/parser/stmt.rs b/src/libsyntax/parse/parser/stmt.rs deleted file mode 100644 index 30e47b7a0b2..00000000000 --- a/src/libsyntax/parse/parser/stmt.rs +++ /dev/null @@ -1,480 +0,0 @@ -use super::{Parser, Restrictions, PrevTokenKind, SemiColonMode, BlockMode}; -use super::expr::LhsExpr; -use super::path::PathStyle; -use super::pat::GateOr; -use super::diagnostics::Error; - -use crate::ptr::P; -use crate::{maybe_whole, ThinVec}; -use crate::ast::{self, DUMMY_NODE_ID, Stmt, StmtKind, Local, Block, BlockCheckMode, Expr, ExprKind}; -use crate::ast::{Attribute, AttrStyle, VisibilityKind, MacStmtStyle, Mac, MacDelimiter}; -use crate::parse::DirectoryOwnership; -use crate::util::classify; -use crate::token; -use crate::source_map::{respan, Span}; -use crate::symbol::{kw, sym}; - -use std::mem; -use errors::{PResult, Applicability}; - -impl<'a> Parser<'a> { - /// Parses a statement. This stops just before trailing semicolons on everything but items. - /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed. - pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> { - Ok(self.parse_stmt_(true)) - } - - fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> { - self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| { - e.emit(); - self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore); - None - }) - } - - fn parse_stmt_without_recovery( - &mut self, - macro_legacy_warnings: bool, - ) -> PResult<'a, Option<Stmt>> { - maybe_whole!(self, NtStmt, |x| Some(x)); - - let attrs = self.parse_outer_attributes()?; - let lo = self.token.span; - - Ok(Some(if self.eat_keyword(kw::Let) { - Stmt { - id: DUMMY_NODE_ID, - kind: StmtKind::Local(self.parse_local(attrs.into())?), - span: lo.to(self.prev_span), - } - } else if let Some(macro_def) = self.eat_macro_def( - &attrs, - &respan(lo, VisibilityKind::Inherited), - lo, - )? { - Stmt { - id: DUMMY_NODE_ID, - kind: StmtKind::Item(macro_def), - span: lo.to(self.prev_span), - } - // Starts like a simple path, being careful to avoid contextual keywords - // such as a union items, item with `crate` visibility or auto trait items. - // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts - // like a path (1 token), but it fact not a path. - // `union::b::c` - path, `union U { ... }` - not a path. - // `crate::b::c` - path, `crate struct S;` - not a path. - } else if self.token.is_path_start() && - !self.token.is_qpath_start() && - !self.is_union_item() && - !self.is_crate_vis() && - !self.is_auto_trait_item() && - !self.is_async_fn() { - let path = self.parse_path(PathStyle::Expr)?; - - if !self.eat(&token::Not) { - let expr = if self.check(&token::OpenDelim(token::Brace)) { - self.parse_struct_expr(lo, path, ThinVec::new())? - } else { - let hi = self.prev_span; - self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()) - }; - - let expr = self.with_res(Restrictions::STMT_EXPR, |this| { - let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?; - this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr)) - })?; - - return Ok(Some(Stmt { - id: DUMMY_NODE_ID, - kind: StmtKind::Expr(expr), - span: lo.to(self.prev_span), - })); - } - - let (delim, tts) = self.expect_delimited_token_tree()?; - let hi = self.prev_span; - - let style = if delim == MacDelimiter::Brace { - MacStmtStyle::Braces - } else { - MacStmtStyle::NoBraces - }; - - let mac = Mac { - path, - tts, - delim, - span: lo.to(hi), - prior_type_ascription: self.last_type_ascription, - }; - let kind = if delim == MacDelimiter::Brace || - self.token == token::Semi || self.token == token::Eof { - StmtKind::Mac(P((mac, style, attrs.into()))) - } - // We used to incorrectly stop parsing macro-expanded statements here. - // If the next token will be an error anyway but could have parsed with the - // earlier behavior, stop parsing here and emit a warning to avoid breakage. - else if macro_legacy_warnings && self.token.can_begin_expr() && - match self.token.kind { - // These can continue an expression, so we can't stop parsing and warn. - token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) | - token::BinOp(token::Minus) | token::BinOp(token::Star) | - token::BinOp(token::And) | token::BinOp(token::Or) | - token::AndAnd | token::OrOr | - token::DotDot | token::DotDotDot | token::DotDotEq => false, - _ => true, - } - { - self.warn_missing_semicolon(); - StmtKind::Mac(P((mac, style, attrs.into()))) - } else { - let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new()); - let e = self.maybe_recover_from_bad_qpath(e, true)?; - let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?; - let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?; - StmtKind::Expr(e) - }; - Stmt { - id: DUMMY_NODE_ID, - span: lo.to(hi), - kind, - } - } else { - // FIXME: Bad copy of attrs - let old_directory_ownership = - mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock); - let item = self.parse_item_(attrs.clone(), false, true)?; - self.directory.ownership = old_directory_ownership; - - match item { - Some(i) => Stmt { - id: DUMMY_NODE_ID, - span: lo.to(i.span), - kind: StmtKind::Item(i), - }, - None => { - let unused_attrs = |attrs: &[Attribute], s: &mut Self| { - if !attrs.is_empty() { - if s.prev_token_kind == PrevTokenKind::DocComment { - s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit(); - } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) { - s.span_err( - s.token.span, "expected statement after outer attribute" - ); - } - } - }; - - // Do not attempt to parse an expression if we're done here. - if self.token == token::Semi { - unused_attrs(&attrs, self); - self.bump(); - let mut last_semi = lo; - while self.token == token::Semi { - last_semi = self.token.span; - self.bump(); - } - // We are encoding a string of semicolons as an - // an empty tuple that spans the excess semicolons - // to preserve this info until the lint stage - return Ok(Some(Stmt { - id: DUMMY_NODE_ID, - span: lo.to(last_semi), - kind: StmtKind::Semi(self.mk_expr(lo.to(last_semi), - ExprKind::Tup(Vec::new()), - ThinVec::new() - )), - })); - } - - if self.token == token::CloseDelim(token::Brace) { - unused_attrs(&attrs, self); - return Ok(None); - } - - // Remainder are line-expr stmts. - let e = self.parse_expr_res( - Restrictions::STMT_EXPR, Some(attrs.into()))?; - Stmt { - id: DUMMY_NODE_ID, - span: lo.to(e.span), - kind: StmtKind::Expr(e), - } - } - } - })) - } - - /// Parses a local variable declaration. - fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> { - let lo = self.prev_span; - let pat = self.parse_top_pat(GateOr::Yes)?; - - let (err, ty) = if self.eat(&token::Colon) { - // Save the state of the parser before parsing type normally, in case there is a `:` - // instead of an `=` typo. - let parser_snapshot_before_type = self.clone(); - let colon_sp = self.prev_span; - match self.parse_ty() { - Ok(ty) => (None, Some(ty)), - Err(mut err) => { - // Rewind to before attempting to parse the type and continue parsing. - let parser_snapshot_after_type = self.clone(); - mem::replace(self, parser_snapshot_before_type); - - let snippet = self.span_to_snippet(pat.span).unwrap(); - err.span_label(pat.span, format!("while parsing the type for `{}`", snippet)); - (Some((parser_snapshot_after_type, colon_sp, err)), None) - } - } - } else { - (None, None) - }; - let init = match (self.parse_initializer(err.is_some()), err) { - (Ok(init), None) => { // init parsed, ty parsed - init - } - (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error - // Could parse the type as if it were the initializer, it is likely there was a - // typo in the code: `:` instead of `=`. Add suggestion and emit the error. - err.span_suggestion_short( - colon_sp, - "use `=` if you meant to assign", - " =".to_string(), - Applicability::MachineApplicable - ); - err.emit(); - // As this was parsed successfully, continue as if the code has been fixed for the - // rest of the file. It will still fail due to the emitted error, but we avoid - // extra noise. - init - } - (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error - init_err.cancel(); - // Couldn't parse the type nor the initializer, only raise the type error and - // return to the parser state before parsing the type as the initializer. - // let x: <parse_error>; - mem::replace(self, snapshot); - return Err(ty_err); - } - (Err(err), None) => { // init error, ty parsed - // Couldn't parse the initializer and we're not attempting to recover a failed - // parse of the type, return the error. - return Err(err); - } - }; - let hi = if self.token == token::Semi { - self.token.span - } else { - self.prev_span - }; - Ok(P(ast::Local { - ty, - pat, - init, - id: DUMMY_NODE_ID, - span: lo.to(hi), - attrs, - })) - } - - /// Parses the RHS of a local variable declaration (e.g., '= 14;'). - fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> { - if self.eat(&token::Eq) { - Ok(Some(self.parse_expr()?)) - } else if skip_eq { - Ok(Some(self.parse_expr()?)) - } else { - Ok(None) - } - } - - fn is_auto_trait_item(&self) -> bool { - // auto trait - (self.token.is_keyword(kw::Auto) && - self.is_keyword_ahead(1, &[kw::Trait])) - || // unsafe auto trait - (self.token.is_keyword(kw::Unsafe) && - self.is_keyword_ahead(1, &[kw::Auto]) && - self.is_keyword_ahead(2, &[kw::Trait])) - } - - /// Parses a block. No inner attributes are allowed. - pub fn parse_block(&mut self) -> PResult<'a, P<Block>> { - maybe_whole!(self, NtBlock, |x| x); - - let lo = self.token.span; - - if !self.eat(&token::OpenDelim(token::Brace)) { - let sp = self.token.span; - let tok = self.this_token_descr(); - let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok)); - let do_not_suggest_help = - self.token.is_keyword(kw::In) || self.token == token::Colon; - - if self.token.is_ident_named(sym::and) { - e.span_suggestion_short( - self.token.span, - "use `&&` instead of `and` for the boolean operator", - "&&".to_string(), - Applicability::MaybeIncorrect, - ); - } - if self.token.is_ident_named(sym::or) { - e.span_suggestion_short( - self.token.span, - "use `||` instead of `or` for the boolean operator", - "||".to_string(), - Applicability::MaybeIncorrect, - ); - } - - // Check to see if the user has written something like - // - // if (cond) - // bar; - // - // which is valid in other languages, but not Rust. - match self.parse_stmt_without_recovery(false) { - Ok(Some(stmt)) => { - if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) - || do_not_suggest_help { - // If the next token is an open brace (e.g., `if a b {`), the place- - // inside-a-block suggestion would be more likely wrong than right. - e.span_label(sp, "expected `{`"); - return Err(e); - } - let mut stmt_span = stmt.span; - // Expand the span to include the semicolon, if it exists. - if self.eat(&token::Semi) { - stmt_span = stmt_span.with_hi(self.prev_span.hi()); - } - if let Ok(snippet) = self.span_to_snippet(stmt_span) { - e.span_suggestion( - stmt_span, - "try placing this code inside a block", - format!("{{ {} }}", snippet), - // Speculative; has been misleading in the past (#46836). - Applicability::MaybeIncorrect, - ); - } - } - Err(mut e) => { - self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore); - e.cancel(); - } - _ => () - } - e.span_label(sp, "expected `{`"); - return Err(e); - } - - self.parse_block_tail(lo, BlockCheckMode::Default) - } - - /// Parses a block. Inner attributes are allowed. - pub(super) fn parse_inner_attrs_and_block( - &mut self - ) -> PResult<'a, (Vec<Attribute>, P<Block>)> { - maybe_whole!(self, NtBlock, |x| (Vec::new(), x)); - - let lo = self.token.span; - self.expect(&token::OpenDelim(token::Brace))?; - Ok((self.parse_inner_attributes()?, - self.parse_block_tail(lo, BlockCheckMode::Default)?)) - } - - /// Parses the rest of a block expression or function body. - /// Precondition: already parsed the '{'. - pub(super) fn parse_block_tail( - &mut self, - lo: Span, - s: BlockCheckMode - ) -> PResult<'a, P<Block>> { - let mut stmts = vec![]; - while !self.eat(&token::CloseDelim(token::Brace)) { - if self.token == token::Eof { - break; - } - let stmt = match self.parse_full_stmt(false) { - Err(mut err) => { - self.maybe_annotate_with_ascription(&mut err, false); - err.emit(); - self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore); - Some(Stmt { - id: DUMMY_NODE_ID, - kind: StmtKind::Expr(self.mk_expr_err(self.token.span)), - span: self.token.span, - }) - } - Ok(stmt) => stmt, - }; - if let Some(stmt) = stmt { - stmts.push(stmt); - } else { - // Found only `;` or `}`. - continue; - }; - } - Ok(P(ast::Block { - stmts, - id: DUMMY_NODE_ID, - rules: s, - span: lo.to(self.prev_span), - })) - } - - /// Parses a statement, including the trailing semicolon. - pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> { - // Skip looking for a trailing semicolon when we have an interpolated statement. - maybe_whole!(self, NtStmt, |x| Some(x)); - - let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? { - Some(stmt) => stmt, - None => return Ok(None), - }; - - let mut eat_semi = true; - match stmt.kind { - StmtKind::Expr(ref expr) if self.token != token::Eof => { - // expression without semicolon - if classify::expr_requires_semi_to_be_stmt(expr) { - // Just check for errors and recover; do not eat semicolon yet. - if let Err(mut e) = - self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)]) - { - e.emit(); - self.recover_stmt(); - // Don't complain about type errors in body tail after parse error (#57383). - let sp = expr.span.to(self.prev_span); - stmt.kind = StmtKind::Expr(self.mk_expr_err(sp)); - } - } - } - StmtKind::Local(..) => { - // We used to incorrectly allow a macro-expanded let statement to lack a semicolon. - if macro_legacy_warnings && self.token != token::Semi { - self.warn_missing_semicolon(); - } else { - self.expect_semi()?; - eat_semi = false; - } - } - _ => {} - } - - if eat_semi && self.eat(&token::Semi) { - stmt = stmt.add_trailing_semicolon(); - } - stmt.span = stmt.span.to(self.prev_span); - Ok(Some(stmt)) - } - - fn warn_missing_semicolon(&self) { - self.diagnostic().struct_span_warn(self.token.span, { - &format!("expected `;`, found {}", self.this_token_descr()) - }).note({ - "this was erroneously allowed and will become a hard error in a future release" - }).emit(); - } -} diff --git a/src/libsyntax/parse/parser/ty.rs b/src/libsyntax/parse/parser/ty.rs deleted file mode 100644 index a891634e611..00000000000 --- a/src/libsyntax/parse/parser/ty.rs +++ /dev/null @@ -1,458 +0,0 @@ -use super::{Parser, PathStyle, PrevTokenKind, TokenType}; -use super::item::ParamCfg; - -use crate::{maybe_whole, maybe_recover_from_interpolated_ty_qpath}; -use crate::ptr::P; -use crate::ast::{self, Ty, TyKind, MutTy, BareFnTy, FunctionRetTy, GenericParam, Lifetime, Ident}; -use crate::ast::{TraitBoundModifier, TraitObjectSyntax, GenericBound, GenericBounds, PolyTraitRef}; -use crate::ast::{Mutability, AnonConst, Mac}; -use crate::token::{self, Token}; -use crate::source_map::Span; -use crate::symbol::{kw}; - -use errors::{PResult, Applicability, pluralize}; - -/// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`, -/// `IDENT<<u8 as Trait>::AssocTy>`. -/// -/// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes -/// that `IDENT` is not the ident of a fn trait. -fn can_continue_type_after_non_fn_ident(t: &Token) -> bool { - t == &token::ModSep || t == &token::Lt || - t == &token::BinOp(token::Shl) -} - -impl<'a> Parser<'a> { - /// Parses a type. - pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> { - self.parse_ty_common(true, true, false) - } - - /// Parses a type in restricted contexts where `+` is not permitted. - /// - /// Example 1: `&'a TYPE` - /// `+` is prohibited to maintain operator priority (P(+) < P(&)). - /// Example 2: `value1 as TYPE + value2` - /// `+` is prohibited to avoid interactions with expression grammar. - pub(super) fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> { - self.parse_ty_common(false, true, false) - } - - /// Parses an optional return type `[ -> TY ]` in a function declaration. - pub(super) fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> { - if self.eat(&token::RArrow) { - Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?)) - } else { - Ok(FunctionRetTy::Default(self.token.span.shrink_to_lo())) - } - } - - pub(super) fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool, - allow_c_variadic: bool) -> PResult<'a, P<Ty>> { - maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery); - maybe_whole!(self, NtTy, |x| x); - - let lo = self.token.span; - let mut impl_dyn_multi = false; - let kind = if self.eat(&token::OpenDelim(token::Paren)) { - // `(TYPE)` is a parenthesized type. - // `(TYPE,)` is a tuple with a single field of type TYPE. - let mut ts = vec![]; - let mut last_comma = false; - while self.token != token::CloseDelim(token::Paren) { - ts.push(self.parse_ty()?); - if self.eat(&token::Comma) { - last_comma = true; - } else { - last_comma = false; - break; - } - } - let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus; - self.expect(&token::CloseDelim(token::Paren))?; - - if ts.len() == 1 && !last_comma { - let ty = ts.into_iter().nth(0).unwrap().into_inner(); - let maybe_bounds = allow_plus && self.token.is_like_plus(); - match ty.kind { - // `(TY_BOUND_NOPAREN) + BOUND + ...`. - TyKind::Path(None, ref path) if maybe_bounds => { - self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)? - } - TyKind::TraitObject(ref bounds, TraitObjectSyntax::None) - if maybe_bounds && bounds.len() == 1 && !trailing_plus => { - let path = match bounds[0] { - GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(), - GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"), - }; - self.parse_remaining_bounds(Vec::new(), path, lo, true)? - } - // `(TYPE)` - _ => TyKind::Paren(P(ty)) - } - } else { - TyKind::Tup(ts) - } - } else if self.eat(&token::Not) { - // Never type `!` - TyKind::Never - } else if self.eat(&token::BinOp(token::Star)) { - // Raw pointer - TyKind::Ptr(self.parse_ptr()?) - } else if self.eat(&token::OpenDelim(token::Bracket)) { - // Array or slice - let t = self.parse_ty()?; - // Parse optional `; EXPR` in `[TYPE; EXPR]` - let t = match self.maybe_parse_fixed_length_of_vec()? { - None => TyKind::Slice(t), - Some(length) => TyKind::Array(t, AnonConst { - id: ast::DUMMY_NODE_ID, - value: length, - }), - }; - self.expect(&token::CloseDelim(token::Bracket))?; - t - } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) { - // Reference - self.expect_and()?; - self.parse_borrowed_pointee()? - } else if self.eat_keyword_noexpect(kw::Typeof) { - // `typeof(EXPR)` - // In order to not be ambiguous, the type must be surrounded by parens. - self.expect(&token::OpenDelim(token::Paren))?; - let e = AnonConst { - id: ast::DUMMY_NODE_ID, - value: self.parse_expr()?, - }; - self.expect(&token::CloseDelim(token::Paren))?; - TyKind::Typeof(e) - } else if self.eat_keyword(kw::Underscore) { - // A type to be inferred `_` - TyKind::Infer - } else if self.token_is_bare_fn_keyword() { - // Function pointer type - self.parse_ty_bare_fn(Vec::new())? - } else if self.check_keyword(kw::For) { - // Function pointer type or bound list (trait object type) starting with a poly-trait. - // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T` - // `for<'lt> Trait1<'lt> + Trait2 + 'a` - let lo = self.token.span; - let lifetime_defs = self.parse_late_bound_lifetime_defs()?; - if self.token_is_bare_fn_keyword() { - self.parse_ty_bare_fn(lifetime_defs)? - } else { - let path = self.parse_path(PathStyle::Type)?; - let parse_plus = allow_plus && self.check_plus(); - self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)? - } - } else if self.eat_keyword(kw::Impl) { - // Always parse bounds greedily for better error recovery. - let bounds = self.parse_generic_bounds(None)?; - impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus; - TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds) - } else if self.check_keyword(kw::Dyn) && - (self.token.span.rust_2018() || - self.look_ahead(1, |t| t.can_begin_bound() && - !can_continue_type_after_non_fn_ident(t))) { - self.bump(); // `dyn` - // Always parse bounds greedily for better error recovery. - let bounds = self.parse_generic_bounds(None)?; - impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus; - TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn) - } else if self.check(&token::Question) || - self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) { - // Bound list (trait object type) - TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?, - TraitObjectSyntax::None) - } else if self.eat_lt() { - // Qualified path - let (qself, path) = self.parse_qpath(PathStyle::Type)?; - TyKind::Path(Some(qself), path) - } else if self.token.is_path_start() { - // Simple path - let path = self.parse_path(PathStyle::Type)?; - if self.eat(&token::Not) { - // Macro invocation in type position - let (delim, tts) = self.expect_delimited_token_tree()?; - let mac = Mac { - path, - tts, - delim, - span: lo.to(self.prev_span), - prior_type_ascription: self.last_type_ascription, - }; - TyKind::Mac(mac) - } else { - // Just a type path or bound list (trait object type) starting with a trait. - // `Type` - // `Trait1 + Trait2 + 'a` - if allow_plus && self.check_plus() { - self.parse_remaining_bounds(Vec::new(), path, lo, true)? - } else { - TyKind::Path(None, path) - } - } - } else if self.check(&token::DotDotDot) { - if allow_c_variadic { - self.eat(&token::DotDotDot); - TyKind::CVarArgs - } else { - return Err(struct_span_fatal!( - self.sess.span_diagnostic, - self.token.span, - E0743, - "only foreign functions are allowed to be C-variadic", - )); - } - } else { - let msg = format!("expected type, found {}", self.this_token_descr()); - let mut err = self.fatal(&msg); - err.span_label(self.token.span, "expected type"); - self.maybe_annotate_with_ascription(&mut err, true); - return Err(err); - }; - - let span = lo.to(self.prev_span); - let ty = self.mk_ty(span, kind); - - // Try to recover from use of `+` with incorrect priority. - self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty); - self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?; - self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery) - } - - fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path, - lo: Span, parse_plus: bool) -> PResult<'a, TyKind> { - let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span)); - let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)]; - if parse_plus { - self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded - bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?); - } - Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None)) - } - - fn parse_ptr(&mut self) -> PResult<'a, MutTy> { - let mutbl = self.parse_const_or_mut().unwrap_or_else(|| { - let span = self.prev_span; - let msg = "expected mut or const in raw pointer type"; - self.struct_span_err(span, msg) - .span_label(span, msg) - .help("use `*mut T` or `*const T` as appropriate") - .emit(); - Mutability::Immutable - }); - let t = self.parse_ty_no_plus()?; - Ok(MutTy { ty: t, mutbl }) - } - - fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> { - if self.eat(&token::Semi) { - Ok(Some(self.parse_expr()?)) - } else { - Ok(None) - } - } - - fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> { - let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None }; - let mutbl = self.parse_mutability(); - let ty = self.parse_ty_no_plus()?; - return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl })); - } - - /// Is the current token one of the keywords that signals a bare function type? - fn token_is_bare_fn_keyword(&mut self) -> bool { - self.check_keyword(kw::Fn) || - self.check_keyword(kw::Unsafe) || - self.check_keyword(kw::Extern) - } - - /// Parses a `TyKind::BareFn` type. - fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> { - /* - - [unsafe] [extern "ABI"] fn (S) -> T - ^~~~^ ^~~~^ ^~^ ^ - | | | | - | | | Return type - | | Argument types - | | - | ABI - Function Style - */ - - let unsafety = self.parse_unsafety(); - let abi = self.parse_extern_abi()?; - self.expect_keyword(kw::Fn)?; - let cfg = ParamCfg { - is_self_allowed: false, - allow_c_variadic: true, - is_name_required: |_| false, - }; - let decl = self.parse_fn_decl(cfg, false)?; - Ok(TyKind::BareFn(P(BareFnTy { - abi, - unsafety, - generic_params, - decl, - }))) - } - - pub(super) fn parse_generic_bounds(&mut self, - colon_span: Option<Span>) -> PResult<'a, GenericBounds> { - self.parse_generic_bounds_common(true, colon_span) - } - - /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`. - /// - /// ``` - /// BOUND = TY_BOUND | LT_BOUND - /// LT_BOUND = LIFETIME (e.g., `'a`) - /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN) - /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`) - /// ``` - fn parse_generic_bounds_common(&mut self, - allow_plus: bool, - colon_span: Option<Span>) -> PResult<'a, GenericBounds> { - let mut bounds = Vec::new(); - let mut negative_bounds = Vec::new(); - let mut last_plus_span = None; - let mut was_negative = false; - loop { - // This needs to be synchronized with `TokenKind::can_begin_bound`. - let is_bound_start = self.check_path() || self.check_lifetime() || - self.check(&token::Not) || // used for error reporting only - self.check(&token::Question) || - self.check_keyword(kw::For) || - self.check(&token::OpenDelim(token::Paren)); - if is_bound_start { - let lo = self.token.span; - let has_parens = self.eat(&token::OpenDelim(token::Paren)); - let inner_lo = self.token.span; - let is_negative = self.eat(&token::Not); - let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None }; - if self.token.is_lifetime() { - if let Some(question_span) = question { - self.span_err(question_span, - "`?` may only modify trait bounds, not lifetime bounds"); - } - bounds.push(GenericBound::Outlives(self.expect_lifetime())); - if has_parens { - let inner_span = inner_lo.to(self.prev_span); - self.expect(&token::CloseDelim(token::Paren))?; - let mut err = self.struct_span_err( - lo.to(self.prev_span), - "parenthesized lifetime bounds are not supported" - ); - if let Ok(snippet) = self.span_to_snippet(inner_span) { - err.span_suggestion_short( - lo.to(self.prev_span), - "remove the parentheses", - snippet.to_owned(), - Applicability::MachineApplicable - ); - } - err.emit(); - } - } else { - let lifetime_defs = self.parse_late_bound_lifetime_defs()?; - let path = self.parse_path(PathStyle::Type)?; - if has_parens { - self.expect(&token::CloseDelim(token::Paren))?; - } - let poly_span = lo.to(self.prev_span); - if is_negative { - was_negative = true; - if let Some(sp) = last_plus_span.or(colon_span) { - negative_bounds.push(sp.to(poly_span)); - } - } else { - let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span); - let modifier = if question.is_some() { - TraitBoundModifier::Maybe - } else { - TraitBoundModifier::None - }; - bounds.push(GenericBound::Trait(poly_trait, modifier)); - } - } - } else { - break - } - - if !allow_plus || !self.eat_plus() { - break - } else { - last_plus_span = Some(self.prev_span); - } - } - - if !negative_bounds.is_empty() || was_negative { - let negative_bounds_len = negative_bounds.len(); - let last_span = negative_bounds.last().map(|sp| *sp); - let mut err = self.struct_span_err( - negative_bounds, - "negative trait bounds are not supported", - ); - if let Some(sp) = last_span { - err.span_label(sp, "negative trait bounds are not supported"); - } - if let Some(bound_list) = colon_span { - let bound_list = bound_list.to(self.prev_span); - let mut new_bound_list = String::new(); - if !bounds.is_empty() { - let mut snippets = bounds.iter().map(|bound| bound.span()) - .map(|span| self.span_to_snippet(span)); - while let Some(Ok(snippet)) = snippets.next() { - new_bound_list.push_str(" + "); - new_bound_list.push_str(&snippet); - } - new_bound_list = new_bound_list.replacen(" +", ":", 1); - } - err.span_suggestion_hidden( - bound_list, - &format!("remove the trait bound{}", pluralize!(negative_bounds_len)), - new_bound_list, - Applicability::MachineApplicable, - ); - } - err.emit(); - } - - return Ok(bounds); - } - - pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> { - if self.eat_keyword(kw::For) { - self.expect_lt()?; - let params = self.parse_generic_params()?; - self.expect_gt()?; - // We rely on AST validation to rule out invalid cases: There must not be type - // parameters, and the lifetime parameters must not have bounds. - Ok(params) - } else { - Ok(Vec::new()) - } - } - - pub fn check_lifetime(&mut self) -> bool { - self.expected_tokens.push(TokenType::Lifetime); - self.token.is_lifetime() - } - - /// Parses a single lifetime `'a` or panics. - pub fn expect_lifetime(&mut self) -> Lifetime { - if let Some(ident) = self.token.lifetime() { - let span = self.token.span; - self.bump(); - Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID } - } else { - self.span_bug(self.token.span, "not a lifetime") - } - } - - pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> { - P(Ty { kind, span, id: ast::DUMMY_NODE_ID }) - } -} diff --git a/src/libsyntax/parse/tests.rs b/src/libsyntax/parse/tests.rs deleted file mode 100644 index 27ca2b6472f..00000000000 --- a/src/libsyntax/parse/tests.rs +++ /dev/null @@ -1,339 +0,0 @@ -use super::*; - -use crate::ast::{self, Name, PatKind}; -use crate::attr::first_attr_value_str_by_name; -use crate::sess::ParseSess; -use crate::parse::{PResult, new_parser_from_source_str}; -use crate::token::Token; -use crate::print::pprust::item_to_string; -use crate::ptr::P; -use crate::source_map::FilePathMapping; -use crate::symbol::{kw, sym}; -use crate::tests::{matches_codepattern, string_to_stream, with_error_checking_parse}; -use crate::tokenstream::{DelimSpan, TokenTree, TokenStream}; -use crate::with_default_globals; -use syntax_pos::{Span, BytePos, Pos}; - -use std::path::PathBuf; - -/// Parses an item. -/// -/// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err` -/// when a syntax error occurred. -fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess) - -> PResult<'_, Option<P<ast::Item>>> { - new_parser_from_source_str(sess, name, source).parse_item() -} - -// Produces a `syntax_pos::span`. -fn sp(a: u32, b: u32) -> Span { - Span::with_root_ctxt(BytePos(a), BytePos(b)) -} - -/// Parses a string, return an expression. -fn string_to_expr(source_str : String) -> P<ast::Expr> { - let ps = ParseSess::new(FilePathMapping::empty()); - with_error_checking_parse(source_str, &ps, |p| { - p.parse_expr() - }) -} - -/// Parses a string, returns an item. -fn string_to_item(source_str : String) -> Option<P<ast::Item>> { - let ps = ParseSess::new(FilePathMapping::empty()); - with_error_checking_parse(source_str, &ps, |p| { - p.parse_item() - }) -} - -#[should_panic] -#[test] fn bad_path_expr_1() { - with_default_globals(|| { - string_to_expr("::abc::def::return".to_string()); - }) -} - -// Checks the token-tree-ization of macros. -#[test] -fn string_to_tts_macro () { - with_default_globals(|| { - let tts: Vec<_> = - string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect(); - let tts: &[TokenTree] = &tts[..]; - - match tts { - [ - TokenTree::Token(Token { kind: token::Ident(name_macro_rules, false), .. }), - TokenTree::Token(Token { kind: token::Not, .. }), - TokenTree::Token(Token { kind: token::Ident(name_zip, false), .. }), - TokenTree::Delimited(_, macro_delim, macro_tts) - ] - if name_macro_rules == &sym::macro_rules && name_zip.as_str() == "zip" => { - let tts = ¯o_tts.trees().collect::<Vec<_>>(); - match &tts[..] { - [ - TokenTree::Delimited(_, first_delim, first_tts), - TokenTree::Token(Token { kind: token::FatArrow, .. }), - TokenTree::Delimited(_, second_delim, second_tts), - ] - if macro_delim == &token::Paren => { - let tts = &first_tts.trees().collect::<Vec<_>>(); - match &tts[..] { - [ - TokenTree::Token(Token { kind: token::Dollar, .. }), - TokenTree::Token(Token { kind: token::Ident(name, false), .. }), - ] - if first_delim == &token::Paren && name.as_str() == "a" => {}, - _ => panic!("value 3: {:?} {:?}", first_delim, first_tts), - } - let tts = &second_tts.trees().collect::<Vec<_>>(); - match &tts[..] { - [ - TokenTree::Token(Token { kind: token::Dollar, .. }), - TokenTree::Token(Token { kind: token::Ident(name, false), .. }), - ] - if second_delim == &token::Paren && name.as_str() == "a" => {}, - _ => panic!("value 4: {:?} {:?}", second_delim, second_tts), - } - }, - _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts), - } - }, - _ => panic!("value: {:?}",tts), - } - }) -} - -#[test] -fn string_to_tts_1() { - with_default_globals(|| { - let tts = string_to_stream("fn a (b : i32) { b; }".to_string()); - - let expected = TokenStream::new(vec![ - TokenTree::token(token::Ident(kw::Fn, false), sp(0, 2)).into(), - TokenTree::token(token::Ident(Name::intern("a"), false), sp(3, 4)).into(), - TokenTree::Delimited( - DelimSpan::from_pair(sp(5, 6), sp(13, 14)), - token::DelimToken::Paren, - TokenStream::new(vec![ - TokenTree::token(token::Ident(Name::intern("b"), false), sp(6, 7)).into(), - TokenTree::token(token::Colon, sp(8, 9)).into(), - TokenTree::token(token::Ident(sym::i32, false), sp(10, 13)).into(), - ]).into(), - ).into(), - TokenTree::Delimited( - DelimSpan::from_pair(sp(15, 16), sp(20, 21)), - token::DelimToken::Brace, - TokenStream::new(vec![ - TokenTree::token(token::Ident(Name::intern("b"), false), sp(17, 18)).into(), - TokenTree::token(token::Semi, sp(18, 19)).into(), - ]).into(), - ).into() - ]); - - assert_eq!(tts, expected); - }) -} - -#[test] fn parse_use() { - with_default_globals(|| { - let use_s = "use foo::bar::baz;"; - let vitem = string_to_item(use_s.to_string()).unwrap(); - let vitem_s = item_to_string(&vitem); - assert_eq!(&vitem_s[..], use_s); - - let use_s = "use foo::bar as baz;"; - let vitem = string_to_item(use_s.to_string()).unwrap(); - let vitem_s = item_to_string(&vitem); - assert_eq!(&vitem_s[..], use_s); - }) -} - -#[test] fn parse_extern_crate() { - with_default_globals(|| { - let ex_s = "extern crate foo;"; - let vitem = string_to_item(ex_s.to_string()).unwrap(); - let vitem_s = item_to_string(&vitem); - assert_eq!(&vitem_s[..], ex_s); - - let ex_s = "extern crate foo as bar;"; - let vitem = string_to_item(ex_s.to_string()).unwrap(); - let vitem_s = item_to_string(&vitem); - assert_eq!(&vitem_s[..], ex_s); - }) -} - -fn get_spans_of_pat_idents(src: &str) -> Vec<Span> { - let item = string_to_item(src.to_string()).unwrap(); - - struct PatIdentVisitor { - spans: Vec<Span> - } - impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor { - fn visit_pat(&mut self, p: &'a ast::Pat) { - match p.kind { - PatKind::Ident(_ , ref ident, _) => { - self.spans.push(ident.span.clone()); - } - _ => { - crate::visit::walk_pat(self, p); - } - } - } - } - let mut v = PatIdentVisitor { spans: Vec::new() }; - crate::visit::walk_item(&mut v, &item); - return v.spans; -} - -#[test] fn span_of_self_arg_pat_idents_are_correct() { - with_default_globals(|| { - - let srcs = ["impl z { fn a (&self, &myarg: i32) {} }", - "impl z { fn a (&mut self, &myarg: i32) {} }", - "impl z { fn a (&'a self, &myarg: i32) {} }", - "impl z { fn a (self, &myarg: i32) {} }", - "impl z { fn a (self: Foo, &myarg: i32) {} }", - ]; - - for &src in &srcs { - let spans = get_spans_of_pat_idents(src); - let (lo, hi) = (spans[0].lo(), spans[0].hi()); - assert!("self" == &src[lo.to_usize()..hi.to_usize()], - "\"{}\" != \"self\". src=\"{}\"", - &src[lo.to_usize()..hi.to_usize()], src) - } - }) -} - -#[test] fn parse_exprs () { - with_default_globals(|| { - // just make sure that they parse.... - string_to_expr("3 + 4".to_string()); - string_to_expr("a::z.froob(b,&(987+3))".to_string()); - }) -} - -#[test] fn attrs_fix_bug () { - with_default_globals(|| { - string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag]) - -> Result<Box<Writer>, String> { -#[cfg(windows)] -fn wb() -> c_int { - (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int -} - -#[cfg(unix)] -fn wb() -> c_int { O_WRONLY as c_int } - -let mut fflags: c_int = wb(); -}".to_string()); - }) -} - -#[test] fn crlf_doc_comments() { - with_default_globals(|| { - let sess = ParseSess::new(FilePathMapping::empty()); - - let name_1 = FileName::Custom("crlf_source_1".to_string()); - let source = "/// doc comment\r\nfn foo() {}".to_string(); - let item = parse_item_from_source_str(name_1, source, &sess) - .unwrap().unwrap(); - let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap(); - assert_eq!(doc.as_str(), "/// doc comment"); - - let name_2 = FileName::Custom("crlf_source_2".to_string()); - let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string(); - let item = parse_item_from_source_str(name_2, source, &sess) - .unwrap().unwrap(); - let docs = item.attrs.iter().filter(|a| a.has_name(sym::doc)) - .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>(); - let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()]; - assert_eq!(&docs[..], b); - - let name_3 = FileName::Custom("clrf_source_3".to_string()); - let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string(); - let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap(); - let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap(); - assert_eq!(doc.as_str(), "/** doc comment\n * with CRLF */"); - }); -} - -#[test] -fn ttdelim_span() { - fn parse_expr_from_source_str( - name: FileName, source: String, sess: &ParseSess - ) -> PResult<'_, P<ast::Expr>> { - new_parser_from_source_str(sess, name, source).parse_expr() - } - - with_default_globals(|| { - let sess = ParseSess::new(FilePathMapping::empty()); - let expr = parse_expr_from_source_str(PathBuf::from("foo").into(), - "foo!( fn main() { body } )".to_string(), &sess).unwrap(); - - let tts: Vec<_> = match expr.kind { - ast::ExprKind::Mac(ref mac) => mac.stream().trees().collect(), - _ => panic!("not a macro"), - }; - - let span = tts.iter().rev().next().unwrap().span(); - - match sess.source_map().span_to_snippet(span) { - Ok(s) => assert_eq!(&s[..], "{ body }"), - Err(_) => panic!("could not get snippet"), - } - }); -} - -// This tests that when parsing a string (rather than a file) we don't try -// and read in a file for a module declaration and just parse a stub. -// See `recurse_into_file_modules` in the parser. -#[test] -fn out_of_line_mod() { - with_default_globals(|| { - let sess = ParseSess::new(FilePathMapping::empty()); - let item = parse_item_from_source_str( - PathBuf::from("foo").into(), - "mod foo { struct S; mod this_does_not_exist; }".to_owned(), - &sess, - ).unwrap().unwrap(); - - if let ast::ItemKind::Mod(ref m) = item.kind { - assert!(m.items.len() == 2); - } else { - panic!(); - } - }); -} - -#[test] -fn eqmodws() { - assert_eq!(matches_codepattern("",""),true); - assert_eq!(matches_codepattern("","a"),false); - assert_eq!(matches_codepattern("a",""),false); - assert_eq!(matches_codepattern("a","a"),true); - assert_eq!(matches_codepattern("a b","a \n\t\r b"),true); - assert_eq!(matches_codepattern("a b ","a \n\t\r b"),true); - assert_eq!(matches_codepattern("a b","a \n\t\r b "),false); - assert_eq!(matches_codepattern("a b","a b"),true); - assert_eq!(matches_codepattern("ab","a b"),false); - assert_eq!(matches_codepattern("a b","ab"),true); - assert_eq!(matches_codepattern(" a b","ab"),true); -} - -#[test] -fn pattern_whitespace() { - assert_eq!(matches_codepattern("","\x0C"), false); - assert_eq!(matches_codepattern("a b ","a \u{0085}\n\t\r b"),true); - assert_eq!(matches_codepattern("a b","a \u{0085}\n\t\r b "),false); -} - -#[test] -fn non_pattern_whitespace() { - // These have the property 'White_Space' but not 'Pattern_White_Space' - assert_eq!(matches_codepattern("a b","a\u{2002}b"), false); - assert_eq!(matches_codepattern("a b","a\u{2002}b"), false); - assert_eq!(matches_codepattern("\u{205F}a b","ab"), false); - assert_eq!(matches_codepattern("a \u{3000}b","ab"), false); -} diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 2203e8d9d06..b2e8d8526fd 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -1,6 +1,6 @@ use crate::ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax}; use crate::ast::{SelfKind, GenericBound, TraitBoundModifier}; -use crate::ast::{Attribute, MacDelimiter, GenericArg}; +use crate::ast::{Attribute, GenericArg, MacArgs}; use crate::util::parser::{self, AssocOp, Fixity}; use crate::util::comments; use crate::attr; @@ -317,11 +317,11 @@ pub fn token_to_string(token: &Token) -> String { } fn token_to_string_ext(token: &Token, convert_dollar_crate: bool) -> String { - let convert_dollar_crate = if convert_dollar_crate { Some(token.span) } else { None }; + let convert_dollar_crate = convert_dollar_crate.then_some(token.span); token_kind_to_string_ext(&token.kind, convert_dollar_crate) } -crate fn nonterminal_to_string(nt: &Nonterminal) -> String { +pub fn nonterminal_to_string(nt: &Nonterminal) -> String { match *nt { token::NtExpr(ref e) => expr_to_string(e), token::NtMeta(ref e) => attr_item_to_string(e), @@ -639,17 +639,22 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) { self.ibox(0); - match item.tokens.trees().next() { - Some(TokenTree::Delimited(_, delim, tts)) => { - self.print_mac_common( - Some(MacHeader::Path(&item.path)), false, None, delim, tts, true, span - ); - } - tree => { + match &item.args { + MacArgs::Delimited(_, delim, tokens) => self.print_mac_common( + Some(MacHeader::Path(&item.path)), + false, + None, + delim.to_token(), + tokens.clone(), + true, + span, + ), + MacArgs::Empty | MacArgs::Eq(..) => { self.print_path(&item.path, false, 0); - if tree.is_some() { + if let MacArgs::Eq(_, tokens) = &item.args { self.space(); - self.print_tts(item.tokens.clone(), true); + self.word_space("="); + self.print_tts(tokens.clone(), true); } } } @@ -939,8 +944,11 @@ impl<'a> State<'a> { self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span) } - crate fn print_mod(&mut self, _mod: &ast::Mod, - attrs: &[ast::Attribute]) { + pub fn print_mod( + &mut self, + _mod: &ast::Mod, + attrs: &[ast::Attribute], + ) { self.print_inner_attributes(attrs); for item in &_mod.items { self.print_item(item); @@ -955,7 +963,7 @@ impl<'a> State<'a> { } } - crate fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) { + pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) { if let Some(lt) = *lifetime { self.print_lifetime(lt); self.nbsp(); @@ -970,7 +978,7 @@ impl<'a> State<'a> { } } - crate fn print_type(&mut self, ty: &ast::Ty) { + pub fn print_type(&mut self, ty: &ast::Ty) { self.maybe_print_comment(ty.span.lo()); self.ibox(0); match ty.kind { @@ -981,16 +989,12 @@ impl<'a> State<'a> { } ast::TyKind::Ptr(ref mt) => { self.s.word("*"); - match mt.mutbl { - ast::Mutability::Mutable => self.word_nbsp("mut"), - ast::Mutability::Immutable => self.word_nbsp("const"), - } - self.print_type(&mt.ty); + self.print_mt(mt, true); } ast::TyKind::Rptr(ref lifetime, ref mt) => { self.s.word("&"); self.print_opt_lifetime(lifetime); - self.print_mt(mt); + self.print_mt(mt, false); } ast::TyKind::Never => { self.s.word("!"); @@ -1010,7 +1014,7 @@ impl<'a> State<'a> { self.pclose(); } ast::TyKind::BareFn(ref f) => { - self.print_ty_fn(f.abi, + self.print_ty_fn(f.ext, f.unsafety, &f.decl, None, @@ -1098,9 +1102,8 @@ impl<'a> State<'a> { } ast::ForeignItemKind::Macro(ref m) => { self.print_mac(m); - match m.delim { - MacDelimiter::Brace => {}, - _ => self.s.word(";") + if m.args.need_semicolon() { + self.s.word(";"); } } } @@ -1229,7 +1232,10 @@ impl<'a> State<'a> { } ast::ItemKind::ForeignMod(ref nmod) => { self.head("extern"); - self.print_abi(nmod.abi); + if let Some(abi) = nmod.abi { + self.print_literal(&abi.as_lit()); + self.nbsp(); + } self.bopen(); self.print_foreign_mod(nmod, &item.attrs); self.bclose(item.span); @@ -1252,19 +1258,6 @@ impl<'a> State<'a> { self.s.word(";"); self.end(); // end the outer ibox } - ast::ItemKind::OpaqueTy(ref bounds, ref generics) => { - self.head(visibility_qualified(&item.vis, "type")); - self.print_ident(item.ident); - self.word_space("= impl"); - self.print_generic_params(&generics.params); - self.end(); // end the inner ibox - - self.print_where_clause(&generics.where_clause); - self.s.space(); - self.print_type_bounds(":", bounds); - self.s.word(";"); - self.end(); // end the outer ibox - } ast::ItemKind::Enum(ref enum_definition, ref params) => { self.print_enum_def( enum_definition, @@ -1372,9 +1365,8 @@ impl<'a> State<'a> { } ast::ItemKind::Mac(ref mac) => { self.print_mac(mac); - match mac.delim { - MacDelimiter::Brace => {} - _ => self.s.word(";"), + if mac.args.need_semicolon() { + self.s.word(";"); } } ast::ItemKind::MacroDef(ref macro_def) => { @@ -1388,8 +1380,8 @@ impl<'a> State<'a> { Some(MacHeader::Keyword(kw)), has_bang, Some(item.ident), - DelimToken::Brace, - macro_def.stream(), + macro_def.body.delim(), + macro_def.body.inner_tokens(), true, item.span, ); @@ -1589,9 +1581,8 @@ impl<'a> State<'a> { } ast::TraitItemKind::Macro(ref mac) => { self.print_mac(mac); - match mac.delim { - MacDelimiter::Brace => {} - _ => self.s.word(";"), + if mac.args.need_semicolon() { + self.s.word(";"); } } } @@ -1617,18 +1608,10 @@ impl<'a> State<'a> { ast::ImplItemKind::TyAlias(ref ty) => { self.print_associated_type(ii.ident, None, Some(ty)); } - ast::ImplItemKind::OpaqueTy(ref bounds) => { - self.word_space("type"); - self.print_ident(ii.ident); - self.word_space("= impl"); - self.print_type_bounds(":", bounds); - self.s.word(";"); - } ast::ImplItemKind::Macro(ref mac) => { self.print_mac(mac); - match mac.delim { - MacDelimiter::Brace => {} - _ => self.s.word(";"), + if mac.args.need_semicolon() { + self.s.word(";"); } } } @@ -1793,10 +1776,10 @@ impl<'a> State<'a> { Some(MacHeader::Path(&m.path)), true, None, - m.delim.to_token(), - m.stream(), + m.args.delim(), + m.args.inner_tokens(), true, - m.span, + m.span(), ); } @@ -1988,14 +1971,21 @@ impl<'a> State<'a> { } fn print_expr_addr_of(&mut self, + kind: ast::BorrowKind, mutability: ast::Mutability, expr: &ast::Expr) { self.s.word("&"); - self.print_mutability(mutability); + match kind { + ast::BorrowKind::Ref => self.print_mutability(mutability, false), + ast::BorrowKind::Raw => { + self.word_nbsp("raw"); + self.print_mutability(mutability, true); + } + } self.print_expr_maybe_paren(expr, parser::PREC_PREFIX) } - crate fn print_expr(&mut self, expr: &ast::Expr) { + pub fn print_expr(&mut self, expr: &ast::Expr) { self.print_expr_outer_attr_style(expr, true) } @@ -2042,8 +2032,8 @@ impl<'a> State<'a> { ast::ExprKind::Unary(op, ref expr) => { self.print_expr_unary(op, expr); } - ast::ExprKind::AddrOf(m, ref expr) => { - self.print_expr_addr_of(m, expr); + ast::ExprKind::AddrOf(k, m, ref expr) => { + self.print_expr_addr_of(k, m, expr); } ast::ExprKind::Lit(ref lit) => { self.print_literal(lit); @@ -2332,7 +2322,7 @@ impl<'a> State<'a> { } } - crate fn print_usize(&mut self, i: usize) { + pub fn print_usize(&mut self, i: usize) { self.s.word(i.to_string()) } @@ -2375,7 +2365,7 @@ impl<'a> State<'a> { match binding_mode { ast::BindingMode::ByRef(mutbl) => { self.word_nbsp("ref"); - self.print_mutability(mutbl); + self.print_mutability(mutbl, false); } ast::BindingMode::ByValue(ast::Mutability::Immutable) => {} ast::BindingMode::ByValue(ast::Mutability::Mutable) => { @@ -2518,17 +2508,17 @@ impl<'a> State<'a> { fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) { match explicit_self.node { SelfKind::Value(m) => { - self.print_mutability(m); + self.print_mutability(m, false); self.s.word("self") } SelfKind::Region(ref lt, m) => { self.s.word("&"); self.print_opt_lifetime(lt); - self.print_mutability(m); + self.print_mutability(m, false); self.s.word("self") } SelfKind::Explicit(ref typ, m) => { - self.print_mutability(m); + self.print_mutability(m, false); self.s.word("self"); self.word_space(":"); self.print_type(typ) @@ -2601,7 +2591,7 @@ impl<'a> State<'a> { } } - crate fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) { + pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) { if !bounds.is_empty() { self.s.word(prefix); let mut first = true; @@ -2760,15 +2750,15 @@ impl<'a> State<'a> { } } - crate fn print_mutability(&mut self, mutbl: ast::Mutability) { + pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) { match mutbl { ast::Mutability::Mutable => self.word_nbsp("mut"), - ast::Mutability::Immutable => {}, + ast::Mutability::Immutable => if print_const { self.word_nbsp("const"); }, } } - crate fn print_mt(&mut self, mt: &ast::MutTy) { - self.print_mutability(mt.mutbl); + crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) { + self.print_mutability(mt.mutbl, print_const); self.print_type(&mt.ty) } @@ -2822,7 +2812,7 @@ impl<'a> State<'a> { } crate fn print_ty_fn(&mut self, - abi: ast::Abi, + ext: ast::Extern, unsafety: ast::Unsafety, decl: &ast::FnDecl, name: Option<ast::Ident>, @@ -2842,7 +2832,7 @@ impl<'a> State<'a> { span: syntax_pos::DUMMY_SP, }; self.print_fn(decl, - ast::FnHeader { unsafety, abi, ..ast::FnHeader::default() }, + ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() }, name, &generics, &source_map::dummy_spanned(ast::VisibilityKind::Inherited)); @@ -2883,18 +2873,21 @@ impl<'a> State<'a> { self.print_asyncness(header.asyncness.node); self.print_unsafety(header.unsafety); - if header.abi.symbol != sym::Rust { - self.word_nbsp("extern"); - self.print_abi(header.abi); + match header.ext { + ast::Extern::None => {} + ast::Extern::Implicit => { + self.word_nbsp("extern"); + } + ast::Extern::Explicit(abi) => { + self.word_nbsp("extern"); + self.print_literal(&abi.as_lit()); + self.nbsp(); + } } self.s.word("fn") } - fn print_abi(&mut self, abi: ast::Abi) { - self.word_nbsp(format!("\"{}\"", abi.symbol)); - } - crate fn print_unsafety(&mut self, s: ast::Unsafety) { match s { ast::Unsafety::Normal => {}, diff --git a/src/libsyntax/print/pprust/tests.rs b/src/libsyntax/print/pprust/tests.rs index 2c6dd0fb1c6..d7725acb5d4 100644 --- a/src/libsyntax/print/pprust/tests.rs +++ b/src/libsyntax/print/pprust/tests.rs @@ -50,6 +50,7 @@ fn test_variant_to_string() { let var = ast::Variant { ident, + vis: source_map::respan(syntax_pos::DUMMY_SP, ast::VisibilityKind::Inherited), attrs: Vec::new(), id: ast::DUMMY_NODE_ID, data: ast::VariantData::Unit(ast::DUMMY_NODE_ID), diff --git a/src/libsyntax/sess.rs b/src/libsyntax/sess.rs deleted file mode 100644 index faad3e4af1e..00000000000 --- a/src/libsyntax/sess.rs +++ /dev/null @@ -1,169 +0,0 @@ -//! Contains `ParseSess` which holds state living beyond what one `Parser` might. -//! It also serves as an input to the parser itself. - -use crate::ast::{CrateConfig, NodeId}; -use crate::early_buffered_lints::{BufferedEarlyLint, BufferedEarlyLintId}; -use crate::source_map::{SourceMap, FilePathMapping}; -use crate::feature_gate::UnstableFeatures; - -use errors::{Applicability, emitter::SilentEmitter, Handler, ColorConfig, DiagnosticBuilder}; -use rustc_data_structures::fx::{FxHashSet, FxHashMap}; -use rustc_data_structures::sync::{Lrc, Lock, Once}; -use syntax_pos::{Symbol, Span, MultiSpan}; -use syntax_pos::edition::Edition; -use syntax_pos::hygiene::ExpnId; - -use std::path::PathBuf; -use std::str; - -/// Collected spans during parsing for places where a certain feature was -/// used and should be feature gated accordingly in `check_crate`. -#[derive(Default)] -pub struct GatedSpans { - pub spans: Lock<FxHashMap<Symbol, Vec<Span>>>, -} - -impl GatedSpans { - /// Feature gate the given `span` under the given `feature` - /// which is same `Symbol` used in `active.rs`. - pub fn gate(&self, feature: Symbol, span: Span) { - self.spans - .borrow_mut() - .entry(feature) - .or_default() - .push(span); - } - - /// Ungate the last span under the given `feature`. - /// Panics if the given `span` wasn't the last one. - /// - /// Using this is discouraged unless you have a really good reason to. - pub fn ungate_last(&self, feature: Symbol, span: Span) { - let removed_span = self.spans - .borrow_mut() - .entry(feature) - .or_default() - .pop() - .unwrap(); - debug_assert_eq!(span, removed_span); - } - - /// Is the provided `feature` gate ungated currently? - /// - /// Using this is discouraged unless you have a really good reason to. - pub fn is_ungated(&self, feature: Symbol) -> bool { - self.spans - .borrow() - .get(&feature) - .map_or(true, |spans| spans.is_empty()) - } - - /// Prepend the given set of `spans` onto the set in `self`. - pub fn merge(&self, mut spans: FxHashMap<Symbol, Vec<Span>>) { - let mut inner = self.spans.borrow_mut(); - for (gate, mut gate_spans) in inner.drain() { - spans.entry(gate).or_default().append(&mut gate_spans); - } - *inner = spans; - } -} - -/// Info about a parsing session. -pub struct ParseSess { - pub span_diagnostic: Handler, - crate unstable_features: UnstableFeatures, - pub config: CrateConfig, - pub edition: Edition, - pub missing_fragment_specifiers: Lock<FxHashSet<Span>>, - /// Places where raw identifiers were used. This is used for feature-gating raw identifiers. - pub raw_identifier_spans: Lock<Vec<Span>>, - /// Used to determine and report recursive module inclusions. - pub(super) included_mod_stack: Lock<Vec<PathBuf>>, - source_map: Lrc<SourceMap>, - pub buffered_lints: Lock<Vec<BufferedEarlyLint>>, - /// Contains the spans of block expressions that could have been incomplete based on the - /// operation token that followed it, but that the parser cannot identify without further - /// analysis. - pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>, - pub injected_crate_name: Once<Symbol>, - pub gated_spans: GatedSpans, - /// The parser has reached `Eof` due to an unclosed brace. Used to silence unnecessary errors. - pub reached_eof: Lock<bool>, -} - -impl ParseSess { - pub fn new(file_path_mapping: FilePathMapping) -> Self { - let cm = Lrc::new(SourceMap::new(file_path_mapping)); - let handler = Handler::with_tty_emitter( - ColorConfig::Auto, - true, - None, - Some(cm.clone()), - ); - ParseSess::with_span_handler(handler, cm) - } - - pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> Self { - Self { - span_diagnostic: handler, - unstable_features: UnstableFeatures::from_environment(), - config: FxHashSet::default(), - edition: ExpnId::root().expn_data().edition, - missing_fragment_specifiers: Lock::new(FxHashSet::default()), - raw_identifier_spans: Lock::new(Vec::new()), - included_mod_stack: Lock::new(vec![]), - source_map, - buffered_lints: Lock::new(vec![]), - ambiguous_block_expr_parse: Lock::new(FxHashMap::default()), - injected_crate_name: Once::new(), - gated_spans: GatedSpans::default(), - reached_eof: Lock::new(false), - } - } - - pub fn with_silent_emitter() -> Self { - let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let handler = Handler::with_emitter(false, None, Box::new(SilentEmitter)); - ParseSess::with_span_handler(handler, cm) - } - - #[inline] - pub fn source_map(&self) -> &SourceMap { - &self.source_map - } - - pub fn buffer_lint( - &self, - lint_id: BufferedEarlyLintId, - span: impl Into<MultiSpan>, - id: NodeId, - msg: &str, - ) { - self.buffered_lints.with_lock(|buffered_lints| { - buffered_lints.push(BufferedEarlyLint{ - span: span.into(), - id, - msg: msg.into(), - lint_id, - }); - }); - } - - /// Extend an error with a suggestion to wrap an expression with parentheses to allow the - /// parser to continue parsing the following operation as part of the same expression. - pub fn expr_parentheses_needed( - &self, - err: &mut DiagnosticBuilder<'_>, - span: Span, - alt_snippet: Option<String>, - ) { - if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) { - err.span_suggestion( - span, - "parentheses are required to parse this as an expression", - format!("({})", snippet), - Applicability::MachineApplicable, - ); - } - } -} diff --git a/src/libsyntax/source_map.rs b/src/libsyntax/source_map.rs deleted file mode 100644 index d9f618602a4..00000000000 --- a/src/libsyntax/source_map.rs +++ /dev/null @@ -1,1035 +0,0 @@ -//! The `SourceMap` tracks all the source code used within a single crate, mapping -//! from integer byte positions to the original source code location. Each bit -//! of source parsed during crate parsing (typically files, in-memory strings, -//! or various bits of macro expansion) cover a continuous range of bytes in the -//! `SourceMap` and are represented by `SourceFile`s. Byte positions are stored in -//! `Span` and used pervasively in the compiler. They are absolute positions -//! within the `SourceMap`, which upon request can be converted to line and column -//! information, source code snippets, etc. - -pub use syntax_pos::*; -pub use syntax_pos::hygiene::{ExpnKind, ExpnData}; - -use rustc_data_structures::fx::FxHashMap; -use rustc_data_structures::stable_hasher::StableHasher; -use rustc_data_structures::sync::{Lrc, Lock, LockGuard, MappedLockGuard}; -use std::cmp; -use std::hash::Hash; -use std::path::{Path, PathBuf}; - -use std::env; -use std::fs; -use std::io; -use log::debug; - -use errors::SourceMapper; - -#[cfg(test)] -mod tests; - -/// Returns the span itself if it doesn't come from a macro expansion, -/// otherwise return the call site span up to the `enclosing_sp` by -/// following the `expn_data` chain. -pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span { - let expn_data1 = sp.ctxt().outer_expn_data(); - let expn_data2 = enclosing_sp.ctxt().outer_expn_data(); - if expn_data1.is_root() || - !expn_data2.is_root() && expn_data1.call_site == expn_data2.call_site { - sp - } else { - original_sp(expn_data1.call_site, enclosing_sp) - } -} - -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)] -pub struct Spanned<T> { - pub node: T, - pub span: Span, -} - -pub fn respan<T>(sp: Span, t: T) -> Spanned<T> { - Spanned {node: t, span: sp} -} - -pub fn dummy_spanned<T>(t: T) -> Spanned<T> { - respan(DUMMY_SP, t) -} - -// _____________________________________________________________________________ -// SourceFile, MultiByteChar, FileName, FileLines -// - -/// An abstraction over the fs operations used by the Parser. -pub trait FileLoader { - /// Query the existence of a file. - fn file_exists(&self, path: &Path) -> bool; - - /// Returns an absolute path to a file, if possible. - fn abs_path(&self, path: &Path) -> Option<PathBuf>; - - /// Read the contents of an UTF-8 file into memory. - fn read_file(&self, path: &Path) -> io::Result<String>; -} - -/// A FileLoader that uses std::fs to load real files. -pub struct RealFileLoader; - -impl FileLoader for RealFileLoader { - fn file_exists(&self, path: &Path) -> bool { - fs::metadata(path).is_ok() - } - - fn abs_path(&self, path: &Path) -> Option<PathBuf> { - if path.is_absolute() { - Some(path.to_path_buf()) - } else { - env::current_dir() - .ok() - .map(|cwd| cwd.join(path)) - } - } - - fn read_file(&self, path: &Path) -> io::Result<String> { - fs::read_to_string(path) - } -} - -// This is a `SourceFile` identifier that is used to correlate `SourceFile`s between -// subsequent compilation sessions (which is something we need to do during -// incremental compilation). -#[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)] -pub struct StableSourceFileId(u128); - -impl StableSourceFileId { - pub fn new(source_file: &SourceFile) -> StableSourceFileId { - StableSourceFileId::new_from_pieces(&source_file.name, - source_file.name_was_remapped, - source_file.unmapped_path.as_ref()) - } - - pub fn new_from_pieces(name: &FileName, - name_was_remapped: bool, - unmapped_path: Option<&FileName>) -> StableSourceFileId { - let mut hasher = StableHasher::new(); - - name.hash(&mut hasher); - name_was_remapped.hash(&mut hasher); - unmapped_path.hash(&mut hasher); - - StableSourceFileId(hasher.finish()) - } -} - -// _____________________________________________________________________________ -// SourceMap -// - -#[derive(Default)] -pub(super) struct SourceMapFiles { - source_files: Vec<Lrc<SourceFile>>, - stable_id_to_source_file: FxHashMap<StableSourceFileId, Lrc<SourceFile>> -} - -pub struct SourceMap { - files: Lock<SourceMapFiles>, - file_loader: Box<dyn FileLoader + Sync + Send>, - // This is used to apply the file path remapping as specified via - // `--remap-path-prefix` to all `SourceFile`s allocated within this `SourceMap`. - path_mapping: FilePathMapping, -} - -impl SourceMap { - pub fn new(path_mapping: FilePathMapping) -> SourceMap { - SourceMap { - files: Default::default(), - file_loader: Box::new(RealFileLoader), - path_mapping, - } - } - - pub fn with_file_loader(file_loader: Box<dyn FileLoader + Sync + Send>, - path_mapping: FilePathMapping) - -> SourceMap { - SourceMap { - files: Default::default(), - file_loader, - path_mapping, - } - } - - pub fn path_mapping(&self) -> &FilePathMapping { - &self.path_mapping - } - - pub fn file_exists(&self, path: &Path) -> bool { - self.file_loader.file_exists(path) - } - - pub fn load_file(&self, path: &Path) -> io::Result<Lrc<SourceFile>> { - let src = self.file_loader.read_file(path)?; - let filename = path.to_owned().into(); - Ok(self.new_source_file(filename, src)) - } - - /// Loads source file as a binary blob. - /// - /// Unlike `load_file`, guarantees that no normalization like BOM-removal - /// takes place. - pub fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>> { - // Ideally, this should use `self.file_loader`, but it can't - // deal with binary files yet. - let bytes = fs::read(path)?; - - // We need to add file to the `SourceMap`, so that it is present - // in dep-info. There's also an edge case that file might be both - // loaded as a binary via `include_bytes!` and as proper `SourceFile` - // via `mod`, so we try to use real file contents and not just an - // empty string. - let text = std::str::from_utf8(&bytes).unwrap_or("") - .to_string(); - self.new_source_file(path.to_owned().into(), text); - Ok(bytes) - } - - pub fn files(&self) -> MappedLockGuard<'_, Vec<Lrc<SourceFile>>> { - LockGuard::map(self.files.borrow(), |files| &mut files.source_files) - } - - pub fn source_file_by_stable_id(&self, stable_id: StableSourceFileId) -> - Option<Lrc<SourceFile>> { - self.files.borrow().stable_id_to_source_file.get(&stable_id).map(|sf| sf.clone()) - } - - fn next_start_pos(&self) -> usize { - match self.files.borrow().source_files.last() { - None => 0, - // Add one so there is some space between files. This lets us distinguish - // positions in the `SourceMap`, even in the presence of zero-length files. - Some(last) => last.end_pos.to_usize() + 1, - } - } - - /// Creates a new `SourceFile`. - /// If a file already exists in the `SourceMap` with the same ID, that file is returned - /// unmodified. - pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc<SourceFile> { - self.try_new_source_file(filename, src) - .unwrap_or_else(|OffsetOverflowError| { - eprintln!("fatal error: rustc does not support files larger than 4GB"); - errors::FatalError.raise() - }) - } - - fn try_new_source_file( - &self, - filename: FileName, - src: String - ) -> Result<Lrc<SourceFile>, OffsetOverflowError> { - let start_pos = self.next_start_pos(); - - // The path is used to determine the directory for loading submodules and - // include files, so it must be before remapping. - // Note that filename may not be a valid path, eg it may be `<anon>` etc, - // but this is okay because the directory determined by `path.pop()` will - // be empty, so the working directory will be used. - let unmapped_path = filename.clone(); - - let (filename, was_remapped) = match filename { - FileName::Real(filename) => { - let (filename, was_remapped) = self.path_mapping.map_prefix(filename); - (FileName::Real(filename), was_remapped) - }, - other => (other, false), - }; - - let file_id = StableSourceFileId::new_from_pieces(&filename, - was_remapped, - Some(&unmapped_path)); - - let lrc_sf = match self.source_file_by_stable_id(file_id) { - Some(lrc_sf) => lrc_sf, - None => { - let source_file = Lrc::new(SourceFile::new( - filename, - was_remapped, - unmapped_path, - src, - Pos::from_usize(start_pos), - )?); - - let mut files = self.files.borrow_mut(); - - files.source_files.push(source_file.clone()); - files.stable_id_to_source_file.insert(file_id, source_file.clone()); - - source_file - } - }; - Ok(lrc_sf) - } - - /// Allocates a new `SourceFile` representing a source file from an external - /// crate. The source code of such an "imported `SourceFile`" is not available, - /// but we still know enough to generate accurate debuginfo location - /// information for things inlined from other crates. - pub fn new_imported_source_file( - &self, - filename: FileName, - name_was_remapped: bool, - crate_of_origin: u32, - src_hash: u128, - name_hash: u128, - source_len: usize, - mut file_local_lines: Vec<BytePos>, - mut file_local_multibyte_chars: Vec<MultiByteChar>, - mut file_local_non_narrow_chars: Vec<NonNarrowChar>, - mut file_local_normalized_pos: Vec<NormalizedPos>, - ) -> Lrc<SourceFile> { - let start_pos = self.next_start_pos(); - - let end_pos = Pos::from_usize(start_pos + source_len); - let start_pos = Pos::from_usize(start_pos); - - for pos in &mut file_local_lines { - *pos = *pos + start_pos; - } - - for mbc in &mut file_local_multibyte_chars { - mbc.pos = mbc.pos + start_pos; - } - - for swc in &mut file_local_non_narrow_chars { - *swc = *swc + start_pos; - } - - for nc in &mut file_local_normalized_pos { - nc.pos = nc.pos + start_pos; - } - - let source_file = Lrc::new(SourceFile { - name: filename, - name_was_remapped, - unmapped_path: None, - crate_of_origin, - src: None, - src_hash, - external_src: Lock::new(ExternalSource::AbsentOk), - start_pos, - end_pos, - lines: file_local_lines, - multibyte_chars: file_local_multibyte_chars, - non_narrow_chars: file_local_non_narrow_chars, - normalized_pos: file_local_normalized_pos, - name_hash, - }); - - let mut files = self.files.borrow_mut(); - - files.source_files.push(source_file.clone()); - files.stable_id_to_source_file.insert(StableSourceFileId::new(&source_file), - source_file.clone()); - - source_file - } - - pub fn mk_substr_filename(&self, sp: Span) -> String { - let pos = self.lookup_char_pos(sp.lo()); - format!("<{}:{}:{}>", - pos.file.name, - pos.line, - pos.col.to_usize() + 1) - } - - // If there is a doctest offset, applies it to the line. - pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize { - return match file { - FileName::DocTest(_, offset) => { - return if *offset >= 0 { - orig + *offset as usize - } else { - orig - (-(*offset)) as usize - } - }, - _ => orig - } - } - - /// Looks up source information about a `BytePos`. - pub fn lookup_char_pos(&self, pos: BytePos) -> Loc { - let chpos = self.bytepos_to_file_charpos(pos); - match self.lookup_line(pos) { - Ok(SourceFileAndLine { sf: f, line: a }) => { - let line = a + 1; // Line numbers start at 1 - let linebpos = f.lines[a]; - let linechpos = self.bytepos_to_file_charpos(linebpos); - let col = chpos - linechpos; - - let col_display = { - let start_width_idx = f - .non_narrow_chars - .binary_search_by_key(&linebpos, |x| x.pos()) - .unwrap_or_else(|x| x); - let end_width_idx = f - .non_narrow_chars - .binary_search_by_key(&pos, |x| x.pos()) - .unwrap_or_else(|x| x); - let special_chars = end_width_idx - start_width_idx; - let non_narrow: usize = f - .non_narrow_chars[start_width_idx..end_width_idx] - .into_iter() - .map(|x| x.width()) - .sum(); - col.0 - special_chars + non_narrow - }; - debug!("byte pos {:?} is on the line at byte pos {:?}", - pos, linebpos); - debug!("char pos {:?} is on the line at char pos {:?}", - chpos, linechpos); - debug!("byte is on line: {}", line); - assert!(chpos >= linechpos); - Loc { - file: f, - line, - col, - col_display, - } - } - Err(f) => { - let col_display = { - let end_width_idx = f - .non_narrow_chars - .binary_search_by_key(&pos, |x| x.pos()) - .unwrap_or_else(|x| x); - let non_narrow: usize = f - .non_narrow_chars[0..end_width_idx] - .into_iter() - .map(|x| x.width()) - .sum(); - chpos.0 - end_width_idx + non_narrow - }; - Loc { - file: f, - line: 0, - col: chpos, - col_display, - } - } - } - } - - // If the corresponding `SourceFile` is empty, does not return a line number. - pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Lrc<SourceFile>> { - let idx = self.lookup_source_file_idx(pos); - - let f = (*self.files.borrow().source_files)[idx].clone(); - - match f.lookup_line(pos) { - Some(line) => Ok(SourceFileAndLine { sf: f, line }), - None => Err(f) - } - } - - /// Returns `Some(span)`, a union of the LHS and RHS span. The LHS must precede the RHS. If - /// there are gaps between LHS and RHS, the resulting union will cross these gaps. - /// For this to work, - /// - /// * the syntax contexts of both spans much match, - /// * the LHS span needs to end on the same line the RHS span begins, - /// * the LHS span must start at or before the RHS span. - pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> { - // Ensure we're at the same expansion ID. - if sp_lhs.ctxt() != sp_rhs.ctxt() { - return None; - } - - let lhs_end = match self.lookup_line(sp_lhs.hi()) { - Ok(x) => x, - Err(_) => return None - }; - let rhs_begin = match self.lookup_line(sp_rhs.lo()) { - Ok(x) => x, - Err(_) => return None - }; - - // If we must cross lines to merge, don't merge. - if lhs_end.line != rhs_begin.line { - return None; - } - - // Ensure these follow the expected order and that we don't overlap. - if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) { - Some(sp_lhs.to(sp_rhs)) - } else { - None - } - } - - pub fn span_to_string(&self, sp: Span) -> String { - if self.files.borrow().source_files.is_empty() && sp.is_dummy() { - return "no-location".to_string(); - } - - let lo = self.lookup_char_pos(sp.lo()); - let hi = self.lookup_char_pos(sp.hi()); - format!("{}:{}:{}: {}:{}", - lo.file.name, - lo.line, - lo.col.to_usize() + 1, - hi.line, - hi.col.to_usize() + 1, - ) - } - - pub fn span_to_filename(&self, sp: Span) -> FileName { - self.lookup_char_pos(sp.lo()).file.name.clone() - } - - pub fn span_to_unmapped_path(&self, sp: Span) -> FileName { - self.lookup_char_pos(sp.lo()).file.unmapped_path.clone() - .expect("`SourceMap::span_to_unmapped_path` called for imported `SourceFile`?") - } - - pub fn is_multiline(&self, sp: Span) -> bool { - let lo = self.lookup_char_pos(sp.lo()); - let hi = self.lookup_char_pos(sp.hi()); - lo.line != hi.line - } - - pub fn span_to_lines(&self, sp: Span) -> FileLinesResult { - debug!("span_to_lines(sp={:?})", sp); - - let lo = self.lookup_char_pos(sp.lo()); - debug!("span_to_lines: lo={:?}", lo); - let hi = self.lookup_char_pos(sp.hi()); - debug!("span_to_lines: hi={:?}", hi); - - if lo.file.start_pos != hi.file.start_pos { - return Err(SpanLinesError::DistinctSources(DistinctSources { - begin: (lo.file.name.clone(), lo.file.start_pos), - end: (hi.file.name.clone(), hi.file.start_pos), - })); - } - assert!(hi.line >= lo.line); - - let mut lines = Vec::with_capacity(hi.line - lo.line + 1); - - // The span starts partway through the first line, - // but after that it starts from offset 0. - let mut start_col = lo.col; - - // For every line but the last, it extends from `start_col` - // and to the end of the line. Be careful because the line - // numbers in Loc are 1-based, so we subtract 1 to get 0-based - // lines. - for line_index in lo.line-1 .. hi.line-1 { - let line_len = lo.file.get_line(line_index) - .map(|s| s.chars().count()) - .unwrap_or(0); - lines.push(LineInfo { line_index, - start_col, - end_col: CharPos::from_usize(line_len) }); - start_col = CharPos::from_usize(0); - } - - // For the last line, it extends from `start_col` to `hi.col`: - lines.push(LineInfo { line_index: hi.line - 1, - start_col, - end_col: hi.col }); - - Ok(FileLines {file: lo.file, lines}) - } - - /// Extracts the source surrounding the given `Span` using the `extract_source` function. The - /// extract function takes three arguments: a string slice containing the source, an index in - /// the slice for the beginning of the span and an index in the slice for the end of the span. - fn span_to_source<F>(&self, sp: Span, extract_source: F) -> Result<String, SpanSnippetError> - where F: Fn(&str, usize, usize) -> Result<String, SpanSnippetError> - { - let local_begin = self.lookup_byte_offset(sp.lo()); - let local_end = self.lookup_byte_offset(sp.hi()); - - if local_begin.sf.start_pos != local_end.sf.start_pos { - return Err(SpanSnippetError::DistinctSources(DistinctSources { - begin: (local_begin.sf.name.clone(), - local_begin.sf.start_pos), - end: (local_end.sf.name.clone(), - local_end.sf.start_pos) - })); - } else { - self.ensure_source_file_source_present(local_begin.sf.clone()); - - let start_index = local_begin.pos.to_usize(); - let end_index = local_end.pos.to_usize(); - let source_len = (local_begin.sf.end_pos - - local_begin.sf.start_pos).to_usize(); - - if start_index > end_index || end_index > source_len { - return Err(SpanSnippetError::MalformedForSourcemap( - MalformedSourceMapPositions { - name: local_begin.sf.name.clone(), - source_len, - begin_pos: local_begin.pos, - end_pos: local_end.pos, - })); - } - - if let Some(ref src) = local_begin.sf.src { - return extract_source(src, start_index, end_index); - } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() { - return extract_source(src, start_index, end_index); - } else { - return Err(SpanSnippetError::SourceNotAvailable { - filename: local_begin.sf.name.clone() - }); - } - } - } - - /// Returns the source snippet as `String` corresponding to the given `Span`. - pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> { - self.span_to_source(sp, |src, start_index, end_index| src.get(start_index..end_index) - .map(|s| s.to_string()) - .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp))) - } - - pub fn span_to_margin(&self, sp: Span) -> Option<usize> { - match self.span_to_prev_source(sp) { - Err(_) => None, - Ok(source) => source.split('\n').last().map(|last_line| { - last_line.len() - last_line.trim_start().len() - }) - } - } - - /// Returns the source snippet as `String` before the given `Span`. - pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> { - self.span_to_source(sp, |src, start_index, _| src.get(..start_index) - .map(|s| s.to_string()) - .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp))) - } - - /// Extends the given `Span` to just after the previous occurrence of `c`. Return the same span - /// if no character could be found or if an error occurred while retrieving the code snippet. - pub fn span_extend_to_prev_char(&self, sp: Span, c: char) -> Span { - if let Ok(prev_source) = self.span_to_prev_source(sp) { - let prev_source = prev_source.rsplit(c).nth(0).unwrap_or("").trim_start(); - if !prev_source.is_empty() && !prev_source.contains('\n') { - return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32)); - } - } - - sp - } - - /// Extends the given `Span` to just after the previous occurrence of `pat` when surrounded by - /// whitespace. Returns the same span if no character could be found or if an error occurred - /// while retrieving the code snippet. - pub fn span_extend_to_prev_str(&self, sp: Span, pat: &str, accept_newlines: bool) -> Span { - // assure that the pattern is delimited, to avoid the following - // fn my_fn() - // ^^^^ returned span without the check - // ---------- correct span - for ws in &[" ", "\t", "\n"] { - let pat = pat.to_owned() + ws; - if let Ok(prev_source) = self.span_to_prev_source(sp) { - let prev_source = prev_source.rsplit(&pat).nth(0).unwrap_or("").trim_start(); - if !prev_source.is_empty() && (!prev_source.contains('\n') || accept_newlines) { - return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32)); - } - } - } - - sp - } - - /// Given a `Span`, tries to get a shorter span ending before the first occurrence of `char` - /// `c`. - pub fn span_until_char(&self, sp: Span, c: char) -> Span { - match self.span_to_snippet(sp) { - Ok(snippet) => { - let snippet = snippet.split(c).nth(0).unwrap_or("").trim_end(); - if !snippet.is_empty() && !snippet.contains('\n') { - sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32)) - } else { - sp - } - } - _ => sp, - } - } - - /// Given a `Span`, tries to get a shorter span ending just after the first occurrence of `char` - /// `c`. - pub fn span_through_char(&self, sp: Span, c: char) -> Span { - if let Ok(snippet) = self.span_to_snippet(sp) { - if let Some(offset) = snippet.find(c) { - return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32)); - } - } - sp - } - - /// Given a `Span`, gets a new `Span` covering the first token and all its trailing whitespace - /// or the original `Span`. - /// - /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned. - pub fn span_until_non_whitespace(&self, sp: Span) -> Span { - let mut whitespace_found = false; - - self.span_take_while(sp, |c| { - if !whitespace_found && c.is_whitespace() { - whitespace_found = true; - } - - if whitespace_found && !c.is_whitespace() { - false - } else { - true - } - }) - } - - /// Given a `Span`, gets a new `Span` covering the first token without its trailing whitespace - /// or the original `Span` in case of error. - /// - /// If `sp` points to `"let mut x"`, then a span pointing at `"let"` will be returned. - pub fn span_until_whitespace(&self, sp: Span) -> Span { - self.span_take_while(sp, |c| !c.is_whitespace()) - } - - /// Given a `Span`, gets a shorter one until `predicate` yields `false`. - pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span - where P: for <'r> FnMut(&'r char) -> bool - { - if let Ok(snippet) = self.span_to_snippet(sp) { - let offset = snippet.chars() - .take_while(predicate) - .map(|c| c.len_utf8()) - .sum::<usize>(); - - sp.with_hi(BytePos(sp.lo().0 + (offset as u32))) - } else { - sp - } - } - - pub fn def_span(&self, sp: Span) -> Span { - self.span_until_char(sp, '{') - } - - /// Returns a new span representing just the start point of this span. - pub fn start_point(&self, sp: Span) -> Span { - let pos = sp.lo().0; - let width = self.find_width_of_character_at_span(sp, false); - let corrected_start_position = pos.checked_add(width).unwrap_or(pos); - let end_point = BytePos(cmp::max(corrected_start_position, sp.lo().0)); - sp.with_hi(end_point) - } - - /// Returns a new span representing just the end point of this span. - pub fn end_point(&self, sp: Span) -> Span { - let pos = sp.hi().0; - - let width = self.find_width_of_character_at_span(sp, false); - let corrected_end_position = pos.checked_sub(width).unwrap_or(pos); - - let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0)); - sp.with_lo(end_point) - } - - /// Returns a new span representing the next character after the end-point of this span. - pub fn next_point(&self, sp: Span) -> Span { - let start_of_next_point = sp.hi().0; - - let width = self.find_width_of_character_at_span(sp, true); - // If the width is 1, then the next span should point to the same `lo` and `hi`. However, - // in the case of a multibyte character, where the width != 1, the next span should - // span multiple bytes to include the whole character. - let end_of_next_point = start_of_next_point.checked_add( - width - 1).unwrap_or(start_of_next_point); - - let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point)); - Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt()) - } - - /// Finds the width of a character, either before or after the provided span. - fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 { - let sp = sp.data(); - if sp.lo == sp.hi { - debug!("find_width_of_character_at_span: early return empty span"); - return 1; - } - - let local_begin = self.lookup_byte_offset(sp.lo); - let local_end = self.lookup_byte_offset(sp.hi); - debug!("find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`", - local_begin, local_end); - - if local_begin.sf.start_pos != local_end.sf.start_pos { - debug!("find_width_of_character_at_span: begin and end are in different files"); - return 1; - } - - let start_index = local_begin.pos.to_usize(); - let end_index = local_end.pos.to_usize(); - debug!("find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`", - start_index, end_index); - - // Disregard indexes that are at the start or end of their spans, they can't fit bigger - // characters. - if (!forwards && end_index == usize::min_value()) || - (forwards && start_index == usize::max_value()) { - debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte"); - return 1; - } - - let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize(); - debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len); - // Ensure indexes are also not malformed. - if start_index > end_index || end_index > source_len { - debug!("find_width_of_character_at_span: source indexes are malformed"); - return 1; - } - - let src = local_begin.sf.external_src.borrow(); - - // We need to extend the snippet to the end of the src rather than to end_index so when - // searching forwards for boundaries we've got somewhere to search. - let snippet = if let Some(ref src) = local_begin.sf.src { - let len = src.len(); - (&src[start_index..len]) - } else if let Some(src) = src.get_source() { - let len = src.len(); - (&src[start_index..len]) - } else { - return 1; - }; - debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet); - - let mut target = if forwards { end_index + 1 } else { end_index - 1 }; - debug!("find_width_of_character_at_span: initial target=`{:?}`", target); - - while !snippet.is_char_boundary(target - start_index) && target < source_len { - target = if forwards { - target + 1 - } else { - match target.checked_sub(1) { - Some(target) => target, - None => { - break; - } - } - }; - debug!("find_width_of_character_at_span: target=`{:?}`", target); - } - debug!("find_width_of_character_at_span: final target=`{:?}`", target); - - if forwards { - (target - end_index) as u32 - } else { - (end_index - target) as u32 - } - } - - pub fn get_source_file(&self, filename: &FileName) -> Option<Lrc<SourceFile>> { - for sf in self.files.borrow().source_files.iter() { - if *filename == sf.name { - return Some(sf.clone()); - } - } - None - } - - /// For a global `BytePos`, computes the local offset within the containing `SourceFile`. - pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos { - let idx = self.lookup_source_file_idx(bpos); - let sf = (*self.files.borrow().source_files)[idx].clone(); - let offset = bpos - sf.start_pos; - SourceFileAndBytePos {sf, pos: offset} - } - - /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`. - pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { - let idx = self.lookup_source_file_idx(bpos); - let map = &(*self.files.borrow().source_files)[idx]; - - // The number of extra bytes due to multibyte chars in the `SourceFile`. - let mut total_extra_bytes = 0; - - for mbc in map.multibyte_chars.iter() { - debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); - if mbc.pos < bpos { - // Every character is at least one byte, so we only - // count the actual extra bytes. - total_extra_bytes += mbc.bytes as u32 - 1; - // We should never see a byte position in the middle of a - // character. - assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32); - } else { - break; - } - } - - assert!(map.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); - CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes as usize) - } - - // Returns the index of the `SourceFile` (in `self.files`) that contains `pos`. - pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize { - self.files.borrow().source_files.binary_search_by_key(&pos, |key| key.start_pos) - .unwrap_or_else(|p| p - 1) - } - - pub fn count_lines(&self) -> usize { - self.files().iter().fold(0, |a, f| a + f.count_lines()) - } - - - pub fn generate_fn_name_span(&self, span: Span) -> Option<Span> { - let prev_span = self.span_extend_to_prev_str(span, "fn", true); - self.span_to_snippet(prev_span).map(|snippet| { - let len = snippet.find(|c: char| !c.is_alphanumeric() && c != '_') - .expect("no label after fn"); - prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32)) - }).ok() - } - - /// Takes the span of a type parameter in a function signature and try to generate a span for - /// the function name (with generics) and a new snippet for this span with the pointed type - /// parameter as a new local type parameter. - /// - /// For instance: - /// ```rust,ignore (pseudo-Rust) - /// // Given span - /// fn my_function(param: T) - /// // ^ Original span - /// - /// // Result - /// fn my_function(param: T) - /// // ^^^^^^^^^^^ Generated span with snippet `my_function<T>` - /// ``` - /// - /// Attention: The method used is very fragile since it essentially duplicates the work of the - /// parser. If you need to use this function or something similar, please consider updating the - /// `SourceMap` functions and this function to something more robust. - pub fn generate_local_type_param_snippet(&self, span: Span) -> Option<(Span, String)> { - // Try to extend the span to the previous "fn" keyword to retrieve the function - // signature. - let sugg_span = self.span_extend_to_prev_str(span, "fn", false); - if sugg_span != span { - if let Ok(snippet) = self.span_to_snippet(sugg_span) { - // Consume the function name. - let mut offset = snippet.find(|c: char| !c.is_alphanumeric() && c != '_') - .expect("no label after fn"); - - // Consume the generics part of the function signature. - let mut bracket_counter = 0; - let mut last_char = None; - for c in snippet[offset..].chars() { - match c { - '<' => bracket_counter += 1, - '>' => bracket_counter -= 1, - '(' => if bracket_counter == 0 { break; } - _ => {} - } - offset += c.len_utf8(); - last_char = Some(c); - } - - // Adjust the suggestion span to encompass the function name with its generics. - let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32)); - - // Prepare the new suggested snippet to append the type parameter that triggered - // the error in the generics of the function signature. - let mut new_snippet = if last_char == Some('>') { - format!("{}, ", &snippet[..(offset - '>'.len_utf8())]) - } else { - format!("{}<", &snippet[..offset]) - }; - new_snippet.push_str( - &self.span_to_snippet(span).unwrap_or_else(|_| "T".to_string())); - new_snippet.push('>'); - - return Some((sugg_span, new_snippet)); - } - } - - None - } -} - -impl SourceMapper for SourceMap { - fn lookup_char_pos(&self, pos: BytePos) -> Loc { - self.lookup_char_pos(pos) - } - fn span_to_lines(&self, sp: Span) -> FileLinesResult { - self.span_to_lines(sp) - } - fn span_to_string(&self, sp: Span) -> String { - self.span_to_string(sp) - } - fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> { - self.span_to_snippet(sp) - } - fn span_to_filename(&self, sp: Span) -> FileName { - self.span_to_filename(sp) - } - fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> { - self.merge_spans(sp_lhs, sp_rhs) - } - fn call_span_if_macro(&self, sp: Span) -> Span { - if self.span_to_filename(sp.clone()).is_macros() { - let v = sp.macro_backtrace(); - if let Some(use_site) = v.last() { - return use_site.call_site; - } - } - sp - } - fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool { - source_file.add_external_src( - || match source_file.name { - FileName::Real(ref name) => self.file_loader.read_file(name).ok(), - _ => None, - } - ) - } - fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize { - self.doctest_offset_line(file, line) - } -} - -#[derive(Clone)] -pub struct FilePathMapping { - mapping: Vec<(PathBuf, PathBuf)>, -} - -impl FilePathMapping { - pub fn empty() -> FilePathMapping { - FilePathMapping { - mapping: vec![] - } - } - - pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping { - FilePathMapping { - mapping, - } - } - - /// Applies any path prefix substitution as defined by the mapping. - /// The return value is the remapped path and a boolean indicating whether - /// the path was affected by the mapping. - pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) { - // NOTE: We are iterating over the mapping entries from last to first - // because entries specified later on the command line should - // take precedence. - for &(ref from, ref to) in self.mapping.iter().rev() { - if let Ok(rest) = path.strip_prefix(from) { - return (to.join(rest), true); - } - } - - (path, false) - } -} diff --git a/src/libsyntax/source_map/tests.rs b/src/libsyntax/source_map/tests.rs deleted file mode 100644 index 15254336bbf..00000000000 --- a/src/libsyntax/source_map/tests.rs +++ /dev/null @@ -1,221 +0,0 @@ -use super::*; - -use rustc_data_structures::sync::Lrc; - -fn init_source_map() -> SourceMap { - let sm = SourceMap::new(FilePathMapping::empty()); - sm.new_source_file( - PathBuf::from("blork.rs").into(), - "first line.\nsecond line".to_string(), - ); - sm.new_source_file( - PathBuf::from("empty.rs").into(), - String::new(), - ); - sm.new_source_file( - PathBuf::from("blork2.rs").into(), - "first line.\nsecond line".to_string(), - ); - sm -} - -/// Tests `lookup_byte_offset`. -#[test] -fn t3() { - let sm = init_source_map(); - - let srcfbp1 = sm.lookup_byte_offset(BytePos(23)); - assert_eq!(srcfbp1.sf.name, PathBuf::from("blork.rs").into()); - assert_eq!(srcfbp1.pos, BytePos(23)); - - let srcfbp1 = sm.lookup_byte_offset(BytePos(24)); - assert_eq!(srcfbp1.sf.name, PathBuf::from("empty.rs").into()); - assert_eq!(srcfbp1.pos, BytePos(0)); - - let srcfbp2 = sm.lookup_byte_offset(BytePos(25)); - assert_eq!(srcfbp2.sf.name, PathBuf::from("blork2.rs").into()); - assert_eq!(srcfbp2.pos, BytePos(0)); -} - -/// Tests `bytepos_to_file_charpos`. -#[test] -fn t4() { - let sm = init_source_map(); - - let cp1 = sm.bytepos_to_file_charpos(BytePos(22)); - assert_eq!(cp1, CharPos(22)); - - let cp2 = sm.bytepos_to_file_charpos(BytePos(25)); - assert_eq!(cp2, CharPos(0)); -} - -/// Tests zero-length `SourceFile`s. -#[test] -fn t5() { - let sm = init_source_map(); - - let loc1 = sm.lookup_char_pos(BytePos(22)); - assert_eq!(loc1.file.name, PathBuf::from("blork.rs").into()); - assert_eq!(loc1.line, 2); - assert_eq!(loc1.col, CharPos(10)); - - let loc2 = sm.lookup_char_pos(BytePos(25)); - assert_eq!(loc2.file.name, PathBuf::from("blork2.rs").into()); - assert_eq!(loc2.line, 1); - assert_eq!(loc2.col, CharPos(0)); -} - -fn init_source_map_mbc() -> SourceMap { - let sm = SourceMap::new(FilePathMapping::empty()); - // "€" is a three-byte UTF8 char. - sm.new_source_file(PathBuf::from("blork.rs").into(), - "fir€st €€€€ line.\nsecond line".to_string()); - sm.new_source_file(PathBuf::from("blork2.rs").into(), - "first line€€.\n€ second line".to_string()); - sm -} - -/// Tests `bytepos_to_file_charpos` in the presence of multi-byte chars. -#[test] -fn t6() { - let sm = init_source_map_mbc(); - - let cp1 = sm.bytepos_to_file_charpos(BytePos(3)); - assert_eq!(cp1, CharPos(3)); - - let cp2 = sm.bytepos_to_file_charpos(BytePos(6)); - assert_eq!(cp2, CharPos(4)); - - let cp3 = sm.bytepos_to_file_charpos(BytePos(56)); - assert_eq!(cp3, CharPos(12)); - - let cp4 = sm.bytepos_to_file_charpos(BytePos(61)); - assert_eq!(cp4, CharPos(15)); -} - -/// Test `span_to_lines` for a span ending at the end of a `SourceFile`. -#[test] -fn t7() { - let sm = init_source_map(); - let span = Span::with_root_ctxt(BytePos(12), BytePos(23)); - let file_lines = sm.span_to_lines(span).unwrap(); - - assert_eq!(file_lines.file.name, PathBuf::from("blork.rs").into()); - assert_eq!(file_lines.lines.len(), 1); - assert_eq!(file_lines.lines[0].line_index, 1); -} - -/// Given a string like " ~~~~~~~~~~~~ ", produces a span -/// converting that range. The idea is that the string has the same -/// length as the input, and we uncover the byte positions. Note -/// that this can span lines and so on. -fn span_from_selection(input: &str, selection: &str) -> Span { - assert_eq!(input.len(), selection.len()); - let left_index = selection.find('~').unwrap() as u32; - let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index); - Span::with_root_ctxt(BytePos(left_index), BytePos(right_index + 1)) -} - -/// Tests `span_to_snippet` and `span_to_lines` for a span converting 3 -/// lines in the middle of a file. -#[test] -fn span_to_snippet_and_lines_spanning_multiple_lines() { - let sm = SourceMap::new(FilePathMapping::empty()); - let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n"; - let selection = " \n ~~\n~~~\n~~~~~ \n \n"; - sm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_string()); - let span = span_from_selection(inputtext, selection); - - // Check that we are extracting the text we thought we were extracting. - assert_eq!(&sm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD"); - - // Check that span_to_lines gives us the complete result with the lines/cols we expected. - let lines = sm.span_to_lines(span).unwrap(); - let expected = vec![ - LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) }, - LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) }, - LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) } - ]; - assert_eq!(lines.lines, expected); -} - -/// Test span_to_snippet for a span ending at the end of a `SourceFile`. -#[test] -fn t8() { - let sm = init_source_map(); - let span = Span::with_root_ctxt(BytePos(12), BytePos(23)); - let snippet = sm.span_to_snippet(span); - - assert_eq!(snippet, Ok("second line".to_string())); -} - -/// Test `span_to_str` for a span ending at the end of a `SourceFile`. -#[test] -fn t9() { - let sm = init_source_map(); - let span = Span::with_root_ctxt(BytePos(12), BytePos(23)); - let sstr = sm.span_to_string(span); - - assert_eq!(sstr, "blork.rs:2:1: 2:12"); -} - -/// Tests failing to merge two spans on different lines. -#[test] -fn span_merging_fail() { - let sm = SourceMap::new(FilePathMapping::empty()); - let inputtext = "bbbb BB\ncc CCC\n"; - let selection1 = " ~~\n \n"; - let selection2 = " \n ~~~\n"; - sm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_owned()); - let span1 = span_from_selection(inputtext, selection1); - let span2 = span_from_selection(inputtext, selection2); - - assert!(sm.merge_spans(span1, span2).is_none()); -} - -/// Returns the span corresponding to the `n`th occurrence of `substring` in `source_text`. -trait SourceMapExtension { - fn span_substr( - &self, - file: &Lrc<SourceFile>, - source_text: &str, - substring: &str, - n: usize, - ) -> Span; -} - -impl SourceMapExtension for SourceMap { - fn span_substr( - &self, - file: &Lrc<SourceFile>, - source_text: &str, - substring: &str, - n: usize, - ) -> Span { - println!( - "span_substr(file={:?}/{:?}, substring={:?}, n={})", - file.name, file.start_pos, substring, n - ); - let mut i = 0; - let mut hi = 0; - loop { - let offset = source_text[hi..].find(substring).unwrap_or_else(|| { - panic!( - "source_text `{}` does not have {} occurrences of `{}`, only {}", - source_text, n, substring, i - ); - }); - let lo = hi + offset; - hi = lo + substring.len(); - if i == n { - let span = Span::with_root_ctxt( - BytePos(lo as u32 + file.start_pos.0), - BytePos(hi as u32 + file.start_pos.0), - ); - assert_eq!(&self.span_to_snippet(span).unwrap()[..], substring); - return span; - } - i += 1; - } - } -} diff --git a/src/libsyntax/tests.rs b/src/libsyntax/tests.rs deleted file mode 100644 index ed457c3627f..00000000000 --- a/src/libsyntax/tests.rs +++ /dev/null @@ -1,1255 +0,0 @@ -use crate::ast; -use crate::parse::source_file_to_stream; -use crate::parse::new_parser_from_source_str; -use crate::parse::parser::Parser; -use crate::sess::ParseSess; -use crate::source_map::{SourceMap, FilePathMapping}; -use crate::tokenstream::TokenStream; -use crate::with_default_globals; - -use errors::emitter::EmitterWriter; -use errors::{PResult, Handler}; -use rustc_data_structures::sync::Lrc; -use syntax_pos::{BytePos, Span, MultiSpan}; - -use std::io; -use std::io::prelude::*; -use std::iter::Peekable; -use std::path::{Path, PathBuf}; -use std::str; -use std::sync::{Arc, Mutex}; - -/// Map string to parser (via tts). -fn string_to_parser(ps: &ParseSess, source_str: String) -> Parser<'_> { - new_parser_from_source_str(ps, PathBuf::from("bogofile").into(), source_str) -} - -crate fn with_error_checking_parse<'a, T, F>(s: String, ps: &'a ParseSess, f: F) -> T where - F: FnOnce(&mut Parser<'a>) -> PResult<'a, T>, -{ - let mut p = string_to_parser(&ps, s); - let x = f(&mut p).unwrap(); - p.sess.span_diagnostic.abort_if_errors(); - x -} - -/// Maps a string to tts, using a made-up filename. -crate fn string_to_stream(source_str: String) -> TokenStream { - let ps = ParseSess::new(FilePathMapping::empty()); - source_file_to_stream( - &ps, - ps.source_map().new_source_file(PathBuf::from("bogofile").into(), - source_str, - ), None).0 -} - -/// Parses a string, returns a crate. -crate fn string_to_crate(source_str : String) -> ast::Crate { - let ps = ParseSess::new(FilePathMapping::empty()); - with_error_checking_parse(source_str, &ps, |p| { - p.parse_crate_mod() - }) -} - -/// Does the given string match the pattern? whitespace in the first string -/// may be deleted or replaced with other whitespace to match the pattern. -/// This function is relatively Unicode-ignorant; fortunately, the careful design -/// of UTF-8 mitigates this ignorance. It doesn't do NKF-normalization(?). -crate fn matches_codepattern(a : &str, b : &str) -> bool { - let mut a_iter = a.chars().peekable(); - let mut b_iter = b.chars().peekable(); - - loop { - let (a, b) = match (a_iter.peek(), b_iter.peek()) { - (None, None) => return true, - (None, _) => return false, - (Some(&a), None) => { - if rustc_lexer::is_whitespace(a) { - break // Trailing whitespace check is out of loop for borrowck. - } else { - return false - } - } - (Some(&a), Some(&b)) => (a, b) - }; - - if rustc_lexer::is_whitespace(a) && rustc_lexer::is_whitespace(b) { - // Skip whitespace for `a` and `b`. - scan_for_non_ws_or_end(&mut a_iter); - scan_for_non_ws_or_end(&mut b_iter); - } else if rustc_lexer::is_whitespace(a) { - // Skip whitespace for `a`. - scan_for_non_ws_or_end(&mut a_iter); - } else if a == b { - a_iter.next(); - b_iter.next(); - } else { - return false - } - } - - // Check if a has *only* trailing whitespace. - a_iter.all(rustc_lexer::is_whitespace) -} - -/// Advances the given peekable `Iterator` until it reaches a non-whitespace character. -fn scan_for_non_ws_or_end<I: Iterator<Item = char>>(iter: &mut Peekable<I>) { - while iter.peek().copied().map(|c| rustc_lexer::is_whitespace(c)) == Some(true) { - iter.next(); - } -} - -/// Identifies a position in the text by the n'th occurrence of a string. -struct Position { - string: &'static str, - count: usize, -} - -struct SpanLabel { - start: Position, - end: Position, - label: &'static str, -} - -crate struct Shared<T: Write> { - pub data: Arc<Mutex<T>>, -} - -impl<T: Write> Write for Shared<T> { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.data.lock().unwrap().write(buf) - } - - fn flush(&mut self) -> io::Result<()> { - self.data.lock().unwrap().flush() - } -} - -fn test_harness(file_text: &str, span_labels: Vec<SpanLabel>, expected_output: &str) { - with_default_globals(|| { - let output = Arc::new(Mutex::new(Vec::new())); - - let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty())); - source_map.new_source_file(Path::new("test.rs").to_owned().into(), file_text.to_owned()); - - let primary_span = make_span(&file_text, &span_labels[0].start, &span_labels[0].end); - let mut msp = MultiSpan::from_span(primary_span); - for span_label in span_labels { - let span = make_span(&file_text, &span_label.start, &span_label.end); - msp.push_span_label(span, span_label.label.to_string()); - println!("span: {:?} label: {:?}", span, span_label.label); - println!("text: {:?}", source_map.span_to_snippet(span)); - } - - let emitter = EmitterWriter::new( - Box::new(Shared { data: output.clone() }), - Some(source_map.clone()), - false, - false, - false, - None, - false, - ); - let handler = Handler::with_emitter(true, None, Box::new(emitter)); - handler.span_err(msp, "foo"); - - assert!(expected_output.chars().next() == Some('\n'), - "expected output should begin with newline"); - let expected_output = &expected_output[1..]; - - let bytes = output.lock().unwrap(); - let actual_output = str::from_utf8(&bytes).unwrap(); - println!("expected output:\n------\n{}------", expected_output); - println!("actual output:\n------\n{}------", actual_output); - - assert!(expected_output == actual_output) - }) -} - -fn make_span(file_text: &str, start: &Position, end: &Position) -> Span { - let start = make_pos(file_text, start); - let end = make_pos(file_text, end) + end.string.len(); // just after matching thing ends - assert!(start <= end); - Span::with_root_ctxt(BytePos(start as u32), BytePos(end as u32)) -} - -fn make_pos(file_text: &str, pos: &Position) -> usize { - let mut remainder = file_text; - let mut offset = 0; - for _ in 0..pos.count { - if let Some(n) = remainder.find(&pos.string) { - offset += n; - remainder = &remainder[n + 1..]; - } else { - panic!("failed to find {} instances of {:?} in {:?}", - pos.count, - pos.string, - file_text); - } - } - offset -} - -#[test] -fn ends_on_col0() { - test_harness(r#" -fn foo() { -} -"#, - vec![ - SpanLabel { - start: Position { - string: "{", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "test", - }, - ], - r#" -error: foo - --> test.rs:2:10 - | -2 | fn foo() { - | __________^ -3 | | } - | |_^ test - -"#); -} - -#[test] -fn ends_on_col2() { - test_harness(r#" -fn foo() { - - - } -"#, - vec![ - SpanLabel { - start: Position { - string: "{", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "test", - }, - ], - r#" -error: foo - --> test.rs:2:10 - | -2 | fn foo() { - | __________^ -3 | | -4 | | -5 | | } - | |___^ test - -"#); -} -#[test] -fn non_nested() { - test_harness(r#" -fn foo() { - X0 Y0 - X1 Y1 - X2 Y2 -} -"#, - vec![ - SpanLabel { - start: Position { - string: "X0", - count: 1, - }, - end: Position { - string: "X2", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "Y2", - count: 1, - }, - label: "`Y` is a good letter too", - }, - ], - r#" -error: foo - --> test.rs:3:3 - | -3 | X0 Y0 - | ____^__- - | | ___| - | || -4 | || X1 Y1 -5 | || X2 Y2 - | ||____^__- `Y` is a good letter too - | |____| - | `X` is a good letter - -"#); -} - -#[test] -fn nested() { - test_harness(r#" -fn foo() { - X0 Y0 - Y1 X1 -} -"#, - vec![ - SpanLabel { - start: Position { - string: "X0", - count: 1, - }, - end: Position { - string: "X1", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "Y1", - count: 1, - }, - label: "`Y` is a good letter too", - }, - ], -r#" -error: foo - --> test.rs:3:3 - | -3 | X0 Y0 - | ____^__- - | | ___| - | || -4 | || Y1 X1 - | ||____-__^ `X` is a good letter - | |_____| - | `Y` is a good letter too - -"#); -} - -#[test] -fn different_overlap() { - test_harness(r#" -fn foo() { - X0 Y0 Z0 - X1 Y1 Z1 - X2 Y2 Z2 - X3 Y3 Z3 -} -"#, - vec![ - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "X2", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Z1", - count: 1, - }, - end: Position { - string: "X3", - count: 1, - }, - label: "`Y` is a good letter too", - }, - ], - r#" -error: foo - --> test.rs:3:6 - | -3 | X0 Y0 Z0 - | ______^ -4 | | X1 Y1 Z1 - | |_________- -5 | || X2 Y2 Z2 - | ||____^ `X` is a good letter -6 | | X3 Y3 Z3 - | |_____- `Y` is a good letter too - -"#); -} - -#[test] -fn triple_overlap() { - test_harness(r#" -fn foo() { - X0 Y0 Z0 - X1 Y1 Z1 - X2 Y2 Z2 -} -"#, - vec![ - SpanLabel { - start: Position { - string: "X0", - count: 1, - }, - end: Position { - string: "X2", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "Y2", - count: 1, - }, - label: "`Y` is a good letter too", - }, - SpanLabel { - start: Position { - string: "Z0", - count: 1, - }, - end: Position { - string: "Z2", - count: 1, - }, - label: "`Z` label", - }, - ], - r#" -error: foo - --> test.rs:3:3 - | -3 | X0 Y0 Z0 - | _____^__-__- - | | ____|__| - | || ___| - | ||| -4 | ||| X1 Y1 Z1 -5 | ||| X2 Y2 Z2 - | |||____^__-__- `Z` label - | ||____|__| - | |____| `Y` is a good letter too - | `X` is a good letter - -"#); -} - -#[test] -fn triple_exact_overlap() { - test_harness(r#" -fn foo() { - X0 Y0 Z0 - X1 Y1 Z1 - X2 Y2 Z2 -} -"#, - vec![ - SpanLabel { - start: Position { - string: "X0", - count: 1, - }, - end: Position { - string: "X2", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "X0", - count: 1, - }, - end: Position { - string: "X2", - count: 1, - }, - label: "`Y` is a good letter too", - }, - SpanLabel { - start: Position { - string: "X0", - count: 1, - }, - end: Position { - string: "X2", - count: 1, - }, - label: "`Z` label", - }, - ], - r#" -error: foo - --> test.rs:3:3 - | -3 | / X0 Y0 Z0 -4 | | X1 Y1 Z1 -5 | | X2 Y2 Z2 - | | ^ - | | | - | | `X` is a good letter - | |____`Y` is a good letter too - | `Z` label - -"#); -} - -#[test] -fn minimum_depth() { - test_harness(r#" -fn foo() { - X0 Y0 Z0 - X1 Y1 Z1 - X2 Y2 Z2 - X3 Y3 Z3 -} -"#, - vec![ - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "X1", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Y1", - count: 1, - }, - end: Position { - string: "Z2", - count: 1, - }, - label: "`Y` is a good letter too", - }, - SpanLabel { - start: Position { - string: "X2", - count: 1, - }, - end: Position { - string: "Y3", - count: 1, - }, - label: "`Z`", - }, - ], - r#" -error: foo - --> test.rs:3:6 - | -3 | X0 Y0 Z0 - | ______^ -4 | | X1 Y1 Z1 - | |____^_- - | ||____| - | | `X` is a good letter -5 | | X2 Y2 Z2 - | |____-______- `Y` is a good letter too - | ____| - | | -6 | | X3 Y3 Z3 - | |________- `Z` - -"#); -} - -#[test] -fn non_overlaping() { - test_harness(r#" -fn foo() { - X0 Y0 Z0 - X1 Y1 Z1 - X2 Y2 Z2 - X3 Y3 Z3 -} -"#, - vec![ - SpanLabel { - start: Position { - string: "X0", - count: 1, - }, - end: Position { - string: "X1", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Y2", - count: 1, - }, - end: Position { - string: "Z3", - count: 1, - }, - label: "`Y` is a good letter too", - }, - ], - r#" -error: foo - --> test.rs:3:3 - | -3 | / X0 Y0 Z0 -4 | | X1 Y1 Z1 - | |____^ `X` is a good letter -5 | X2 Y2 Z2 - | ______- -6 | | X3 Y3 Z3 - | |__________- `Y` is a good letter too - -"#); -} - -#[test] -fn overlaping_start_and_end() { - test_harness(r#" -fn foo() { - X0 Y0 Z0 - X1 Y1 Z1 - X2 Y2 Z2 - X3 Y3 Z3 -} -"#, - vec![ - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "X1", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Z1", - count: 1, - }, - end: Position { - string: "Z3", - count: 1, - }, - label: "`Y` is a good letter too", - }, - ], - r#" -error: foo - --> test.rs:3:6 - | -3 | X0 Y0 Z0 - | ______^ -4 | | X1 Y1 Z1 - | |____^____- - | ||____| - | | `X` is a good letter -5 | | X2 Y2 Z2 -6 | | X3 Y3 Z3 - | |___________- `Y` is a good letter too - -"#); -} - -#[test] -fn multiple_labels_primary_without_message() { - test_harness(r#" -fn foo() { - a { b { c } d } -} -"#, - vec![ - SpanLabel { - start: Position { - string: "b", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "", - }, - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "`a` is a good letter", - }, - SpanLabel { - start: Position { - string: "c", - count: 1, - }, - end: Position { - string: "c", - count: 1, - }, - label: "", - }, - ], - r#" -error: foo - --> test.rs:3:7 - | -3 | a { b { c } d } - | ----^^^^-^^-- `a` is a good letter - -"#); -} - -#[test] -fn multiple_labels_secondary_without_message() { - test_harness(r#" -fn foo() { - a { b { c } d } -} -"#, - vec![ - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "`a` is a good letter", - }, - SpanLabel { - start: Position { - string: "b", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "", - }, - ], - r#" -error: foo - --> test.rs:3:3 - | -3 | a { b { c } d } - | ^^^^-------^^ `a` is a good letter - -"#); -} - -#[test] -fn multiple_labels_primary_without_message_2() { - test_harness(r#" -fn foo() { - a { b { c } d } -} -"#, - vec![ - SpanLabel { - start: Position { - string: "b", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "`b` is a good letter", - }, - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "", - }, - SpanLabel { - start: Position { - string: "c", - count: 1, - }, - end: Position { - string: "c", - count: 1, - }, - label: "", - }, - ], - r#" -error: foo - --> test.rs:3:7 - | -3 | a { b { c } d } - | ----^^^^-^^-- - | | - | `b` is a good letter - -"#); -} - -#[test] -fn multiple_labels_secondary_without_message_2() { - test_harness(r#" -fn foo() { - a { b { c } d } -} -"#, - vec![ - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "", - }, - SpanLabel { - start: Position { - string: "b", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "`b` is a good letter", - }, - ], - r#" -error: foo - --> test.rs:3:3 - | -3 | a { b { c } d } - | ^^^^-------^^ - | | - | `b` is a good letter - -"#); -} - -#[test] -fn multiple_labels_secondary_without_message_3() { - test_harness(r#" -fn foo() { - a bc d -} -"#, - vec![ - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "b", - count: 1, - }, - label: "`a` is a good letter", - }, - SpanLabel { - start: Position { - string: "c", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "", - }, - ], - r#" -error: foo - --> test.rs:3:3 - | -3 | a bc d - | ^^^^---- - | | - | `a` is a good letter - -"#); -} - -#[test] -fn multiple_labels_without_message() { - test_harness(r#" -fn foo() { - a { b { c } d } -} -"#, - vec![ - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "", - }, - SpanLabel { - start: Position { - string: "b", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "", - }, - ], - r#" -error: foo - --> test.rs:3:3 - | -3 | a { b { c } d } - | ^^^^-------^^ - -"#); -} - -#[test] -fn multiple_labels_without_message_2() { - test_harness(r#" -fn foo() { - a { b { c } d } -} -"#, - vec![ - SpanLabel { - start: Position { - string: "b", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "", - }, - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "", - }, - SpanLabel { - start: Position { - string: "c", - count: 1, - }, - end: Position { - string: "c", - count: 1, - }, - label: "", - }, - ], - r#" -error: foo - --> test.rs:3:7 - | -3 | a { b { c } d } - | ----^^^^-^^-- - -"#); -} - -#[test] -fn multiple_labels_with_message() { - test_harness(r#" -fn foo() { - a { b { c } d } -} -"#, - vec![ - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "`a` is a good letter", - }, - SpanLabel { - start: Position { - string: "b", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "`b` is a good letter", - }, - ], - r#" -error: foo - --> test.rs:3:3 - | -3 | a { b { c } d } - | ^^^^-------^^ - | | | - | | `b` is a good letter - | `a` is a good letter - -"#); -} - -#[test] -fn single_label_with_message() { - test_harness(r#" -fn foo() { - a { b { c } d } -} -"#, - vec![ - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "`a` is a good letter", - }, - ], - r#" -error: foo - --> test.rs:3:3 - | -3 | a { b { c } d } - | ^^^^^^^^^^^^^ `a` is a good letter - -"#); -} - -#[test] -fn single_label_without_message() { - test_harness(r#" -fn foo() { - a { b { c } d } -} -"#, - vec![ - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "", - }, - ], - r#" -error: foo - --> test.rs:3:3 - | -3 | a { b { c } d } - | ^^^^^^^^^^^^^ - -"#); -} - -#[test] -fn long_snippet() { - test_harness(r#" -fn foo() { - X0 Y0 Z0 - X1 Y1 Z1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 - X2 Y2 Z2 - X3 Y3 Z3 -} -"#, - vec![ - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "X1", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Z1", - count: 1, - }, - end: Position { - string: "Z3", - count: 1, - }, - label: "`Y` is a good letter too", - }, - ], - r#" -error: foo - --> test.rs:3:6 - | -3 | X0 Y0 Z0 - | ______^ -4 | | X1 Y1 Z1 - | |____^____- - | ||____| - | | `X` is a good letter -5 | | 1 -6 | | 2 -7 | | 3 -... | -15 | | X2 Y2 Z2 -16 | | X3 Y3 Z3 - | |___________- `Y` is a good letter too - -"#); -} - -#[test] -fn long_snippet_multiple_spans() { - test_harness(r#" -fn foo() { - X0 Y0 Z0 -1 -2 -3 - X1 Y1 Z1 -4 -5 -6 - X2 Y2 Z2 -7 -8 -9 -10 - X3 Y3 Z3 -} -"#, - vec![ - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "Y3", - count: 1, - }, - label: "`Y` is a good letter", - }, - SpanLabel { - start: Position { - string: "Z1", - count: 1, - }, - end: Position { - string: "Z2", - count: 1, - }, - label: "`Z` is a good letter too", - }, - ], - r#" -error: foo - --> test.rs:3:6 - | -3 | X0 Y0 Z0 - | ______^ -4 | | 1 -5 | | 2 -6 | | 3 -7 | | X1 Y1 Z1 - | |_________- -8 | || 4 -9 | || 5 -10 | || 6 -11 | || X2 Y2 Z2 - | ||__________- `Z` is a good letter too -... | -15 | | 10 -16 | | X3 Y3 Z3 - | |_______^ `Y` is a good letter - -"#); -} diff --git a/src/libsyntax/token.rs b/src/libsyntax/token.rs index 6f3da344ccf..6f45211ac5f 100644 --- a/src/libsyntax/token.rs +++ b/src/libsyntax/token.rs @@ -14,11 +14,12 @@ use syntax_pos::{self, Span, DUMMY_SP}; use std::fmt; use std::mem; -#[cfg(target_arch = "x86_64")] -use rustc_data_structures::static_assert_size; +use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::Lrc; +use rustc_macros::HashStable_Generic; #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +#[derive(HashStable_Generic)] pub enum BinOpToken { Plus, Minus, @@ -34,6 +35,7 @@ pub enum BinOpToken { /// A delimiter token. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] +#[derive(HashStable_Generic)] pub enum DelimToken { /// A round parenthesis (i.e., `(` or `)`). Paren, @@ -55,7 +57,7 @@ impl DelimToken { } } -#[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)] +#[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub enum LitKind { Bool, // AST only, must never appear in a `Token` Byte, @@ -70,7 +72,7 @@ pub enum LitKind { } /// A literal token. -#[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)] +#[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub struct Lit { pub kind: LitKind, pub symbol: Symbol, @@ -107,14 +109,14 @@ impl fmt::Display for Lit { impl LitKind { /// An English article for the literal token kind. - crate fn article(self) -> &'static str { + pub fn article(self) -> &'static str { match self { Integer | Err => "an", _ => "a", } } - crate fn descr(self) -> &'static str { + pub fn descr(self) -> &'static str { match self { Bool => panic!("literal token contains `Lit::Bool`"), Byte => "byte", @@ -141,12 +143,12 @@ impl Lit { } } -pub(crate) fn ident_can_begin_expr(name: ast::Name, span: Span, is_raw: bool) -> bool { +pub fn ident_can_begin_expr(name: ast::Name, span: Span, is_raw: bool) -> bool { let ident_token = Token::new(Ident(name, is_raw), span); token_can_begin_expr(&ident_token) } -pub(crate) fn token_can_begin_expr(ident_token: &Token) -> bool { +pub fn token_can_begin_expr(ident_token: &Token) -> bool { !ident_token.is_reserved_ident() || ident_token.is_path_segment_keyword() || match ident_token.kind { @@ -191,7 +193,7 @@ fn ident_can_begin_type(name: ast::Name, span: Span, is_raw: bool) -> bool { ].contains(&name) } -#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)] +#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub enum TokenKind { /* Expression-operator symbols. */ Eq, @@ -261,9 +263,9 @@ pub enum TokenKind { // `TokenKind` is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(target_arch = "x86_64")] -static_assert_size!(TokenKind, 16); +rustc_data_structures::static_assert_size!(TokenKind, 16); -#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)] +#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub struct Token { pub kind: TokenKind, pub span: Span, @@ -276,7 +278,7 @@ impl TokenKind { /// Returns tokens that are likely to be typed accidentally instead of the current token. /// Enables better error recovery when the wrong token is found. - crate fn similar_tokens(&self) -> Option<Vec<TokenKind>> { + pub fn similar_tokens(&self) -> Option<Vec<TokenKind>> { match *self { Comma => Some(vec![Dot, Lt, Semi]), Semi => Some(vec![Colon, Comma]), @@ -291,7 +293,7 @@ impl Token { } /// Some token that will be thrown away later. - crate fn dummy() -> Self { + pub fn dummy() -> Self { Token::new(TokenKind::Whitespace, DUMMY_SP) } @@ -305,7 +307,7 @@ impl Token { mem::replace(self, Token::dummy()) } - crate fn is_op(&self) -> bool { + pub fn is_op(&self) -> bool { match self.kind { OpenDelim(..) | CloseDelim(..) | Literal(..) | DocComment(..) | Ident(..) | Lifetime(..) | Interpolated(..) | @@ -314,7 +316,7 @@ impl Token { } } - crate fn is_like_plus(&self) -> bool { + pub fn is_like_plus(&self) -> bool { match self.kind { BinOp(Plus) | BinOpEq(Plus) => true, _ => false, @@ -377,7 +379,7 @@ impl Token { } /// Returns `true` if the token can appear at the start of a const param. - crate fn can_begin_const_arg(&self) -> bool { + pub fn can_begin_const_arg(&self) -> bool { match self.kind { OpenDelim(Brace) => true, Interpolated(ref nt) => match **nt { @@ -389,7 +391,7 @@ impl Token { } /// Returns `true` if the token can appear at the start of a generic bound. - crate fn can_begin_bound(&self) -> bool { + pub fn can_begin_bound(&self) -> bool { self.is_path_start() || self.is_lifetime() || self.is_keyword(kw::For) || self == &Question || self == &OpenDelim(Paren) } @@ -446,13 +448,13 @@ impl Token { } /// Returns `true` if the token is a lifetime. - crate fn is_lifetime(&self) -> bool { + pub fn is_lifetime(&self) -> bool { self.lifetime().is_some() } /// Returns `true` if the token is a identifier whose name is the given /// string slice. - crate fn is_ident_named(&self, name: Symbol) -> bool { + pub fn is_ident_named(&self, name: Symbol) -> bool { self.ident().map_or(false, |(ident, _)| ident.name == name) } @@ -469,7 +471,7 @@ impl Token { /// Would `maybe_whole_expr` in `parser.rs` return `Ok(..)`? /// That is, is this a pre-parsed expression dropped into the token stream /// (which happens while parsing the result of macro expansion)? - crate fn is_whole_expr(&self) -> bool { + pub fn is_whole_expr(&self) -> bool { if let Interpolated(ref nt) = self.kind { if let NtExpr(_) | NtLiteral(_) | NtPath(_) | NtIdent(..) | NtBlock(_) = **nt { return true; @@ -480,16 +482,16 @@ impl Token { } /// Returns `true` if the token is either the `mut` or `const` keyword. - crate fn is_mutability(&self) -> bool { + pub fn is_mutability(&self) -> bool { self.is_keyword(kw::Mut) || self.is_keyword(kw::Const) } - crate fn is_qpath_start(&self) -> bool { + pub fn is_qpath_start(&self) -> bool { self == &Lt || self == &BinOp(Shl) } - crate fn is_path_start(&self) -> bool { + pub fn is_path_start(&self) -> bool { self == &ModSep || self.is_qpath_start() || self.is_path() || self.is_path_segment_keyword() || self.is_ident() && !self.is_reserved_ident() } @@ -499,23 +501,23 @@ impl Token { self.is_non_raw_ident_where(|id| id.name == kw) } - crate fn is_path_segment_keyword(&self) -> bool { + pub fn is_path_segment_keyword(&self) -> bool { self.is_non_raw_ident_where(ast::Ident::is_path_segment_keyword) } // Returns true for reserved identifiers used internally for elided lifetimes, // unnamed method parameters, crate root module, error recovery etc. - crate fn is_special_ident(&self) -> bool { + pub fn is_special_ident(&self) -> bool { self.is_non_raw_ident_where(ast::Ident::is_special) } /// Returns `true` if the token is a keyword used in the language. - crate fn is_used_keyword(&self) -> bool { + pub fn is_used_keyword(&self) -> bool { self.is_non_raw_ident_where(ast::Ident::is_used_keyword) } /// Returns `true` if the token is a keyword reserved for possible future use. - crate fn is_unused_keyword(&self) -> bool { + pub fn is_unused_keyword(&self) -> bool { self.is_non_raw_ident_where(ast::Ident::is_unused_keyword) } @@ -525,7 +527,7 @@ impl Token { } /// Returns `true` if the token is the identifier `true` or `false`. - crate fn is_bool_lit(&self) -> bool { + pub fn is_bool_lit(&self) -> bool { self.is_non_raw_ident_where(|id| id.name.is_bool_lit()) } @@ -537,7 +539,7 @@ impl Token { } } - crate fn glue(&self, joint: &Token) -> Option<Token> { + pub fn glue(&self, joint: &Token) -> Option<Token> { let kind = match self.kind { Eq => match joint.kind { Eq => EqEq, @@ -726,3 +728,11 @@ impl fmt::Debug for Nonterminal { } } } + +impl<CTX> HashStable<CTX> for Nonterminal + where CTX: crate::HashStableContext +{ + fn hash_stable(&self, _hcx: &mut CTX, _hasher: &mut StableHasher) { + panic!("interpolated tokens should not be present in the HIR") + } +} diff --git a/src/libsyntax/tokenstream.rs b/src/libsyntax/tokenstream.rs index 6e1bb85ce1a..491b9a9ade4 100644 --- a/src/libsyntax/tokenstream.rs +++ b/src/libsyntax/tokenstream.rs @@ -16,16 +16,13 @@ use crate::token::{self, DelimToken, Token, TokenKind}; use syntax_pos::{Span, DUMMY_SP}; -#[cfg(target_arch = "x86_64")] -use rustc_data_structures::static_assert_size; +use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_macros::HashStable_Generic; use rustc_data_structures::sync::Lrc; use smallvec::{SmallVec, smallvec}; use std::{iter, mem}; -#[cfg(test)] -mod tests; - /// When the main rust parser encounters a syntax-extension invocation, it /// parses the arguments to the invocation as a token-tree. This is a very /// loose structure, such that all sorts of different AST-fragments can @@ -38,7 +35,7 @@ mod tests; /// /// The RHS of an MBE macro is the only place `SubstNt`s are substituted. /// Nothing special happens to misnamed or misplaced `SubstNt`s. -#[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)] +#[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)] pub enum TokenTree { /// A single token Token(Token), @@ -120,6 +117,16 @@ impl TokenTree { } } +impl<CTX> HashStable<CTX> for TokenStream + where CTX: crate::HashStableContext +{ + fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { + for sub_tt in self.trees() { + sub_tt.hash_stable(hcx, hasher); + } + } +} + /// A `TokenStream` is an abstract sequence of tokens, organized into `TokenTree`s. /// /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s @@ -132,7 +139,7 @@ pub type TreeAndJoint = (TokenTree, IsJoint); // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(target_arch = "x86_64")] -static_assert_size!(TokenStream, 8); +rustc_data_structures::static_assert_size!(TokenStream, 8); #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable, RustcDecodable)] pub enum IsJoint { @@ -218,7 +225,15 @@ impl TokenStream { self.0.len() } - pub(crate) fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream { + pub fn span(&self) -> Option<Span> { + match &**self.0 { + [] => None, + [(tt, _)] => Some(tt.span()), + [(tt_start, _), .., (tt_end, _)] => Some(tt_start.span().to(tt_end.span())), + } + } + + pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream { match streams.len() { 0 => TokenStream::default(), 1 => streams.pop().unwrap(), @@ -449,7 +464,7 @@ impl Cursor { } } -#[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)] +#[derive(Debug, Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)] pub struct DelimSpan { pub open: Span, pub close: Span, diff --git a/src/libsyntax/tokenstream/tests.rs b/src/libsyntax/tokenstream/tests.rs deleted file mode 100644 index 5017e5f5424..00000000000 --- a/src/libsyntax/tokenstream/tests.rs +++ /dev/null @@ -1,108 +0,0 @@ -use super::*; - -use crate::ast::Name; -use crate::with_default_globals; -use crate::tests::string_to_stream; -use syntax_pos::{Span, BytePos}; - -fn string_to_ts(string: &str) -> TokenStream { - string_to_stream(string.to_owned()) -} - -fn sp(a: u32, b: u32) -> Span { - Span::with_root_ctxt(BytePos(a), BytePos(b)) -} - -#[test] -fn test_concat() { - with_default_globals(|| { - let test_res = string_to_ts("foo::bar::baz"); - let test_fst = string_to_ts("foo::bar"); - let test_snd = string_to_ts("::baz"); - let eq_res = TokenStream::from_streams(smallvec![test_fst, test_snd]); - assert_eq!(test_res.trees().count(), 5); - assert_eq!(eq_res.trees().count(), 5); - assert_eq!(test_res.eq_unspanned(&eq_res), true); - }) -} - -#[test] -fn test_to_from_bijection() { - with_default_globals(|| { - let test_start = string_to_ts("foo::bar(baz)"); - let test_end = test_start.trees().collect(); - assert_eq!(test_start, test_end) - }) -} - -#[test] -fn test_eq_0() { - with_default_globals(|| { - let test_res = string_to_ts("foo"); - let test_eqs = string_to_ts("foo"); - assert_eq!(test_res, test_eqs) - }) -} - -#[test] -fn test_eq_1() { - with_default_globals(|| { - let test_res = string_to_ts("::bar::baz"); - let test_eqs = string_to_ts("::bar::baz"); - assert_eq!(test_res, test_eqs) - }) -} - -#[test] -fn test_eq_3() { - with_default_globals(|| { - let test_res = string_to_ts(""); - let test_eqs = string_to_ts(""); - assert_eq!(test_res, test_eqs) - }) -} - -#[test] -fn test_diseq_0() { - with_default_globals(|| { - let test_res = string_to_ts("::bar::baz"); - let test_eqs = string_to_ts("bar::baz"); - assert_eq!(test_res == test_eqs, false) - }) -} - -#[test] -fn test_diseq_1() { - with_default_globals(|| { - let test_res = string_to_ts("(bar,baz)"); - let test_eqs = string_to_ts("bar,baz"); - assert_eq!(test_res == test_eqs, false) - }) -} - -#[test] -fn test_is_empty() { - with_default_globals(|| { - let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect(); - let test1: TokenStream = - TokenTree::token(token::Ident(Name::intern("a"), false), sp(0, 1)).into(); - let test2 = string_to_ts("foo(bar::baz)"); - - assert_eq!(test0.is_empty(), true); - assert_eq!(test1.is_empty(), false); - assert_eq!(test2.is_empty(), false); - }) -} - -#[test] -fn test_dotdotdot() { - with_default_globals(|| { - let mut builder = TokenStreamBuilder::new(); - builder.push(TokenTree::token(token::Dot, sp(0, 1)).joint()); - builder.push(TokenTree::token(token::Dot, sp(1, 2)).joint()); - builder.push(TokenTree::token(token::Dot, sp(2, 3))); - let stream = builder.build(); - assert!(stream.eq_unspanned(&string_to_ts("..."))); - assert_eq!(stream.trees().count(), 1); - }) -} diff --git a/src/libsyntax/util/comments.rs b/src/libsyntax/util/comments.rs index 448b4f3b825..5e9b7bf8322 100644 --- a/src/libsyntax/util/comments.rs +++ b/src/libsyntax/util/comments.rs @@ -32,14 +32,14 @@ pub struct Comment { pub pos: BytePos, } -crate fn is_line_doc_comment(s: &str) -> bool { +pub fn is_line_doc_comment(s: &str) -> bool { let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') || s.starts_with("//!"); debug!("is {:?} a doc comment? {}", s, res); res } -crate fn is_block_doc_comment(s: &str) -> bool { +pub fn is_block_doc_comment(s: &str) -> bool { // Prevent `/**/` from being parsed as a doc comment let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') || s.starts_with("/*!")) && s.len() >= 5; @@ -47,7 +47,8 @@ crate fn is_block_doc_comment(s: &str) -> bool { res } -crate fn is_doc_comment(s: &str) -> bool { +// FIXME(#64197): Try to privatize this again. +pub fn is_doc_comment(s: &str) -> bool { (s.starts_with("///") && is_line_doc_comment(s)) || s.starts_with("//!") || (s.starts_with("/**") && is_block_doc_comment(s)) || s.starts_with("/*!") } diff --git a/src/libsyntax/util/lev_distance.rs b/src/libsyntax/util/lev_distance.rs index 4127a8c7fce..efb3c2396c3 100644 --- a/src/libsyntax/util/lev_distance.rs +++ b/src/libsyntax/util/lev_distance.rs @@ -77,6 +77,6 @@ pub fn find_best_match_for_name<'a, T>(iter_names: T, if let Some(candidate) = case_insensitive_match { Some(candidate) // exact case insensitive match has a higher priority } else { - if let Some((candidate, _)) = levenstein_match { Some(candidate) } else { None } + levenstein_match.map(|(candidate, _)| candidate) } } diff --git a/src/libsyntax/util/literal.rs b/src/libsyntax/util/literal.rs index d4c9b7850c5..af7afab6b9b 100644 --- a/src/libsyntax/util/literal.rs +++ b/src/libsyntax/util/literal.rs @@ -14,7 +14,7 @@ use rustc_lexer::unescape::{unescape_raw_str, unescape_raw_byte_str}; use std::ascii; -crate enum LitError { +pub enum LitError { NotLiteral, LexerError, InvalidSuffix, @@ -185,12 +185,12 @@ impl LitKind { impl Lit { /// Converts literal token into an AST literal. - crate fn from_lit_token(token: token::Lit, span: Span) -> Result<Lit, LitError> { + pub fn from_lit_token(token: token::Lit, span: Span) -> Result<Lit, LitError> { Ok(Lit { token, kind: LitKind::from_lit_token(token)?, span }) } /// Converts arbitrary token into an AST literal. - crate fn from_token(token: &Token) -> Result<Lit, LitError> { + pub fn from_token(token: &Token) -> Result<Lit, LitError> { let lit = match token.kind { token::Ident(name, false) if name.is_bool_lit() => token::Lit::new(token::Bool, name, None), @@ -217,8 +217,8 @@ impl Lit { Lit { token: kind.to_lit_token(), kind, span } } - /// Losslessly convert an AST literal into a token tree. - crate fn token_tree(&self) -> TokenTree { + /// Losslessly convert an AST literal into a token stream. + pub fn token_tree(&self) -> TokenTree { let token = match self.token.kind { token::Bool => token::Ident(self.token.symbol, false), _ => token::Literal(self.token), diff --git a/src/libsyntax/util/parser.rs b/src/libsyntax/util/parser.rs index edb708d7e97..df72fdc8014 100644 --- a/src/libsyntax/util/parser.rs +++ b/src/libsyntax/util/parser.rs @@ -69,7 +69,7 @@ pub enum Fixity { impl AssocOp { /// Creates a new AssocOP from a token - crate fn from_token(t: &Token) -> Option<AssocOp> { + pub fn from_token(t: &Token) -> Option<AssocOp> { use AssocOp::*; match t.kind { token::BinOpEq(k) => Some(AssignOp(k)), @@ -358,7 +358,7 @@ impl ExprPrecedence { } /// In `let p = e`, operators with precedence `<=` this one requires parenthesis in `e`. -crate fn prec_let_scrutinee_needs_par() -> usize { +pub fn prec_let_scrutinee_needs_par() -> usize { AssocOp::LAnd.precedence() } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index ea2dc357e6e..4ee09b4b87a 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -263,10 +263,6 @@ pub fn walk_item<'a, V: Visitor<'a>>(visitor: &mut V, item: &'a Item) { visitor.visit_ty(typ); visitor.visit_generics(generics) } - ItemKind::OpaqueTy(ref bounds, ref generics) => { - walk_list!(visitor, visit_param_bound, bounds); - visitor.visit_generics(generics) - } ItemKind::Enum(ref enum_definition, ref generics) => { visitor.visit_generics(generics); visitor.visit_enum_def(enum_definition, generics, item.id, item.span) @@ -314,6 +310,7 @@ pub fn walk_variant<'a, V: Visitor<'a>>(visitor: &mut V, variant: &'a Variant) where V: Visitor<'a>, { visitor.visit_ident(variant.ident); + visitor.visit_vis(&variant.vis); visitor.visit_variant_data(&variant.data); walk_list!(visitor, visit_anon_const, &variant.disr_expr); walk_list!(visitor, visit_attribute, &variant.attrs); @@ -585,6 +582,7 @@ pub fn walk_fn<'a, V>(visitor: &mut V, kind: FnKind<'a>, declaration: &'a FnDecl } pub fn walk_trait_item<'a, V: Visitor<'a>>(visitor: &mut V, trait_item: &'a TraitItem) { + visitor.visit_vis(&trait_item.vis); visitor.visit_ident(trait_item.ident); walk_list!(visitor, visit_attribute, &trait_item.attrs); visitor.visit_generics(&trait_item.generics); @@ -628,9 +626,6 @@ pub fn walk_impl_item<'a, V: Visitor<'a>>(visitor: &mut V, impl_item: &'a ImplIt ImplItemKind::TyAlias(ref ty) => { visitor.visit_ty(ty); } - ImplItemKind::OpaqueTy(ref bounds) => { - walk_list!(visitor, visit_param_bound, bounds); - } ImplItemKind::Macro(ref mac) => { visitor.visit_mac(mac); } @@ -713,7 +708,7 @@ pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) { visitor.visit_expr(left_expression); visitor.visit_expr(right_expression) } - ExprKind::AddrOf(_, ref subexpression) | ExprKind::Unary(_, ref subexpression) => { + ExprKind::AddrOf(_, _, ref subexpression) | ExprKind::Unary(_, ref subexpression) => { visitor.visit_expr(subexpression) } ExprKind::Cast(ref subexpression, ref typ) | ExprKind::Type(ref subexpression, ref typ) => { @@ -846,11 +841,19 @@ pub fn walk_vis<'a, V: Visitor<'a>>(visitor: &mut V, vis: &'a Visibility) { pub fn walk_attribute<'a, V: Visitor<'a>>(visitor: &mut V, attr: &'a Attribute) { match attr.kind { - AttrKind::Normal(ref item) => visitor.visit_tts(item.tokens.clone()), + AttrKind::Normal(ref item) => walk_mac_args(visitor, &item.args), AttrKind::DocComment(_) => {} } } +pub fn walk_mac_args<'a, V: Visitor<'a>>(visitor: &mut V, args: &'a MacArgs) { + match args { + MacArgs::Empty => {} + MacArgs::Delimited(_dspan, _delim, tokens) => visitor.visit_tts(tokens.clone()), + MacArgs::Eq(_eq_span, tokens) => visitor.visit_tts(tokens.clone()), + } +} + pub fn walk_tt<'a, V: Visitor<'a>>(visitor: &mut V, tt: TokenTree) { match tt { TokenTree::Token(token) => visitor.visit_token(token), |
