2 use rustc_ast::token::{self, Nonterminal, NonterminalKind, Token};
3 use rustc_ast_pretty::pprust;
4 use rustc_errors::PResult;
5 use rustc_span::symbol::{kw, Ident};
7 use crate::parser::pat::RecoverComma;
8 use crate::parser::{FollowedByType, ForceCollect, Parser, PathStyle};
11 /// Checks whether a non-terminal may begin with a particular token.
13 /// Returning `false` is a *stability guarantee* that such a matcher will *never* begin with that
14 /// token. Be conservative (return true) if not sure.
15 pub fn nonterminal_may_begin_with(kind: NonterminalKind, token: &Token) -> bool {
16 /// Checks whether the non-terminal may contain a single (non-keyword) identifier.
17 fn may_be_ident(nt: &token::Nonterminal) -> bool {
19 token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) | token::NtLifetime(_) => {
27 NonterminalKind::Expr => {
28 token.can_begin_expr()
29 // This exception is here for backwards compatibility.
30 && !token.is_keyword(kw::Let)
31 // This exception is here for backwards compatibility.
32 && !token.is_keyword(kw::Const)
34 NonterminalKind::Ty => token.can_begin_type(),
35 NonterminalKind::Ident => get_macro_ident(token).is_some(),
36 NonterminalKind::Literal => token.can_begin_literal_maybe_minus(),
37 NonterminalKind::Vis => match token.kind {
38 // The follow-set of :vis + "priv" keyword + interpolated
39 token::Comma | token::Ident(..) | token::Interpolated(..) => true,
40 _ => token.can_begin_type(),
42 NonterminalKind::Block => match token.kind {
43 token::OpenDelim(token::Brace) => true,
44 token::Interpolated(ref nt) => !matches!(
56 NonterminalKind::Path | NonterminalKind::Meta => match token.kind {
57 token::ModSep | token::Ident(..) => true,
58 token::Interpolated(ref nt) => match **nt {
59 token::NtPath(_) | token::NtMeta(_) => true,
60 _ => may_be_ident(&nt),
64 NonterminalKind::PatParam { .. } | NonterminalKind::PatWithOr { .. } => {
66 token::Ident(..) | // box, ref, mut, and other identifiers (can stricten)
67 token::OpenDelim(token::Paren) | // tuple pattern
68 token::OpenDelim(token::Bracket) | // slice pattern
69 token::BinOp(token::And) | // reference
70 token::BinOp(token::Minus) | // negative literal
71 token::AndAnd | // double reference
72 token::Literal(..) | // literal
73 token::DotDot | // range pattern (future compat)
74 token::DotDotDot | // range pattern (future compat)
75 token::ModSep | // path
76 token::Lt | // path (UFCS constant)
77 token::BinOp(token::Shl) => true, // path (double UFCS)
78 // leading vert `|` or-pattern
79 token::BinOp(token::Or) => matches!(kind, NonterminalKind::PatWithOr {..}),
80 token::Interpolated(ref nt) => may_be_ident(nt),
84 NonterminalKind::Lifetime => match token.kind {
85 token::Lifetime(_) => true,
86 token::Interpolated(ref nt) => {
87 matches!(**nt, token::NtLifetime(_) | token::NtTT(_))
91 NonterminalKind::TT | NonterminalKind::Item | NonterminalKind::Stmt => {
92 !matches!(token.kind, token::CloseDelim(_))
97 /// Parse a non-terminal (e.g. MBE `:pat` or `:ident`).
98 pub fn parse_nonterminal(&mut self, kind: NonterminalKind) -> PResult<'a, Nonterminal> {
99 // Any `Nonterminal` which stores its tokens (currently `NtItem` and `NtExpr`)
100 // needs to have them force-captured here.
101 // A `macro_rules!` invocation may pass a captured item/expr to a proc-macro,
102 // which requires having captured tokens available. Since we cannot determine
103 // in advance whether or not a proc-macro will be (transitively) invoked,
104 // we always capture tokens for any `Nonterminal` which needs them.
106 NonterminalKind::Item => match self.parse_item(ForceCollect::Yes)? {
107 Some(item) => token::NtItem(item),
109 return Err(self.struct_span_err(self.token.span, "expected an item keyword"));
112 NonterminalKind::Block => {
113 // While a block *expression* may have attributes (e.g. `#[my_attr] { ... }`),
114 // the ':block' matcher does not support them
115 token::NtBlock(self.collect_tokens_no_attrs(|this| this.parse_block())?)
117 NonterminalKind::Stmt => match self.parse_stmt(ForceCollect::Yes)? {
118 Some(s) => token::NtStmt(s),
120 return Err(self.struct_span_err(self.token.span, "expected a statement"));
123 NonterminalKind::PatParam { .. } | NonterminalKind::PatWithOr { .. } => {
124 token::NtPat(self.collect_tokens_no_attrs(|this| match kind {
125 NonterminalKind::PatParam { .. } => this.parse_pat_no_top_alt(None),
126 NonterminalKind::PatWithOr { .. } => {
127 this.parse_pat_allow_top_alt(None, RecoverComma::No)
133 NonterminalKind::Expr => token::NtExpr(self.parse_expr_force_collect()?),
134 NonterminalKind::Literal => {
135 // The `:literal` matcher does not support attributes
137 self.collect_tokens_no_attrs(|this| this.parse_literal_maybe_minus())?,
141 NonterminalKind::Ty => {
142 token::NtTy(self.collect_tokens_no_attrs(|this| this.parse_ty())?)
144 // this could be handled like a token, since it is one
145 NonterminalKind::Ident => {
146 if let Some((ident, is_raw)) = get_macro_ident(&self.token) {
148 token::NtIdent(ident, is_raw)
150 let token_str = pprust::token_to_string(&self.token);
151 let msg = &format!("expected ident, found {}", &token_str);
152 return Err(self.struct_span_err(self.token.span, msg));
155 NonterminalKind::Path => token::NtPath(
156 self.collect_tokens_no_attrs(|this| this.parse_path(PathStyle::Type))?,
158 NonterminalKind::Meta => token::NtMeta(P(self.parse_attr_item(true)?)),
159 NonterminalKind::TT => token::NtTT(self.parse_token_tree()),
160 NonterminalKind::Vis => token::NtVis(
161 self.collect_tokens_no_attrs(|this| this.parse_visibility(FollowedByType::Yes))?,
163 NonterminalKind::Lifetime => {
164 if self.check_lifetime() {
165 token::NtLifetime(self.expect_lifetime().ident)
167 let token_str = pprust::token_to_string(&self.token);
168 let msg = &format!("expected a lifetime, found `{}`", &token_str);
169 return Err(self.struct_span_err(self.token.span, msg));
176 /// The token is an identifier, but not `_`.
177 /// We prohibit passing `_` to macros expecting `ident` for now.
178 fn get_macro_ident(token: &Token) -> Option<(Ident, bool)> {
179 token.ident().filter(|(ident, _)| ident.name != kw::Underscore)