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