]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/path.rs
Recover from a misplaced inner doc comment
[rust.git] / compiler / rustc_parse / src / parser / path.rs
1 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
2 use super::{Parser, TokenType};
3 use crate::maybe_whole;
4 use rustc_ast::ptr::P;
5 use rustc_ast::token::{self, Token};
6 use rustc_ast::{self as ast, AngleBracketedArg, AngleBracketedArgs, ParenthesizedArgs};
7 use rustc_ast::{AnonConst, AssocTyConstraint, AssocTyConstraintKind, BlockCheckMode};
8 use rustc_ast::{GenericArg, GenericArgs};
9 use rustc_ast::{Path, PathSegment, QSelf};
10 use rustc_errors::{pluralize, Applicability, PResult};
11 use rustc_span::source_map::{BytePos, Span};
12 use rustc_span::symbol::{kw, sym, Ident};
13
14 use std::mem;
15 use tracing::debug;
16
17 /// Specifies how to parse a path.
18 #[derive(Copy, Clone, PartialEq)]
19 pub enum PathStyle {
20     /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
21     /// with something else. For example, in expressions `segment < ....` can be interpreted
22     /// as a comparison and `segment ( ....` can be interpreted as a function call.
23     /// In all such contexts the non-path interpretation is preferred by default for practical
24     /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
25     /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
26     Expr,
27     /// In other contexts, notably in types, no ambiguity exists and paths can be written
28     /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
29     /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
30     Type,
31     /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
32     /// visibilities or attributes.
33     /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
34     /// (paths in "mod" contexts have to be checked later for absence of generic arguments
35     /// anyway, due to macros), but it is used to avoid weird suggestions about expected
36     /// tokens when something goes wrong.
37     Mod,
38 }
39
40 impl<'a> Parser<'a> {
41     /// Parses a qualified path.
42     /// Assumes that the leading `<` has been parsed already.
43     ///
44     /// `qualified_path = <type [as trait_ref]>::path`
45     ///
46     /// # Examples
47     /// `<T>::default`
48     /// `<T as U>::a`
49     /// `<T as U>::F::a<S>` (without disambiguator)
50     /// `<T as U>::F::a::<S>` (with disambiguator)
51     pub(super) fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, Path)> {
52         let lo = self.prev_token.span;
53         let ty = self.parse_ty()?;
54
55         // `path` will contain the prefix of the path up to the `>`,
56         // if any (e.g., `U` in the `<T as U>::*` examples
57         // above). `path_span` has the span of that path, or an empty
58         // span in the case of something like `<T>::Bar`.
59         let (mut path, path_span);
60         if self.eat_keyword(kw::As) {
61             let path_lo = self.token.span;
62             path = self.parse_path(PathStyle::Type)?;
63             path_span = path_lo.to(self.prev_token.span);
64         } else {
65             path_span = self.token.span.to(self.token.span);
66             path = ast::Path { segments: Vec::new(), span: path_span, tokens: None };
67         }
68
69         // See doc comment for `unmatched_angle_bracket_count`.
70         self.expect(&token::Gt)?;
71         if self.unmatched_angle_bracket_count > 0 {
72             self.unmatched_angle_bracket_count -= 1;
73             debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
74         }
75
76         if !self.recover_colon_before_qpath_proj() {
77             self.expect(&token::ModSep)?;
78         }
79
80         let qself = QSelf { ty, path_span, position: path.segments.len() };
81         self.parse_path_segments(&mut path.segments, style)?;
82
83         Ok((
84             qself,
85             Path { segments: path.segments, span: lo.to(self.prev_token.span), tokens: None },
86         ))
87     }
88
89     /// Recover from an invalid single colon, when the user likely meant a qualified path.
90     /// We avoid emitting this if not followed by an identifier, as our assumption that the user
91     /// intended this to be a qualified path may not be correct.
92     ///
93     /// ```ignore (diagnostics)
94     /// <Bar as Baz<T>>:Qux
95     ///                ^ help: use double colon
96     /// ```
97     fn recover_colon_before_qpath_proj(&mut self) -> bool {
98         if self.token.kind != token::Colon
99             || self.look_ahead(1, |t| !t.is_ident() || t.is_reserved_ident())
100         {
101             return false;
102         }
103
104         self.bump(); // colon
105
106         self.diagnostic()
107             .struct_span_err(
108                 self.prev_token.span,
109                 "found single colon before projection in qualified path",
110             )
111             .span_suggestion(
112                 self.prev_token.span,
113                 "use double colon",
114                 "::".to_string(),
115                 Applicability::MachineApplicable,
116             )
117             .emit();
118
119         true
120     }
121
122     /// Parses simple paths.
123     ///
124     /// `path = [::] segment+`
125     /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
126     ///
127     /// # Examples
128     /// `a::b::C<D>` (without disambiguator)
129     /// `a::b::C::<D>` (with disambiguator)
130     /// `Fn(Args)` (without disambiguator)
131     /// `Fn::(Args)` (with disambiguator)
132     pub(super) fn parse_path(&mut self, style: PathStyle) -> PResult<'a, Path> {
133         maybe_whole!(self, NtPath, |path| {
134             if style == PathStyle::Mod && path.segments.iter().any(|segment| segment.args.is_some())
135             {
136                 self.struct_span_err(
137                     path.segments
138                         .iter()
139                         .filter_map(|segment| segment.args.as_ref())
140                         .map(|arg| arg.span())
141                         .collect::<Vec<_>>(),
142                     "unexpected generic arguments in path",
143                 )
144                 .emit();
145             }
146             path
147         });
148
149         let lo = self.token.span;
150         let mut segments = Vec::new();
151         let mod_sep_ctxt = self.token.span.ctxt();
152         if self.eat(&token::ModSep) {
153             segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
154         }
155         self.parse_path_segments(&mut segments, style)?;
156
157         Ok(Path { segments, span: lo.to(self.prev_token.span), tokens: None })
158     }
159
160     pub(super) fn parse_path_segments(
161         &mut self,
162         segments: &mut Vec<PathSegment>,
163         style: PathStyle,
164     ) -> PResult<'a, ()> {
165         loop {
166             let segment = self.parse_path_segment(style)?;
167             if style == PathStyle::Expr {
168                 // In order to check for trailing angle brackets, we must have finished
169                 // recursing (`parse_path_segment` can indirectly call this function),
170                 // that is, the next token must be the highlighted part of the below example:
171                 //
172                 // `Foo::<Bar as Baz<T>>::Qux`
173                 //                      ^ here
174                 //
175                 // As opposed to the below highlight (if we had only finished the first
176                 // recursion):
177                 //
178                 // `Foo::<Bar as Baz<T>>::Qux`
179                 //                     ^ here
180                 //
181                 // `PathStyle::Expr` is only provided at the root invocation and never in
182                 // `parse_path_segment` to recurse and therefore can be checked to maintain
183                 // this invariant.
184                 self.check_trailing_angle_brackets(&segment, &[&token::ModSep]);
185             }
186             segments.push(segment);
187
188             if self.is_import_coupler() || !self.eat(&token::ModSep) {
189                 return Ok(());
190             }
191         }
192     }
193
194     pub(super) fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
195         let ident = self.parse_path_segment_ident()?;
196         let is_args_start = |token: &Token| {
197             matches!(
198                 token.kind,
199                 token::Lt
200                     | token::BinOp(token::Shl)
201                     | token::OpenDelim(token::Paren)
202                     | token::LArrow
203             )
204         };
205         let check_args_start = |this: &mut Self| {
206             this.expected_tokens.extend_from_slice(&[
207                 TokenType::Token(token::Lt),
208                 TokenType::Token(token::OpenDelim(token::Paren)),
209             ]);
210             is_args_start(&this.token)
211         };
212
213         Ok(
214             if style == PathStyle::Type && check_args_start(self)
215                 || style != PathStyle::Mod
216                     && self.check(&token::ModSep)
217                     && self.look_ahead(1, |t| is_args_start(t))
218             {
219                 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
220                 // it isn't, then we reset the unmatched angle bracket count as we're about to start
221                 // parsing a new path.
222                 if style == PathStyle::Expr {
223                     self.unmatched_angle_bracket_count = 0;
224                     self.max_angle_bracket_count = 0;
225                 }
226
227                 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
228                 self.eat(&token::ModSep);
229                 let lo = self.token.span;
230                 let args = if self.eat_lt() {
231                     // `<'a, T, A = U>`
232                     let args =
233                         self.parse_angle_args_with_leading_angle_bracket_recovery(style, lo)?;
234                     self.expect_gt()?;
235                     let span = lo.to(self.prev_token.span);
236                     AngleBracketedArgs { args, span }.into()
237                 } else {
238                     // `(T, U) -> R`
239                     let (inputs, _) = self.parse_paren_comma_seq(|p| p.parse_ty())?;
240                     let inputs_span = lo.to(self.prev_token.span);
241                     let span = ident.span.to(self.prev_token.span);
242                     let output =
243                         self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)?;
244                     ParenthesizedArgs { span, inputs, inputs_span, output }.into()
245                 };
246
247                 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
248             } else {
249                 // Generic arguments are not found.
250                 PathSegment::from_ident(ident)
251             },
252         )
253     }
254
255     pub(super) fn parse_path_segment_ident(&mut self) -> PResult<'a, Ident> {
256         match self.token.ident() {
257             Some((ident, false)) if ident.is_path_segment_keyword() => {
258                 self.bump();
259                 Ok(ident)
260             }
261             _ => self.parse_ident(),
262         }
263     }
264
265     /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
266     /// For the purposes of understanding the parsing logic of generic arguments, this function
267     /// can be thought of being the same as just calling `self.parse_angle_args()` if the source
268     /// had the correct amount of leading angle brackets.
269     ///
270     /// ```ignore (diagnostics)
271     /// bar::<<<<T as Foo>::Output>();
272     ///      ^^ help: remove extra angle brackets
273     /// ```
274     fn parse_angle_args_with_leading_angle_bracket_recovery(
275         &mut self,
276         style: PathStyle,
277         lo: Span,
278     ) -> PResult<'a, Vec<AngleBracketedArg>> {
279         // We need to detect whether there are extra leading left angle brackets and produce an
280         // appropriate error and suggestion. This cannot be implemented by looking ahead at
281         // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
282         // then there won't be matching `>` tokens to find.
283         //
284         // To explain how this detection works, consider the following example:
285         //
286         // ```ignore (diagnostics)
287         // bar::<<<<T as Foo>::Output>();
288         //      ^^ help: remove extra angle brackets
289         // ```
290         //
291         // Parsing of the left angle brackets starts in this function. We start by parsing the
292         // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
293         // `eat_lt`):
294         //
295         // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
296         // *Unmatched count:* 1
297         // *`parse_path_segment` calls deep:* 0
298         //
299         // This has the effect of recursing as this function is called if a `<` character
300         // is found within the expected generic arguments:
301         //
302         // *Upcoming tokens:* `<<<T as Foo>::Output>;`
303         // *Unmatched count:* 2
304         // *`parse_path_segment` calls deep:* 1
305         //
306         // Eventually we will have recursed until having consumed all of the `<` tokens and
307         // this will be reflected in the count:
308         //
309         // *Upcoming tokens:* `T as Foo>::Output>;`
310         // *Unmatched count:* 4
311         // `parse_path_segment` calls deep:* 3
312         //
313         // The parser will continue until reaching the first `>` - this will decrement the
314         // unmatched angle bracket count and return to the parent invocation of this function
315         // having succeeded in parsing:
316         //
317         // *Upcoming tokens:* `::Output>;`
318         // *Unmatched count:* 3
319         // *`parse_path_segment` calls deep:* 2
320         //
321         // This will continue until the next `>` character which will also return successfully
322         // to the parent invocation of this function and decrement the count:
323         //
324         // *Upcoming tokens:* `;`
325         // *Unmatched count:* 2
326         // *`parse_path_segment` calls deep:* 1
327         //
328         // At this point, this function will expect to find another matching `>` character but
329         // won't be able to and will return an error. This will continue all the way up the
330         // call stack until the first invocation:
331         //
332         // *Upcoming tokens:* `;`
333         // *Unmatched count:* 2
334         // *`parse_path_segment` calls deep:* 0
335         //
336         // In doing this, we have managed to work out how many unmatched leading left angle
337         // brackets there are, but we cannot recover as the unmatched angle brackets have
338         // already been consumed. To remedy this, we keep a snapshot of the parser state
339         // before we do the above. We can then inspect whether we ended up with a parsing error
340         // and unmatched left angle brackets and if so, restore the parser state before we
341         // consumed any `<` characters to emit an error and consume the erroneous tokens to
342         // recover by attempting to parse again.
343         //
344         // In practice, the recursion of this function is indirect and there will be other
345         // locations that consume some `<` characters - as long as we update the count when
346         // this happens, it isn't an issue.
347
348         let is_first_invocation = style == PathStyle::Expr;
349         // Take a snapshot before attempting to parse - we can restore this later.
350         let snapshot = if is_first_invocation { Some(self.clone()) } else { None };
351
352         debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
353         match self.parse_angle_args() {
354             Ok(args) => Ok(args),
355             Err(mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
356                 // Swap `self` with our backup of the parser state before attempting to parse
357                 // generic arguments.
358                 let snapshot = mem::replace(self, snapshot.unwrap());
359
360                 // Eat the unmatched angle brackets.
361                 let all_angle_brackets = (0..snapshot.unmatched_angle_bracket_count)
362                     .fold(true, |a, _| a && self.eat_lt());
363
364                 if !all_angle_brackets {
365                     // If there are other tokens in between the extraneous `<`s, we cannot simply
366                     // suggest to remove them. This check also prevents us from accidentally ending
367                     // up in the middle of a multibyte character (issue #84104).
368                     let _ = mem::replace(self, snapshot);
369                     Err(e)
370                 } else {
371                     // Cancel error from being unable to find `>`. We know the error
372                     // must have been this due to a non-zero unmatched angle bracket
373                     // count.
374                     e.cancel();
375
376                     debug!(
377                         "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
378                          snapshot.count={:?}",
379                         snapshot.unmatched_angle_bracket_count,
380                     );
381
382                     // Make a span over ${unmatched angle bracket count} characters.
383                     // This is safe because `all_angle_brackets` ensures that there are only `<`s,
384                     // i.e. no multibyte characters, in this range.
385                     let span =
386                         lo.with_hi(lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count));
387                     self.struct_span_err(
388                         span,
389                         &format!(
390                             "unmatched angle bracket{}",
391                             pluralize!(snapshot.unmatched_angle_bracket_count)
392                         ),
393                     )
394                     .span_suggestion(
395                         span,
396                         &format!(
397                             "remove extra angle bracket{}",
398                             pluralize!(snapshot.unmatched_angle_bracket_count)
399                         ),
400                         String::new(),
401                         Applicability::MachineApplicable,
402                     )
403                     .emit();
404
405                     // Try again without unmatched angle bracket characters.
406                     self.parse_angle_args()
407                 }
408             }
409             Err(e) => Err(e),
410         }
411     }
412
413     /// Parses (possibly empty) list of generic arguments / associated item constraints,
414     /// possibly including trailing comma.
415     pub(super) fn parse_angle_args(&mut self) -> PResult<'a, Vec<AngleBracketedArg>> {
416         let mut args = Vec::new();
417         while let Some(arg) = self.parse_angle_arg()? {
418             args.push(arg);
419             if !self.eat(&token::Comma) {
420                 if !self.token.kind.should_end_const_arg() {
421                     if self.handle_ambiguous_unbraced_const_arg(&mut args)? {
422                         // We've managed to (partially) recover, so continue trying to parse
423                         // arguments.
424                         continue;
425                     }
426                 }
427                 break;
428             }
429         }
430         Ok(args)
431     }
432
433     /// Parses a single argument in the angle arguments `<...>` of a path segment.
434     fn parse_angle_arg(&mut self) -> PResult<'a, Option<AngleBracketedArg>> {
435         let lo = self.token.span;
436         let arg = self.parse_generic_arg()?;
437         match arg {
438             Some(arg) => {
439                 if self.check(&token::Colon) | self.check(&token::Eq) {
440                     let (ident, gen_args) = match self.get_ident_from_generic_arg(arg) {
441                         Ok(ident_gen_args) => ident_gen_args,
442                         Err(arg) => return Ok(Some(AngleBracketedArg::Arg(arg))),
443                     };
444                     let kind = if self.eat(&token::Colon) {
445                         // Parse associated type constraint bound.
446
447                         let bounds = self.parse_generic_bounds(Some(self.prev_token.span))?;
448                         AssocTyConstraintKind::Bound { bounds }
449                     } else if self.eat(&token::Eq) {
450                         // Parse associated type equality constraint
451
452                         let ty = self.parse_assoc_equality_term(ident, self.prev_token.span)?;
453                         AssocTyConstraintKind::Equality { ty }
454                     } else {
455                         unreachable!();
456                     };
457
458                     let span = lo.to(self.prev_token.span);
459
460                     // Gate associated type bounds, e.g., `Iterator<Item: Ord>`.
461                     if let AssocTyConstraintKind::Bound { .. } = kind {
462                         self.sess.gated_spans.gate(sym::associated_type_bounds, span);
463                     }
464                     let constraint =
465                         AssocTyConstraint { id: ast::DUMMY_NODE_ID, ident, gen_args, kind, span };
466                     Ok(Some(AngleBracketedArg::Constraint(constraint)))
467                 } else {
468                     Ok(Some(AngleBracketedArg::Arg(arg)))
469                 }
470             }
471             _ => Ok(None),
472         }
473     }
474
475     /// Parse the term to the right of an associated item equality constraint.
476     /// That is, parse `<term>` in `Item = <term>`.
477     /// Right now, this only admits types in `<term>`.
478     fn parse_assoc_equality_term(&mut self, ident: Ident, eq: Span) -> PResult<'a, P<ast::Ty>> {
479         let arg = self.parse_generic_arg()?;
480         let span = ident.span.to(self.prev_token.span);
481         match arg {
482             Some(GenericArg::Type(ty)) => return Ok(ty),
483             Some(GenericArg::Const(expr)) => {
484                 self.struct_span_err(span, "cannot constrain an associated constant to a value")
485                     .span_label(ident.span, "this associated constant...")
486                     .span_label(expr.value.span, "...cannot be constrained to this value")
487                     .emit();
488             }
489             Some(GenericArg::Lifetime(lt)) => {
490                 self.struct_span_err(span, "associated lifetimes are not supported")
491                     .span_label(lt.ident.span, "the lifetime is given here")
492                     .help("if you meant to specify a trait object, write `dyn Trait + 'lifetime`")
493                     .emit();
494             }
495             None => {
496                 let after_eq = eq.shrink_to_hi();
497                 let before_next = self.token.span.shrink_to_lo();
498                 self.struct_span_err(after_eq.to(before_next), "missing type to the right of `=`")
499                     .span_suggestion(
500                         self.sess.source_map().next_point(eq).to(before_next),
501                         "to constrain the associated type, add a type after `=`",
502                         " TheType".to_string(),
503                         Applicability::HasPlaceholders,
504                     )
505                     .span_suggestion(
506                         eq.to(before_next),
507                         &format!("remove the `=` if `{}` is a type", ident),
508                         String::new(),
509                         Applicability::MaybeIncorrect,
510                     )
511                     .emit();
512             }
513         }
514         Ok(self.mk_ty(span, ast::TyKind::Err))
515     }
516
517     /// We do not permit arbitrary expressions as const arguments. They must be one of:
518     /// - An expression surrounded in `{}`.
519     /// - A literal.
520     /// - A numeric literal prefixed by `-`.
521     /// - A single-segment path.
522     pub(super) fn expr_is_valid_const_arg(&self, expr: &P<rustc_ast::Expr>) -> bool {
523         match &expr.kind {
524             ast::ExprKind::Block(_, _) | ast::ExprKind::Lit(_) => true,
525             ast::ExprKind::Unary(ast::UnOp::Neg, expr) => {
526                 matches!(expr.kind, ast::ExprKind::Lit(_))
527             }
528             // We can only resolve single-segment paths at the moment, because multi-segment paths
529             // require type-checking: see `visit_generic_arg` in `src/librustc_resolve/late.rs`.
530             ast::ExprKind::Path(None, path)
531                 if path.segments.len() == 1 && path.segments[0].args.is_none() =>
532             {
533                 true
534             }
535             _ => false,
536         }
537     }
538
539     /// Parse a const argument, e.g. `<3>`. It is assumed the angle brackets will be parsed by
540     /// the caller.
541     pub(super) fn parse_const_arg(&mut self) -> PResult<'a, AnonConst> {
542         // Parse const argument.
543         let value = if let token::OpenDelim(token::Brace) = self.token.kind {
544             self.parse_block_expr(
545                 None,
546                 self.token.span,
547                 BlockCheckMode::Default,
548                 ast::AttrVec::new(),
549             )?
550         } else {
551             self.handle_unambiguous_unbraced_const_arg()?
552         };
553         Ok(AnonConst { id: ast::DUMMY_NODE_ID, value })
554     }
555
556     /// Parse a generic argument in a path segment.
557     /// This does not include constraints, e.g., `Item = u8`, which is handled in `parse_angle_arg`.
558     pub(super) fn parse_generic_arg(&mut self) -> PResult<'a, Option<GenericArg>> {
559         let start = self.token.span;
560         let arg = if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
561             // Parse lifetime argument.
562             GenericArg::Lifetime(self.expect_lifetime())
563         } else if self.check_const_arg() {
564             // Parse const argument.
565             GenericArg::Const(self.parse_const_arg()?)
566         } else if self.check_type() {
567             // Parse type argument.
568             match self.parse_ty() {
569                 Ok(ty) => GenericArg::Type(ty),
570                 Err(err) => {
571                     // Try to recover from possible `const` arg without braces.
572                     return self.recover_const_arg(start, err).map(Some);
573                 }
574             }
575         } else {
576             return Ok(None);
577         };
578         Ok(Some(arg))
579     }
580
581     fn get_ident_from_generic_arg(
582         &self,
583         gen_arg: GenericArg,
584     ) -> Result<(Ident, Option<GenericArgs>), GenericArg> {
585         if let GenericArg::Type(ty) = &gen_arg {
586             if let ast::TyKind::Path(qself, path) = &ty.kind {
587                 if qself.is_none() && path.segments.len() == 1 {
588                     let seg = &path.segments[0];
589                     return Ok((seg.ident, seg.args.as_deref().cloned()));
590                 }
591             }
592         }
593         Err(gen_arg)
594     }
595 }