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