]> git.lizzy.rs Git - rust.git/blobdiff - src/librustc_parse/parser/item.rs
ast: Implement `TryFrom<ItemKind>` for associated and foreign items
[rust.git] / src / librustc_parse / parser / item.rs
index d9e28716c84c7fdc57dc76ddda28e8745f3acf89..08e74034e86a1be9920b7f9c7b20cc1572b604e6 100644 (file)
@@ -4,21 +4,27 @@
 
 use crate::maybe_whole;
 
+use rustc_ast::ast::{self, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID};
+use rustc_ast::ast::{AssocItem, AssocItemKind, ForeignItemKind, Item, ItemKind};
+use rustc_ast::ast::{
+    Async, Const, Defaultness, IsAuto, PathSegment, Unsafe, UseTree, UseTreeKind,
+};
+use rustc_ast::ast::{
+    BindingMode, Block, FnDecl, FnSig, Mac, MacArgs, MacDelimiter, Param, SelfKind,
+};
+use rustc_ast::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
+use rustc_ast::ast::{FnHeader, ForeignItem, Mutability, Visibility, VisibilityKind};
+use rustc_ast::ptr::P;
+use rustc_ast::token;
+use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
 use rustc_ast_pretty::pprust;
 use rustc_errors::{struct_span_err, Applicability, PResult, StashKey};
+use rustc_span::edition::Edition;
 use rustc_span::source_map::{self, Span};
 use rustc_span::symbol::{kw, sym, Symbol};
-use syntax::ast::{self, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID};
-use syntax::ast::{AssocItem, AssocItemKind, ForeignItemKind, Item, ItemKind};
-use syntax::ast::{Async, Const, Defaultness, IsAuto, PathSegment, Unsafe, UseTree, UseTreeKind};
-use syntax::ast::{BindingMode, Block, FnDecl, FnSig, Mac, MacArgs, MacDelimiter, Param, SelfKind};
-use syntax::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
-use syntax::ast::{FnHeader, ForeignItem, Mutability, Visibility, VisibilityKind};
-use syntax::ptr::P;
-use syntax::token;
-use syntax::tokenstream::{DelimSpan, TokenStream, TokenTree};
 
 use log::debug;
+use std::convert::TryFrom;
 use std::mem;
 
 pub(super) type ItemInfo = (Ident, ItemKind);
@@ -636,22 +642,22 @@ pub fn parse_impl_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
     }
 
     pub fn parse_trait_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
-        self.parse_assoc_item(|t| t.span.rust_2018())
+        self.parse_assoc_item(|edition| edition >= Edition::Edition2018)
     }
 
     /// Parses associated items.
     fn parse_assoc_item(&mut self, req_name: ReqName) -> PResult<'a, Option<Option<P<AssocItem>>>> {
         Ok(self.parse_item_(req_name)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
-            let kind = match kind {
-                ItemKind::Mac(a) => AssocItemKind::Macro(a),
-                ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
-                ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
-                ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
-                ItemKind::Static(a, _, b) => {
-                    self.struct_span_err(span, "associated `static` items are not allowed").emit();
-                    AssocItemKind::Const(Defaultness::Final, a, b)
-                }
-                _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
+            let kind = match AssocItemKind::try_from(kind) {
+                Ok(kind) => kind,
+                Err(kind) => match kind {
+                    ItemKind::Static(a, _, b) => {
+                        self.struct_span_err(span, "associated `static` items are not allowed")
+                            .emit();
+                        AssocItemKind::Const(Defaultness::Final, a, b)
+                    }
+                    _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
+                },
             };
             Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
         }))
@@ -741,11 +747,10 @@ fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
     }
 
     fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
-        match self.token.kind {
+        match self.normalized_token.kind {
             token::Ident(name @ kw::Underscore, false) => {
-                let span = self.token.span;
                 self.bump();
-                Ok(Ident::new(name, span))
+                Ok(Ident::new(name, self.normalized_prev_token.span))
             }
             _ => self.parse_ident(),
         }
@@ -829,16 +834,15 @@ fn parse_item_foreign_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a,
     /// Parses a foreign item (one in an `extern { ... }` block).
     pub fn parse_foreign_item(&mut self) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
         Ok(self.parse_item_(|_| true)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
-            let kind = match kind {
-                ItemKind::Mac(a) => ForeignItemKind::Macro(a),
-                ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
-                ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
-                ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
-                ItemKind::Const(_, a, b) => {
-                    self.error_on_foreign_const(span, ident);
-                    ForeignItemKind::Static(a, Mutability::Not, b)
-                }
-                _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
+            let kind = match ForeignItemKind::try_from(kind) {
+                Ok(kind) => kind,
+                Err(kind) => match kind {
+                    ItemKind::Const(_, a, b) => {
+                        self.error_on_foreign_const(span, ident);
+                        ForeignItemKind::Static(a, Mutability::Not, b)
+                    }
+                    _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
+                },
             };
             Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
         }))
@@ -1163,13 +1167,13 @@ fn parse_single_struct_field(
                 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 {
+                if !seen_comma && comma_after_doc_seen {
                     seen_comma = true;
                 }
                 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
                     err.emit();
                 } else {
-                    if seen_comma == false {
+                    if !seen_comma {
                         let sp = self.sess.source_map().next_point(previous_span);
                         err.span_suggestion(
                             sp,
@@ -1381,7 +1385,7 @@ fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
 ///
 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
-type ReqName = fn(&token::Token) -> bool;
+type ReqName = fn(Edition) -> bool;
 
 /// Parsing of functions and methods.
 impl<'a> Parser<'a> {
@@ -1537,7 +1541,7 @@ fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResu
 
         let is_name_required = match self.token.kind {
             token::DotDotDot => false,
-            _ => req_name(&self.token),
+            _ => req_name(self.normalized_token.span.edition()),
         };
         let (pat, ty) = if is_name_required || self.is_named_param() {
             debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
@@ -1603,12 +1607,11 @@ fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResu
     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 {
+            match this.normalized_token.kind {
                 // Preserve hygienic context.
                 token::Ident(name, _) => {
-                    let span = this.token.span;
                     this.bump();
-                    Ident::new(name, span)
+                    Ident::new(name, this.normalized_prev_token.span)
                 }
                 _ => unreachable!(),
             }
@@ -1645,7 +1648,7 @@ fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
         // 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 {
+        let (eself, eself_ident, eself_hi) = match self.normalized_token.kind {
             token::BinOp(token::And) => {
                 let eself = if is_isolated_self(self, 1) {
                     // `&self`