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::token::{self, Token};
7 use syntax_pos::source_map::{Span, BytePos};
8 use syntax_pos::symbol::{kw, sym};
13 /// Specifies how to parse a path.
14 #[derive(Copy, Clone, PartialEq)]
16 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
17 /// with something else. For example, in expressions `segment < ....` can be interpreted
18 /// as a comparison and `segment ( ....` can be interpreted as a function call.
19 /// In all such contexts the non-path interpretation is preferred by default for practical
20 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
21 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
23 /// In other contexts, notably in types, no ambiguity exists and paths can be written
24 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
25 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
27 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
28 /// visibilities or attributes.
29 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
30 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
31 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
32 /// tokens when something goes wrong.
37 /// Parses a qualified path.
38 /// Assumes that the leading `<` has been parsed already.
40 /// `qualified_path = <type [as trait_ref]>::path`
45 /// `<T as U>::F::a<S>` (without disambiguator)
46 /// `<T as U>::F::a::<S>` (with disambiguator)
47 pub(super) fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, Path)> {
48 let lo = self.prev_span;
49 let ty = self.parse_ty()?;
51 // `path` will contain the prefix of the path up to the `>`,
52 // if any (e.g., `U` in the `<T as U>::*` examples
53 // above). `path_span` has the span of that path, or an empty
54 // span in the case of something like `<T>::Bar`.
55 let (mut path, path_span);
56 if self.eat_keyword(kw::As) {
57 let path_lo = self.token.span;
58 path = self.parse_path(PathStyle::Type)?;
59 path_span = path_lo.to(self.prev_span);
61 path_span = self.token.span.to(self.token.span);
62 path = ast::Path { segments: Vec::new(), span: path_span };
65 // See doc comment for `unmatched_angle_bracket_count`.
66 self.expect(&token::Gt)?;
67 if self.unmatched_angle_bracket_count > 0 {
68 self.unmatched_angle_bracket_count -= 1;
69 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
72 self.expect(&token::ModSep)?;
74 let qself = QSelf { ty, path_span, position: path.segments.len() };
75 self.parse_path_segments(&mut path.segments, style)?;
77 Ok((qself, Path { segments: path.segments, span: lo.to(self.prev_span) }))
80 /// Parses simple paths.
82 /// `path = [::] segment+`
83 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
86 /// `a::b::C<D>` (without disambiguator)
87 /// `a::b::C::<D>` (with disambiguator)
88 /// `Fn(Args)` (without disambiguator)
89 /// `Fn::(Args)` (with disambiguator)
90 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, Path> {
91 maybe_whole!(self, NtPath, |path| {
92 if style == PathStyle::Mod &&
93 path.segments.iter().any(|segment| segment.args.is_some()) {
94 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
99 let lo = self.meta_var_span.unwrap_or(self.token.span);
100 let mut segments = Vec::new();
101 let mod_sep_ctxt = self.token.span.ctxt();
102 if self.eat(&token::ModSep) {
103 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
105 self.parse_path_segments(&mut segments, style)?;
107 Ok(Path { segments, span: lo.to(self.prev_span) })
110 pub(super) fn parse_path_segments(
112 segments: &mut Vec<PathSegment>,
114 ) -> PResult<'a, ()> {
116 let segment = self.parse_path_segment(style)?;
117 if style == PathStyle::Expr {
118 // In order to check for trailing angle brackets, we must have finished
119 // recursing (`parse_path_segment` can indirectly call this function),
120 // that is, the next token must be the highlighted part of the below example:
122 // `Foo::<Bar as Baz<T>>::Qux`
125 // As opposed to the below highlight (if we had only finished the first
128 // `Foo::<Bar as Baz<T>>::Qux`
131 // `PathStyle::Expr` is only provided at the root invocation and never in
132 // `parse_path_segment` to recurse and therefore can be checked to maintain
134 self.check_trailing_angle_brackets(&segment, token::ModSep);
136 segments.push(segment);
138 if self.is_import_coupler() || !self.eat(&token::ModSep) {
144 pub(super) fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
145 let ident = self.parse_path_segment_ident()?;
147 let is_args_start = |token: &Token| match token.kind {
148 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
149 | token::LArrow => true,
152 let check_args_start = |this: &mut Self| {
153 this.expected_tokens.extend_from_slice(
154 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
156 is_args_start(&this.token)
159 Ok(if style == PathStyle::Type && check_args_start(self) ||
160 style != PathStyle::Mod && self.check(&token::ModSep)
161 && self.look_ahead(1, |t| is_args_start(t)) {
162 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
163 // it isn't, then we reset the unmatched angle bracket count as we're about to start
164 // parsing a new path.
165 if style == PathStyle::Expr {
166 self.unmatched_angle_bracket_count = 0;
167 self.max_angle_bracket_count = 0;
170 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
171 self.eat(&token::ModSep);
172 let lo = self.token.span;
173 let args = if self.eat_lt() {
175 let (args, constraints) =
176 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
178 let span = lo.to(self.prev_span);
179 AngleBracketedArgs { args, constraints, span }.into()
182 let (inputs, _) = self.parse_paren_comma_seq(|p| p.parse_ty())?;
183 let span = ident.span.to(self.prev_span);
184 let output = self.parse_ret_ty(false, false)?;
185 ParenthesizedArgs { inputs, output, span }.into()
188 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
190 // Generic arguments are not found.
191 PathSegment::from_ident(ident)
195 pub(super) fn parse_path_segment_ident(&mut self) -> PResult<'a, Ident> {
196 match self.token.kind {
197 token::Ident(name, _) if name.is_path_segment_keyword() => {
198 let span = self.token.span;
200 Ok(Ident::new(name, span))
202 _ => self.parse_ident(),
206 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
207 /// For the purposes of understanding the parsing logic of generic arguments, this function
208 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
209 /// had the correct amount of leading angle brackets.
211 /// ```ignore (diagnostics)
212 /// bar::<<<<T as Foo>::Output>();
213 /// ^^ help: remove extra angle brackets
215 fn parse_generic_args_with_leaning_angle_bracket_recovery(
219 ) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
220 // We need to detect whether there are extra leading left angle brackets and produce an
221 // appropriate error and suggestion. This cannot be implemented by looking ahead at
222 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
223 // then there won't be matching `>` tokens to find.
225 // To explain how this detection works, consider the following example:
227 // ```ignore (diagnostics)
228 // bar::<<<<T as Foo>::Output>();
229 // ^^ help: remove extra angle brackets
232 // Parsing of the left angle brackets starts in this function. We start by parsing the
233 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
236 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
237 // *Unmatched count:* 1
238 // *`parse_path_segment` calls deep:* 0
240 // This has the effect of recursing as this function is called if a `<` character
241 // is found within the expected generic arguments:
243 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
244 // *Unmatched count:* 2
245 // *`parse_path_segment` calls deep:* 1
247 // Eventually we will have recursed until having consumed all of the `<` tokens and
248 // this will be reflected in the count:
250 // *Upcoming tokens:* `T as Foo>::Output>;`
251 // *Unmatched count:* 4
252 // `parse_path_segment` calls deep:* 3
254 // The parser will continue until reaching the first `>` - this will decrement the
255 // unmatched angle bracket count and return to the parent invocation of this function
256 // having succeeded in parsing:
258 // *Upcoming tokens:* `::Output>;`
259 // *Unmatched count:* 3
260 // *`parse_path_segment` calls deep:* 2
262 // This will continue until the next `>` character which will also return successfully
263 // to the parent invocation of this function and decrement the count:
265 // *Upcoming tokens:* `;`
266 // *Unmatched count:* 2
267 // *`parse_path_segment` calls deep:* 1
269 // At this point, this function will expect to find another matching `>` character but
270 // won't be able to and will return an error. This will continue all the way up the
271 // call stack until the first invocation:
273 // *Upcoming tokens:* `;`
274 // *Unmatched count:* 2
275 // *`parse_path_segment` calls deep:* 0
277 // In doing this, we have managed to work out how many unmatched leading left angle
278 // brackets there are, but we cannot recover as the unmatched angle brackets have
279 // already been consumed. To remedy this, we keep a snapshot of the parser state
280 // before we do the above. We can then inspect whether we ended up with a parsing error
281 // and unmatched left angle brackets and if so, restore the parser state before we
282 // consumed any `<` characters to emit an error and consume the erroneous tokens to
283 // recover by attempting to parse again.
285 // In practice, the recursion of this function is indirect and there will be other
286 // locations that consume some `<` characters - as long as we update the count when
287 // this happens, it isn't an issue.
289 let is_first_invocation = style == PathStyle::Expr;
290 // Take a snapshot before attempting to parse - we can restore this later.
291 let snapshot = if is_first_invocation {
297 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
298 match self.parse_generic_args() {
299 Ok(value) => Ok(value),
300 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
301 // Cancel error from being unable to find `>`. We know the error
302 // must have been this due to a non-zero unmatched angle bracket
306 // Swap `self` with our backup of the parser state before attempting to parse
307 // generic arguments.
308 let snapshot = mem::replace(self, snapshot.unwrap());
311 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
312 snapshot.count={:?}",
313 snapshot.unmatched_angle_bracket_count,
316 // Eat the unmatched angle brackets.
317 for _ in 0..snapshot.unmatched_angle_bracket_count {
321 // Make a span over ${unmatched angle bracket count} characters.
322 let span = lo.with_hi(
323 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
329 "unmatched angle bracket{}",
330 pluralize!(snapshot.unmatched_angle_bracket_count)
336 "remove extra angle bracket{}",
337 pluralize!(snapshot.unmatched_angle_bracket_count)
340 Applicability::MachineApplicable,
344 // Try again without unmatched angle bracket characters.
345 self.parse_generic_args()
351 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
352 /// possibly including trailing comma.
353 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<AssocTyConstraint>)> {
354 let mut args = Vec::new();
355 let mut constraints = Vec::new();
356 let mut misplaced_assoc_ty_constraints: Vec<Span> = Vec::new();
357 let mut assoc_ty_constraints: Vec<Span> = Vec::new();
359 let args_lo = self.token.span;
362 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
363 // Parse lifetime argument.
364 args.push(GenericArg::Lifetime(self.expect_lifetime()));
365 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
366 } else if self.check_ident()
367 && self.look_ahead(1, |t| t == &token::Eq || t == &token::Colon)
369 // Parse associated type constraint.
370 let lo = self.token.span;
371 let ident = self.parse_ident()?;
372 let kind = if self.eat(&token::Eq) {
373 AssocTyConstraintKind::Equality {
374 ty: self.parse_ty()?,
376 } else if self.eat(&token::Colon) {
377 AssocTyConstraintKind::Bound {
378 bounds: self.parse_generic_bounds(Some(self.prev_span))?,
384 let span = lo.to(self.prev_span);
386 // Gate associated type bounds, e.g., `Iterator<Item: Ord>`.
387 if let AssocTyConstraintKind::Bound { .. } = kind {
388 self.sess.gated_spans.gate(sym::associated_type_bounds, span);
391 constraints.push(AssocTyConstraint {
392 id: ast::DUMMY_NODE_ID,
397 assoc_ty_constraints.push(span);
398 } else if self.check_const_arg() {
399 // Parse const argument.
400 let expr = if let token::OpenDelim(token::Brace) = self.token.kind {
401 self.parse_block_expr(
402 None, self.token.span, BlockCheckMode::Default, ast::AttrVec::new()
404 } else if self.token.is_ident() {
405 // FIXME(const_generics): to distinguish between idents for types and consts,
406 // we should introduce a GenericArg::Ident in the AST and distinguish when
407 // lowering to the HIR. For now, idents for const args are not permitted.
408 if self.token.is_bool_lit() {
409 self.parse_literal_maybe_minus()?
412 self.fatal("identifiers may currently not be used for const generics")
416 self.parse_literal_maybe_minus()?
418 let value = AnonConst {
419 id: ast::DUMMY_NODE_ID,
422 args.push(GenericArg::Const(value));
423 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
424 } else if self.check_type() {
425 // Parse type argument.
426 args.push(GenericArg::Type(self.parse_ty()?));
427 misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints);
432 if !self.eat(&token::Comma) {
437 // FIXME: we would like to report this in ast_validation instead, but we currently do not
438 // preserve ordering of generic parameters with respect to associated type binding, so we
439 // lose that information after parsing.
440 if misplaced_assoc_ty_constraints.len() > 0 {
441 let mut err = self.struct_span_err(
442 args_lo.to(self.prev_span),
443 "associated type bindings must be declared after generic parameters",
445 for span in misplaced_assoc_ty_constraints {
448 "this associated type binding should be moved after the generic parameters",
454 Ok((args, constraints))