From 90f891d8ae9073623769fac18f00c4f1031fcb59 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sun, 3 Nov 2019 14:58:01 +0300 Subject: syntax: Avoid span arithmetics for delimiter tokens --- src/libsyntax/parse/parser.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/libsyntax/parse/parser.rs') diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 6ead1ce811d..bce36d259ac 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -210,12 +210,12 @@ impl TokenCursor { loop { let tree = if !self.frame.open_delim { self.frame.open_delim = true; - TokenTree::open_tt(self.frame.span.open, self.frame.delim) + 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.close, self.frame.delim) + TokenTree::close_tt(self.frame.span, self.frame.delim) } else if let Some(frame) = self.stack.pop() { self.frame = frame; continue -- cgit 1.4.1-3-g733a5 From fe95cd2f4b3a722e023dc7bba8ff65136be441ca Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Wed, 30 Oct 2019 16:38:16 +0100 Subject: revamp pre-expansion gating infra --- src/libsyntax/feature_gate/check.rs | 10 ++--- src/libsyntax/parse/parser.rs | 2 +- src/libsyntax/parse/parser/expr.rs | 19 +++++----- src/libsyntax/parse/parser/generics.rs | 5 ++- src/libsyntax/parse/parser/item.rs | 8 ++-- src/libsyntax/parse/parser/pat.rs | 16 +++----- src/libsyntax/parse/parser/path.rs | 4 +- src/libsyntax/sess.rs | 69 ++++++++++++++++++---------------- 8 files changed, 65 insertions(+), 68 deletions(-) (limited to 'src/libsyntax/parse/parser.rs') diff --git a/src/libsyntax/feature_gate/check.rs b/src/libsyntax/feature_gate/check.rs index d9cc5f6c169..ea9946a8b7a 100644 --- a/src/libsyntax/feature_gate/check.rs +++ b/src/libsyntax/feature_gate/check.rs @@ -862,18 +862,17 @@ pub fn check_crate(krate: &ast::Crate, maybe_stage_features(&parse_sess.span_diagnostic, krate, unstable); let mut visitor = PostExpansionVisitor { parse_sess, features }; + let spans = parse_sess.gated_spans.spans.borrow(); macro_rules! gate_all { - ($gate:ident, $msg:literal) => { gate_all!($gate, $gate, $msg); }; - ($spans:ident, $gate:ident, $msg:literal) => { - for span in &*parse_sess.gated_spans.$spans.borrow() { + ($gate:ident, $msg:literal) => { + for span in spans.get(&sym::$gate).unwrap_or(&vec![]) { gate_feature!(&visitor, $gate, *span, $msg); } } } - gate_all!(let_chains, "`let` expressions in this position are experimental"); gate_all!(async_closure, "async closures are unstable"); - gate_all!(yields, generators, "yield syntax is experimental"); + 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"); @@ -901,7 +900,6 @@ pub fn check_crate(krate: &ast::Crate, gate_all!(try_blocks, "`try` blocks are unstable"); gate_all!(label_break_value, "labels on blocks are unstable"); gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead"); - // To avoid noise about type ascription in common syntax errors, // only emit if it is the *only* error. (Also check it last.) if parse_sess.span_diagnostic.err_count() == 0 { diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 7652c730e51..efd716e7c4a 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -1121,7 +1121,7 @@ impl<'a> Parser<'a> { self.expected_tokens.push(TokenType::Keyword(kw::Crate)); if self.is_crate_vis() { self.bump(); // `crate` - self.sess.gated_spans.crate_visibility_modifier.borrow_mut().push(self.prev_span); + self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_span); return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate))); } diff --git a/src/libsyntax/parse/parser/expr.rs b/src/libsyntax/parse/parser/expr.rs index 97b1092452a..79be67528b9 100644 --- a/src/libsyntax/parse/parser/expr.rs +++ b/src/libsyntax/parse/parser/expr.rs @@ -16,10 +16,10 @@ use crate::parse::token::{self, Token, TokenKind}; use crate::print::pprust; use crate::ptr::P; use crate::source_map::{self, Span}; -use crate::symbol::{kw, sym}; use crate::util::parser::{AssocOp, Fixity, prec_let_scrutinee_needs_par}; use errors::Applicability; +use syntax_pos::symbol::{kw, sym}; use syntax_pos::Symbol; use std::mem; use rustc_data_structures::thin_vec::ThinVec; @@ -252,7 +252,7 @@ impl<'a> Parser<'a> { 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.type_ascription.borrow_mut().push(lhs.span); + 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 @@ -455,7 +455,7 @@ impl<'a> Parser<'a> { 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.box_syntax.borrow_mut().push(span); + self.sess.gated_spans.gate(sym::box_syntax, span); (span, ExprKind::Box(e)) } token::Ident(..) if self.token.is_ident_named(sym::not) => { @@ -1045,7 +1045,7 @@ impl<'a> Parser<'a> { } let span = lo.to(hi); - self.sess.gated_spans.yields.borrow_mut().push(span); + 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) { @@ -1264,7 +1264,7 @@ impl<'a> Parser<'a> { outer_attrs: ThinVec, ) -> PResult<'a, P> { if let Some(label) = opt_label { - self.sess.gated_spans.label_break_value.borrow_mut().push(label.ident.span); + self.sess.gated_spans.gate(sym::label_break_value, label.ident.span); } self.expect(&token::OpenDelim(token::Brace))?; @@ -1293,7 +1293,7 @@ impl<'a> Parser<'a> { }; if asyncness.is_async() { // Feature-gate `async ||` closures. - self.sess.gated_spans.async_closure.borrow_mut().push(self.prev_span); + self.sess.gated_spans.gate(sym::async_closure, self.prev_span); } let capture_clause = self.parse_capture_clause(); @@ -1415,8 +1415,7 @@ impl<'a> Parser<'a> { if let ExprKind::Let(..) = cond.kind { // Remove the last feature gating of a `let` expression since it's stable. - let last = self.sess.gated_spans.let_chains.borrow_mut().pop(); - debug_assert_eq!(cond.span, last.unwrap()); + self.sess.gated_spans.ungate_last(sym::let_chains, cond.span); } Ok(cond) @@ -1433,7 +1432,7 @@ impl<'a> Parser<'a> { |this| this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into()) )?; let span = lo.to(expr.span); - self.sess.gated_spans.let_chains.borrow_mut().push(span); + self.sess.gated_spans.gate(sym::let_chains, span); Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs)) } @@ -1654,7 +1653,7 @@ impl<'a> Parser<'a> { Err(error) } else { let span = span_lo.to(body.span); - self.sess.gated_spans.try_blocks.borrow_mut().push(span); + self.sess.gated_spans.gate(sym::try_blocks, span); Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs)) } } diff --git a/src/libsyntax/parse/parser/generics.rs b/src/libsyntax/parse/parser/generics.rs index 51caae69c86..3c094750b4d 100644 --- a/src/libsyntax/parse/parser/generics.rs +++ b/src/libsyntax/parse/parser/generics.rs @@ -3,7 +3,8 @@ use super::{Parser, PResult}; use crate::ast::{self, WhereClause, GenericParam, GenericParamKind, GenericBounds, Attribute}; use crate::parse::token; use crate::source_map::DUMMY_SP; -use crate::symbol::kw; + +use syntax_pos::symbol::{kw, sym}; impl<'a> Parser<'a> { /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`. @@ -62,7 +63,7 @@ impl<'a> Parser<'a> { self.expect(&token::Colon)?; let ty = self.parse_ty()?; - self.sess.gated_spans.const_generics.borrow_mut().push(lo.to(self.prev_span)); + self.sess.gated_spans.gate(sym::const_generics, lo.to(self.prev_span)); Ok(GenericParam { ident, diff --git a/src/libsyntax/parse/parser/item.rs b/src/libsyntax/parse/parser/item.rs index 5b60e7e6dba..51e96b55c72 100644 --- a/src/libsyntax/parse/parser/item.rs +++ b/src/libsyntax/parse/parser/item.rs @@ -147,9 +147,7 @@ impl<'a> Parser<'a> { let unsafety = self.parse_unsafety(); if self.check_keyword(kw::Extern) { - self.sess.gated_spans.const_extern_fn.borrow_mut().push( - lo.to(self.token.span) - ); + self.sess.gated_spans.gate(sym::const_extern_fn, lo.to(self.token.span)); } let abi = self.parse_extern_abi()?; self.bump(); // `fn` @@ -830,7 +828,7 @@ impl<'a> Parser<'a> { .emit(); } - self.sess.gated_spans.trait_alias.borrow_mut().push(whole_span); + self.sess.gated_spans.gate(sym::trait_alias, whole_span); Ok((ident, ItemKind::TraitAlias(tps, bounds), None)) } else { @@ -1712,7 +1710,7 @@ impl<'a> Parser<'a> { let span = lo.to(self.prev_span); if !def.legacy { - self.sess.gated_spans.decl_macro.borrow_mut().push(span); + self.sess.gated_spans.gate(sym::decl_macro, span); } Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec()))) diff --git a/src/libsyntax/parse/parser/pat.rs b/src/libsyntax/parse/parser/pat.rs index 969d5dd8374..cc8738edff7 100644 --- a/src/libsyntax/parse/parser/pat.rs +++ b/src/libsyntax/parse/parser/pat.rs @@ -8,9 +8,8 @@ use crate::mut_visit::{noop_visit_pat, noop_visit_mac, MutVisitor}; use crate::parse::token::{self}; use crate::print::pprust; use crate::source_map::{respan, Span, Spanned}; -use crate::symbol::kw; use crate::ThinVec; - +use syntax_pos::symbol::{kw, sym}; use errors::{Applicability, DiagnosticBuilder}; type Expected = Option<&'static str>; @@ -52,11 +51,8 @@ impl<'a> Parser<'a> { // 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 { - let mut or_pattern_spans = self.sess.gated_spans.or_patterns.borrow_mut(); - if or_pattern_spans.is_empty() { - or_pattern_spans.push(leading_vert_span); - } + 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) @@ -117,7 +113,7 @@ impl<'a> Parser<'a> { // Feature gate the or-pattern if instructed: if gate_or == GateOr::Yes { - self.sess.gated_spans.or_patterns.borrow_mut().push(or_pattern_span); + self.sess.gated_spans.gate(sym::or_patterns, or_pattern_span); } Ok(self.mk_pat(or_pattern_span, PatKind::Or(pats))) @@ -325,7 +321,7 @@ impl<'a> Parser<'a> { } else if self.eat_keyword(kw::Box) { // Parse `box pat` let pat = self.parse_pat_with_range_pat(false, None)?; - self.sess.gated_spans.box_patterns.borrow_mut().push(lo.to(self.prev_span)); + 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` @@ -612,7 +608,7 @@ impl<'a> Parser<'a> { } fn excluded_range_end(&self, span: Span) -> RangeEnd { - self.sess.gated_spans.exclusive_range_pattern.borrow_mut().push(span); + self.sess.gated_spans.gate(sym::exclusive_range_pattern, span); RangeEnd::Excluded } diff --git a/src/libsyntax/parse/parser/path.rs b/src/libsyntax/parse/parser/path.rs index f9944e36e2f..4438d61d9ee 100644 --- a/src/libsyntax/parse/parser/path.rs +++ b/src/libsyntax/parse/parser/path.rs @@ -5,7 +5,7 @@ use crate::ast::{self, QSelf, Path, PathSegment, Ident, ParenthesizedArgs, Angle use crate::ast::{AnonConst, GenericArg, AssocTyConstraint, AssocTyConstraintKind, BlockCheckMode}; use crate::parse::token::{self, Token}; use crate::source_map::{Span, BytePos}; -use crate::symbol::kw; +use syntax_pos::symbol::{kw, sym}; use std::mem; use log::debug; @@ -426,7 +426,7 @@ impl<'a> Parser<'a> { // Gate associated type bounds, e.g., `Iterator`. if let AssocTyConstraintKind::Bound { .. } = kind { - self.sess.gated_spans.associated_type_bounds.borrow_mut().push(span); + self.sess.gated_spans.gate(sym::associated_type_bounds, span); } constraints.push(AssocTyConstraint { diff --git a/src/libsyntax/sess.rs b/src/libsyntax/sess.rs index 30f8c56a056..f677d544bc3 100644 --- a/src/libsyntax/sess.rs +++ b/src/libsyntax/sess.rs @@ -20,38 +20,43 @@ use std::str; /// used and should be feature gated accordingly in `check_crate`. #[derive(Default)] crate struct GatedSpans { - /// Spans collected for gating `let_chains`, e.g. `if a && let b = c {}`. - crate let_chains: Lock>, - /// Spans collected for gating `async_closure`, e.g. `async || ..`. - crate async_closure: Lock>, - /// Spans collected for gating `yield e?` expressions (`generators` gate). - crate yields: Lock>, - /// Spans collected for gating `or_patterns`, e.g. `Some(Foo | Bar)`. - crate or_patterns: Lock>, - /// Spans collected for gating `const_extern_fn`, e.g. `const extern fn foo`. - crate const_extern_fn: Lock>, - /// Spans collected for gating `trait_alias`, e.g. `trait Foo = Ord + Eq;`. - pub trait_alias: Lock>, - /// Spans collected for gating `associated_type_bounds`, e.g. `Iterator`. - pub associated_type_bounds: Lock>, - /// Spans collected for gating `crate_visibility_modifier`, e.g. `crate fn`. - pub crate_visibility_modifier: Lock>, - /// Spans collected for gating `const_generics`, e.g. `const N: usize`. - pub const_generics: Lock>, - /// Spans collected for gating `decl_macro`, e.g. `macro m() {}`. - pub decl_macro: Lock>, - /// Spans collected for gating `box_patterns`, e.g. `box 0`. - pub box_patterns: Lock>, - /// Spans collected for gating `exclusive_range_pattern`, e.g. `0..2`. - pub exclusive_range_pattern: Lock>, - /// Spans collected for gating `try_blocks`, e.g. `try { a? + b? }`. - pub try_blocks: Lock>, - /// Spans collected for gating `label_break_value`, e.g. `'label: { ... }`. - pub label_break_value: Lock>, - /// Spans collected for gating `box_syntax`, e.g. `box $expr`. - pub box_syntax: Lock>, - /// Spans collected for gating `type_ascription`, e.g. `42: usize`. - pub type_ascription: Lock>, + crate spans: Lock>>, +} + +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()) + } } /// Info about a parsing session. -- cgit 1.4.1-3-g733a5 From beddf67a4b1ce5f1e14a67690644690c4b1bcfaa Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Sun, 27 Oct 2019 23:14:35 +0100 Subject: parser: don't hardcode ABIs into grammar --- src/librustc/error_codes.rs | 1 + src/librustc/hir/lowering.rs | 2 +- src/librustc/hir/lowering/item.rs | 25 +- src/librustc_save_analysis/sig.rs | 26 +- src/libsyntax/ast.rs | 24 +- src/libsyntax/error_codes.rs | 1 - src/libsyntax/feature_gate/check.rs | 63 ++--- src/libsyntax/parse/parser.rs | 38 +-- src/libsyntax/parse/parser/item.rs | 21 +- src/libsyntax/print/pprust.rs | 13 +- src/libsyntax/print/pprust/tests.rs | 7 +- src/libsyntax_ext/deriving/generic/mod.rs | 31 +-- src/libsyntax_pos/symbol.rs | 1 + .../ui/feature-gated-feature-in-macro-arg.stderr | 8 +- .../feature-gate-abi-msp430-interrupt.stderr | 4 +- src/test/ui/feature-gates/feature-gate-abi.stderr | 272 ++++++++++----------- .../feature-gate-abi_unadjusted.stderr | 8 +- .../feature-gates/feature-gate-intrinsics.stderr | 12 +- ...ature-gate-unboxed-closures-manual-impls.stderr | 16 +- .../feature-gate-unboxed-closures.stderr | 8 +- 20 files changed, 296 insertions(+), 285 deletions(-) (limited to 'src/libsyntax/parse/parser.rs') diff --git a/src/librustc/error_codes.rs b/src/librustc/error_codes.rs index f5ff92e69bc..cf892127a30 100644 --- a/src/librustc/error_codes.rs +++ b/src/librustc/error_codes.rs @@ -2336,6 +2336,7 @@ the future, [RFC 2091] prohibits their implementation without a follow-up RFC. E0657, // `impl Trait` can only capture lifetimes bound at the fn level E0687, // in-band lifetimes cannot be used in `fn`/`Fn` syntax E0688, // in-band lifetimes cannot be mixed with explicit lifetime binders + E0703, // invalid ABI // E0707, // multiple elided lifetimes used in arguments of `async fn` E0708, // `async` non-`move` closures with parameters are not currently // supported diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 230fbb16b87..6344c7a233c 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1216,7 +1216,7 @@ impl<'a> LoweringContext<'a> { ImplTraitContext::disallowed(), ), unsafety: this.lower_unsafety(f.unsafety), - abi: f.abi, + abi: this.lower_abi(f.abi), decl: this.lower_fn_decl(&f.decl, None, false, None), param_names: this.lower_fn_params_to_names(&f.decl), })) diff --git a/src/librustc/hir/lowering/item.rs b/src/librustc/hir/lowering/item.rs index f1b999cdd6f..5fe463d783f 100644 --- a/src/librustc/hir/lowering/item.rs +++ b/src/librustc/hir/lowering/item.rs @@ -12,6 +12,7 @@ use crate::hir::def::{Res, DefKind}; use crate::util::nodemap::NodeMap; use rustc_data_structures::thin_vec::ThinVec; +use rustc_target::spec::abi; use std::collections::BTreeSet; use smallvec::SmallVec; @@ -735,7 +736,7 @@ impl LoweringContext<'_> { fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod { hir::ForeignMod { - abi: fm.abi, + abi: self.lower_abi(fm.abi), items: fm.items .iter() .map(|x| self.lower_foreign_item(x)) @@ -1291,10 +1292,30 @@ impl LoweringContext<'_> { unsafety: self.lower_unsafety(h.unsafety), asyncness: self.lower_asyncness(h.asyncness.node), constness: self.lower_constness(h.constness), - abi: h.abi, + abi: self.lower_abi(h.abi), } } + pub(super) fn lower_abi(&mut self, abi: Abi) -> abi::Abi { + abi::lookup(&abi.symbol.as_str()).unwrap_or_else(|| { + self.error_on_invalid_abi(abi); + abi::Abi::Rust + }) + } + + fn error_on_invalid_abi(&self, abi: Abi) { + struct_span_err!( + self.sess, + abi.span, + E0703, + "invalid ABI: found `{}`", + abi.symbol + ) + .span_label(abi.span, "invalid ABI") + .help(&format!("valid ABIs: {}", abi::all_names().join(", "))) + .emit(); + } + pub(super) fn lower_unsafety(&mut self, u: Unsafety) -> hir::Unsafety { match u { Unsafety::Unsafe => hir::Unsafety::Unsafe, diff --git a/src/librustc_save_analysis/sig.rs b/src/librustc_save_analysis/sig.rs index 203bd4d4167..019e92717b5 100644 --- a/src/librustc_save_analysis/sig.rs +++ b/src/librustc_save_analysis/sig.rs @@ -32,7 +32,7 @@ use rls_data::{SigElement, Signature}; use rustc::hir::def::{Res, DefKind}; use syntax::ast::{self, NodeId}; use syntax::print::pprust; - +use syntax_pos::sym; pub fn item_signature(item: &ast::Item, scx: &SaveContext<'_, '_>) -> Option { if !scx.config.signatures { @@ -157,6 +157,12 @@ fn text_sig(text: String) -> Signature { } } +fn push_abi(text: &mut String, abi: ast::Abi) { + if abi.symbol != sym::Rust { + text.push_str(&format!("extern \"{}\" ", abi.symbol)); + } +} + impl Sig for ast::Ty { fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext<'_, '_>) -> Result { let id = Some(self.id); @@ -231,11 +237,7 @@ impl Sig for ast::Ty { if f.unsafety == ast::Unsafety::Unsafe { text.push_str("unsafe "); } - if f.abi != rustc_target::spec::abi::Abi::Rust { - text.push_str("extern"); - text.push_str(&f.abi.to_string()); - text.push(' '); - } + push_abi(&mut text, f.abi); text.push_str("fn("); let mut defs = vec![]; @@ -385,11 +387,7 @@ impl Sig for ast::Item { if header.unsafety == ast::Unsafety::Unsafe { text.push_str("unsafe "); } - if header.abi != rustc_target::spec::abi::Abi::Rust { - text.push_str("extern"); - text.push_str(&header.abi.to_string()); - text.push(' '); - } + push_abi(&mut text, header.abi); text.push_str("fn "); let mut sig = name_and_generics(text, offset, generics, self.id, self.ident, scx)?; @@ -948,11 +946,7 @@ fn make_method_signature( if m.header.unsafety == ast::Unsafety::Unsafe { text.push_str("unsafe "); } - if m.header.abi != rustc_target::spec::abi::Abi::Rust { - text.push_str("extern"); - text.push_str(&m.header.abi.to_string()); - text.push(' '); - } + push_abi(&mut text, m.header.abi); text.push_str("fn "); let mut sig = name_and_generics(text, 0, generics, id, ident, scx)?; diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 2392b809150..f761c35cd5c 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -38,7 +38,6 @@ 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_target::spec::abi::Abi; #[cfg(target_arch = "x86_64")] use rustc_data_structures::static_assert_size; @@ -2358,6 +2357,27 @@ 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 } + } +} + +impl Default for Abi { + fn default() -> Self { + Self::new(sym::Rust, DUMMY_SP) + } +} + /// A function header. /// /// All the information between the visibility and the name of the function is @@ -2376,7 +2396,7 @@ impl Default for FnHeader { unsafety: Unsafety::Normal, asyncness: dummy_spanned(IsAsync::NotAsync), constness: dummy_spanned(Constness::NotConst), - abi: Abi::Rust, + abi: Abi::default(), } } } diff --git a/src/libsyntax/error_codes.rs b/src/libsyntax/error_codes.rs index 941df5ea570..c23c8d65a7f 100644 --- a/src/libsyntax/error_codes.rs +++ b/src/libsyntax/error_codes.rs @@ -540,6 +540,5 @@ equivalent in Rust would be to use macros directly. E0630, E0693, // incorrect `repr(align)` attribute format // E0694, // an unknown tool name found in scoped attributes - E0703, // invalid ABI E0717, // rustc_promotable without stability attribute } diff --git a/src/libsyntax/feature_gate/check.rs b/src/libsyntax/feature_gate/check.rs index b7e75ff3a7e..213e9680524 100644 --- a/src/libsyntax/feature_gate/check.rs +++ b/src/libsyntax/feature_gate/check.rs @@ -18,7 +18,6 @@ use crate::tokenstream::TokenTree; use errors::{Applicability, DiagnosticBuilder, Handler}; use rustc_data_structures::fx::FxHashMap; -use rustc_target::spec::abi::Abi; use syntax_pos::{Span, DUMMY_SP, MultiSpan}; use log::debug; @@ -192,62 +191,70 @@ macro_rules! gate_feature_post { } impl<'a> PostExpansionVisitor<'a> { - fn check_abi(&self, abi: Abi, span: Span) { - match abi { - Abi::RustIntrinsic => { + fn check_abi(&self, abi: ast::Abi) { + let ast::Abi { symbol, span } = abi; + + match &*symbol.as_str() { + // Stable + "Rust" | + "C" | + "cdecl" | + "stdcall" | + "fastcall" | + "aapcs" | + "win64" | + "sysv64" | + "system" => {} + "rust-intrinsic" => { gate_feature_post!(&self, intrinsics, span, "intrinsics are subject to change"); }, - Abi::PlatformIntrinsic => { + "platform-intrinsic" => { gate_feature_post!(&self, platform_intrinsics, span, "platform intrinsics are experimental and possibly buggy"); }, - Abi::Vectorcall => { + "vectorcall" => { gate_feature_post!(&self, abi_vectorcall, span, "vectorcall is experimental and subject to change"); }, - Abi::Thiscall => { + "thiscall" => { gate_feature_post!(&self, abi_thiscall, span, "thiscall is experimental and subject to change"); }, - Abi::RustCall => { + "rust-call" => { gate_feature_post!(&self, unboxed_closures, span, "rust-call ABI is subject to change"); }, - Abi::PtxKernel => { + "ptx-kernel" => { gate_feature_post!(&self, abi_ptx, span, "PTX ABIs are experimental and subject to change"); }, - Abi::Unadjusted => { + "unadjusted" => { gate_feature_post!(&self, abi_unadjusted, span, "unadjusted ABI is an implementation detail and perma-unstable"); }, - Abi::Msp430Interrupt => { + "msp430-interrupt" => { gate_feature_post!(&self, abi_msp430_interrupt, span, "msp430-interrupt ABI is experimental and subject to change"); }, - Abi::X86Interrupt => { + "x86-interrupt" => { gate_feature_post!(&self, abi_x86_interrupt, span, "x86-interrupt ABI is experimental and subject to change"); }, - Abi::AmdGpuKernel => { + "amdgpu-kernel" => { gate_feature_post!(&self, abi_amdgpu_kernel, span, "amdgpu-kernel ABI is experimental and subject to change"); }, - Abi::EfiApi => { + "efiapi" => { gate_feature_post!(&self, abi_efiapi, span, "efiapi ABI is experimental and subject to change"); }, - // Stable - Abi::Cdecl | - Abi::Stdcall | - Abi::Fastcall | - Abi::Aapcs | - Abi::Win64 | - Abi::SysV64 | - Abi::Rust | - Abi::C | - Abi::System => {} + abi => { + self.parse_sess.span_diagnostic.delay_span_bug( + span, + &format!("unrecognized ABI not caught in lowering: {}", abi), + ) + } } } @@ -373,7 +380,7 @@ 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, i.span); + self.check_abi(foreign_module.abi); } ast::ItemKind::Fn(..) => { @@ -503,7 +510,7 @@ 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, ty.span); + self.check_abi(bare_fn_ty.abi); } ast::TyKind::Never => { gate_feature_post!(&self, never_type, ty.span, @@ -597,7 +604,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, span); + self.check_abi(header.abi); } if fn_decl.c_variadic() { @@ -631,7 +638,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, ti.span); + self.check_abi(sig.header.abi); } if sig.decl.c_variadic() { gate_feature_post!(&self, c_variadic, ti.span, diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 7652c730e51..382c1a517aa 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -12,7 +12,7 @@ mod diagnostics; use diagnostics::Error; use crate::ast::{ - self, DUMMY_NODE_ID, AttrStyle, Attribute, CrateSugar, Ident, + self, Abi, DUMMY_NODE_ID, AttrStyle, Attribute, CrateSugar, Ident, IsAsync, MacDelimiter, Mutability, StrStyle, Visibility, VisibilityKind, Unsafety, }; use crate::parse::{PResult, Directory, DirectoryOwnership}; @@ -28,7 +28,6 @@ use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint}; use crate::ThinVec; use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError}; -use rustc_target::spec::abi::{self, Abi}; use syntax_pos::{Span, BytePos, DUMMY_SP, FileName}; use log::debug; @@ -1208,48 +1207,27 @@ impl<'a> Parser<'a> { /// Parses `extern` followed by an optional ABI string, or nothing. fn parse_extern_abi(&mut self) -> PResult<'a, Abi> { - if self.eat_keyword(kw::Extern) { - Ok(self.parse_opt_abi()?.unwrap_or(Abi::C)) + Ok(if self.eat_keyword(kw::Extern) { + let ext_sp = self.prev_span; + self.parse_opt_abi()?.unwrap_or_else(|| Abi::new(sym::C, ext_sp)) } else { - Ok(Abi::Rust) - } + Abi::default() + }) } - /// Parses a string as an ABI spec on an extern type or module. Consumes - /// the `extern` keyword, if one is found. + /// Parses a string as an ABI spec on an extern type or module. fn parse_opt_abi(&mut self) -> PResult<'a, Option> { match self.token.kind { token::Literal(token::Lit { kind: token::Str, symbol, suffix }) | token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => { self.expect_no_suffix(self.token.span, "an ABI spec", suffix); self.bump(); - match abi::lookup(&symbol.as_str()) { - Some(abi) => Ok(Some(abi)), - None => { - self.error_on_invalid_abi(symbol); - Ok(None) - } - } + Ok(Some(Abi::new(symbol, self.prev_span))) } _ => Ok(None), } } - /// Emit an error where `symbol` is an invalid ABI. - fn error_on_invalid_abi(&self, symbol: Symbol) { - let prev_span = self.prev_span; - struct_span_err!( - self.sess.span_diagnostic, - prev_span, - E0703, - "invalid ABI: found `{}`", - symbol - ) - .span_label(prev_span, "invalid ABI") - .help(&format!("valid ABIs: {}", abi::all_names().join(", "))) - .emit(); - } - /// 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() { diff --git a/src/libsyntax/parse/parser/item.rs b/src/libsyntax/parse/parser/item.rs index cc6235c6fc7..76411e7cf13 100644 --- a/src/libsyntax/parse/parser/item.rs +++ b/src/libsyntax/parse/parser/item.rs @@ -3,7 +3,7 @@ use super::diagnostics::{Error, dummy_arg, ConsumeClosingDelim}; use crate::maybe_whole; use crate::ptr::P; -use crate::ast::{self, DUMMY_NODE_ID, Ident, Attribute, AttrKind, AttrStyle, AnonConst, Item}; +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}; @@ -17,7 +17,6 @@ use crate::ThinVec; use log::debug; use std::mem; -use rustc_target::spec::abi::Abi; use errors::{Applicability, DiagnosticBuilder, DiagnosticId, StashKey}; use syntax_pos::BytePos; @@ -111,7 +110,7 @@ impl<'a> Parser<'a> { return Ok(Some(self.parse_item_extern_crate(lo, vis, attrs)?)); } - let opt_abi = self.parse_opt_abi()?; + let abi = self.parse_opt_abi()?.unwrap_or_else(|| Abi::new(sym::C, extern_sp)); if self.eat_keyword(kw::Fn) { // EXTERN FUNCTION ITEM @@ -120,12 +119,12 @@ impl<'a> Parser<'a> { unsafety: Unsafety::Normal, asyncness: respan(fn_span, IsAsync::NotAsync), constness: respan(fn_span, Constness::NotConst), - abi: opt_abi.unwrap_or(Abi::C), + 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, opt_abi, vis, attrs, extern_sp)?, + self.parse_item_foreign_mod(lo, abi, vis, attrs, extern_sp)?, )); } @@ -201,7 +200,7 @@ impl<'a> Parser<'a> { unsafety, asyncness, constness: respan(fn_span, Constness::NotConst), - abi: Abi::Rust, + abi: Abi::new(sym::Rust, fn_span), }; return self.parse_item_fn(lo, vis, attrs, header); } @@ -238,7 +237,7 @@ impl<'a> Parser<'a> { unsafety: Unsafety::Normal, asyncness: respan(fn_span, IsAsync::NotAsync), constness: respan(fn_span, Constness::NotConst), - abi: Abi::Rust, + abi: Abi::new(sym::Rust, fn_span), }; return self.parse_item_fn(lo, vis, attrs, header); } @@ -1115,15 +1114,13 @@ impl<'a> Parser<'a> { fn parse_item_foreign_mod( &mut self, lo: Span, - opt_abi: Option, + abi: Abi, visibility: Visibility, mut attrs: Vec, extern_sp: Span, ) -> PResult<'a, P> { self.expect(&token::OpenDelim(token::Brace))?; - let abi = opt_abi.unwrap_or(Abi::C); - attrs.extend(self.parse_inner_attributes()?); let mut foreign_items = vec![]; @@ -1801,7 +1798,7 @@ impl<'a> Parser<'a> { ) -> PResult<'a, Option>> { let (ident, decl, generics) = self.parse_fn_sig(ParamCfg { is_self_allowed: false, - allow_c_variadic: header.abi == Abi::C && header.unsafety == Unsafety::Unsafe, + 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()?; @@ -1930,7 +1927,7 @@ impl<'a> Parser<'a> { 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::Rust) + (respan(const_span, Constness::Const), unsafety, Abi::default()) } else { let abi = self.parse_extern_abi()?; (respan(self.prev_span, Constness::NotConst), unsafety, abi) diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index c8afe8a1ff4..1d59c13a9d0 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -14,7 +14,6 @@ use crate::sess::ParseSess; use crate::symbol::{kw, sym}; use crate::tokenstream::{self, TokenStream, TokenTree}; -use rustc_target::spec::abi::{self, Abi}; use syntax_pos::{self, BytePos}; use syntax_pos::{FileName, Span}; @@ -1230,7 +1229,7 @@ impl<'a> State<'a> { } ast::ItemKind::ForeignMod(ref nmod) => { self.head("extern"); - self.word_nbsp(nmod.abi.to_string()); + self.print_abi(nmod.abi); self.bopen(); self.print_foreign_mod(nmod, &item.attrs); self.bclose(item.span); @@ -2823,7 +2822,7 @@ impl<'a> State<'a> { } crate fn print_ty_fn(&mut self, - abi: abi::Abi, + abi: ast::Abi, unsafety: ast::Unsafety, decl: &ast::FnDecl, name: Option, @@ -2884,14 +2883,18 @@ impl<'a> State<'a> { self.print_asyncness(header.asyncness.node); self.print_unsafety(header.unsafety); - if header.abi != Abi::Rust { + if header.abi.symbol != sym::Rust { self.word_nbsp("extern"); - self.word_nbsp(header.abi.to_string()); + self.print_abi(header.abi); } 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 faa70edbfa2..2c6dd0fb1c6 100644 --- a/src/libsyntax/print/pprust/tests.rs +++ b/src/libsyntax/print/pprust/tests.rs @@ -34,12 +34,7 @@ fn test_fun_to_string() { assert_eq!( fun_to_string( &decl, - ast::FnHeader { - unsafety: ast::Unsafety::Normal, - constness: source_map::dummy_spanned(ast::Constness::NotConst), - asyncness: source_map::dummy_spanned(ast::IsAsync::NotAsync), - abi: Abi::Rust, - }, + ast::FnHeader::default(), abba_ident, &generics ), diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index 2e5ae235893..b18fd50ae76 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -182,8 +182,7 @@ use std::iter; use std::vec; use rustc_data_structures::thin_vec::ThinVec; -use rustc_target::spec::abi::Abi; -use syntax::ast::{self, BinOpKind, EnumDef, Expr, Generics, Ident, PatKind}; +use syntax::ast::{self, Abi, BinOpKind, EnumDef, Expr, Generics, Ident, PatKind}; use syntax::ast::{VariantData, GenericParamKind, GenericArg}; use syntax::attr; use syntax::source_map::respan; @@ -738,7 +737,7 @@ impl<'a> TraitDef<'a> { self, type_ident, generics, - Abi::Rust, + sym::Rust, explicit_self, tys, body) @@ -793,7 +792,7 @@ impl<'a> TraitDef<'a> { self, type_ident, generics, - Abi::Rust, + sym::Rust, explicit_self, tys, body) @@ -919,7 +918,7 @@ impl<'a> MethodDef<'a> { trait_: &TraitDef<'_>, type_ident: Ident, generics: &Generics, - abi: Abi, + abi: Symbol, explicit_self: Option, arg_types: Vec<(Ident, P)>, body: P) @@ -949,23 +948,27 @@ impl<'a> MethodDef<'a> { ast::Unsafety::Normal }; + let trait_lo_sp = trait_.span.shrink_to_lo(); + + let sig = ast::MethodSig { + header: ast::FnHeader { + unsafety, + abi: Abi::new(abi, trait_lo_sp), + ..ast::FnHeader::default() + }, + decl: fn_decl, + }; + // Create the method. ast::ImplItem { id: ast::DUMMY_NODE_ID, attrs: self.attributes.clone(), generics: fn_generics, span: trait_.span, - vis: respan(trait_.span.shrink_to_lo(), ast::VisibilityKind::Inherited), + vis: respan(trait_lo_sp, ast::VisibilityKind::Inherited), defaultness: ast::Defaultness::Final, ident: method_ident, - kind: ast::ImplItemKind::Method(ast::MethodSig { - header: ast::FnHeader { - unsafety, abi, - ..ast::FnHeader::default() - }, - decl: fn_decl, - }, - body_block), + kind: ast::ImplItemKind::Method(sig, body_block), tokens: None, } } diff --git a/src/libsyntax_pos/symbol.rs b/src/libsyntax_pos/symbol.rs index 3f7b3e5b3d8..2bdd8eacd11 100644 --- a/src/libsyntax_pos/symbol.rs +++ b/src/libsyntax_pos/symbol.rs @@ -563,6 +563,7 @@ symbols! { rust_2018_preview, rust_begin_unwind, rustc, + Rust, RustcDecodable, RustcEncodable, rustc_allocator, diff --git a/src/test/ui/feature-gated-feature-in-macro-arg.stderr b/src/test/ui/feature-gated-feature-in-macro-arg.stderr index 5ee05154c3a..218e0292776 100644 --- a/src/test/ui/feature-gated-feature-in-macro-arg.stderr +++ b/src/test/ui/feature-gated-feature-in-macro-arg.stderr @@ -1,10 +1,8 @@ error[E0658]: intrinsics are subject to change - --> $DIR/feature-gated-feature-in-macro-arg.rs:8:9 + --> $DIR/feature-gated-feature-in-macro-arg.rs:8:16 | -LL | / extern "rust-intrinsic" { -LL | | fn atomic_fence(); -LL | | } - | |_________^ +LL | extern "rust-intrinsic" { + | ^^^^^^^^^^^^^^^^ | = help: add `#![feature(intrinsics)]` to the crate attributes to enable diff --git a/src/test/ui/feature-gates/feature-gate-abi-msp430-interrupt.stderr b/src/test/ui/feature-gates/feature-gate-abi-msp430-interrupt.stderr index 0d2e355535d..d58a2d91b2b 100644 --- a/src/test/ui/feature-gates/feature-gate-abi-msp430-interrupt.stderr +++ b/src/test/ui/feature-gates/feature-gate-abi-msp430-interrupt.stderr @@ -1,8 +1,8 @@ error[E0658]: msp430-interrupt ABI is experimental and subject to change - --> $DIR/feature-gate-abi-msp430-interrupt.rs:4:1 + --> $DIR/feature-gate-abi-msp430-interrupt.rs:4:8 | LL | extern "msp430-interrupt" fn foo() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/38487 = help: add `#![feature(abi_msp430_interrupt)]` to the crate attributes to enable diff --git a/src/test/ui/feature-gates/feature-gate-abi.stderr b/src/test/ui/feature-gates/feature-gate-abi.stderr index 0f2622f1065..6db6cb49cef 100644 --- a/src/test/ui/feature-gates/feature-gate-abi.stderr +++ b/src/test/ui/feature-gates/feature-gate-abi.stderr @@ -1,591 +1,591 @@ error[E0658]: intrinsics are subject to change - --> $DIR/feature-gate-abi.rs:13:1 + --> $DIR/feature-gate-abi.rs:13:8 | LL | extern "rust-intrinsic" fn f1() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^ | = help: add `#![feature(intrinsics)]` to the crate attributes to enable error[E0658]: platform intrinsics are experimental and possibly buggy - --> $DIR/feature-gate-abi.rs:15:1 + --> $DIR/feature-gate-abi.rs:15:8 | LL | extern "platform-intrinsic" fn f2() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/27731 = help: add `#![feature(platform_intrinsics)]` to the crate attributes to enable error[E0658]: vectorcall is experimental and subject to change - --> $DIR/feature-gate-abi.rs:17:1 + --> $DIR/feature-gate-abi.rs:17:8 | LL | extern "vectorcall" fn f3() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = help: add `#![feature(abi_vectorcall)]` to the crate attributes to enable error[E0658]: rust-call ABI is subject to change - --> $DIR/feature-gate-abi.rs:18:1 + --> $DIR/feature-gate-abi.rs:18:8 | LL | extern "rust-call" fn f4() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/29625 = help: add `#![feature(unboxed_closures)]` to the crate attributes to enable error[E0658]: msp430-interrupt ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:19:1 + --> $DIR/feature-gate-abi.rs:19:8 | LL | extern "msp430-interrupt" fn f5() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/38487 = help: add `#![feature(abi_msp430_interrupt)]` to the crate attributes to enable error[E0658]: PTX ABIs are experimental and subject to change - --> $DIR/feature-gate-abi.rs:20:1 + --> $DIR/feature-gate-abi.rs:20:8 | LL | extern "ptx-kernel" fn f6() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/38788 = help: add `#![feature(abi_ptx)]` to the crate attributes to enable error[E0658]: x86-interrupt ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:21:1 + --> $DIR/feature-gate-abi.rs:21:8 | LL | extern "x86-interrupt" fn f7() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/40180 = help: add `#![feature(abi_x86_interrupt)]` to the crate attributes to enable error[E0658]: thiscall is experimental and subject to change - --> $DIR/feature-gate-abi.rs:22:1 + --> $DIR/feature-gate-abi.rs:22:8 | LL | extern "thiscall" fn f8() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^ | = help: add `#![feature(abi_thiscall)]` to the crate attributes to enable error[E0658]: amdgpu-kernel ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:23:1 + --> $DIR/feature-gate-abi.rs:23:8 | LL | extern "amdgpu-kernel" fn f9() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/51575 = help: add `#![feature(abi_amdgpu_kernel)]` to the crate attributes to enable error[E0658]: efiapi ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:24:1 + --> $DIR/feature-gate-abi.rs:24:8 | LL | extern "efiapi" fn f10() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/65815 = help: add `#![feature(abi_efiapi)]` to the crate attributes to enable error[E0658]: intrinsics are subject to change - --> $DIR/feature-gate-abi.rs:28:5 + --> $DIR/feature-gate-abi.rs:28:12 | LL | extern "rust-intrinsic" fn m1(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^ | = help: add `#![feature(intrinsics)]` to the crate attributes to enable error[E0658]: platform intrinsics are experimental and possibly buggy - --> $DIR/feature-gate-abi.rs:30:5 + --> $DIR/feature-gate-abi.rs:30:12 | LL | extern "platform-intrinsic" fn m2(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/27731 = help: add `#![feature(platform_intrinsics)]` to the crate attributes to enable error[E0658]: vectorcall is experimental and subject to change - --> $DIR/feature-gate-abi.rs:32:5 + --> $DIR/feature-gate-abi.rs:32:12 | LL | extern "vectorcall" fn m3(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = help: add `#![feature(abi_vectorcall)]` to the crate attributes to enable error[E0658]: rust-call ABI is subject to change - --> $DIR/feature-gate-abi.rs:33:5 + --> $DIR/feature-gate-abi.rs:33:12 | LL | extern "rust-call" fn m4(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/29625 = help: add `#![feature(unboxed_closures)]` to the crate attributes to enable error[E0658]: msp430-interrupt ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:34:5 + --> $DIR/feature-gate-abi.rs:34:12 | LL | extern "msp430-interrupt" fn m5(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/38487 = help: add `#![feature(abi_msp430_interrupt)]` to the crate attributes to enable error[E0658]: PTX ABIs are experimental and subject to change - --> $DIR/feature-gate-abi.rs:35:5 + --> $DIR/feature-gate-abi.rs:35:12 | LL | extern "ptx-kernel" fn m6(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/38788 = help: add `#![feature(abi_ptx)]` to the crate attributes to enable error[E0658]: x86-interrupt ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:36:5 + --> $DIR/feature-gate-abi.rs:36:12 | LL | extern "x86-interrupt" fn m7(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/40180 = help: add `#![feature(abi_x86_interrupt)]` to the crate attributes to enable error[E0658]: thiscall is experimental and subject to change - --> $DIR/feature-gate-abi.rs:37:5 + --> $DIR/feature-gate-abi.rs:37:12 | LL | extern "thiscall" fn m8(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^ | = help: add `#![feature(abi_thiscall)]` to the crate attributes to enable error[E0658]: amdgpu-kernel ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:38:5 + --> $DIR/feature-gate-abi.rs:38:12 | LL | extern "amdgpu-kernel" fn m9(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/51575 = help: add `#![feature(abi_amdgpu_kernel)]` to the crate attributes to enable error[E0658]: efiapi ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:39:5 + --> $DIR/feature-gate-abi.rs:39:12 | LL | extern "efiapi" fn m10(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/65815 = help: add `#![feature(abi_efiapi)]` to the crate attributes to enable error[E0658]: vectorcall is experimental and subject to change - --> $DIR/feature-gate-abi.rs:41:5 + --> $DIR/feature-gate-abi.rs:41:12 | LL | extern "vectorcall" fn dm3() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = help: add `#![feature(abi_vectorcall)]` to the crate attributes to enable error[E0658]: rust-call ABI is subject to change - --> $DIR/feature-gate-abi.rs:42:5 + --> $DIR/feature-gate-abi.rs:42:12 | LL | extern "rust-call" fn dm4() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/29625 = help: add `#![feature(unboxed_closures)]` to the crate attributes to enable error[E0658]: msp430-interrupt ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:43:5 + --> $DIR/feature-gate-abi.rs:43:12 | LL | extern "msp430-interrupt" fn dm5() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/38487 = help: add `#![feature(abi_msp430_interrupt)]` to the crate attributes to enable error[E0658]: PTX ABIs are experimental and subject to change - --> $DIR/feature-gate-abi.rs:44:5 + --> $DIR/feature-gate-abi.rs:44:12 | LL | extern "ptx-kernel" fn dm6() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/38788 = help: add `#![feature(abi_ptx)]` to the crate attributes to enable error[E0658]: x86-interrupt ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:45:5 + --> $DIR/feature-gate-abi.rs:45:12 | LL | extern "x86-interrupt" fn dm7() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/40180 = help: add `#![feature(abi_x86_interrupt)]` to the crate attributes to enable error[E0658]: thiscall is experimental and subject to change - --> $DIR/feature-gate-abi.rs:46:5 + --> $DIR/feature-gate-abi.rs:46:12 | LL | extern "thiscall" fn dm8() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^ | = help: add `#![feature(abi_thiscall)]` to the crate attributes to enable error[E0658]: amdgpu-kernel ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:47:5 + --> $DIR/feature-gate-abi.rs:47:12 | LL | extern "amdgpu-kernel" fn dm9() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/51575 = help: add `#![feature(abi_amdgpu_kernel)]` to the crate attributes to enable error[E0658]: efiapi ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:48:5 + --> $DIR/feature-gate-abi.rs:48:12 | LL | extern "efiapi" fn dm10() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/65815 = help: add `#![feature(abi_efiapi)]` to the crate attributes to enable error[E0658]: intrinsics are subject to change - --> $DIR/feature-gate-abi.rs:55:5 + --> $DIR/feature-gate-abi.rs:55:12 | LL | extern "rust-intrinsic" fn m1() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^ | = help: add `#![feature(intrinsics)]` to the crate attributes to enable error[E0658]: platform intrinsics are experimental and possibly buggy - --> $DIR/feature-gate-abi.rs:57:5 + --> $DIR/feature-gate-abi.rs:57:12 | LL | extern "platform-intrinsic" fn m2() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/27731 = help: add `#![feature(platform_intrinsics)]` to the crate attributes to enable error[E0658]: vectorcall is experimental and subject to change - --> $DIR/feature-gate-abi.rs:59:5 + --> $DIR/feature-gate-abi.rs:59:12 | LL | extern "vectorcall" fn m3() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = help: add `#![feature(abi_vectorcall)]` to the crate attributes to enable error[E0658]: rust-call ABI is subject to change - --> $DIR/feature-gate-abi.rs:60:5 + --> $DIR/feature-gate-abi.rs:60:12 | LL | extern "rust-call" fn m4() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/29625 = help: add `#![feature(unboxed_closures)]` to the crate attributes to enable error[E0658]: msp430-interrupt ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:61:5 + --> $DIR/feature-gate-abi.rs:61:12 | LL | extern "msp430-interrupt" fn m5() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/38487 = help: add `#![feature(abi_msp430_interrupt)]` to the crate attributes to enable error[E0658]: PTX ABIs are experimental and subject to change - --> $DIR/feature-gate-abi.rs:62:5 + --> $DIR/feature-gate-abi.rs:62:12 | LL | extern "ptx-kernel" fn m6() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/38788 = help: add `#![feature(abi_ptx)]` to the crate attributes to enable error[E0658]: x86-interrupt ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:63:5 + --> $DIR/feature-gate-abi.rs:63:12 | LL | extern "x86-interrupt" fn m7() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/40180 = help: add `#![feature(abi_x86_interrupt)]` to the crate attributes to enable error[E0658]: thiscall is experimental and subject to change - --> $DIR/feature-gate-abi.rs:64:5 + --> $DIR/feature-gate-abi.rs:64:12 | LL | extern "thiscall" fn m8() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^ | = help: add `#![feature(abi_thiscall)]` to the crate attributes to enable error[E0658]: amdgpu-kernel ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:65:5 + --> $DIR/feature-gate-abi.rs:65:12 | LL | extern "amdgpu-kernel" fn m9() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/51575 = help: add `#![feature(abi_amdgpu_kernel)]` to the crate attributes to enable error[E0658]: efiapi ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:66:5 + --> $DIR/feature-gate-abi.rs:66:12 | LL | extern "efiapi" fn m10() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/65815 = help: add `#![feature(abi_efiapi)]` to the crate attributes to enable error[E0658]: intrinsics are subject to change - --> $DIR/feature-gate-abi.rs:71:5 + --> $DIR/feature-gate-abi.rs:71:12 | LL | extern "rust-intrinsic" fn im1() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^ | = help: add `#![feature(intrinsics)]` to the crate attributes to enable error[E0658]: platform intrinsics are experimental and possibly buggy - --> $DIR/feature-gate-abi.rs:73:5 + --> $DIR/feature-gate-abi.rs:73:12 | LL | extern "platform-intrinsic" fn im2() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/27731 = help: add `#![feature(platform_intrinsics)]` to the crate attributes to enable error[E0658]: vectorcall is experimental and subject to change - --> $DIR/feature-gate-abi.rs:75:5 + --> $DIR/feature-gate-abi.rs:75:12 | LL | extern "vectorcall" fn im3() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = help: add `#![feature(abi_vectorcall)]` to the crate attributes to enable error[E0658]: rust-call ABI is subject to change - --> $DIR/feature-gate-abi.rs:76:5 + --> $DIR/feature-gate-abi.rs:76:12 | LL | extern "rust-call" fn im4() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/29625 = help: add `#![feature(unboxed_closures)]` to the crate attributes to enable error[E0658]: msp430-interrupt ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:77:5 + --> $DIR/feature-gate-abi.rs:77:12 | LL | extern "msp430-interrupt" fn im5() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/38487 = help: add `#![feature(abi_msp430_interrupt)]` to the crate attributes to enable error[E0658]: PTX ABIs are experimental and subject to change - --> $DIR/feature-gate-abi.rs:78:5 + --> $DIR/feature-gate-abi.rs:78:12 | LL | extern "ptx-kernel" fn im6() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/38788 = help: add `#![feature(abi_ptx)]` to the crate attributes to enable error[E0658]: x86-interrupt ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:79:5 + --> $DIR/feature-gate-abi.rs:79:12 | LL | extern "x86-interrupt" fn im7() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/40180 = help: add `#![feature(abi_x86_interrupt)]` to the crate attributes to enable error[E0658]: thiscall is experimental and subject to change - --> $DIR/feature-gate-abi.rs:80:5 + --> $DIR/feature-gate-abi.rs:80:12 | LL | extern "thiscall" fn im8() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^ | = help: add `#![feature(abi_thiscall)]` to the crate attributes to enable error[E0658]: amdgpu-kernel ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:81:5 + --> $DIR/feature-gate-abi.rs:81:12 | LL | extern "amdgpu-kernel" fn im9() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/51575 = help: add `#![feature(abi_amdgpu_kernel)]` to the crate attributes to enable error[E0658]: efiapi ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:82:5 + --> $DIR/feature-gate-abi.rs:82:12 | LL | extern "efiapi" fn im10() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/65815 = help: add `#![feature(abi_efiapi)]` to the crate attributes to enable error[E0658]: intrinsics are subject to change - --> $DIR/feature-gate-abi.rs:86:11 + --> $DIR/feature-gate-abi.rs:86:18 | LL | type A1 = extern "rust-intrinsic" fn(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^ | = help: add `#![feature(intrinsics)]` to the crate attributes to enable error[E0658]: platform intrinsics are experimental and possibly buggy - --> $DIR/feature-gate-abi.rs:87:11 + --> $DIR/feature-gate-abi.rs:87:18 | LL | type A2 = extern "platform-intrinsic" fn(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/27731 = help: add `#![feature(platform_intrinsics)]` to the crate attributes to enable error[E0658]: vectorcall is experimental and subject to change - --> $DIR/feature-gate-abi.rs:88:11 + --> $DIR/feature-gate-abi.rs:88:18 | LL | type A3 = extern "vectorcall" fn(); - | ^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = help: add `#![feature(abi_vectorcall)]` to the crate attributes to enable error[E0658]: rust-call ABI is subject to change - --> $DIR/feature-gate-abi.rs:89:11 + --> $DIR/feature-gate-abi.rs:89:18 | LL | type A4 = extern "rust-call" fn(); - | ^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/29625 = help: add `#![feature(unboxed_closures)]` to the crate attributes to enable error[E0658]: msp430-interrupt ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:90:11 + --> $DIR/feature-gate-abi.rs:90:18 | LL | type A5 = extern "msp430-interrupt" fn(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/38487 = help: add `#![feature(abi_msp430_interrupt)]` to the crate attributes to enable error[E0658]: PTX ABIs are experimental and subject to change - --> $DIR/feature-gate-abi.rs:91:11 + --> $DIR/feature-gate-abi.rs:91:18 | LL | type A6 = extern "ptx-kernel" fn (); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/38788 = help: add `#![feature(abi_ptx)]` to the crate attributes to enable error[E0658]: x86-interrupt ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:92:11 + --> $DIR/feature-gate-abi.rs:92:18 | LL | type A7 = extern "x86-interrupt" fn(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/40180 = help: add `#![feature(abi_x86_interrupt)]` to the crate attributes to enable error[E0658]: thiscall is experimental and subject to change - --> $DIR/feature-gate-abi.rs:93:11 + --> $DIR/feature-gate-abi.rs:93:18 | LL | type A8 = extern "thiscall" fn(); - | ^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^ | = help: add `#![feature(abi_thiscall)]` to the crate attributes to enable error[E0658]: amdgpu-kernel ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:94:11 + --> $DIR/feature-gate-abi.rs:94:18 | LL | type A9 = extern "amdgpu-kernel" fn(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/51575 = help: add `#![feature(abi_amdgpu_kernel)]` to the crate attributes to enable error[E0658]: efiapi ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:95:12 + --> $DIR/feature-gate-abi.rs:95:19 | LL | type A10 = extern "efiapi" fn(); - | ^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/65815 = help: add `#![feature(abi_efiapi)]` to the crate attributes to enable error[E0658]: intrinsics are subject to change - --> $DIR/feature-gate-abi.rs:98:1 + --> $DIR/feature-gate-abi.rs:98:8 | LL | extern "rust-intrinsic" {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^ | = help: add `#![feature(intrinsics)]` to the crate attributes to enable error[E0658]: platform intrinsics are experimental and possibly buggy - --> $DIR/feature-gate-abi.rs:99:1 + --> $DIR/feature-gate-abi.rs:99:8 | LL | extern "platform-intrinsic" {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/27731 = help: add `#![feature(platform_intrinsics)]` to the crate attributes to enable error[E0658]: vectorcall is experimental and subject to change - --> $DIR/feature-gate-abi.rs:100:1 + --> $DIR/feature-gate-abi.rs:100:8 | LL | extern "vectorcall" {} - | ^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = help: add `#![feature(abi_vectorcall)]` to the crate attributes to enable error[E0658]: rust-call ABI is subject to change - --> $DIR/feature-gate-abi.rs:101:1 + --> $DIR/feature-gate-abi.rs:101:8 | LL | extern "rust-call" {} - | ^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/29625 = help: add `#![feature(unboxed_closures)]` to the crate attributes to enable error[E0658]: msp430-interrupt ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:102:1 + --> $DIR/feature-gate-abi.rs:102:8 | LL | extern "msp430-interrupt" {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/38487 = help: add `#![feature(abi_msp430_interrupt)]` to the crate attributes to enable error[E0658]: PTX ABIs are experimental and subject to change - --> $DIR/feature-gate-abi.rs:103:1 + --> $DIR/feature-gate-abi.rs:103:8 | LL | extern "ptx-kernel" {} - | ^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/38788 = help: add `#![feature(abi_ptx)]` to the crate attributes to enable error[E0658]: x86-interrupt ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:104:1 + --> $DIR/feature-gate-abi.rs:104:8 | LL | extern "x86-interrupt" {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/40180 = help: add `#![feature(abi_x86_interrupt)]` to the crate attributes to enable error[E0658]: thiscall is experimental and subject to change - --> $DIR/feature-gate-abi.rs:105:1 + --> $DIR/feature-gate-abi.rs:105:8 | LL | extern "thiscall" {} - | ^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^ | = help: add `#![feature(abi_thiscall)]` to the crate attributes to enable error[E0658]: amdgpu-kernel ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:106:1 + --> $DIR/feature-gate-abi.rs:106:8 | LL | extern "amdgpu-kernel" {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/51575 = help: add `#![feature(abi_amdgpu_kernel)]` to the crate attributes to enable error[E0658]: efiapi ABI is experimental and subject to change - --> $DIR/feature-gate-abi.rs:107:1 + --> $DIR/feature-gate-abi.rs:107:8 | LL | extern "efiapi" {} - | ^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/65815 = help: add `#![feature(abi_efiapi)]` to the crate attributes to enable diff --git a/src/test/ui/feature-gates/feature-gate-abi_unadjusted.stderr b/src/test/ui/feature-gates/feature-gate-abi_unadjusted.stderr index 4954a7d1f71..1757befec35 100644 --- a/src/test/ui/feature-gates/feature-gate-abi_unadjusted.stderr +++ b/src/test/ui/feature-gates/feature-gate-abi_unadjusted.stderr @@ -1,10 +1,8 @@ error[E0658]: unadjusted ABI is an implementation detail and perma-unstable - --> $DIR/feature-gate-abi_unadjusted.rs:1:1 + --> $DIR/feature-gate-abi_unadjusted.rs:1:8 | -LL | / extern "unadjusted" fn foo() { -LL | | -LL | | } - | |_^ +LL | extern "unadjusted" fn foo() { + | ^^^^^^^^^^^^ | = help: add `#![feature(abi_unadjusted)]` to the crate attributes to enable diff --git a/src/test/ui/feature-gates/feature-gate-intrinsics.stderr b/src/test/ui/feature-gates/feature-gate-intrinsics.stderr index 101a10e8df7..8f943d357ce 100644 --- a/src/test/ui/feature-gates/feature-gate-intrinsics.stderr +++ b/src/test/ui/feature-gates/feature-gate-intrinsics.stderr @@ -1,18 +1,16 @@ error[E0658]: intrinsics are subject to change - --> $DIR/feature-gate-intrinsics.rs:1:1 + --> $DIR/feature-gate-intrinsics.rs:1:8 | -LL | / extern "rust-intrinsic" { -LL | | fn bar(); -LL | | } - | |_^ +LL | extern "rust-intrinsic" { + | ^^^^^^^^^^^^^^^^ | = help: add `#![feature(intrinsics)]` to the crate attributes to enable error[E0658]: intrinsics are subject to change - --> $DIR/feature-gate-intrinsics.rs:5:1 + --> $DIR/feature-gate-intrinsics.rs:5:8 | LL | extern "rust-intrinsic" fn baz() {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^ | = help: add `#![feature(intrinsics)]` to the crate attributes to enable diff --git a/src/test/ui/feature-gates/feature-gate-unboxed-closures-manual-impls.stderr b/src/test/ui/feature-gates/feature-gate-unboxed-closures-manual-impls.stderr index c05379c71ee..657bf13c873 100644 --- a/src/test/ui/feature-gates/feature-gate-unboxed-closures-manual-impls.stderr +++ b/src/test/ui/feature-gates/feature-gate-unboxed-closures-manual-impls.stderr @@ -1,35 +1,35 @@ error[E0658]: rust-call ABI is subject to change - --> $DIR/feature-gate-unboxed-closures-manual-impls.rs:11:5 + --> $DIR/feature-gate-unboxed-closures-manual-impls.rs:11:12 | LL | extern "rust-call" fn call(self, args: ()) -> () {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/29625 = help: add `#![feature(unboxed_closures)]` to the crate attributes to enable error[E0658]: rust-call ABI is subject to change - --> $DIR/feature-gate-unboxed-closures-manual-impls.rs:17:5 + --> $DIR/feature-gate-unboxed-closures-manual-impls.rs:17:12 | LL | extern "rust-call" fn call_once(self, args: ()) -> () {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/29625 = help: add `#![feature(unboxed_closures)]` to the crate attributes to enable error[E0658]: rust-call ABI is subject to change - --> $DIR/feature-gate-unboxed-closures-manual-impls.rs:23:5 + --> $DIR/feature-gate-unboxed-closures-manual-impls.rs:23:12 | LL | extern "rust-call" fn call_mut(&self, args: ()) -> () {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/29625 = help: add `#![feature(unboxed_closures)]` to the crate attributes to enable error[E0658]: rust-call ABI is subject to change - --> $DIR/feature-gate-unboxed-closures-manual-impls.rs:29:5 + --> $DIR/feature-gate-unboxed-closures-manual-impls.rs:29:12 | LL | extern "rust-call" fn call_once(&self, args: ()) -> () {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/29625 = help: add `#![feature(unboxed_closures)]` to the crate attributes to enable diff --git a/src/test/ui/feature-gates/feature-gate-unboxed-closures.stderr b/src/test/ui/feature-gates/feature-gate-unboxed-closures.stderr index 723c6619887..f343a42eb8f 100644 --- a/src/test/ui/feature-gates/feature-gate-unboxed-closures.stderr +++ b/src/test/ui/feature-gates/feature-gate-unboxed-closures.stderr @@ -1,10 +1,8 @@ error[E0658]: rust-call ABI is subject to change - --> $DIR/feature-gate-unboxed-closures.rs:9:5 + --> $DIR/feature-gate-unboxed-closures.rs:9:12 | -LL | / extern "rust-call" fn call_once(self, (a, b): (u32, u32)) -> u32 { -LL | | a + b -LL | | } - | |_____^ +LL | extern "rust-call" fn call_once(self, (a, b): (u32, u32)) -> u32 { + | ^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/29625 = help: add `#![feature(unboxed_closures)]` to the crate attributes to enable -- cgit 1.4.1-3-g733a5 From 1db4d607e7621a7d813743e83125859a47970f79 Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Mon, 28 Oct 2019 00:29:23 +0100 Subject: parser: allow ABIs from literal macro fragments --- src/libsyntax/parse/parser.rs | 40 +++++++++++++++------- src/libsyntax/parse/parser/expr.rs | 6 +++- src/libsyntax/parse/parser/item.rs | 2 +- src/libsyntax/parse/token.rs | 7 ---- src/test/ui/parser/bad-lit-suffixes.rs | 4 +-- src/test/ui/parser/bad-lit-suffixes.stderr | 4 +-- .../ui/parser/extern-abi-from-mac-literal-frag.rs | 26 ++++++++++++++ 7 files changed, 63 insertions(+), 26 deletions(-) create mode 100644 src/test/ui/parser/extern-abi-from-mac-literal-frag.rs (limited to 'src/libsyntax/parse/parser.rs') diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 382c1a517aa..0c358b1caaf 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -1205,27 +1205,41 @@ impl<'a> Parser<'a> { Ok(()) } - /// Parses `extern` followed by an optional ABI string, or nothing. + /// 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) { - let ext_sp = self.prev_span; - self.parse_opt_abi()?.unwrap_or_else(|| Abi::new(sym::C, ext_sp)) + self.parse_opt_abi()? } else { Abi::default() }) } - /// Parses a string as an ABI spec on an extern type or module. - fn parse_opt_abi(&mut self) -> PResult<'a, Option> { - match self.token.kind { - token::Literal(token::Lit { kind: token::Str, symbol, suffix }) | - token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => { - self.expect_no_suffix(self.token.span, "an ABI spec", suffix); - self.bump(); - Ok(Some(Abi::new(symbol, self.prev_span))) + /// 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(); + } } - _ => Ok(None), - } + 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. diff --git a/src/libsyntax/parse/parser/expr.rs b/src/libsyntax/parse/parser/expr.rs index 97b1092452a..80ea8f380fb 100644 --- a/src/libsyntax/parse/parser/expr.rs +++ b/src/libsyntax/parse/parser/expr.rs @@ -1116,7 +1116,11 @@ impl<'a> Parser<'a> { Err(self.span_fatal(token.span, &msg)) } Err(err) => { - let (lit, span) = (token.expect_lit(), token.span); + 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 diff --git a/src/libsyntax/parse/parser/item.rs b/src/libsyntax/parse/parser/item.rs index 76411e7cf13..ebb1cf12996 100644 --- a/src/libsyntax/parse/parser/item.rs +++ b/src/libsyntax/parse/parser/item.rs @@ -110,7 +110,7 @@ impl<'a> Parser<'a> { return Ok(Some(self.parse_item_extern_crate(lo, vis, attrs)?)); } - let abi = self.parse_opt_abi()?.unwrap_or_else(|| Abi::new(sym::C, extern_sp)); + let abi = self.parse_opt_abi()?; if self.eat_keyword(kw::Fn) { // EXTERN FUNCTION ITEM diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index ea82aad0eae..6f3da344ccf 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -402,13 +402,6 @@ impl Token { } } - crate fn expect_lit(&self) -> Lit { - match self.kind { - Literal(lit) => lit, - _ => panic!("`expect_lit` called on non-literal"), - } - } - /// Returns `true` if the token is any literal, a minus (which can prefix a literal, /// for example a '-42', or one of the boolean idents). pub fn can_begin_literal_or_bool(&self) -> bool { diff --git a/src/test/ui/parser/bad-lit-suffixes.rs b/src/test/ui/parser/bad-lit-suffixes.rs index 9f301db0995..7db83674efc 100644 --- a/src/test/ui/parser/bad-lit-suffixes.rs +++ b/src/test/ui/parser/bad-lit-suffixes.rs @@ -1,9 +1,9 @@ extern - "C"suffix //~ ERROR suffixes on an ABI spec are invalid + "C"suffix //~ ERROR suffixes on a string literal are invalid fn foo() {} extern - "C"suffix //~ ERROR suffixes on an ABI spec are invalid + "C"suffix //~ ERROR suffixes on a string literal are invalid {} fn main() { diff --git a/src/test/ui/parser/bad-lit-suffixes.stderr b/src/test/ui/parser/bad-lit-suffixes.stderr index 208fcf43d91..6b0049298ff 100644 --- a/src/test/ui/parser/bad-lit-suffixes.stderr +++ b/src/test/ui/parser/bad-lit-suffixes.stderr @@ -1,10 +1,10 @@ -error: suffixes on an ABI spec are invalid +error: suffixes on a string literal are invalid --> $DIR/bad-lit-suffixes.rs:2:5 | LL | "C"suffix | ^^^^^^^^^ invalid suffix `suffix` -error: suffixes on an ABI spec are invalid +error: suffixes on a string literal are invalid --> $DIR/bad-lit-suffixes.rs:6:5 | LL | "C"suffix diff --git a/src/test/ui/parser/extern-abi-from-mac-literal-frag.rs b/src/test/ui/parser/extern-abi-from-mac-literal-frag.rs new file mode 100644 index 00000000000..cb23f2c808c --- /dev/null +++ b/src/test/ui/parser/extern-abi-from-mac-literal-frag.rs @@ -0,0 +1,26 @@ +// check-pass + +// In this test we check that the parser accepts an ABI string when it +// comes from a macro `literal` fragment as opposed to a hardcoded string. + +fn main() {} + +macro_rules! abi_from_lit_frag { + ($abi:literal) => { + extern $abi { + fn _import(); + } + + extern $abi fn _export() {} + + type _PTR = extern $abi fn(); + } +} + +mod rust { + abi_from_lit_frag!("Rust"); +} + +mod c { + abi_from_lit_frag!("C"); +} -- cgit 1.4.1-3-g733a5 From da116223c709392db3741d966cb49ea0407de19e Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Fri, 25 Oct 2019 04:57:40 +0200 Subject: move parse/parser.rs -> parse/parser/mod.rs --- src/libsyntax/parse/parser.rs | 1391 ------------------------------------- src/libsyntax/parse/parser/mod.rs | 1391 +++++++++++++++++++++++++++++++++++++ 2 files changed, 1391 insertions(+), 1391 deletions(-) delete mode 100644 src/libsyntax/parse/parser.rs create mode 100644 src/libsyntax/parse/parser/mod.rs (limited to 'src/libsyntax/parse/parser.rs') diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs deleted file mode 100644 index 1284e89f195..00000000000 --- a/src/libsyntax/parse/parser.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::{PResult, Directory, DirectoryOwnership}; -use crate::parse::lexer::UnmatchedBrace; -use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration}; -use crate::parse::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::{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, - /// 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, - expected_tokens: Vec, - 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, - last_unexpected_token_span: Option, - 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, -} - -#[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), - Was(Option), -} - -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::().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::() - } else { - [TokenTree::token(token::Pound, sp), body] - .iter().cloned().collect::() - }, - ))); - - 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, - /// `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>, - 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(&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( - &mut self, - ket: &TokenKind, - sep: SeqSep, - f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, Vec> { - 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( - &mut self, - ket: &TokenKind, - sep: SeqSep, - f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec, 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( - &mut self, - kets: &[&TokenKind], - sep: SeqSep, - expect: TokenExpectType, - mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec, 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( - &mut self, - bra: &TokenKind, - ket: &TokenKind, - sep: SeqSep, - f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec, 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( - &mut self, - delim: DelimToken, - f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec, bool)> { - self.parse_unspanned_seq( - &token::OpenDelim(delim), - &token::CloseDelim(delim), - SeqSep::trailing_allowed(token::Comma), - f, - ) - } - - fn parse_paren_comma_seq( - &mut self, - f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec, 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(&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 { - 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>, - ) -> PResult<'a, ThinVec> { - 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> { - 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(&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`, 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( - &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)> { - 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> { - // `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, 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/mod.rs b/src/libsyntax/parse/parser/mod.rs new file mode 100644 index 00000000000..1284e89f195 --- /dev/null +++ b/src/libsyntax/parse/parser/mod.rs @@ -0,0 +1,1391 @@ +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::{PResult, Directory, DirectoryOwnership}; +use crate::parse::lexer::UnmatchedBrace; +use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration}; +use crate::parse::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::{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, + /// 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, + expected_tokens: Vec, + 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, + last_unexpected_token_span: Option, + 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, +} + +#[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), + Was(Option), +} + +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::().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::() + } else { + [TokenTree::token(token::Pound, sp), body] + .iter().cloned().collect::() + }, + ))); + + 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, + /// `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>, + 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(&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( + &mut self, + ket: &TokenKind, + sep: SeqSep, + f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, + ) -> PResult<'a, Vec> { + 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( + &mut self, + ket: &TokenKind, + sep: SeqSep, + f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, + ) -> PResult<'a, (Vec, 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( + &mut self, + kets: &[&TokenKind], + sep: SeqSep, + expect: TokenExpectType, + mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, + ) -> PResult<'a, (Vec, 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( + &mut self, + bra: &TokenKind, + ket: &TokenKind, + sep: SeqSep, + f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, + ) -> PResult<'a, (Vec, 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( + &mut self, + delim: DelimToken, + f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, + ) -> PResult<'a, (Vec, bool)> { + self.parse_unspanned_seq( + &token::OpenDelim(delim), + &token::CloseDelim(delim), + SeqSep::trailing_allowed(token::Comma), + f, + ) + } + + fn parse_paren_comma_seq( + &mut self, + f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, + ) -> PResult<'a, (Vec, 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(&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 { + 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>, + ) -> PResult<'a, ThinVec> { + 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> { + 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(&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`, 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( + &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)> { + 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> { + // `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, 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()); + } +} -- cgit 1.4.1-3-g733a5