]>
Commit | Line | Data |
---|---|---|
e74abb32 | 1 | pub mod attr; |
6a06907d | 2 | mod attr_wrapper; |
3dfed10e | 3 | mod diagnostics; |
416331ca | 4 | mod expr; |
3dfed10e | 5 | mod generics; |
416331ca | 6 | mod item; |
3dfed10e | 7 | mod nonterminal; |
dfeec247 | 8 | mod pat; |
416331ca | 9 | mod path; |
dfeec247 | 10 | mod stmt; |
3dfed10e | 11 | mod ty; |
416331ca | 12 | |
9ffffee4 | 13 | use crate::lexer::UnmatchedDelim; |
6a06907d | 14 | pub use attr_wrapper::AttrWrapper; |
29967ef6 | 15 | pub use diagnostics::AttemptLocalParseRecovery; |
a2a8927a | 16 | pub(crate) use item::FnParseMode; |
5e7ed085 | 17 | pub use pat::{CommaRecoveryMode, RecoverColon, RecoverComma}; |
3dfed10e | 18 | pub use path::PathStyle; |
60c5eb7d | 19 | |
74b04a01 | 20 | use rustc_ast::ptr::P; |
04454e1e | 21 | use rustc_ast::token::{self, Delimiter, Nonterminal, Token, TokenKind}; |
9ffffee4 FG |
22 | use rustc_ast::tokenstream::{AttributesData, DelimSpan, Spacing}; |
23 | use rustc_ast::tokenstream::{TokenStream, TokenTree, TokenTreeCursor}; | |
487cf647 | 24 | use rustc_ast::util::case::Case; |
cdc7bbd5 | 25 | use rustc_ast::AttrId; |
3dfed10e | 26 | use rustc_ast::DUMMY_NODE_ID; |
9c376795 | 27 | use rustc_ast::{self as ast, AnonConst, AttrStyle, Const, DelimArgs, Extern}; |
487cf647 | 28 | use rustc_ast::{Async, AttrArgs, AttrArgsEq, Expr, ExprKind, MacDelimiter, Mutability, StrLit}; |
04454e1e | 29 | use rustc_ast::{HasAttrs, HasTokens, Unsafe, Visibility, VisibilityKind}; |
74b04a01 | 30 | use rustc_ast_pretty::pprust; |
cdc7bbd5 | 31 | use rustc_data_structures::fx::FxHashMap; |
353b0b11 | 32 | use rustc_data_structures::sync::Ordering; |
29967ef6 | 33 | use rustc_errors::PResult; |
5e7ed085 | 34 | use rustc_errors::{ |
2b03887a | 35 | Applicability, DiagnosticBuilder, ErrorGuaranteed, FatalError, IntoDiagnostic, MultiSpan, |
5e7ed085 | 36 | }; |
74b04a01 | 37 | use rustc_session::parse::ParseSess; |
04454e1e | 38 | use rustc_span::source_map::{Span, DUMMY_SP}; |
f9f354fc | 39 | use rustc_span::symbol::{kw, sym, Ident, Symbol}; |
cdc7bbd5 | 40 | use std::ops::Range; |
dfeec247 | 41 | use std::{cmp, mem, slice}; |
9ffffee4 FG |
42 | use thin_vec::ThinVec; |
43 | use tracing::debug; | |
60c5eb7d | 44 | |
2b03887a | 45 | use crate::errors::{ |
49aad941 | 46 | self, IncorrectVisibilityRestriction, MismatchedClosingDelimiter, NonStringAbiLiteral, |
2b03887a FG |
47 | }; |
48 | ||
9fa01778 | 49 | bitflags::bitflags! { |
94b46f34 | 50 | struct Restrictions: u8 { |
ea8adc8c XL |
51 | const STMT_EXPR = 1 << 0; |
52 | const NO_STRUCT_LITERAL = 1 << 1; | |
29967ef6 | 53 | const CONST_EXPR = 1 << 2; |
064997fb | 54 | const ALLOW_LET = 1 << 3; |
1a4d82fc | 55 | } |
223e47cc LB |
56 | } |
57 | ||
8faf50e0 | 58 | #[derive(Clone, Copy, PartialEq, Debug)] |
e74abb32 | 59 | enum SemiColonMode { |
7453a54e SL |
60 | Break, |
61 | Ignore, | |
9fa01778 | 62 | Comma, |
7453a54e SL |
63 | } |
64 | ||
8faf50e0 | 65 | #[derive(Clone, Copy, PartialEq, Debug)] |
e74abb32 | 66 | enum BlockMode { |
cc61c64b XL |
67 | Break, |
68 | Ignore, | |
69 | } | |
70 | ||
5869c6ff XL |
71 | /// Whether or not we should force collection of tokens for an AST node, |
72 | /// regardless of whether or not it has attributes | |
17df50a5 | 73 | #[derive(Clone, Copy, PartialEq)] |
5869c6ff XL |
74 | pub enum ForceCollect { |
75 | Yes, | |
76 | No, | |
77 | } | |
78 | ||
cdc7bbd5 | 79 | #[derive(Debug, Eq, PartialEq)] |
5869c6ff XL |
80 | pub enum TrailingToken { |
81 | None, | |
82 | Semi, | |
2b03887a | 83 | Gt, |
6a06907d XL |
84 | /// If the trailing token is a comma, then capture it |
85 | /// Otherwise, ignore the trailing token | |
86 | MaybeComma, | |
5869c6ff XL |
87 | } |
88 | ||
e1599b0c | 89 | /// Like `maybe_whole_expr`, but for things other than expressions. |
416331ca | 90 | #[macro_export] |
1a4d82fc | 91 | macro_rules! maybe_whole { |
c30ab7b3 | 92 | ($p:expr, $constructor:ident, |$x:ident| $e:expr) => { |
dc9dc135 | 93 | if let token::Interpolated(nt) = &$p.token.kind { |
532ac7d7 XL |
94 | if let token::$constructor(x) = &**nt { |
95 | let $x = x.clone(); | |
c30ab7b3 SL |
96 | $p.bump(); |
97 | return Ok($e); | |
223e47cc | 98 | } |
1a4d82fc | 99 | } |
c30ab7b3 | 100 | }; |
1a4d82fc | 101 | } |
223e47cc | 102 | |
532ac7d7 | 103 | /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`. |
416331ca | 104 | #[macro_export] |
532ac7d7 XL |
105 | macro_rules! maybe_recover_from_interpolated_ty_qpath { |
106 | ($self: expr, $allow_qpath_recovery: expr) => { | |
5e7ed085 | 107 | if $allow_qpath_recovery |
487cf647 | 108 | && $self.may_recover() |
5e7ed085 FG |
109 | && $self.look_ahead(1, |t| t == &token::ModSep) |
110 | && let token::Interpolated(nt) = &$self.token.kind | |
111 | && let token::NtTy(ty) = &**nt | |
112 | { | |
532ac7d7 XL |
113 | let ty = ty.clone(); |
114 | $self.bump(); | |
74b04a01 | 115 | return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty); |
532ac7d7 | 116 | } |
dfeec247 | 117 | }; |
532ac7d7 XL |
118 | } |
119 | ||
2b03887a FG |
120 | #[derive(Clone, Copy)] |
121 | pub enum Recovery { | |
122 | Allowed, | |
123 | Forbidden, | |
124 | } | |
125 | ||
041b39d2 | 126 | #[derive(Clone)] |
1a4d82fc JJ |
127 | pub struct Parser<'a> { |
128 | pub sess: &'a ParseSess, | |
74b04a01 | 129 | /// The current token. |
dc9dc135 | 130 | pub token: Token, |
29967ef6 XL |
131 | /// The spacing for the current token |
132 | pub token_spacing: Spacing, | |
74b04a01 XL |
133 | /// The previous token. |
134 | pub prev_token: Token, | |
cdc7bbd5 | 135 | pub capture_cfg: bool, |
94b46f34 | 136 | restrictions: Restrictions, |
e74abb32 | 137 | expected_tokens: Vec<TokenType>, |
04454e1e FG |
138 | // Important: This must only be advanced from `bump` to ensure that |
139 | // `token_cursor.num_next_calls` is updated properly. | |
e1599b0c | 140 | token_cursor: TokenCursor, |
94b46f34 | 141 | desugar_doc_comments: bool, |
9fa01778 XL |
142 | /// This field is used to keep track of how many left angle brackets we have seen. This is |
143 | /// required in order to detect extra leading left angle brackets (`<` characters) and error | |
144 | /// appropriately. | |
145 | /// | |
146 | /// See the comments in the `parse_path_segment` function for more details. | |
e74abb32 XL |
147 | unmatched_angle_bracket_count: u32, |
148 | max_angle_bracket_count: u32, | |
353b0b11 | 149 | |
e74abb32 | 150 | last_unexpected_token_span: Option<Span>, |
dc9dc135 | 151 | /// If present, this `Parser` is not parsing Rust code but rather a macro call. |
e74abb32 | 152 | subparser_name: Option<&'static str>, |
cdc7bbd5 | 153 | capture_state: CaptureState, |
c295e0f8 XL |
154 | /// This allows us to recover when the user forget to add braces around |
155 | /// multiple statements in the closure body. | |
156 | pub current_closure: Option<ClosureSpans>, | |
2b03887a FG |
157 | /// Whether the parser is allowed to do recovery. |
158 | /// This is disabled when parsing macro arguments, see #103534 | |
159 | pub recovery: Recovery, | |
c295e0f8 XL |
160 | } |
161 | ||
2b03887a | 162 | // This type is used a lot, e.g. it's cloned when matching many declarative macro rules with nonterminals. Make sure |
04454e1e FG |
163 | // it doesn't unintentionally get bigger. |
164 | #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] | |
49aad941 | 165 | rustc_data_structures::static_assert_size!(Parser<'_>, 272); |
04454e1e | 166 | |
5e7ed085 | 167 | /// Stores span information about a closure. |
c295e0f8 XL |
168 | #[derive(Clone)] |
169 | pub struct ClosureSpans { | |
170 | pub whole_closure: Span, | |
171 | pub closing_pipe: Span, | |
172 | pub body: Span, | |
cdc7bbd5 XL |
173 | } |
174 | ||
175 | /// Indicates a range of tokens that should be replaced by | |
176 | /// the tokens in the provided vector. This is used in two | |
177 | /// places during token collection: | |
178 | /// | |
179 | /// 1. During the parsing of an AST node that may have a `#[derive]` | |
180 | /// attribute, we parse a nested AST node that has `#[cfg]` or `#[cfg_attr]` | |
181 | /// In this case, we use a `ReplaceRange` to replace the entire inner AST node | |
182 | /// with `FlatToken::AttrTarget`, allowing us to perform eager cfg-expansion | |
f2b60f7d | 183 | /// on an `AttrTokenStream`. |
cdc7bbd5 XL |
184 | /// |
185 | /// 2. When we parse an inner attribute while collecting tokens. We | |
186 | /// remove inner attributes from the token stream entirely, and | |
187 | /// instead track them through the `attrs` field on the AST node. | |
188 | /// This allows us to easily manipulate them (for example, removing | |
189 | /// the first macro inner attribute to invoke a proc-macro). | |
190 | /// When create a `TokenStream`, the inner attributes get inserted | |
191 | /// into the proper place in the token stream. | |
192 | pub type ReplaceRange = (Range<u32>, Vec<(FlatToken, Spacing)>); | |
193 | ||
194 | /// Controls how we capture tokens. Capturing can be expensive, | |
195 | /// so we try to avoid performing capturing in cases where | |
f2b60f7d | 196 | /// we will never need an `AttrTokenStream`. |
cdc7bbd5 XL |
197 | #[derive(Copy, Clone)] |
198 | pub enum Capturing { | |
199 | /// We aren't performing any capturing - this is the default mode. | |
200 | No, | |
201 | /// We are capturing tokens | |
202 | Yes, | |
203 | } | |
204 | ||
205 | #[derive(Clone)] | |
206 | struct CaptureState { | |
207 | capturing: Capturing, | |
208 | replace_ranges: Vec<ReplaceRange>, | |
209 | inner_attr_ranges: FxHashMap<AttrId, ReplaceRange>, | |
1a4d82fc JJ |
210 | } |
211 | ||
9ffffee4 FG |
212 | /// Iterator over a `TokenStream` that produces `Token`s. It's a bit odd that |
213 | /// we (a) lex tokens into a nice tree structure (`TokenStream`), and then (b) | |
214 | /// use this type to emit them as a linear sequence. But a linear sequence is | |
215 | /// what the parser expects, for the most part. | |
041b39d2 | 216 | #[derive(Clone)] |
e1599b0c | 217 | struct TokenCursor { |
9ffffee4 FG |
218 | // Cursor for the current (innermost) token stream. The delimiters for this |
219 | // token stream are found in `self.stack.last()`; when that is `None` then | |
220 | // we are in the outermost token stream which never has delimiters. | |
221 | tree_cursor: TokenTreeCursor, | |
222 | ||
223 | // Token streams surrounding the current one. The delimiters for stack[n]'s | |
224 | // tokens are in `stack[n-1]`. `stack[0]` (when present) has no delimiters | |
225 | // because it's the outermost token stream which never has delimiters. | |
226 | stack: Vec<(TokenTreeCursor, Delimiter, DelimSpan)>, | |
227 | ||
29967ef6 | 228 | desugar_doc_comments: bool, |
9ffffee4 | 229 | |
04454e1e | 230 | // Counts the number of calls to `{,inlined_}next`. |
29967ef6 | 231 | num_next_calls: usize, |
9ffffee4 | 232 | |
fc512014 XL |
233 | // During parsing, we may sometimes need to 'unglue' a |
234 | // glued token into two component tokens | |
235 | // (e.g. '>>' into '>' and '>), so that the parser | |
236 | // can consume them one at a time. This process | |
237 | // bypasses the normal capturing mechanism | |
238 | // (e.g. `num_next_calls` will not be incremented), | |
239 | // since the 'unglued' tokens due not exist in | |
240 | // the original `TokenStream`. | |
241 | // | |
242 | // If we end up consuming both unglued tokens, | |
243 | // then this is not an issue - we'll end up | |
244 | // capturing the single 'glued' token. | |
245 | // | |
246 | // However, in certain circumstances, we may | |
247 | // want to capture just the first 'unglued' token. | |
248 | // For example, capturing the `Vec<u8>` | |
249 | // in `Option<Vec<u8>>` requires us to unglue | |
cdc7bbd5 | 250 | // the trailing `>>` token. The `break_last_token` |
fc512014 XL |
251 | // field is used to track this token - it gets |
252 | // appended to the captured stream when | |
f2b60f7d | 253 | // we evaluate a `LazyAttrTokenStream`. |
cdc7bbd5 | 254 | break_last_token: bool, |
8bb4bdeb XL |
255 | } |
256 | ||
8bb4bdeb | 257 | impl TokenCursor { |
04454e1e FG |
258 | fn next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing) { |
259 | self.inlined_next(desugar_doc_comments) | |
5e7ed085 FG |
260 | } |
261 | ||
262 | /// This always-inlined version should only be used on hot code paths. | |
263 | #[inline(always)] | |
04454e1e | 264 | fn inlined_next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing) { |
8bb4bdeb | 265 | loop { |
04454e1e FG |
266 | // FIXME: we currently don't return `Delimiter` open/close delims. To fix #67062 we will |
267 | // need to, whereupon the `delim != Delimiter::Invisible` conditions below can be | |
268 | // removed. | |
9ffffee4 | 269 | if let Some(tree) = self.tree_cursor.next_ref() { |
04454e1e | 270 | match tree { |
064997fb | 271 | &TokenTree::Token(ref token, spacing) => match (desugar_doc_comments, token) { |
04454e1e | 272 | (true, &Token { kind: token::DocComment(_, attr_style, data), span }) => { |
9ffffee4 FG |
273 | let desugared = self.desugar(attr_style, data, span); |
274 | self.tree_cursor.replace_prev_and_rewind(desugared); | |
275 | // Continue to get the first token of the desugared doc comment. | |
276 | } | |
277 | _ => { | |
278 | debug_assert!(!matches!( | |
279 | token.kind, | |
280 | token::OpenDelim(_) | token::CloseDelim(_) | |
281 | )); | |
282 | return (token.clone(), spacing); | |
04454e1e | 283 | } |
04454e1e FG |
284 | }, |
285 | &TokenTree::Delimited(sp, delim, ref tts) => { | |
9ffffee4 FG |
286 | let trees = tts.clone().into_trees(); |
287 | self.stack.push((mem::replace(&mut self.tree_cursor, trees), delim, sp)); | |
04454e1e FG |
288 | if delim != Delimiter::Invisible { |
289 | return (Token::new(token::OpenDelim(delim), sp.open), Spacing::Alone); | |
290 | } | |
f2b60f7d | 291 | // No open delimiter to return; continue on to the next iteration. |
04454e1e FG |
292 | } |
293 | }; | |
9ffffee4 FG |
294 | } else if let Some((tree_cursor, delim, span)) = self.stack.pop() { |
295 | // We have exhausted this token stream. Move back to its parent token stream. | |
296 | self.tree_cursor = tree_cursor; | |
297 | if delim != Delimiter::Invisible { | |
04454e1e FG |
298 | return (Token::new(token::CloseDelim(delim), span.close), Spacing::Alone); |
299 | } | |
04454e1e | 300 | // No close delimiter to return; continue on to the next iteration. |
8bb4bdeb | 301 | } else { |
9ffffee4 | 302 | // We have exhausted the outermost token stream. |
04454e1e | 303 | return (Token::new(token::Eof, DUMMY_SP), Spacing::Alone); |
8bb4bdeb XL |
304 | } |
305 | } | |
306 | } | |
307 | ||
9ffffee4 FG |
308 | // Desugar a doc comment into something like `#[doc = r"foo"]`. |
309 | fn desugar(&mut self, attr_style: AttrStyle, data: Symbol, span: Span) -> Vec<TokenTree> { | |
8bb4bdeb | 310 | // Searches for the occurrences of `"#*` and returns the minimum number of `#`s |
2b03887a FG |
311 | // required to wrap the text. E.g. |
312 | // - `abc d` is wrapped as `r"abc d"` (num_of_hashes = 0) | |
313 | // - `abc "d"` is wrapped as `r#"abc "d""#` (num_of_hashes = 1) | |
9c376795 | 314 | // - `abc "##d##"` is wrapped as `r###"abc ##"d"##"###` (num_of_hashes = 3) |
8bb4bdeb XL |
315 | let mut num_of_hashes = 0; |
316 | let mut count = 0; | |
3dfed10e | 317 | for ch in data.as_str().chars() { |
8bb4bdeb XL |
318 | count = match ch { |
319 | '"' => 1, | |
320 | '#' if count > 0 => count + 1, | |
321 | _ => 0, | |
322 | }; | |
323 | num_of_hashes = cmp::max(num_of_hashes, count); | |
324 | } | |
325 | ||
9ffffee4 | 326 | // `/// foo` becomes `doc = r"foo"`. |
04454e1e | 327 | let delim_span = DelimSpan::from_single(span); |
0731742a XL |
328 | let body = TokenTree::Delimited( |
329 | delim_span, | |
04454e1e | 330 | Delimiter::Bracket, |
dc9dc135 | 331 | [ |
064997fb FG |
332 | TokenTree::token_alone(token::Ident(sym::doc, false), span), |
333 | TokenTree::token_alone(token::Eq, span), | |
334 | TokenTree::token_alone( | |
335 | TokenKind::lit(token::StrRaw(num_of_hashes), data, None), | |
336 | span, | |
337 | ), | |
0731742a | 338 | ] |
064997fb | 339 | .into_iter() |
74b04a01 | 340 | .collect::<TokenStream>(), |
0731742a | 341 | ); |
8bb4bdeb | 342 | |
9ffffee4 FG |
343 | if attr_style == AttrStyle::Inner { |
344 | vec![ | |
345 | TokenTree::token_alone(token::Pound, span), | |
346 | TokenTree::token_alone(token::Not, span), | |
347 | body, | |
348 | ] | |
349 | } else { | |
350 | vec![TokenTree::token_alone(token::Pound, span), body] | |
351 | } | |
8bb4bdeb XL |
352 | } |
353 | } | |
354 | ||
5869c6ff | 355 | #[derive(Debug, Clone, PartialEq)] |
e74abb32 | 356 | enum TokenType { |
dc9dc135 XL |
357 | Token(TokenKind), |
358 | Keyword(Symbol), | |
1a4d82fc | 359 | Operator, |
32a655c1 SL |
360 | Lifetime, |
361 | Ident, | |
362 | Path, | |
363 | Type, | |
9fa01778 | 364 | Const, |
1a4d82fc | 365 | } |
223e47cc | 366 | |
1a4d82fc | 367 | impl TokenType { |
e74abb32 | 368 | fn to_string(&self) -> String { |
487cf647 FG |
369 | match self { |
370 | TokenType::Token(t) => format!("`{}`", pprust::token_kind_to_string(t)), | |
dc9dc135 | 371 | TokenType::Keyword(kw) => format!("`{}`", kw), |
32a655c1 SL |
372 | TokenType::Operator => "an operator".to_string(), |
373 | TokenType::Lifetime => "lifetime".to_string(), | |
374 | TokenType::Ident => "identifier".to_string(), | |
375 | TokenType::Path => "path".to_string(), | |
376 | TokenType::Type => "type".to_string(), | |
fc512014 | 377 | TokenType::Const => "a const expression".to_string(), |
1a4d82fc JJ |
378 | } |
379 | } | |
223e47cc LB |
380 | } |
381 | ||
8faf50e0 | 382 | #[derive(Copy, Clone, Debug)] |
e74abb32 | 383 | enum TokenExpectType { |
ea8adc8c XL |
384 | Expect, |
385 | NoExpect, | |
386 | } | |
387 | ||
e74abb32 XL |
388 | /// A sequence separator. |
389 | struct SeqSep { | |
390 | /// The separator token. | |
391 | sep: Option<TokenKind>, | |
392 | /// `true` if a trailing separator is allowed. | |
393 | trailing_sep_allowed: bool, | |
394 | } | |
395 | ||
396 | impl SeqSep { | |
397 | fn trailing_allowed(t: TokenKind) -> SeqSep { | |
dfeec247 | 398 | SeqSep { sep: Some(t), trailing_sep_allowed: true } |
e74abb32 XL |
399 | } |
400 | ||
401 | fn none() -> SeqSep { | |
dfeec247 | 402 | SeqSep { sep: None, trailing_sep_allowed: false } |
e74abb32 XL |
403 | } |
404 | } | |
405 | ||
dfeec247 XL |
406 | pub enum FollowedByType { |
407 | Yes, | |
408 | No, | |
409 | } | |
410 | ||
2b03887a FG |
411 | #[derive(Clone, Copy, PartialEq, Eq)] |
412 | pub enum TokenDescription { | |
413 | ReservedIdentifier, | |
414 | Keyword, | |
415 | ReservedKeyword, | |
416 | DocComment, | |
dfeec247 XL |
417 | } |
418 | ||
2b03887a FG |
419 | impl TokenDescription { |
420 | pub fn from_token(token: &Token) -> Option<Self> { | |
421 | match token.kind { | |
422 | _ if token.is_special_ident() => Some(TokenDescription::ReservedIdentifier), | |
423 | _ if token.is_used_keyword() => Some(TokenDescription::Keyword), | |
424 | _ if token.is_unused_keyword() => Some(TokenDescription::ReservedKeyword), | |
425 | token::DocComment(..) => Some(TokenDescription::DocComment), | |
426 | _ => None, | |
427 | } | |
dfeec247 XL |
428 | } |
429 | } | |
60c5eb7d | 430 | |
2b03887a FG |
431 | pub(super) fn token_descr(token: &Token) -> String { |
432 | let name = pprust::token_to_string(token).to_string(); | |
433 | ||
434 | let kind = TokenDescription::from_token(token).map(|kind| match kind { | |
435 | TokenDescription::ReservedIdentifier => "reserved identifier", | |
436 | TokenDescription::Keyword => "keyword", | |
437 | TokenDescription::ReservedKeyword => "reserved keyword", | |
438 | TokenDescription::DocComment => "doc comment", | |
439 | }); | |
440 | ||
441 | if let Some(kind) = kind { format!("{} `{}`", kind, name) } else { format!("`{}`", name) } | |
442 | } | |
443 | ||
1a4d82fc | 444 | impl<'a> Parser<'a> { |
dc9dc135 XL |
445 | pub fn new( |
446 | sess: &'a ParseSess, | |
447 | tokens: TokenStream, | |
dc9dc135 XL |
448 | desugar_doc_comments: bool, |
449 | subparser_name: Option<&'static str>, | |
450 | ) -> Self { | |
c30ab7b3 | 451 | let mut parser = Parser { |
3b2f2976 | 452 | sess, |
dc9dc135 | 453 | token: Token::dummy(), |
29967ef6 | 454 | token_spacing: Spacing::Alone, |
74b04a01 | 455 | prev_token: Token::dummy(), |
cdc7bbd5 | 456 | capture_cfg: false, |
d9579d0f | 457 | restrictions: Restrictions::empty(), |
1a4d82fc | 458 | expected_tokens: Vec::new(), |
8bb4bdeb | 459 | token_cursor: TokenCursor { |
9ffffee4 | 460 | tree_cursor: tokens.into_trees(), |
8bb4bdeb | 461 | stack: Vec::new(), |
29967ef6 XL |
462 | num_next_calls: 0, |
463 | desugar_doc_comments, | |
cdc7bbd5 | 464 | break_last_token: false, |
8bb4bdeb | 465 | }, |
3b2f2976 | 466 | desugar_doc_comments, |
9fa01778 XL |
467 | unmatched_angle_bracket_count: 0, |
468 | max_angle_bracket_count: 0, | |
9fa01778 | 469 | last_unexpected_token_span: None, |
dc9dc135 | 470 | subparser_name, |
cdc7bbd5 XL |
471 | capture_state: CaptureState { |
472 | capturing: Capturing::No, | |
473 | replace_ranges: Vec::new(), | |
474 | inner_attr_ranges: Default::default(), | |
475 | }, | |
c295e0f8 | 476 | current_closure: None, |
2b03887a | 477 | recovery: Recovery::Allowed, |
c30ab7b3 SL |
478 | }; |
479 | ||
74b04a01 XL |
480 | // Make parser point to the first token. |
481 | parser.bump(); | |
7cac9316 | 482 | |
c30ab7b3 SL |
483 | parser |
484 | } | |
485 | ||
487cf647 FG |
486 | pub fn recovery(mut self, recovery: Recovery) -> Self { |
487 | self.recovery = recovery; | |
2b03887a FG |
488 | self |
489 | } | |
490 | ||
491 | /// Whether the parser is allowed to recover from broken code. | |
492 | /// | |
493 | /// If this returns false, recovering broken code into valid code (especially if this recovery does lookahead) | |
494 | /// is not allowed. All recovery done by the parser must be gated behind this check. | |
495 | /// | |
496 | /// Technically, this only needs to restrict eager recovery by doing lookahead at more tokens. | |
497 | /// But making the distinction is very subtle, and simply forbidding all recovery is a lot simpler to uphold. | |
498 | fn may_recover(&self) -> bool { | |
499 | matches!(self.recovery, Recovery::Allowed) | |
500 | } | |
501 | ||
29967ef6 | 502 | pub fn unexpected<T>(&mut self) -> PResult<'a, T> { |
9346a6ac | 503 | match self.expect_one_of(&[], &[]) { |
9cc50fc6 | 504 | Err(e) => Err(e), |
e74abb32 XL |
505 | // We can get `Ok(true)` from `recover_closing_delimiter` |
506 | // which is called in `expected_one_of_not_found`. | |
507 | Ok(_) => FatalError.raise(), | |
9346a6ac | 508 | } |
1a4d82fc JJ |
509 | } |
510 | ||
9fa01778 | 511 | /// Expects and consumes the token `t`. Signals an error if the next token is not `t`. |
dc9dc135 | 512 | pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { |
1a4d82fc JJ |
513 | if self.expected_tokens.is_empty() { |
514 | if self.token == *t { | |
9cc50fc6 | 515 | self.bump(); |
9fa01778 | 516 | Ok(false) |
1a4d82fc | 517 | } else { |
dc9dc135 | 518 | self.unexpected_try_recover(t) |
1a4d82fc JJ |
519 | } |
520 | } else { | |
94b46f34 | 521 | self.expect_one_of(slice::from_ref(t), &[]) |
1a4d82fc JJ |
522 | } |
523 | } | |
524 | ||
9c376795 | 525 | /// Expect next token to be edible or inedible token. If edible, |
1a4d82fc | 526 | /// then consume it; if inedible, then return without consuming |
9c376795 | 527 | /// anything. Signal a fatal error if next token is unexpected. |
9fa01778 XL |
528 | pub fn expect_one_of( |
529 | &mut self, | |
dc9dc135 XL |
530 | edible: &[TokenKind], |
531 | inedible: &[TokenKind], | |
9fa01778 | 532 | ) -> PResult<'a, bool /* recovered */> { |
dc9dc135 | 533 | if edible.contains(&self.token.kind) { |
9cc50fc6 | 534 | self.bump(); |
9fa01778 | 535 | Ok(false) |
dc9dc135 | 536 | } else if inedible.contains(&self.token.kind) { |
1a4d82fc | 537 | // leave it in the input |
9fa01778 | 538 | Ok(false) |
49aad941 FG |
539 | } else if self.token.kind != token::Eof |
540 | && self.last_unexpected_token_span == Some(self.token.span) | |
541 | { | |
9fa01778 | 542 | FatalError.raise(); |
1a4d82fc | 543 | } else { |
dc9dc135 | 544 | self.expected_one_of_not_found(edible, inedible) |
1a4d82fc | 545 | } |
970d7e83 LB |
546 | } |
547 | ||
dfeec247 | 548 | // Public for rustfmt usage. |
f9f354fc | 549 | pub fn parse_ident(&mut self) -> PResult<'a, Ident> { |
2c00a5a8 XL |
550 | self.parse_ident_common(true) |
551 | } | |
552 | ||
f9f354fc | 553 | fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { |
353b0b11 FG |
554 | let (ident, is_raw) = self.ident_or_err(recover)?; |
555 | ||
17df50a5 | 556 | if !is_raw && ident.is_reserved() { |
353b0b11 | 557 | let mut err = self.expected_ident_found_err(); |
17df50a5 XL |
558 | if recover { |
559 | err.emit(); | |
560 | } else { | |
561 | return Err(err); | |
970d7e83 | 562 | } |
970d7e83 | 563 | } |
17df50a5 XL |
564 | self.bump(); |
565 | Ok(ident) | |
970d7e83 LB |
566 | } |
567 | ||
353b0b11 FG |
568 | fn ident_or_err(&mut self, recover: bool) -> PResult<'a, (Ident, /* is_raw */ bool)> { |
569 | let result = self.token.ident().ok_or_else(|| self.expected_ident_found(recover)); | |
570 | ||
571 | let (ident, is_raw) = match result { | |
572 | Ok(ident) => ident, | |
573 | Err(err) => match err { | |
574 | // we recovered! | |
575 | Ok(ident) => ident, | |
576 | Err(err) => return Err(err), | |
577 | }, | |
578 | }; | |
579 | ||
580 | Ok((ident, is_raw)) | |
581 | } | |
582 | ||
9fa01778 | 583 | /// Checks if the next token is `tok`, and returns `true` if so. |
1a4d82fc | 584 | /// |
7453a54e | 585 | /// This method will automatically add `tok` to `expected_tokens` if `tok` is not |
1a4d82fc | 586 | /// encountered. |
e74abb32 | 587 | fn check(&mut self, tok: &TokenKind) -> bool { |
1a4d82fc | 588 | let is_present = self.token == *tok; |
dfeec247 XL |
589 | if !is_present { |
590 | self.expected_tokens.push(TokenType::Token(tok.clone())); | |
591 | } | |
1a4d82fc | 592 | is_present |
970d7e83 LB |
593 | } |
594 | ||
923072b8 FG |
595 | fn check_noexpect(&self, tok: &TokenKind) -> bool { |
596 | self.token == *tok | |
597 | } | |
598 | ||
599 | /// Consumes a token 'tok' if it exists. Returns whether the given token was present. | |
600 | /// | |
601 | /// the main purpose of this function is to reduce the cluttering of the suggestions list | |
602 | /// which using the normal eat method could introduce in some cases. | |
603 | pub fn eat_noexpect(&mut self, tok: &TokenKind) -> bool { | |
604 | let is_present = self.check_noexpect(tok); | |
605 | if is_present { | |
606 | self.bump() | |
607 | } | |
608 | is_present | |
609 | } | |
610 | ||
9fa01778 | 611 | /// Consumes a token 'tok' if it exists. Returns whether the given token was present. |
dc9dc135 | 612 | pub fn eat(&mut self, tok: &TokenKind) -> bool { |
1a4d82fc | 613 | let is_present = self.check(tok); |
dfeec247 XL |
614 | if is_present { |
615 | self.bump() | |
616 | } | |
9cc50fc6 | 617 | is_present |
970d7e83 LB |
618 | } |
619 | ||
e74abb32 XL |
620 | /// If the next token is the given keyword, returns `true` without eating it. |
621 | /// An expectation is also added for diagnostics purposes. | |
dc9dc135 | 622 | fn check_keyword(&mut self, kw: Symbol) -> bool { |
85aaf69f SL |
623 | self.expected_tokens.push(TokenType::Keyword(kw)); |
624 | self.token.is_keyword(kw) | |
625 | } | |
626 | ||
487cf647 FG |
627 | fn check_keyword_case(&mut self, kw: Symbol, case: Case) -> bool { |
628 | if self.check_keyword(kw) { | |
629 | return true; | |
630 | } | |
631 | ||
632 | if case == Case::Insensitive | |
633 | && let Some((ident, /* is_raw */ false)) = self.token.ident() | |
634 | && ident.as_str().to_lowercase() == kw.as_str().to_lowercase() { | |
635 | true | |
636 | } else { | |
637 | false | |
638 | } | |
639 | } | |
640 | ||
e74abb32 XL |
641 | /// If the next token is the given keyword, eats it and returns `true`. |
642 | /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes. | |
dfeec247 XL |
643 | // Public for rustfmt usage. |
644 | pub fn eat_keyword(&mut self, kw: Symbol) -> bool { | |
85aaf69f | 645 | if self.check_keyword(kw) { |
9cc50fc6 SL |
646 | self.bump(); |
647 | true | |
85aaf69f | 648 | } else { |
9cc50fc6 | 649 | false |
85aaf69f SL |
650 | } |
651 | } | |
652 | ||
487cf647 FG |
653 | /// Eats a keyword, optionally ignoring the case. |
654 | /// If the case differs (and is ignored) an error is issued. | |
655 | /// This is useful for recovery. | |
656 | fn eat_keyword_case(&mut self, kw: Symbol, case: Case) -> bool { | |
657 | if self.eat_keyword(kw) { | |
658 | return true; | |
659 | } | |
660 | ||
661 | if case == Case::Insensitive | |
662 | && let Some((ident, /* is_raw */ false)) = self.token.ident() | |
663 | && ident.as_str().to_lowercase() == kw.as_str().to_lowercase() { | |
49aad941 FG |
664 | self.sess.emit_err(errors::KwBadCase { |
665 | span: ident.span, | |
666 | kw: kw.as_str() | |
667 | }); | |
487cf647 FG |
668 | self.bump(); |
669 | return true; | |
670 | } | |
671 | ||
672 | false | |
673 | } | |
674 | ||
dc9dc135 | 675 | fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { |
1a4d82fc | 676 | if self.token.is_keyword(kw) { |
9cc50fc6 SL |
677 | self.bump(); |
678 | true | |
1a4d82fc | 679 | } else { |
9cc50fc6 | 680 | false |
1a4d82fc | 681 | } |
970d7e83 LB |
682 | } |
683 | ||
9fa01778 XL |
684 | /// If the given word is not a keyword, signals an error. |
685 | /// If the next token is not the given word, signals an error. | |
686 | /// Otherwise, eats it. | |
dc9dc135 | 687 | fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { |
dfeec247 | 688 | if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } |
970d7e83 LB |
689 | } |
690 | ||
74b04a01 XL |
691 | /// Is the given keyword `kw` followed by a non-reserved identifier? |
692 | fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { | |
693 | self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) | |
694 | } | |
695 | ||
e74abb32 XL |
696 | fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { |
697 | if ok { | |
32a655c1 SL |
698 | true |
699 | } else { | |
e74abb32 | 700 | self.expected_tokens.push(typ); |
32a655c1 SL |
701 | false |
702 | } | |
703 | } | |
704 | ||
e74abb32 XL |
705 | fn check_ident(&mut self) -> bool { |
706 | self.check_or_expected(self.token.is_ident(), TokenType::Ident) | |
707 | } | |
708 | ||
32a655c1 | 709 | fn check_path(&mut self) -> bool { |
e74abb32 | 710 | self.check_or_expected(self.token.is_path_start(), TokenType::Path) |
32a655c1 SL |
711 | } |
712 | ||
713 | fn check_type(&mut self) -> bool { | |
e74abb32 | 714 | self.check_or_expected(self.token.can_begin_type(), TokenType::Type) |
32a655c1 SL |
715 | } |
716 | ||
9fa01778 | 717 | fn check_const_arg(&mut self) -> bool { |
e74abb32 XL |
718 | self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) |
719 | } | |
720 | ||
9c376795 FG |
721 | fn check_const_closure(&self) -> bool { |
722 | self.is_keyword_ahead(0, &[kw::Const]) | |
723 | && self.look_ahead(1, |t| match &t.kind { | |
9ffffee4 FG |
724 | // async closures do not work with const closures, so we do not parse that here. |
725 | token::Ident(kw::Move | kw::Static, _) | token::OrOr | token::BinOp(token::Or) => { | |
726 | true | |
727 | } | |
9c376795 FG |
728 | _ => false, |
729 | }) | |
730 | } | |
731 | ||
29967ef6 XL |
732 | fn check_inline_const(&self, dist: usize) -> bool { |
733 | self.is_keyword_ahead(dist, &[kw::Const]) | |
487cf647 FG |
734 | && self.look_ahead(dist + 1, |t| match &t.kind { |
735 | token::Interpolated(nt) => matches!(**nt, token::NtBlock(..)), | |
04454e1e | 736 | token::OpenDelim(Delimiter::Brace) => true, |
29967ef6 XL |
737 | _ => false, |
738 | }) | |
739 | } | |
740 | ||
e74abb32 XL |
741 | /// Checks to see if the next token is either `+` or `+=`. |
742 | /// Otherwise returns `false`. | |
743 | fn check_plus(&mut self) -> bool { | |
744 | self.check_or_expected( | |
745 | self.token.is_like_plus(), | |
746 | TokenType::Token(token::BinOp(token::Plus)), | |
747 | ) | |
9fa01778 XL |
748 | } |
749 | ||
74b04a01 XL |
750 | /// Eats the expected token if it's present possibly breaking |
751 | /// compound tokens like multi-character operators in process. | |
752 | /// Returns `true` if the token was eaten. | |
753 | fn break_and_eat(&mut self, expected: TokenKind) -> bool { | |
754 | if self.token.kind == expected { | |
755 | self.bump(); | |
756 | return true; | |
757 | } | |
758 | match self.token.kind.break_two_token_op() { | |
759 | Some((first, second)) if first == expected => { | |
760 | let first_span = self.sess.source_map().start_point(self.token.span); | |
761 | let second_span = self.token.span.with_lo(first_span.hi()); | |
762 | self.token = Token::new(first, first_span); | |
fc512014 XL |
763 | // Keep track of this token - if we end token capturing now, |
764 | // we'll want to append this token to the captured stream. | |
765 | // | |
766 | // If we consume any additional tokens, then this token | |
767 | // is not needed (we'll capture the entire 'glued' token), | |
04454e1e | 768 | // and `bump` will set this field to `None` |
cdc7bbd5 | 769 | self.token_cursor.break_last_token = true; |
29967ef6 XL |
770 | // Use the spacing of the glued token as the spacing |
771 | // of the unglued second token. | |
772 | self.bump_with((Token::new(second, second_span), self.token_spacing)); | |
94b46f34 XL |
773 | true |
774 | } | |
74b04a01 XL |
775 | _ => { |
776 | self.expected_tokens.push(TokenType::Token(expected)); | |
777 | false | |
94b46f34 | 778 | } |
94b46f34 XL |
779 | } |
780 | } | |
781 | ||
74b04a01 XL |
782 | /// Eats `+` possibly breaking tokens like `+=` in process. |
783 | fn eat_plus(&mut self) -> bool { | |
784 | self.break_and_eat(token::BinOp(token::Plus)) | |
785 | } | |
786 | ||
787 | /// Eats `&` possibly breaking tokens like `&&` in process. | |
788 | /// Signals an error if `&` is not eaten. | |
9cc50fc6 | 789 | fn expect_and(&mut self) -> PResult<'a, ()> { |
74b04a01 | 790 | if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() } |
ea8adc8c XL |
791 | } |
792 | ||
74b04a01 XL |
793 | /// Eats `|` possibly breaking tokens like `||` in process. |
794 | /// Signals an error if `|` was not eaten. | |
ea8adc8c | 795 | fn expect_or(&mut self) -> PResult<'a, ()> { |
74b04a01 | 796 | if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } |
970d7e83 LB |
797 | } |
798 | ||
74b04a01 | 799 | /// Eats `<` possibly breaking tokens like `<<` in process. |
9cc50fc6 | 800 | fn eat_lt(&mut self) -> bool { |
74b04a01 | 801 | let ate = self.break_and_eat(token::Lt); |
9fa01778 XL |
802 | if ate { |
803 | // See doc comment for `unmatched_angle_bracket_count`. | |
804 | self.unmatched_angle_bracket_count += 1; | |
805 | self.max_angle_bracket_count += 1; | |
806 | debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); | |
1a4d82fc | 807 | } |
9fa01778 | 808 | ate |
1a4d82fc JJ |
809 | } |
810 | ||
74b04a01 XL |
811 | /// Eats `<` possibly breaking tokens like `<<` in process. |
812 | /// Signals an error if `<` was not eaten. | |
9cc50fc6 | 813 | fn expect_lt(&mut self) -> PResult<'a, ()> { |
74b04a01 | 814 | if self.eat_lt() { Ok(()) } else { self.unexpected() } |
1a4d82fc JJ |
815 | } |
816 | ||
74b04a01 XL |
817 | /// Eats `>` possibly breaking tokens like `>>` in process. |
818 | /// Signals an error if `>` was not eaten. | |
94b46f34 | 819 | fn expect_gt(&mut self) -> PResult<'a, ()> { |
74b04a01 XL |
820 | if self.break_and_eat(token::Gt) { |
821 | // See doc comment for `unmatched_angle_bracket_count`. | |
822 | if self.unmatched_angle_bracket_count > 0 { | |
823 | self.unmatched_angle_bracket_count -= 1; | |
824 | debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count); | |
dfeec247 | 825 | } |
74b04a01 XL |
826 | Ok(()) |
827 | } else { | |
828 | self.unexpected() | |
1a4d82fc JJ |
829 | } |
830 | } | |
831 | ||
416331ca | 832 | fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool { |
dfeec247 XL |
833 | kets.iter().any(|k| match expect { |
834 | TokenExpectType::Expect => self.check(k), | |
835 | TokenExpectType::NoExpect => self.token == **k, | |
416331ca XL |
836 | }) |
837 | } | |
838 | ||
e74abb32 | 839 | fn parse_seq_to_before_tokens<T>( |
b7449926 | 840 | &mut self, |
dc9dc135 | 841 | kets: &[&TokenKind], |
b7449926 XL |
842 | sep: SeqSep, |
843 | expect: TokenExpectType, | |
416331ca | 844 | mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, |
9ffffee4 | 845 | ) -> PResult<'a, (ThinVec<T>, bool /* trailing */, bool /* recovered */)> { |
9fa01778 XL |
846 | let mut first = true; |
847 | let mut recovered = false; | |
416331ca | 848 | let mut trailing = false; |
9ffffee4 | 849 | let mut v = ThinVec::new(); |
cdc7bbd5 | 850 | |
416331ca XL |
851 | while !self.expect_any_with_type(kets, expect) { |
852 | if let token::CloseDelim(..) | token::Eof = self.token.kind { | |
dfeec247 | 853 | break; |
416331ca | 854 | } |
487cf647 | 855 | if let Some(t) = &sep.sep { |
7cac9316 XL |
856 | if first { |
857 | first = false; | |
858 | } else { | |
9fa01778 | 859 | match self.expect(t) { |
c295e0f8 XL |
860 | Ok(false) => { |
861 | self.current_closure.take(); | |
862 | } | |
9fa01778 | 863 | Ok(true) => { |
c295e0f8 | 864 | self.current_closure.take(); |
9fa01778 XL |
865 | recovered = true; |
866 | break; | |
abe05a73 | 867 | } |
60c5eb7d | 868 | Err(mut expect_err) => { |
74b04a01 | 869 | let sp = self.prev_token.span.shrink_to_hi(); |
60c5eb7d XL |
870 | let token_str = pprust::token_kind_to_string(t); |
871 | ||
c295e0f8 XL |
872 | match self.current_closure.take() { |
873 | Some(closure_spans) if self.token.kind == TokenKind::Semi => { | |
874 | // Finding a semicolon instead of a comma | |
875 | // after a closure body indicates that the | |
876 | // closure body may be a block but the user | |
877 | // forgot to put braces around its | |
878 | // statements. | |
879 | ||
880 | self.recover_missing_braces_around_closure_body( | |
881 | closure_spans, | |
882 | expect_err, | |
883 | )?; | |
884 | ||
885 | continue; | |
886 | } | |
887 | ||
888 | _ => { | |
889 | // Attempt to keep parsing if it was a similar separator. | |
487cf647 | 890 | if let Some(tokens) = t.similar_tokens() { |
353b0b11 | 891 | if tokens.contains(&self.token.kind) { |
c295e0f8 XL |
892 | self.bump(); |
893 | } | |
894 | } | |
9fa01778 XL |
895 | } |
896 | } | |
60c5eb7d | 897 | |
f9f354fc XL |
898 | // If this was a missing `@` in a binding pattern |
899 | // bail with a suggestion | |
900 | // https://github.com/rust-lang/rust/issues/72373 | |
f035d41b | 901 | if self.prev_token.is_ident() && self.token.kind == token::DotDot { |
f9f354fc XL |
902 | let msg = format!( |
903 | "if you meant to bind the contents of \ | |
904 | the rest of the array pattern into `{}`, use `@`", | |
905 | pprust::token_to_string(&self.prev_token) | |
906 | ); | |
907 | expect_err | |
908 | .span_suggestion_verbose( | |
909 | self.prev_token.span.shrink_to_hi().until(self.token.span), | |
49aad941 | 910 | msg, |
04454e1e | 911 | " @ ", |
f9f354fc XL |
912 | Applicability::MaybeIncorrect, |
913 | ) | |
914 | .emit(); | |
915 | break; | |
916 | } | |
917 | ||
e1599b0c | 918 | // Attempt to keep parsing if it was an omitted separator. |
9fa01778 XL |
919 | match f(self) { |
920 | Ok(t) => { | |
60c5eb7d XL |
921 | // Parsed successfully, therefore most probably the code only |
922 | // misses a separator. | |
923 | expect_err | |
924 | .span_suggestion_short( | |
5869c6ff | 925 | sp, |
49aad941 | 926 | format!("missing `{}`", token_str), |
04454e1e | 927 | token_str, |
60c5eb7d XL |
928 | Applicability::MaybeIncorrect, |
929 | ) | |
930 | .emit(); | |
931 | ||
9fa01778 XL |
932 | v.push(t); |
933 | continue; | |
dfeec247 | 934 | } |
5e7ed085 | 935 | Err(e) => { |
60c5eb7d XL |
936 | // Parsing failed, therefore it must be something more serious |
937 | // than just a missing separator. | |
487cf647 FG |
938 | for xx in &e.children { |
939 | // propagate the help message from sub error 'e' to main error 'expect_err; | |
940 | expect_err.children.push(xx.clone()); | |
941 | } | |
9fa01778 | 942 | e.cancel(); |
49aad941 FG |
943 | if self.token == token::Colon { |
944 | // we will try to recover in `maybe_recover_struct_lit_bad_delims` | |
945 | return Err(expect_err); | |
946 | } else { | |
947 | expect_err.emit(); | |
948 | break; | |
949 | } | |
9fa01778 | 950 | } |
abe05a73 XL |
951 | } |
952 | } | |
7453a54e SL |
953 | } |
954 | } | |
7453a54e | 955 | } |
416331ca XL |
956 | if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { |
957 | trailing = true; | |
7453a54e SL |
958 | break; |
959 | } | |
960 | ||
abe05a73 XL |
961 | let t = f(self)?; |
962 | v.push(t); | |
970d7e83 | 963 | } |
7453a54e | 964 | |
416331ca | 965 | Ok((v, trailing, recovered)) |
970d7e83 LB |
966 | } |
967 | ||
c295e0f8 XL |
968 | fn recover_missing_braces_around_closure_body( |
969 | &mut self, | |
970 | closure_spans: ClosureSpans, | |
5e7ed085 | 971 | mut expect_err: DiagnosticBuilder<'_, ErrorGuaranteed>, |
c295e0f8 XL |
972 | ) -> PResult<'a, ()> { |
973 | let initial_semicolon = self.token.span; | |
974 | ||
975 | while self.eat(&TokenKind::Semi) { | |
9ffffee4 FG |
976 | let _ = |
977 | self.parse_stmt_without_recovery(false, ForceCollect::Yes).unwrap_or_else(|e| { | |
978 | e.cancel(); | |
979 | None | |
980 | }); | |
c295e0f8 XL |
981 | } |
982 | ||
983 | expect_err.set_primary_message( | |
984 | "closure bodies that contain statements must be surrounded by braces", | |
985 | ); | |
986 | ||
987 | let preceding_pipe_span = closure_spans.closing_pipe; | |
988 | let following_token_span = self.token.span; | |
989 | ||
990 | let mut first_note = MultiSpan::from(vec![initial_semicolon]); | |
991 | first_note.push_span_label( | |
992 | initial_semicolon, | |
064997fb | 993 | "this `;` turns the preceding closure into a statement", |
c295e0f8 XL |
994 | ); |
995 | first_note.push_span_label( | |
996 | closure_spans.body, | |
064997fb | 997 | "this expression is a statement because of the trailing semicolon", |
c295e0f8 XL |
998 | ); |
999 | expect_err.span_note(first_note, "statement found outside of a block"); | |
1000 | ||
1001 | let mut second_note = MultiSpan::from(vec![closure_spans.whole_closure]); | |
064997fb | 1002 | second_note.push_span_label(closure_spans.whole_closure, "this is the parsed closure..."); |
c295e0f8 XL |
1003 | second_note.push_span_label( |
1004 | following_token_span, | |
064997fb | 1005 | "...but likely you meant the closure to end here", |
c295e0f8 XL |
1006 | ); |
1007 | expect_err.span_note(second_note, "the closure body may be incorrectly delimited"); | |
1008 | ||
1009 | expect_err.set_span(vec![preceding_pipe_span, following_token_span]); | |
1010 | ||
1011 | let opening_suggestion_str = " {".to_string(); | |
1012 | let closing_suggestion_str = "}".to_string(); | |
1013 | ||
1014 | expect_err.multipart_suggestion( | |
1015 | "try adding braces", | |
1016 | vec![ | |
1017 | (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str), | |
1018 | (following_token_span.shrink_to_lo(), closing_suggestion_str), | |
1019 | ], | |
1020 | Applicability::MaybeIncorrect, | |
1021 | ); | |
1022 | ||
1023 | expect_err.emit(); | |
1024 | ||
1025 | Ok(()) | |
1026 | } | |
1027 | ||
dfeec247 XL |
1028 | /// Parses a sequence, not including the closing delimiter. The function |
1029 | /// `f` must consume tokens until reaching the next separator or | |
1030 | /// closing bracket. | |
1031 | fn parse_seq_to_before_end<T>( | |
1032 | &mut self, | |
1033 | ket: &TokenKind, | |
1034 | sep: SeqSep, | |
1035 | f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, | |
9ffffee4 | 1036 | ) -> PResult<'a, (ThinVec<T>, bool, bool)> { |
dfeec247 XL |
1037 | self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f) |
1038 | } | |
1039 | ||
1040 | /// Parses a sequence, including the closing delimiter. The function | |
1041 | /// `f` must consume tokens until reaching the next separator or | |
1042 | /// closing bracket. | |
1043 | fn parse_seq_to_end<T>( | |
1044 | &mut self, | |
1045 | ket: &TokenKind, | |
1046 | sep: SeqSep, | |
1047 | f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, | |
9ffffee4 | 1048 | ) -> PResult<'a, (ThinVec<T>, bool /* trailing */)> { |
dfeec247 XL |
1049 | let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; |
1050 | if !recovered { | |
1051 | self.eat(ket); | |
1052 | } | |
1053 | Ok((val, trailing)) | |
1054 | } | |
1055 | ||
9fa01778 XL |
1056 | /// Parses a sequence, including the closing delimiter. The function |
1057 | /// `f` must consume tokens until reaching the next separator or | |
1a4d82fc | 1058 | /// closing bracket. |
416331ca | 1059 | fn parse_unspanned_seq<T>( |
9fa01778 | 1060 | &mut self, |
dc9dc135 XL |
1061 | bra: &TokenKind, |
1062 | ket: &TokenKind, | |
9fa01778 | 1063 | sep: SeqSep, |
416331ca | 1064 | f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, |
9ffffee4 | 1065 | ) -> PResult<'a, (ThinVec<T>, bool)> { |
54a0048b | 1066 | self.expect(bra)?; |
dfeec247 | 1067 | self.parse_seq_to_end(ket, sep, f) |
416331ca XL |
1068 | } |
1069 | ||
1070 | fn parse_delim_comma_seq<T>( | |
1071 | &mut self, | |
04454e1e | 1072 | delim: Delimiter, |
416331ca | 1073 | f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, |
9ffffee4 | 1074 | ) -> PResult<'a, (ThinVec<T>, bool)> { |
416331ca XL |
1075 | self.parse_unspanned_seq( |
1076 | &token::OpenDelim(delim), | |
1077 | &token::CloseDelim(delim), | |
1078 | SeqSep::trailing_allowed(token::Comma), | |
1079 | f, | |
1080 | ) | |
1081 | } | |
1082 | ||
1083 | fn parse_paren_comma_seq<T>( | |
1084 | &mut self, | |
1085 | f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, | |
9ffffee4 | 1086 | ) -> PResult<'a, (ThinVec<T>, bool)> { |
04454e1e | 1087 | self.parse_delim_comma_seq(Delimiter::Parenthesis, f) |
970d7e83 LB |
1088 | } |
1089 | ||
74b04a01 | 1090 | /// Advance the parser by one token using provided token as the next one. |
5e7ed085 FG |
1091 | fn bump_with(&mut self, next: (Token, Spacing)) { |
1092 | self.inlined_bump_with(next) | |
1093 | } | |
1094 | ||
1095 | /// This always-inlined version should only be used on hot code paths. | |
1096 | #[inline(always)] | |
1097 | fn inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { | |
74b04a01 XL |
1098 | // Update the current and previous tokens. |
1099 | self.prev_token = mem::replace(&mut self.token, next_token); | |
29967ef6 | 1100 | self.token_spacing = next_spacing; |
9e0c209e | 1101 | |
74b04a01 | 1102 | // Diagnostics. |
7453a54e | 1103 | self.expected_tokens.clear(); |
223e47cc | 1104 | } |
7453a54e | 1105 | |
74b04a01 XL |
1106 | /// Advance the parser by one token. |
1107 | pub fn bump(&mut self) { | |
04454e1e FG |
1108 | // Note: destructuring here would give nicer code, but it was found in #96210 to be slower |
1109 | // than `.0`/`.1` access. | |
1110 | let mut next = self.token_cursor.inlined_next(self.desugar_doc_comments); | |
1111 | self.token_cursor.num_next_calls += 1; | |
1112 | // We've retrieved an token from the underlying | |
1113 | // cursor, so we no longer need to worry about | |
1114 | // an unglued token. See `break_and_eat` for more details | |
1115 | self.token_cursor.break_last_token = false; | |
1116 | if next.0.span.is_dummy() { | |
1117 | // Tweak the location for better diagnostics, but keep syntactic context intact. | |
1118 | let fallback_span = self.token.span; | |
1119 | next.0.span = fallback_span.with_ctxt(next.0.span.ctxt()); | |
1120 | } | |
1121 | debug_assert!(!matches!( | |
1122 | next.0.kind, | |
1123 | token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible) | |
1124 | )); | |
1125 | self.inlined_bump_with(next) | |
74b04a01 XL |
1126 | } |
1127 | ||
e74abb32 XL |
1128 | /// Look-ahead `dist` tokens of `self.token` and get access to that token there. |
1129 | /// When `dist == 0` then the current token is looked at. | |
1130 | pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { | |
c30ab7b3 | 1131 | if dist == 0 { |
e74abb32 | 1132 | return looker(&self.token); |
223e47cc | 1133 | } |
8bb4bdeb | 1134 | |
9ffffee4 FG |
1135 | let tree_cursor = &self.token_cursor.tree_cursor; |
1136 | if let Some(&(_, delim, span)) = self.token_cursor.stack.last() | |
1137 | && delim != Delimiter::Invisible | |
1138 | { | |
cdc7bbd5 | 1139 | let all_normal = (0..dist).all(|i| { |
9ffffee4 | 1140 | let token = tree_cursor.look_ahead(i); |
04454e1e | 1141 | !matches!(token, Some(TokenTree::Delimited(_, Delimiter::Invisible, _))) |
cdc7bbd5 XL |
1142 | }); |
1143 | if all_normal { | |
9ffffee4 | 1144 | return match tree_cursor.look_ahead(dist - 1) { |
cdc7bbd5 | 1145 | Some(tree) => match tree { |
064997fb | 1146 | TokenTree::Token(token, _) => looker(token), |
cdc7bbd5 XL |
1147 | TokenTree::Delimited(dspan, delim, _) => { |
1148 | looker(&Token::new(token::OpenDelim(*delim), dspan.open)) | |
1149 | } | |
1150 | }, | |
04454e1e | 1151 | None => looker(&Token::new(token::CloseDelim(delim), span.close)), |
cdc7bbd5 XL |
1152 | }; |
1153 | } | |
29967ef6 | 1154 | } |
cdc7bbd5 XL |
1155 | |
1156 | let mut cursor = self.token_cursor.clone(); | |
1157 | let mut i = 0; | |
1158 | let mut token = Token::dummy(); | |
1159 | while i < dist { | |
04454e1e | 1160 | token = cursor.next(/* desugar_doc_comments */ false).0; |
cdc7bbd5 XL |
1161 | if matches!( |
1162 | token.kind, | |
04454e1e | 1163 | token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible) |
cdc7bbd5 XL |
1164 | ) { |
1165 | continue; | |
1166 | } | |
1167 | i += 1; | |
1168 | } | |
1169 | return looker(&token); | |
223e47cc | 1170 | } |
ff7c6d11 | 1171 | |
dc9dc135 XL |
1172 | /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. |
1173 | fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { | |
1174 | self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) | |
223e47cc | 1175 | } |
223e47cc | 1176 | |
9fa01778 | 1177 | /// Parses asyncness: `async` or nothing. |
487cf647 FG |
1178 | fn parse_asyncness(&mut self, case: Case) -> Async { |
1179 | if self.eat_keyword_case(kw::Async, case) { | |
74b04a01 XL |
1180 | let span = self.prev_token.uninterpolated_span(); |
1181 | Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID } | |
8faf50e0 | 1182 | } else { |
74b04a01 | 1183 | Async::No |
8faf50e0 XL |
1184 | } |
1185 | } | |
1186 | ||
9fa01778 | 1187 | /// Parses unsafety: `unsafe` or nothing. |
487cf647 FG |
1188 | fn parse_unsafety(&mut self, case: Case) -> Unsafe { |
1189 | if self.eat_keyword_case(kw::Unsafe, case) { | |
74b04a01 XL |
1190 | Unsafe::Yes(self.prev_token.uninterpolated_span()) |
1191 | } else { | |
1192 | Unsafe::No | |
1193 | } | |
1194 | } | |
1195 | ||
1196 | /// Parses constness: `const` or nothing. | |
487cf647 | 1197 | fn parse_constness(&mut self, case: Case) -> Const { |
9ffffee4 FG |
1198 | self.parse_constness_(case, false) |
1199 | } | |
1200 | ||
353b0b11 FG |
1201 | /// Parses constness for closures (case sensitive, feature-gated) |
1202 | fn parse_closure_constness(&mut self) -> Const { | |
1203 | let constness = self.parse_constness_(Case::Sensitive, true); | |
1204 | if let Const::Yes(span) = constness { | |
1205 | self.sess.gated_spans.gate(sym::const_closures, span); | |
1206 | } | |
1207 | constness | |
9ffffee4 FG |
1208 | } |
1209 | ||
1210 | fn parse_constness_(&mut self, case: Case, is_closure: bool) -> Const { | |
1211 | // Avoid const blocks and const closures to be parsed as const items | |
1212 | if (self.check_const_closure() == is_closure) | |
1213 | && self.look_ahead(1, |t| t != &token::OpenDelim(Delimiter::Brace)) | |
487cf647 | 1214 | && self.eat_keyword_case(kw::Const, case) |
29967ef6 | 1215 | { |
74b04a01 XL |
1216 | Const::Yes(self.prev_token.uninterpolated_span()) |
1217 | } else { | |
1218 | Const::No | |
1219 | } | |
1a4d82fc JJ |
1220 | } |
1221 | ||
29967ef6 | 1222 | /// Parses inline const expressions. |
3c0e092e XL |
1223 | fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P<Expr>> { |
1224 | if pat { | |
1225 | self.sess.gated_spans.gate(sym::inline_const_pat, span); | |
1226 | } else { | |
1227 | self.sess.gated_spans.gate(sym::inline_const, span); | |
1228 | } | |
29967ef6 | 1229 | self.eat_keyword(kw::Const); |
04454e1e | 1230 | let (attrs, blk) = self.parse_inner_attrs_and_block()?; |
29967ef6 XL |
1231 | let anon_const = AnonConst { |
1232 | id: DUMMY_NODE_ID, | |
f2b60f7d | 1233 | value: self.mk_expr(blk.span, ExprKind::Block(blk, None)), |
29967ef6 | 1234 | }; |
fc512014 | 1235 | let blk_span = anon_const.value.span; |
9c376795 | 1236 | Ok(self.mk_expr_with_attrs(span.to(blk_span), ExprKind::ConstBlock(anon_const), attrs)) |
29967ef6 XL |
1237 | } |
1238 | ||
416331ca XL |
1239 | /// Parses mutability (`mut` or nothing). |
1240 | fn parse_mutability(&mut self) -> Mutability { | |
dfeec247 | 1241 | if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } |
223e47cc LB |
1242 | } |
1243 | ||
e74abb32 XL |
1244 | /// Possibly parses mutability (`const` or `mut`). |
1245 | fn parse_const_or_mut(&mut self) -> Option<Mutability> { | |
1246 | if self.eat_keyword(kw::Mut) { | |
dfeec247 | 1247 | Some(Mutability::Mut) |
e74abb32 | 1248 | } else if self.eat_keyword(kw::Const) { |
dfeec247 | 1249 | Some(Mutability::Not) |
e74abb32 XL |
1250 | } else { |
1251 | None | |
1252 | } | |
1253 | } | |
1254 | ||
416331ca | 1255 | fn parse_field_name(&mut self) -> PResult<'a, Ident> { |
dfeec247 XL |
1256 | if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind |
1257 | { | |
2b03887a FG |
1258 | if let Some(suffix) = suffix { |
1259 | self.expect_no_tuple_index_suffix(self.token.span, suffix); | |
1260 | } | |
416331ca | 1261 | self.bump(); |
74b04a01 | 1262 | Ok(Ident::new(symbol, self.prev_token.span)) |
223e47cc | 1263 | } else { |
6a06907d | 1264 | self.parse_ident_common(true) |
223e47cc LB |
1265 | } |
1266 | } | |
1267 | ||
487cf647 FG |
1268 | fn parse_delim_args(&mut self) -> PResult<'a, P<DelimArgs>> { |
1269 | if let Some(args) = self.parse_delim_args_inner() { Ok(P(args)) } else { self.unexpected() } | |
60c5eb7d XL |
1270 | } |
1271 | ||
487cf647 FG |
1272 | fn parse_attr_args(&mut self) -> PResult<'a, AttrArgs> { |
1273 | Ok(if let Some(args) = self.parse_delim_args_inner() { | |
1274 | AttrArgs::Delimited(args) | |
1275 | } else { | |
1276 | if self.eat(&token::Eq) { | |
1277 | let eq_span = self.prev_token.span; | |
1278 | AttrArgs::Eq(eq_span, AttrArgsEq::Ast(self.parse_expr_force_collect()?)) | |
1279 | } else { | |
1280 | AttrArgs::Empty | |
1281 | } | |
1282 | }) | |
60c5eb7d XL |
1283 | } |
1284 | ||
487cf647 | 1285 | fn parse_delim_args_inner(&mut self) -> Option<DelimArgs> { |
9ffffee4 | 1286 | let delimited = self.check(&token::OpenDelim(Delimiter::Parenthesis)) |
487cf647 | 1287 | || self.check(&token::OpenDelim(Delimiter::Bracket)) |
9ffffee4 FG |
1288 | || self.check(&token::OpenDelim(Delimiter::Brace)); |
1289 | ||
1290 | delimited.then(|| { | |
1291 | // We've confirmed above that there is a delimiter so unwrapping is OK. | |
1292 | let TokenTree::Delimited(dspan, delim, tokens) = self.parse_token_tree() else { unreachable!() }; | |
1293 | ||
1294 | DelimArgs { dspan, delim: MacDelimiter::from_token(delim).unwrap(), tokens } | |
1295 | }) | |
416331ca | 1296 | } |
041b39d2 | 1297 | |
e74abb32 XL |
1298 | fn parse_or_use_outer_attributes( |
1299 | &mut self, | |
6a06907d XL |
1300 | already_parsed_attrs: Option<AttrWrapper>, |
1301 | ) -> PResult<'a, AttrWrapper> { | |
416331ca XL |
1302 | if let Some(attrs) = already_parsed_attrs { |
1303 | Ok(attrs) | |
970d7e83 | 1304 | } else { |
6a06907d | 1305 | self.parse_outer_attributes() |
970d7e83 LB |
1306 | } |
1307 | } | |
1308 | ||
416331ca | 1309 | /// Parses a single token tree from the input. |
3dfed10e | 1310 | pub(crate) fn parse_token_tree(&mut self) -> TokenTree { |
dc9dc135 | 1311 | match self.token.kind { |
416331ca | 1312 | token::OpenDelim(..) => { |
9ffffee4 FG |
1313 | // Grab the tokens within the delimiters. |
1314 | let tree_cursor = &self.token_cursor.tree_cursor; | |
1315 | let stream = tree_cursor.stream.clone(); | |
1316 | let (_, delim, span) = *self.token_cursor.stack.last().unwrap(); | |
04454e1e FG |
1317 | |
1318 | // Advance the token cursor through the entire delimited | |
1319 | // sequence. After getting the `OpenDelim` we are *within* the | |
1320 | // delimited sequence, i.e. at depth `d`. After getting the | |
1321 | // matching `CloseDelim` we are *after* the delimited sequence, | |
1322 | // i.e. at depth `d - 1`. | |
1323 | let target_depth = self.token_cursor.stack.len() - 1; | |
1324 | loop { | |
29967ef6 XL |
1325 | // Advance one token at a time, so `TokenCursor::next()` |
1326 | // can capture these tokens if necessary. | |
1327 | self.bump(); | |
04454e1e FG |
1328 | if self.token_cursor.stack.len() == target_depth { |
1329 | debug_assert!(matches!(self.token.kind, token::CloseDelim(_))); | |
1330 | break; | |
1331 | } | |
29967ef6 | 1332 | } |
04454e1e | 1333 | |
29967ef6 | 1334 | // Consume close delimiter |
0731742a | 1335 | self.bump(); |
29967ef6 | 1336 | TokenTree::Delimited(span, delim, stream) |
dfeec247 | 1337 | } |
416331ca XL |
1338 | token::CloseDelim(_) | token::Eof => unreachable!(), |
1339 | _ => { | |
416331ca | 1340 | self.bump(); |
064997fb | 1341 | TokenTree::Token(self.prev_token.clone(), Spacing::Alone) |
0731742a | 1342 | } |
0731742a XL |
1343 | } |
1344 | } | |
1345 | ||
416331ca XL |
1346 | /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF. |
1347 | pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> { | |
1348 | let mut tts = Vec::new(); | |
1349 | while self.token != token::Eof { | |
1350 | tts.push(self.parse_token_tree()); | |
54a0048b | 1351 | } |
416331ca | 1352 | Ok(tts) |
54a0048b SL |
1353 | } |
1354 | ||
416331ca XL |
1355 | pub fn parse_tokens(&mut self) -> TokenStream { |
1356 | let mut result = Vec::new(); | |
1357 | loop { | |
1358 | match self.token.kind { | |
1359 | token::Eof | token::CloseDelim(..) => break, | |
064997fb | 1360 | _ => result.push(self.parse_token_tree()), |
ff7c6d11 | 1361 | } |
223e47cc | 1362 | } |
416331ca | 1363 | TokenStream::new(result) |
223e47cc LB |
1364 | } |
1365 | ||
416331ca XL |
1366 | /// Evaluates the closure with restrictions in place. |
1367 | /// | |
1368 | /// Afters the closure is evaluated, restrictions are reset. | |
e74abb32 | 1369 | fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T { |
416331ca | 1370 | let old = self.restrictions; |
e74abb32 XL |
1371 | self.restrictions = res; |
1372 | let res = f(self); | |
416331ca | 1373 | self.restrictions = old; |
e74abb32 | 1374 | res |
8faf50e0 XL |
1375 | } |
1376 | ||
923072b8 FG |
1377 | /// Parses `pub` and `pub(in path)` plus shortcuts `pub(crate)` for `pub(in crate)`, `pub(self)` |
1378 | /// for `pub(in self)` and `pub(super)` for `pub(in super)`. | |
416331ca | 1379 | /// If the following element can't be a tuple (i.e., it's a function definition), then |
3c0e092e | 1380 | /// it's not a tuple struct field), and the contents within the parentheses aren't valid, |
416331ca | 1381 | /// so emit a proper diagnostic. |
1b1a35ee XL |
1382 | // Public for rustfmt usage. |
1383 | pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { | |
04454e1e | 1384 | maybe_whole!(self, NtVis, |x| x.into_inner()); |
dc9dc135 | 1385 | |
416331ca XL |
1386 | if !self.eat_keyword(kw::Pub) { |
1387 | // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no | |
1388 | // keyword to grab a span from for inherited visibility; an empty span at the | |
1389 | // beginning of the current token would seem to be the "Schelling span". | |
1b1a35ee XL |
1390 | return Ok(Visibility { |
1391 | span: self.token.span.shrink_to_lo(), | |
1392 | kind: VisibilityKind::Inherited, | |
1393 | tokens: None, | |
1394 | }); | |
416331ca | 1395 | } |
74b04a01 | 1396 | let lo = self.prev_token.span; |
223e47cc | 1397 | |
04454e1e | 1398 | if self.check(&token::OpenDelim(Delimiter::Parenthesis)) { |
416331ca XL |
1399 | // We don't `self.bump()` the `(` yet because this might be a struct definition where |
1400 | // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`. | |
1401 | // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so | |
1402 | // by the following tokens. | |
923072b8 | 1403 | if self.is_keyword_ahead(1, &[kw::In]) { |
e74abb32 | 1404 | // Parse `pub(in path)`. |
416331ca XL |
1405 | self.bump(); // `(` |
1406 | self.bump(); // `in` | |
1407 | let path = self.parse_path(PathStyle::Mod)?; // `path` | |
04454e1e | 1408 | self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)` |
f2b60f7d FG |
1409 | let vis = VisibilityKind::Restricted { |
1410 | path: P(path), | |
1411 | id: ast::DUMMY_NODE_ID, | |
1412 | shorthand: false, | |
1413 | }; | |
1b1a35ee XL |
1414 | return Ok(Visibility { |
1415 | span: lo.to(self.prev_token.span), | |
1416 | kind: vis, | |
1417 | tokens: None, | |
1418 | }); | |
04454e1e | 1419 | } else if self.look_ahead(2, |t| t == &token::CloseDelim(Delimiter::Parenthesis)) |
923072b8 | 1420 | && self.is_keyword_ahead(1, &[kw::Crate, kw::Super, kw::SelfLower]) |
416331ca | 1421 | { |
923072b8 | 1422 | // Parse `pub(crate)`, `pub(self)`, or `pub(super)`. |
416331ca | 1423 | self.bump(); // `(` |
923072b8 | 1424 | let path = self.parse_path(PathStyle::Mod)?; // `crate`/`super`/`self` |
04454e1e | 1425 | self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)` |
f2b60f7d FG |
1426 | let vis = VisibilityKind::Restricted { |
1427 | path: P(path), | |
1428 | id: ast::DUMMY_NODE_ID, | |
1429 | shorthand: true, | |
1430 | }; | |
1b1a35ee XL |
1431 | return Ok(Visibility { |
1432 | span: lo.to(self.prev_token.span), | |
1433 | kind: vis, | |
1434 | tokens: None, | |
1435 | }); | |
60c5eb7d XL |
1436 | } else if let FollowedByType::No = fbt { |
1437 | // Provide this diagnostic if a type cannot follow; | |
1438 | // in particular, if this is not a tuple struct. | |
e74abb32 XL |
1439 | self.recover_incorrect_vis_restriction()?; |
1440 | // Emit diagnostic, but continue with public visibility. | |
532ac7d7 | 1441 | } |
223e47cc | 1442 | } |
223e47cc | 1443 | |
1b1a35ee | 1444 | Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) |
223e47cc LB |
1445 | } |
1446 | ||
e74abb32 XL |
1447 | /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }` |
1448 | fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> { | |
1449 | self.bump(); // `(` | |
1450 | let path = self.parse_path(PathStyle::Mod)?; | |
04454e1e | 1451 | self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)` |
e74abb32 | 1452 | |
e74abb32 | 1453 | let path_str = pprust::path_to_string(&path); |
2b03887a | 1454 | self.sess.emit_err(IncorrectVisibilityRestriction { span: path.span, inner_str: path_str }); |
e74abb32 XL |
1455 | |
1456 | Ok(()) | |
1457 | } | |
1458 | ||
60c5eb7d | 1459 | /// Parses `extern string_literal?`. |
487cf647 FG |
1460 | fn parse_extern(&mut self, case: Case) -> Extern { |
1461 | if self.eat_keyword_case(kw::Extern, case) { | |
064997fb FG |
1462 | let mut extern_span = self.prev_token.span; |
1463 | let abi = self.parse_abi(); | |
1464 | if let Some(abi) = abi { | |
1465 | extern_span = extern_span.to(abi.span); | |
1466 | } | |
1467 | Extern::from_abi(abi, extern_span) | |
1468 | } else { | |
1469 | Extern::None | |
1470 | } | |
e74abb32 XL |
1471 | } |
1472 | ||
60c5eb7d XL |
1473 | /// Parses a string literal as an ABI spec. |
1474 | fn parse_abi(&mut self) -> Option<StrLit> { | |
1475 | match self.parse_str_lit() { | |
1476 | Ok(str_lit) => Some(str_lit), | |
1477 | Err(Some(lit)) => match lit.kind { | |
f2b60f7d | 1478 | ast::LitKind::Err => None, |
60c5eb7d | 1479 | _ => { |
2b03887a | 1480 | self.sess.emit_err(NonStringAbiLiteral { span: lit.span }); |
60c5eb7d | 1481 | None |
223e47cc | 1482 | } |
dfeec247 | 1483 | }, |
60c5eb7d | 1484 | Err(None) => None, |
223e47cc LB |
1485 | } |
1486 | } | |
1487 | ||
04454e1e | 1488 | pub fn collect_tokens_no_attrs<R: HasAttrs + HasTokens>( |
5869c6ff XL |
1489 | &mut self, |
1490 | f: impl FnOnce(&mut Self) -> PResult<'a, R>, | |
1491 | ) -> PResult<'a, R> { | |
6a06907d XL |
1492 | // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use |
1493 | // `ForceCollect::Yes` | |
1494 | self.collect_tokens_trailing_token( | |
1495 | AttrWrapper::empty(), | |
1496 | ForceCollect::Yes, | |
1497 | |this, _attrs| Ok((f(this)?, TrailingToken::None)), | |
1498 | ) | |
3b2f2976 XL |
1499 | } |
1500 | ||
0531ce1d XL |
1501 | /// `::{` or `::*` |
1502 | fn is_import_coupler(&mut self) -> bool { | |
dfeec247 XL |
1503 | self.check(&token::ModSep) |
1504 | && self.look_ahead(1, |t| { | |
04454e1e | 1505 | *t == token::OpenDelim(Delimiter::Brace) || *t == token::BinOp(token::Star) |
dfeec247 | 1506 | }) |
a7813a04 | 1507 | } |
1b1a35ee XL |
1508 | |
1509 | pub fn clear_expected_tokens(&mut self) { | |
1510 | self.expected_tokens.clear(); | |
1511 | } | |
9c376795 FG |
1512 | |
1513 | pub fn approx_token_stream_pos(&self) -> usize { | |
1514 | self.token_cursor.num_next_calls | |
1515 | } | |
e74abb32 | 1516 | } |
532ac7d7 | 1517 | |
923072b8 | 1518 | pub(crate) fn make_unclosed_delims_error( |
9ffffee4 | 1519 | unmatched: UnmatchedDelim, |
e74abb32 | 1520 | sess: &ParseSess, |
5e7ed085 | 1521 | ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>> { |
e74abb32 | 1522 | // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to |
9ffffee4 | 1523 | // `unmatched_delims` only for error recovery in the `Parser`. |
e74abb32 | 1524 | let found_delim = unmatched.found_delim?; |
2b03887a | 1525 | let mut spans = vec![unmatched.found_span]; |
e74abb32 | 1526 | if let Some(sp) = unmatched.unclosed_span { |
2b03887a FG |
1527 | spans.push(sp); |
1528 | }; | |
1529 | let err = MismatchedClosingDelimiter { | |
1530 | spans, | |
1531 | delimiter: pprust::token_kind_to_string(&token::CloseDelim(found_delim)).to_string(), | |
1532 | unmatched: unmatched.found_span, | |
1533 | opening_candidate: unmatched.candidate_span, | |
1534 | unclosed: unmatched.unclosed_span, | |
1535 | } | |
1536 | .into_diagnostic(&sess.span_diagnostic); | |
e74abb32 | 1537 | Some(err) |
223e47cc | 1538 | } |
9fa01778 | 1539 | |
9ffffee4 | 1540 | pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedDelim>, sess: &ParseSess) { |
353b0b11 FG |
1541 | let _ = sess.reached_eof.fetch_or( |
1542 | unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()), | |
1543 | Ordering::Relaxed, | |
1544 | ); | |
e74abb32 | 1545 | for unmatched in unclosed_delims.drain(..) { |
f9f354fc | 1546 | if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { |
74b04a01 | 1547 | e.emit(); |
f9f354fc | 1548 | } |
9fa01778 | 1549 | } |
9fa01778 | 1550 | } |
cdc7bbd5 | 1551 | |
f2b60f7d FG |
1552 | /// A helper struct used when building an `AttrTokenStream` from |
1553 | /// a `LazyAttrTokenStream`. Both delimiter and non-delimited tokens | |
cdc7bbd5 | 1554 | /// are stored as `FlatToken::Token`. A vector of `FlatToken`s |
f2b60f7d FG |
1555 | /// is then 'parsed' to build up an `AttrTokenStream` with nested |
1556 | /// `AttrTokenTree::Delimited` tokens. | |
cdc7bbd5 XL |
1557 | #[derive(Debug, Clone)] |
1558 | pub enum FlatToken { | |
1559 | /// A token - this holds both delimiter (e.g. '{' and '}') | |
1560 | /// and non-delimiter tokens | |
1561 | Token(Token), | |
1562 | /// Holds the `AttributesData` for an AST node. The | |
1563 | /// `AttributesData` is inserted directly into the | |
f2b60f7d FG |
1564 | /// constructed `AttrTokenStream` as |
1565 | /// an `AttrTokenTree::Attributes`. | |
cdc7bbd5 XL |
1566 | AttrTarget(AttributesData), |
1567 | /// A special 'empty' token that is ignored during the conversion | |
f2b60f7d | 1568 | /// to an `AttrTokenStream`. This is used to simplify the |
cdc7bbd5 XL |
1569 | /// handling of replace ranges. |
1570 | Empty, | |
1571 | } | |
5e7ed085 FG |
1572 | |
1573 | #[derive(Debug)] | |
1574 | pub enum NtOrTt { | |
1575 | Nt(Nonterminal), | |
1576 | Tt(TokenTree), | |
1577 | } |