Skip to main content

rustc_parse/parser/
nonterminal.rs

1use rustc_ast::token::NtExprKind::*;
2use rustc_ast::token::NtPatKind::*;
3use rustc_ast::token::{self, InvisibleOrigin, MetaVarKind, NonterminalKind, Token};
4use rustc_ast_pretty::pprust;
5use rustc_errors::PResult;
6use rustc_span::{Ident, kw};
7
8use crate::errors::UnexpectedNonterminal;
9use crate::parser::pat::{CommaRecoveryMode, RecoverColon, RecoverComma};
10use crate::parser::{
11    AllowConstBlockItems, FollowedByType, ForceCollect, ParseNtResult, Parser, PathStyle,
12};
13
14impl<'a> Parser<'a> {
15    /// Checks whether a non-terminal may begin with a particular token.
16    ///
17    /// Returning `false` is a *stability guarantee* that such a matcher will *never* begin with
18    /// that token. Be conservative (return true) if not sure. Inlined because it has a single call
19    /// site.
20    #[inline]
21    pub fn nonterminal_may_begin_with(kind: NonterminalKind, token: &Token) -> bool {
22        /// Checks whether the non-terminal may contain a single (non-keyword) identifier.
23        fn may_be_ident(kind: MetaVarKind) -> bool {
24            match kind {
25                MetaVarKind::Stmt
26                | MetaVarKind::Pat(_)
27                | MetaVarKind::Expr { .. }
28                | MetaVarKind::Ty { .. }
29                | MetaVarKind::Meta { .. }
30                | MetaVarKind::Path => true,
31                // `true`, `false`
32                MetaVarKind::Literal => true,
33
34                MetaVarKind::Item | MetaVarKind::Block | MetaVarKind::Vis | MetaVarKind::Guard => {
35                    false
36                }
37
38                MetaVarKind::Ident | MetaVarKind::Lifetime | MetaVarKind::TT => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
39            }
40        }
41
42        match kind {
43            // `expr_2021` and earlier
44            NonterminalKind::Expr(Expr2021 { .. }) => {
45                token.can_begin_expr()
46                // This exception is here for backwards compatibility.
47                && !token.is_keyword(kw::Let)
48                // This exception is here for backwards compatibility.
49                && !token.is_keyword(kw::Const)
50            }
51            // Current edition expressions
52            NonterminalKind::Expr(Expr) => {
53                // In Edition 2024, `_` is considered an expression, so we
54                // need to allow it here because `token.can_begin_expr()` does
55                // not consider `_` to be an expression.
56                //
57                // Because `can_begin_expr` is used elsewhere, we need to reduce
58                // the scope of where the `_` is considered an expression to
59                // just macro parsing code.
60                (token.can_begin_expr() || token.is_keyword(kw::Underscore))
61                // This exception is here for backwards compatibility.
62                && !token.is_keyword(kw::Let)
63            }
64            NonterminalKind::Ty => token.can_begin_type(),
65            NonterminalKind::Ident => get_macro_ident(token).is_some(),
66            NonterminalKind::Literal => token.can_begin_literal_maybe_minus(),
67            NonterminalKind::Vis => match token.kind {
68                // The follow-set of :vis + "priv" keyword + interpolated/metavar-expansion.
69                token::Comma
70                | token::Ident(..)
71                | token::NtIdent(..)
72                | token::NtLifetime(..)
73                | token::OpenInvisible(InvisibleOrigin::MetaVar(_)) => true,
74                _ => token.can_begin_type(),
75            },
76            NonterminalKind::Block => match &token.kind {
77                token::OpenBrace => true,
78                token::NtLifetime(..) => true,
79                token::OpenInvisible(InvisibleOrigin::MetaVar(k)) => match k {
80                    MetaVarKind::Block
81                    | MetaVarKind::Stmt
82                    | MetaVarKind::Expr { .. }
83                    | MetaVarKind::Literal => true,
84                    MetaVarKind::Item
85                    | MetaVarKind::Pat(_)
86                    | MetaVarKind::Ty { .. }
87                    | MetaVarKind::Meta { .. }
88                    | MetaVarKind::Path
89                    | MetaVarKind::Vis
90                    | MetaVarKind::Guard => false,
91                    MetaVarKind::Lifetime | MetaVarKind::Ident | MetaVarKind::TT => {
92                        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
93                    }
94                },
95                _ => false,
96            },
97            NonterminalKind::Path | NonterminalKind::Meta => match &token.kind {
98                token::PathSep | token::Ident(..) | token::NtIdent(..) => true,
99                token::OpenInvisible(InvisibleOrigin::MetaVar(kind)) => may_be_ident(*kind),
100                _ => false,
101            },
102            NonterminalKind::Pat(pat_kind) => token.can_begin_pattern(pat_kind),
103            NonterminalKind::Lifetime => match &token.kind {
104                token::Lifetime(..) | token::NtLifetime(..) => true,
105                _ => false,
106            },
107            NonterminalKind::Guard => match token.kind {
108                token::OpenInvisible(InvisibleOrigin::MetaVar(MetaVarKind::Guard)) => true,
109                _ => token.is_keyword(kw::If),
110            },
111            NonterminalKind::TT | NonterminalKind::Item | NonterminalKind::Stmt => {
112                token.kind.close_delim().is_none()
113            }
114        }
115    }
116
117    /// Parse a non-terminal (e.g. MBE `:pat` or `:ident`). Inlined because there is only one call
118    /// site.
119    #[inline]
120    pub fn parse_nonterminal(&mut self, kind: NonterminalKind) -> PResult<'a, ParseNtResult> {
121        // A `macro_rules!` invocation may pass a captured item/expr to a proc-macro,
122        // which requires having captured tokens available. Since we cannot determine
123        // in advance whether or not a proc-macro will be (transitively) invoked,
124        // we always capture tokens for any nonterminal that needs them.
125        match kind {
126            // Note that TT is treated differently to all the others.
127            NonterminalKind::TT => Ok(ParseNtResult::Tt(self.parse_token_tree())),
128            NonterminalKind::Item => match self
129                .parse_item(ForceCollect::Yes, AllowConstBlockItems::Yes)?
130            {
131                Some(item) => Ok(ParseNtResult::Item(item)),
132                None => Err(self.dcx().create_err(UnexpectedNonterminal::Item(self.token.span))),
133            },
134            NonterminalKind::Block => {
135                // While a block *expression* may have attributes (e.g. `#[my_attr] { ... }`),
136                // the ':block' matcher does not support them
137                Ok(ParseNtResult::Block(self.collect_tokens_no_attrs(|this| this.parse_block())?))
138            }
139            NonterminalKind::Stmt => match self.parse_stmt(ForceCollect::Yes)? {
140                Some(stmt) => Ok(ParseNtResult::Stmt(Box::new(stmt))),
141                None => {
142                    Err(self.dcx().create_err(UnexpectedNonterminal::Statement(self.token.span)))
143                }
144            },
145            NonterminalKind::Pat(pat_kind) => Ok(ParseNtResult::Pat(
146                self.collect_tokens_no_attrs(|this| match pat_kind {
147                    PatParam { .. } => this.parse_pat_no_top_alt(None, None),
148                    PatWithOr => this.parse_pat_no_top_guard(
149                        None,
150                        RecoverComma::No,
151                        RecoverColon::No,
152                        CommaRecoveryMode::EitherTupleOrPipe,
153                    ),
154                })
155                .map(Box::new)?,
156                pat_kind,
157            )),
158            NonterminalKind::Expr(expr_kind) => {
159                Ok(ParseNtResult::Expr(self.parse_expr_force_collect()?, expr_kind))
160            }
161            NonterminalKind::Literal => {
162                // The `:literal` matcher does not support attributes.
163                Ok(ParseNtResult::Literal(
164                    self.collect_tokens_no_attrs(|this| this.parse_literal_maybe_minus())?,
165                ))
166            }
167            NonterminalKind::Ty => Ok(ParseNtResult::Ty(
168                self.collect_tokens_no_attrs(|this| this.parse_ty_no_question_mark_recover())?,
169            )),
170            // This could be handled like a token, since it is one.
171            NonterminalKind::Ident => {
172                if let Some((ident, is_raw)) = get_macro_ident(&self.token) {
173                    self.bump();
174                    Ok(ParseNtResult::Ident(ident, is_raw))
175                } else {
176                    Err(self.dcx().create_err(UnexpectedNonterminal::Ident {
177                        span: self.token.span,
178                        token: pprust::token_to_string(&self.token),
179                    }))
180                }
181            }
182            NonterminalKind::Path => Ok(ParseNtResult::Path(Box::new(
183                self.collect_tokens_no_attrs(|this| this.parse_path(PathStyle::Type))?,
184            ))),
185            NonterminalKind::Meta => {
186                Ok(ParseNtResult::Meta(Box::new(self.parse_attr_item(ForceCollect::Yes)?)))
187            }
188            NonterminalKind::Vis => Ok(ParseNtResult::Vis(Box::new(
189                self.collect_tokens_no_attrs(|this| this.parse_visibility(FollowedByType::Yes))?,
190            ))),
191            NonterminalKind::Lifetime => {
192                // We want to keep `'keyword` parsing, just like `keyword` is still
193                // an ident for nonterminal purposes.
194                if let Some((ident, is_raw)) = self.token.lifetime() {
195                    self.bump();
196                    Ok(ParseNtResult::Lifetime(ident, is_raw))
197                } else {
198                    Err(self.dcx().create_err(UnexpectedNonterminal::Lifetime {
199                        span: self.token.span,
200                        token: pprust::token_to_string(&self.token),
201                    }))
202                }
203            }
204            NonterminalKind::Guard => {
205                Ok(ParseNtResult::Guard(self.expect_match_arm_guard(ForceCollect::Yes)?))
206            }
207        }
208    }
209}
210
211/// The token is an identifier, but not `_`.
212/// We prohibit passing `_` to macros expecting `ident` for now.
213fn get_macro_ident(token: &Token) -> Option<(Ident, token::IdentIsRaw)> {
214    token.ident().filter(|(ident, _)| ident.name != kw::Underscore)
215}