]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/path.rs
Rollup merge of #68984 - ecstatic-morse:const-u8-is-ascii, r=sfackler
[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.unnormalized_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.token.kind {
242             token::Ident(name, _) if name.is_path_segment_keyword() => {
243                 let span = self.token.span;
244                 self.bump();
245                 Ok(Ident::new(name, span))
246             }
247             _ => self.parse_ident(),
248         }
249     }
250
251     /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
252     /// For the purposes of understanding the parsing logic of generic arguments, this function
253     /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
254     /// had the correct amount of leading angle brackets.
255     ///
256     /// ```ignore (diagnostics)
257     /// bar::<<<<T as Foo>::Output>();
258     ///      ^^ help: remove extra angle brackets
259     /// ```
260     fn parse_generic_args_with_leading_angle_bracket_recovery(
261         &mut self,
262         style: PathStyle,
263         lo: Span,
264     ) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
265         // We need to detect whether there are extra leading left angle brackets and produce an
266         // appropriate error and suggestion. This cannot be implemented by looking ahead at
267         // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
268         // then there won't be matching `>` tokens to find.
269         //
270         // To explain how this detection works, consider the following example:
271         //
272         // ```ignore (diagnostics)
273         // bar::<<<<T as Foo>::Output>();
274         //      ^^ help: remove extra angle brackets
275         // ```
276         //
277         // Parsing of the left angle brackets starts in this function. We start by parsing the
278         // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
279         // `eat_lt`):
280         //
281         // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
282         // *Unmatched count:* 1
283         // *`parse_path_segment` calls deep:* 0
284         //
285         // This has the effect of recursing as this function is called if a `<` character
286         // is found within the expected generic arguments:
287         //
288         // *Upcoming tokens:* `<<<T as Foo>::Output>;`
289         // *Unmatched count:* 2
290         // *`parse_path_segment` calls deep:* 1
291         //
292         // Eventually we will have recursed until having consumed all of the `<` tokens and
293         // this will be reflected in the count:
294         //
295         // *Upcoming tokens:* `T as Foo>::Output>;`
296         // *Unmatched count:* 4
297         // `parse_path_segment` calls deep:* 3
298         //
299         // The parser will continue until reaching the first `>` - this will decrement the
300         // unmatched angle bracket count and return to the parent invocation of this function
301         // having succeeded in parsing:
302         //
303         // *Upcoming tokens:* `::Output>;`
304         // *Unmatched count:* 3
305         // *`parse_path_segment` calls deep:* 2
306         //
307         // This will continue until the next `>` character which will also return successfully
308         // to the parent invocation of this function and decrement the count:
309         //
310         // *Upcoming tokens:* `;`
311         // *Unmatched count:* 2
312         // *`parse_path_segment` calls deep:* 1
313         //
314         // At this point, this function will expect to find another matching `>` character but
315         // won't be able to and will return an error. This will continue all the way up the
316         // call stack until the first invocation:
317         //
318         // *Upcoming tokens:* `;`
319         // *Unmatched count:* 2
320         // *`parse_path_segment` calls deep:* 0
321         //
322         // In doing this, we have managed to work out how many unmatched leading left angle
323         // brackets there are, but we cannot recover as the unmatched angle brackets have
324         // already been consumed. To remedy this, we keep a snapshot of the parser state
325         // before we do the above. We can then inspect whether we ended up with a parsing error
326         // and unmatched left angle brackets and if so, restore the parser state before we
327         // consumed any `<` characters to emit an error and consume the erroneous tokens to
328         // recover by attempting to parse again.
329         //
330         // In practice, the recursion of this function is indirect and there will be other
331         // locations that consume some `<` characters - as long as we update the count when
332         // this happens, it isn't an issue.
333
334         let is_first_invocation = style == PathStyle::Expr;
335         // Take a snapshot before attempting to parse - we can restore this later.
336         let snapshot = if is_first_invocation { Some(self.clone()) } else { None };
337
338         debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
339         match self.parse_generic_args() {
340             Ok(value) => Ok(value),
341             Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
342                 // Cancel error from being unable to find `>`. We know the error
343                 // must have been this due to a non-zero unmatched angle bracket
344                 // count.
345                 e.cancel();
346
347                 // Swap `self` with our backup of the parser state before attempting to parse
348                 // generic arguments.
349                 let snapshot = mem::replace(self, snapshot.unwrap());
350
351                 debug!(
352                     "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
353                      snapshot.count={:?}",
354                     snapshot.unmatched_angle_bracket_count,
355                 );
356
357                 // Eat the unmatched angle brackets.
358                 for _ in 0..snapshot.unmatched_angle_bracket_count {
359                     self.eat_lt();
360                 }
361
362                 // Make a span over ${unmatched angle bracket count} characters.
363                 let span = lo.with_hi(lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count));
364                 self.struct_span_err(
365                     span,
366                     &format!(
367                         "unmatched angle bracket{}",
368                         pluralize!(snapshot.unmatched_angle_bracket_count)
369                     ),
370                 )
371                 .span_suggestion(
372                     span,
373                     &format!(
374                         "remove extra angle bracket{}",
375                         pluralize!(snapshot.unmatched_angle_bracket_count)
376                     ),
377                     String::new(),
378                     Applicability::MachineApplicable,
379                 )
380                 .emit();
381
382                 // Try again without unmatched angle bracket characters.
383                 self.parse_generic_args()
384             }
385             Err(e) => Err(e),
386         }
387     }
388
389     /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
390     /// possibly including trailing comma.
391     fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
392         let mut args = Vec::new();
393         let mut constraints = Vec::new();
394         let mut misplaced_assoc_ty_constraints: Vec<Span> = Vec::new();
395         let mut assoc_ty_constraints: Vec<Span> = Vec::new();
396
397         let args_lo = self.token.span;
398
399         loop {
400             if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
401                 // Parse lifetime argument.
402                 args.push(GenericArg::Lifetime(self.expect_lifetime()));
403                 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
404             } else if self.check_ident()
405                 && self.look_ahead(1, |t| t == &token::Eq || t == &token::Colon)
406             {
407                 // Parse associated type constraint.
408                 let lo = self.token.span;
409                 let ident = self.parse_ident()?;
410                 let kind = if self.eat(&token::Eq) {
411                     AssocTyConstraintKind::Equality { ty: self.parse_ty()? }
412                 } else if self.eat(&token::Colon) {
413                     AssocTyConstraintKind::Bound {
414                         bounds: self.parse_generic_bounds(Some(self.prev_span))?,
415                     }
416                 } else {
417                     unreachable!();
418                 };
419
420                 let span = lo.to(self.prev_span);
421
422                 // Gate associated type bounds, e.g., `Iterator<Item: Ord>`.
423                 if let AssocTyConstraintKind::Bound { .. } = kind {
424                     self.sess.gated_spans.gate(sym::associated_type_bounds, span);
425                 }
426
427                 constraints.push(AssocTyConstraint { id: ast::DUMMY_NODE_ID, ident, kind, span });
428                 assoc_ty_constraints.push(span);
429             } else if self.check_const_arg() {
430                 // Parse const argument.
431                 let expr = if let token::OpenDelim(token::Brace) = self.token.kind {
432                     self.parse_block_expr(
433                         None,
434                         self.token.span,
435                         BlockCheckMode::Default,
436                         ast::AttrVec::new(),
437                     )?
438                 } else if self.token.is_ident() {
439                     // FIXME(const_generics): to distinguish between idents for types and consts,
440                     // we should introduce a GenericArg::Ident in the AST and distinguish when
441                     // lowering to the HIR. For now, idents for const args are not permitted.
442                     if self.token.is_bool_lit() {
443                         self.parse_literal_maybe_minus()?
444                     } else {
445                         let span = self.token.span;
446                         let msg = "identifiers may currently not be used for const generics";
447                         self.struct_span_err(span, msg).emit();
448                         let block = self.mk_block_err(span);
449                         self.mk_expr(span, ast::ExprKind::Block(block, None), ast::AttrVec::new())
450                     }
451                 } else {
452                     self.parse_literal_maybe_minus()?
453                 };
454                 let value = AnonConst { id: ast::DUMMY_NODE_ID, value: expr };
455                 args.push(GenericArg::Const(value));
456                 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
457             } else if self.check_type() {
458                 // Parse type argument.
459                 args.push(GenericArg::Type(self.parse_ty()?));
460                 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
461             } else {
462                 break;
463             }
464
465             if !self.eat(&token::Comma) {
466                 break;
467             }
468         }
469
470         // FIXME: we would like to report this in ast_validation instead, but we currently do not
471         // preserve ordering of generic parameters with respect to associated type binding, so we
472         // lose that information after parsing.
473         if misplaced_assoc_ty_constraints.len() > 0 {
474             let mut err = self.struct_span_err(
475                 args_lo.to(self.prev_span),
476                 "associated type bindings must be declared after generic parameters",
477             );
478             for span in misplaced_assoc_ty_constraints {
479                 err.span_label(
480                     span,
481                     "this associated type binding should be moved after the generic parameters",
482                 );
483             }
484             err.emit();
485         }
486
487         Ok((args, constraints))
488     }
489 }