]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_parse/src/parser/nonterminal.rs
New upstream version 1.67.1+dfsg1
[rustc.git] / compiler / rustc_parse / src / parser / nonterminal.rs
CommitLineData
3dfed10e 1use rustc_ast::ptr::P;
04454e1e
FG
2use rustc_ast::token::{self, Delimiter, NonterminalKind, Token};
3use rustc_ast::HasTokens;
3dfed10e
XL
4use rustc_ast_pretty::pprust;
5use rustc_errors::PResult;
6use rustc_span::symbol::{kw, Ident};
7
5e7ed085
FG
8use crate::parser::pat::{CommaRecoveryMode, RecoverColon, RecoverComma};
9use crate::parser::{FollowedByType, ForceCollect, NtOrTt, Parser, PathStyle};
3dfed10e
XL
10
11impl<'a> Parser<'a> {
12 /// Checks whether a non-terminal may begin with a particular token.
13 ///
04454e1e
FG
14 /// Returning `false` is a *stability guarantee* that such a matcher will *never* begin with
15 /// that token. Be conservative (return true) if not sure. Inlined because it has a single call
16 /// site.
17 #[inline]
5869c6ff 18 pub fn nonterminal_may_begin_with(kind: NonterminalKind, token: &Token) -> bool {
3dfed10e
XL
19 /// Checks whether the non-terminal may contain a single (non-keyword) identifier.
20 fn may_be_ident(nt: &token::Nonterminal) -> bool {
21 match *nt {
22 token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) | token::NtLifetime(_) => {
23 false
24 }
25 _ => true,
26 }
27 }
28
29 match kind {
30 NonterminalKind::Expr => {
31 token.can_begin_expr()
32 // This exception is here for backwards compatibility.
33 && !token.is_keyword(kw::Let)
b9856134
XL
34 // This exception is here for backwards compatibility.
35 && !token.is_keyword(kw::Const)
3dfed10e
XL
36 }
37 NonterminalKind::Ty => token.can_begin_type(),
38 NonterminalKind::Ident => get_macro_ident(token).is_some(),
39 NonterminalKind::Literal => token.can_begin_literal_maybe_minus(),
40 NonterminalKind::Vis => match token.kind {
41 // The follow-set of :vis + "priv" keyword + interpolated
42 token::Comma | token::Ident(..) | token::Interpolated(..) => true,
43 _ => token.can_begin_type(),
44 },
487cf647 45 NonterminalKind::Block => match &token.kind {
04454e1e 46 token::OpenDelim(Delimiter::Brace) => true,
487cf647 47 token::Interpolated(nt) => !matches!(
5869c6ff
XL
48 **nt,
49 token::NtItem(_)
50 | token::NtPat(_)
51 | token::NtTy(_)
52 | token::NtIdent(..)
53 | token::NtMeta(_)
54 | token::NtPath(_)
55 | token::NtVis(_)
56 ),
3dfed10e
XL
57 _ => false,
58 },
487cf647 59 NonterminalKind::Path | NonterminalKind::Meta => match &token.kind {
3dfed10e 60 token::ModSep | token::Ident(..) => true,
487cf647 61 token::Interpolated(nt) => match **nt {
3dfed10e
XL
62 token::NtPath(_) | token::NtMeta(_) => true,
63 _ => may_be_ident(&nt),
64 },
65 _ => false,
66 },
cdc7bbd5 67 NonterminalKind::PatParam { .. } | NonterminalKind::PatWithOr { .. } => {
487cf647 68 match &token.kind {
f2b60f7d
FG
69 token::Ident(..) | // box, ref, mut, and other identifiers (can stricten)
70 token::OpenDelim(Delimiter::Parenthesis) | // tuple pattern
71 token::OpenDelim(Delimiter::Bracket) | // slice pattern
72 token::BinOp(token::And) | // reference
73 token::BinOp(token::Minus) | // negative literal
74 token::AndAnd | // double reference
75 token::Literal(..) | // literal
76 token::DotDot | // range pattern (future compat)
77 token::DotDotDot | // range pattern (future compat)
78 token::ModSep | // path
79 token::Lt | // path (UFCS constant)
80 token::BinOp(token::Shl) => true, // path (double UFCS)
fc512014 81 // leading vert `|` or-pattern
cdc7bbd5 82 token::BinOp(token::Or) => matches!(kind, NonterminalKind::PatWithOr {..}),
487cf647 83 token::Interpolated(nt) => may_be_ident(nt),
3dfed10e 84 _ => false,
cdc7bbd5
XL
85 }
86 }
487cf647 87 NonterminalKind::Lifetime => match &token.kind {
3dfed10e 88 token::Lifetime(_) => true,
487cf647 89 token::Interpolated(nt) => {
5e7ed085 90 matches!(**nt, token::NtLifetime(_))
29967ef6 91 }
3dfed10e
XL
92 _ => false,
93 },
29967ef6
XL
94 NonterminalKind::TT | NonterminalKind::Item | NonterminalKind::Stmt => {
95 !matches!(token.kind, token::CloseDelim(_))
96 }
3dfed10e
XL
97 }
98 }
99
04454e1e
FG
100 /// Parse a non-terminal (e.g. MBE `:pat` or `:ident`). Inlined because there is only one call
101 /// site.
102 #[inline]
5e7ed085 103 pub fn parse_nonterminal(&mut self, kind: NonterminalKind) -> PResult<'a, NtOrTt> {
3dfed10e
XL
104 // Any `Nonterminal` which stores its tokens (currently `NtItem` and `NtExpr`)
105 // needs to have them force-captured here.
106 // A `macro_rules!` invocation may pass a captured item/expr to a proc-macro,
107 // which requires having captured tokens available. Since we cannot determine
108 // in advance whether or not a proc-macro will be (transitively) invoked,
109 // we always capture tokens for any `Nonterminal` which needs them.
17df50a5 110 let mut nt = match kind {
5e7ed085
FG
111 // Note that TT is treated differently to all the others.
112 NonterminalKind::TT => return Ok(NtOrTt::Tt(self.parse_token_tree())),
5869c6ff
XL
113 NonterminalKind::Item => match self.parse_item(ForceCollect::Yes)? {
114 Some(item) => token::NtItem(item),
115 None => {
3dfed10e
XL
116 return Err(self.struct_span_err(self.token.span, "expected an item keyword"));
117 }
118 },
1b1a35ee 119 NonterminalKind::Block => {
6a06907d
XL
120 // While a block *expression* may have attributes (e.g. `#[my_attr] { ... }`),
121 // the ':block' matcher does not support them
122 token::NtBlock(self.collect_tokens_no_attrs(|this| this.parse_block())?)
1b1a35ee 123 }
5869c6ff 124 NonterminalKind::Stmt => match self.parse_stmt(ForceCollect::Yes)? {
04454e1e 125 Some(s) => token::NtStmt(P(s)),
5869c6ff
XL
126 None => {
127 return Err(self.struct_span_err(self.token.span, "expected a statement"));
1b1a35ee 128 }
5869c6ff 129 },
cdc7bbd5 130 NonterminalKind::PatParam { .. } | NonterminalKind::PatWithOr { .. } => {
6a06907d 131 token::NtPat(self.collect_tokens_no_attrs(|this| match kind {
cdc7bbd5 132 NonterminalKind::PatParam { .. } => this.parse_pat_no_top_alt(None),
5e7ed085
FG
133 NonterminalKind::PatWithOr { .. } => this.parse_pat_allow_top_alt(
134 None,
135 RecoverComma::No,
136 RecoverColon::No,
137 CommaRecoveryMode::EitherTupleOrPipe,
138 ),
5869c6ff
XL
139 _ => unreachable!(),
140 })?)
3dfed10e 141 }
6a06907d 142
cdc7bbd5 143 NonterminalKind::Expr => token::NtExpr(self.parse_expr_force_collect()?),
1b1a35ee 144 NonterminalKind::Literal => {
6a06907d
XL
145 // The `:literal` matcher does not support attributes
146 token::NtLiteral(
147 self.collect_tokens_no_attrs(|this| this.parse_literal_maybe_minus())?,
148 )
149 }
150
5e7ed085
FG
151 NonterminalKind::Ty => token::NtTy(
152 self.collect_tokens_no_attrs(|this| this.parse_no_question_mark_recover())?,
153 ),
154
3dfed10e 155 // this could be handled like a token, since it is one
94222f64
XL
156 NonterminalKind::Ident
157 if let Some((ident, is_raw)) = get_macro_ident(&self.token) =>
158 {
159 self.bump();
160 token::NtIdent(ident, is_raw)
161 }
3dfed10e 162 NonterminalKind::Ident => {
94222f64
XL
163 let token_str = pprust::token_to_string(&self.token);
164 let msg = &format!("expected ident, found {}", &token_str);
165 return Err(self.struct_span_err(self.token.span, msg));
3dfed10e 166 }
6a06907d 167 NonterminalKind::Path => token::NtPath(
04454e1e 168 P(self.collect_tokens_no_attrs(|this| this.parse_path(PathStyle::Type))?),
6a06907d 169 ),
cdc7bbd5 170 NonterminalKind::Meta => token::NtMeta(P(self.parse_attr_item(true)?)),
5869c6ff 171 NonterminalKind::Vis => token::NtVis(
04454e1e 172 P(self.collect_tokens_no_attrs(|this| this.parse_visibility(FollowedByType::Yes))?),
5869c6ff 173 ),
3dfed10e
XL
174 NonterminalKind::Lifetime => {
175 if self.check_lifetime() {
176 token::NtLifetime(self.expect_lifetime().ident)
177 } else {
178 let token_str = pprust::token_to_string(&self.token);
179 let msg = &format!("expected a lifetime, found `{}`", &token_str);
180 return Err(self.struct_span_err(self.token.span, msg));
181 }
182 }
17df50a5
XL
183 };
184
185 // If tokens are supported at all, they should be collected.
186 if matches!(nt.tokens_mut(), Some(None)) {
187 panic!(
188 "Missing tokens for nt {:?} at {:?}: {:?}",
189 nt,
190 nt.span(),
191 pprust::nonterminal_to_string(&nt)
192 );
193 }
194
5e7ed085 195 Ok(NtOrTt::Nt(nt))
3dfed10e
XL
196 }
197}
198
199/// The token is an identifier, but not `_`.
200/// We prohibit passing `_` to macros expecting `ident` for now.
201fn get_macro_ident(token: &Token) -> Option<(Ident, bool)> {
202 token.ident().filter(|(ident, _)| ident.name != kw::Underscore)
203}