]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/path.rs
Auto merge of #69255 - estebank:e0599-details, r=varkor
[rust.git] / src / librustc_parse / parser / path.rs
1 use super::ty::{AllowPlus, RecoverQPath};
2 use super::{Parser, TokenType};
3 use crate::maybe_whole;
4 use rustc_errors::{pluralize, Applicability, PResult};
5 use rustc_span::source_map::{BytePos, Span};
6 use rustc_span::symbol::{kw, sym};
7 use syntax::ast::{self, AngleBracketedArgs, Ident, ParenthesizedArgs, Path, PathSegment, QSelf};
8 use syntax::ast::{
9     AnonConst, AssocTyConstraint, AssocTyConstraintKind, BlockCheckMode, GenericArg,
10 };
11 use syntax::token::{self, Token};
12
13 use log::debug;
14 use std::mem;
15
16 /// Specifies how to parse a path.
17 #[derive(Copy, Clone, PartialEq)]
18 pub enum PathStyle {
19     /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
20     /// with something else. For example, in expressions `segment < ....` can be interpreted
21     /// as a comparison and `segment ( ....` can be interpreted as a function call.
22     /// In all such contexts the non-path interpretation is preferred by default for practical
23     /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
24     /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
25     Expr,
26     /// In other contexts, notably in types, no ambiguity exists and paths can be written
27     /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
28     /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
29     Type,
30     /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
31     /// visibilities or attributes.
32     /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
33     /// (paths in "mod" contexts have to be checked later for absence of generic arguments
34     /// anyway, due to macros), but it is used to avoid weird suggestions about expected
35     /// tokens when something goes wrong.
36     Mod,
37 }
38
39 impl<'a> Parser<'a> {
40     /// Parses a qualified path.
41     /// Assumes that the leading `<` has been parsed already.
42     ///
43     /// `qualified_path = <type [as trait_ref]>::path`
44     ///
45     /// # Examples
46     /// `<T>::default`
47     /// `<T as U>::a`
48     /// `<T as U>::F::a<S>` (without disambiguator)
49     /// `<T as U>::F::a::<S>` (with disambiguator)
50     pub(super) fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, Path)> {
51         let lo = self.prev_span;
52         let ty = self.parse_ty()?;
53
54         // `path` will contain the prefix of the path up to the `>`,
55         // if any (e.g., `U` in the `<T as U>::*` examples
56         // above). `path_span` has the span of that path, or an empty
57         // span in the case of something like `<T>::Bar`.
58         let (mut path, path_span);
59         if self.eat_keyword(kw::As) {
60             let path_lo = self.token.span;
61             path = self.parse_path(PathStyle::Type)?;
62             path_span = path_lo.to(self.prev_span);
63         } else {
64             path_span = self.token.span.to(self.token.span);
65             path = ast::Path { segments: Vec::new(), span: path_span };
66         }
67
68         // See doc comment for `unmatched_angle_bracket_count`.
69         self.expect(&token::Gt)?;
70         if self.unmatched_angle_bracket_count > 0 {
71             self.unmatched_angle_bracket_count -= 1;
72             debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
73         }
74
75         if !self.recover_colon_before_qpath_proj() {
76             self.expect(&token::ModSep)?;
77         }
78
79         let qself = QSelf { ty, path_span, position: path.segments.len() };
80         self.parse_path_segments(&mut path.segments, style)?;
81
82         Ok((qself, Path { segments: path.segments, span: lo.to(self.prev_span) }))
83     }
84
85     /// Recover from an invalid single colon, when the user likely meant a qualified path.
86     /// We avoid emitting this if not followed by an identifier, as our assumption that the user
87     /// intended this to be a qualified path may not be correct.
88     ///
89     /// ```ignore (diagnostics)
90     /// <Bar as Baz<T>>:Qux
91     ///                ^ help: use double colon
92     /// ```
93     fn recover_colon_before_qpath_proj(&mut self) -> bool {
94         if self.token.kind != token::Colon
95             || self.look_ahead(1, |t| !t.is_ident() || t.is_reserved_ident())
96         {
97             return false;
98         }
99
100         self.bump(); // colon
101
102         self.diagnostic()
103             .struct_span_err(
104                 self.prev_span,
105                 "found single colon before projection in qualified path",
106             )
107             .span_suggestion(
108                 self.prev_span,
109                 "use double colon",
110                 "::".to_string(),
111                 Applicability::MachineApplicable,
112             )
113             .emit();
114
115         true
116     }
117
118     /// Parses simple paths.
119     ///
120     /// `path = [::] segment+`
121     /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
122     ///
123     /// # Examples
124     /// `a::b::C<D>` (without disambiguator)
125     /// `a::b::C::<D>` (with disambiguator)
126     /// `Fn(Args)` (without disambiguator)
127     /// `Fn::(Args)` (with disambiguator)
128     pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, Path> {
129         maybe_whole!(self, NtPath, |path| {
130             if style == PathStyle::Mod && path.segments.iter().any(|segment| segment.args.is_some())
131             {
132                 self.struct_span_err(path.span, "unexpected generic arguments in path").emit();
133             }
134             path
135         });
136
137         let lo = self.token.span;
138         let mut segments = Vec::new();
139         let mod_sep_ctxt = self.token.span.ctxt();
140         if self.eat(&token::ModSep) {
141             segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
142         }
143         self.parse_path_segments(&mut segments, style)?;
144
145         Ok(Path { segments, span: lo.to(self.prev_span) })
146     }
147
148     pub(super) fn parse_path_segments(
149         &mut self,
150         segments: &mut Vec<PathSegment>,
151         style: PathStyle,
152     ) -> PResult<'a, ()> {
153         loop {
154             let segment = self.parse_path_segment(style)?;
155             if style == PathStyle::Expr {
156                 // In order to check for trailing angle brackets, we must have finished
157                 // recursing (`parse_path_segment` can indirectly call this function),
158                 // that is, the next token must be the highlighted part of the below example:
159                 //
160                 // `Foo::<Bar as Baz<T>>::Qux`
161                 //                      ^ here
162                 //
163                 // As opposed to the below highlight (if we had only finished the first
164                 // recursion):
165                 //
166                 // `Foo::<Bar as Baz<T>>::Qux`
167                 //                     ^ here
168                 //
169                 // `PathStyle::Expr` is only provided at the root invocation and never in
170                 // `parse_path_segment` to recurse and therefore can be checked to maintain
171                 // this invariant.
172                 self.check_trailing_angle_brackets(&segment, token::ModSep);
173             }
174             segments.push(segment);
175
176             if self.is_import_coupler() || !self.eat(&token::ModSep) {
177                 return Ok(());
178             }
179         }
180     }
181
182     pub(super) fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
183         let ident = self.parse_path_segment_ident()?;
184
185         let is_args_start = |token: &Token| match token.kind {
186             token::Lt
187             | token::BinOp(token::Shl)
188             | token::OpenDelim(token::Paren)
189             | token::LArrow => true,
190             _ => false,
191         };
192         let check_args_start = |this: &mut Self| {
193             this.expected_tokens.extend_from_slice(&[
194                 TokenType::Token(token::Lt),
195                 TokenType::Token(token::OpenDelim(token::Paren)),
196             ]);
197             is_args_start(&this.token)
198         };
199
200         Ok(
201             if style == PathStyle::Type && check_args_start(self)
202                 || style != PathStyle::Mod
203                     && self.check(&token::ModSep)
204                     && self.look_ahead(1, |t| is_args_start(t))
205             {
206                 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
207                 // it isn't, then we reset the unmatched angle bracket count as we're about to start
208                 // parsing a new path.
209                 if style == PathStyle::Expr {
210                     self.unmatched_angle_bracket_count = 0;
211                     self.max_angle_bracket_count = 0;
212                 }
213
214                 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
215                 self.eat(&token::ModSep);
216                 let lo = self.token.span;
217                 let args = if self.eat_lt() {
218                     // `<'a, T, A = U>`
219                     let (args, constraints) =
220                         self.parse_generic_args_with_leading_angle_bracket_recovery(style, lo)?;
221                     self.expect_gt()?;
222                     let span = lo.to(self.prev_span);
223                     AngleBracketedArgs { args, constraints, span }.into()
224                 } else {
225                     // `(T, U) -> R`
226                     let (inputs, _) = self.parse_paren_comma_seq(|p| p.parse_ty())?;
227                     let span = ident.span.to(self.prev_span);
228                     let output = self.parse_ret_ty(AllowPlus::No, RecoverQPath::No)?;
229                     ParenthesizedArgs { inputs, output, span }.into()
230                 };
231
232                 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
233             } else {
234                 // Generic arguments are not found.
235                 PathSegment::from_ident(ident)
236             },
237         )
238     }
239
240     pub(super) fn parse_path_segment_ident(&mut self) -> PResult<'a, Ident> {
241         match self.normalized_token.kind {
242             token::Ident(name, _) if name.is_path_segment_keyword() => {
243                 self.bump();
244                 Ok(Ident::new(name, self.normalized_prev_token.span))
245             }
246             _ => self.parse_ident(),
247         }
248     }
249
250     /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
251     /// For the purposes of understanding the parsing logic of generic arguments, this function
252     /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
253     /// had the correct amount of leading angle brackets.
254     ///
255     /// ```ignore (diagnostics)
256     /// bar::<<<<T as Foo>::Output>();
257     ///      ^^ help: remove extra angle brackets
258     /// ```
259     fn parse_generic_args_with_leading_angle_bracket_recovery(
260         &mut self,
261         style: PathStyle,
262         lo: Span,
263     ) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
264         // We need to detect whether there are extra leading left angle brackets and produce an
265         // appropriate error and suggestion. This cannot be implemented by looking ahead at
266         // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
267         // then there won't be matching `>` tokens to find.
268         //
269         // To explain how this detection works, consider the following example:
270         //
271         // ```ignore (diagnostics)
272         // bar::<<<<T as Foo>::Output>();
273         //      ^^ help: remove extra angle brackets
274         // ```
275         //
276         // Parsing of the left angle brackets starts in this function. We start by parsing the
277         // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
278         // `eat_lt`):
279         //
280         // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
281         // *Unmatched count:* 1
282         // *`parse_path_segment` calls deep:* 0
283         //
284         // This has the effect of recursing as this function is called if a `<` character
285         // is found within the expected generic arguments:
286         //
287         // *Upcoming tokens:* `<<<T as Foo>::Output>;`
288         // *Unmatched count:* 2
289         // *`parse_path_segment` calls deep:* 1
290         //
291         // Eventually we will have recursed until having consumed all of the `<` tokens and
292         // this will be reflected in the count:
293         //
294         // *Upcoming tokens:* `T as Foo>::Output>;`
295         // *Unmatched count:* 4
296         // `parse_path_segment` calls deep:* 3
297         //
298         // The parser will continue until reaching the first `>` - this will decrement the
299         // unmatched angle bracket count and return to the parent invocation of this function
300         // having succeeded in parsing:
301         //
302         // *Upcoming tokens:* `::Output>;`
303         // *Unmatched count:* 3
304         // *`parse_path_segment` calls deep:* 2
305         //
306         // This will continue until the next `>` character which will also return successfully
307         // to the parent invocation of this function and decrement the count:
308         //
309         // *Upcoming tokens:* `;`
310         // *Unmatched count:* 2
311         // *`parse_path_segment` calls deep:* 1
312         //
313         // At this point, this function will expect to find another matching `>` character but
314         // won't be able to and will return an error. This will continue all the way up the
315         // call stack until the first invocation:
316         //
317         // *Upcoming tokens:* `;`
318         // *Unmatched count:* 2
319         // *`parse_path_segment` calls deep:* 0
320         //
321         // In doing this, we have managed to work out how many unmatched leading left angle
322         // brackets there are, but we cannot recover as the unmatched angle brackets have
323         // already been consumed. To remedy this, we keep a snapshot of the parser state
324         // before we do the above. We can then inspect whether we ended up with a parsing error
325         // and unmatched left angle brackets and if so, restore the parser state before we
326         // consumed any `<` characters to emit an error and consume the erroneous tokens to
327         // recover by attempting to parse again.
328         //
329         // In practice, the recursion of this function is indirect and there will be other
330         // locations that consume some `<` characters - as long as we update the count when
331         // this happens, it isn't an issue.
332
333         let is_first_invocation = style == PathStyle::Expr;
334         // Take a snapshot before attempting to parse - we can restore this later.
335         let snapshot = if is_first_invocation { Some(self.clone()) } else { None };
336
337         debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
338         match self.parse_generic_args() {
339             Ok(value) => Ok(value),
340             Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
341                 // Cancel error from being unable to find `>`. We know the error
342                 // must have been this due to a non-zero unmatched angle bracket
343                 // count.
344                 e.cancel();
345
346                 // Swap `self` with our backup of the parser state before attempting to parse
347                 // generic arguments.
348                 let snapshot = mem::replace(self, snapshot.unwrap());
349
350                 debug!(
351                     "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
352                      snapshot.count={:?}",
353                     snapshot.unmatched_angle_bracket_count,
354                 );
355
356                 // Eat the unmatched angle brackets.
357                 for _ in 0..snapshot.unmatched_angle_bracket_count {
358                     self.eat_lt();
359                 }
360
361                 // Make a span over ${unmatched angle bracket count} characters.
362                 let span = lo.with_hi(lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count));
363                 self.struct_span_err(
364                     span,
365                     &format!(
366                         "unmatched angle bracket{}",
367                         pluralize!(snapshot.unmatched_angle_bracket_count)
368                     ),
369                 )
370                 .span_suggestion(
371                     span,
372                     &format!(
373                         "remove extra angle bracket{}",
374                         pluralize!(snapshot.unmatched_angle_bracket_count)
375                     ),
376                     String::new(),
377                     Applicability::MachineApplicable,
378                 )
379                 .emit();
380
381                 // Try again without unmatched angle bracket characters.
382                 self.parse_generic_args()
383             }
384             Err(e) => Err(e),
385         }
386     }
387
388     /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
389     /// possibly including trailing comma.
390     fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
391         let mut args = Vec::new();
392         let mut constraints = Vec::new();
393         let mut misplaced_assoc_ty_constraints: Vec<Span> = Vec::new();
394         let mut assoc_ty_constraints: Vec<Span> = Vec::new();
395
396         let args_lo = self.token.span;
397
398         loop {
399             if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
400                 // Parse lifetime argument.
401                 args.push(GenericArg::Lifetime(self.expect_lifetime()));
402                 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
403             } else if self.check_ident()
404                 && self.look_ahead(1, |t| t == &token::Eq || t == &token::Colon)
405             {
406                 // Parse associated type constraint.
407                 let lo = self.token.span;
408                 let ident = self.parse_ident()?;
409                 let kind = if self.eat(&token::Eq) {
410                     AssocTyConstraintKind::Equality { ty: self.parse_ty()? }
411                 } else if self.eat(&token::Colon) {
412                     AssocTyConstraintKind::Bound {
413                         bounds: self.parse_generic_bounds(Some(self.prev_span))?,
414                     }
415                 } else {
416                     unreachable!();
417                 };
418
419                 let span = lo.to(self.prev_span);
420
421                 // Gate associated type bounds, e.g., `Iterator<Item: Ord>`.
422                 if let AssocTyConstraintKind::Bound { .. } = kind {
423                     self.sess.gated_spans.gate(sym::associated_type_bounds, span);
424                 }
425
426                 constraints.push(AssocTyConstraint { id: ast::DUMMY_NODE_ID, ident, kind, span });
427                 assoc_ty_constraints.push(span);
428             } else if self.check_const_arg() {
429                 // Parse const argument.
430                 let expr = if let token::OpenDelim(token::Brace) = self.token.kind {
431                     self.parse_block_expr(
432                         None,
433                         self.token.span,
434                         BlockCheckMode::Default,
435                         ast::AttrVec::new(),
436                     )?
437                 } else if self.token.is_ident() {
438                     // FIXME(const_generics): to distinguish between idents for types and consts,
439                     // we should introduce a GenericArg::Ident in the AST and distinguish when
440                     // lowering to the HIR. For now, idents for const args are not permitted.
441                     if self.token.is_bool_lit() {
442                         self.parse_literal_maybe_minus()?
443                     } else {
444                         let span = self.token.span;
445                         let msg = "identifiers may currently not be used for const generics";
446                         self.struct_span_err(span, msg).emit();
447                         let block = self.mk_block_err(span);
448                         self.mk_expr(span, ast::ExprKind::Block(block, None), ast::AttrVec::new())
449                     }
450                 } else {
451                     self.parse_literal_maybe_minus()?
452                 };
453                 let value = AnonConst { id: ast::DUMMY_NODE_ID, value: expr };
454                 args.push(GenericArg::Const(value));
455                 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
456             } else if self.check_type() {
457                 // Parse type argument.
458                 args.push(GenericArg::Type(self.parse_ty()?));
459                 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
460             } else {
461                 break;
462             }
463
464             if !self.eat(&token::Comma) {
465                 break;
466             }
467         }
468
469         // FIXME: we would like to report this in ast_validation instead, but we currently do not
470         // preserve ordering of generic parameters with respect to associated type binding, so we
471         // lose that information after parsing.
472         if misplaced_assoc_ty_constraints.len() > 0 {
473             let mut err = self.struct_span_err(
474                 args_lo.to(self.prev_span),
475                 "associated type bindings must be declared after generic parameters",
476             );
477             for span in misplaced_assoc_ty_constraints {
478                 err.span_label(
479                     span,
480                     "this associated type binding should be moved after the generic parameters",
481                 );
482             }
483             err.emit();
484         }
485
486         Ok((args, constraints))
487     }
488 }