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