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