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;
8 use syntax::token::{self, Token};
9 use syntax_pos::source_map::{Span, BytePos};
10 use syntax_pos::symbol::{kw, sym};
15 /// Specifies how to parse a path.
16 #[derive(Copy, Clone, PartialEq)]
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.
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.
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.
39 /// Parses a qualified path.
40 /// Assumes that the leading `<` has been parsed already.
42 /// `qualified_path = <type [as trait_ref]>::path`
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()?;
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);
63 path_span = self.token.span.to(self.token.span);
64 path = ast::Path { segments: Vec::new(), span: path_span };
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);
74 self.expect(&token::ModSep)?;
76 let qself = QSelf { ty, path_span, position: path.segments.len() };
77 self.parse_path_segments(&mut path.segments, style)?;
79 Ok((qself, Path { segments: path.segments, span: lo.to(self.prev_span) }))
82 /// Parses simple paths.
84 /// `path = [::] segment+`
85 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
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");
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)));
107 self.parse_path_segments(&mut segments, style)?;
109 Ok(Path { segments, span: lo.to(self.prev_span) })
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]`
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()),
126 if let Some(path) = meta_ident {
130 self.parse_path(style)
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)?;
140 if !self.eat(&token::Comma) {
141 self.expect(&token::CloseDelim(token::Paren))?;
148 pub(super) fn parse_path_segments(
150 segments: &mut Vec<PathSegment>,
152 ) -> PResult<'a, ()> {
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:
160 // `Foo::<Bar as Baz<T>>::Qux`
163 // As opposed to the below highlight (if we had only finished the first
166 // `Foo::<Bar as Baz<T>>::Qux`
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
172 self.check_trailing_angle_brackets(&segment, token::ModSep);
174 segments.push(segment);
176 if self.is_import_coupler() || !self.eat(&token::ModSep) {
182 pub(super) fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
183 let ident = self.parse_path_segment_ident()?;
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,
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))]
194 is_args_start(&this.token)
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;
208 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
209 self.eat(&token::ModSep);
210 let lo = self.token.span;
211 let args = if self.eat_lt() {
213 let (args, constraints) =
214 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
216 let span = lo.to(self.prev_span);
217 AngleBracketedArgs { args, constraints, span }.into()
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)?)
227 ParenthesizedArgs { inputs, output, span }.into()
230 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
232 // Generic arguments are not found.
233 PathSegment::from_ident(ident)
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;
242 Ok(Ident::new(name, span))
244 _ => self.parse_ident(),
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.
253 /// ```ignore (diagnostics)
254 /// bar::<<<<T as Foo>::Output>();
255 /// ^^ help: remove extra angle brackets
257 fn parse_generic_args_with_leaning_angle_bracket_recovery(
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.
267 // To explain how this detection works, consider the following example:
269 // ```ignore (diagnostics)
270 // bar::<<<<T as Foo>::Output>();
271 // ^^ help: remove extra angle brackets
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
278 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
279 // *Unmatched count:* 1
280 // *`parse_path_segment` calls deep:* 0
282 // This has the effect of recursing as this function is called if a `<` character
283 // is found within the expected generic arguments:
285 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
286 // *Unmatched count:* 2
287 // *`parse_path_segment` calls deep:* 1
289 // Eventually we will have recursed until having consumed all of the `<` tokens and
290 // this will be reflected in the count:
292 // *Upcoming tokens:* `T as Foo>::Output>;`
293 // *Unmatched count:* 4
294 // `parse_path_segment` calls deep:* 3
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:
300 // *Upcoming tokens:* `::Output>;`
301 // *Unmatched count:* 3
302 // *`parse_path_segment` calls deep:* 2
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:
307 // *Upcoming tokens:* `;`
308 // *Unmatched count:* 2
309 // *`parse_path_segment` calls deep:* 1
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:
315 // *Upcoming tokens:* `;`
316 // *Unmatched count:* 2
317 // *`parse_path_segment` calls deep:* 0
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.
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.
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 {
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
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());
353 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
354 snapshot.count={:?}",
355 snapshot.unmatched_angle_bracket_count,
358 // Eat the unmatched angle brackets.
359 for _ in 0..snapshot.unmatched_angle_bracket_count {
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)
371 "unmatched angle bracket{}",
372 pluralize!(snapshot.unmatched_angle_bracket_count)
378 "remove extra angle bracket{}",
379 pluralize!(snapshot.unmatched_angle_bracket_count)
382 Applicability::MachineApplicable,
386 // Try again without unmatched angle bracket characters.
387 self.parse_generic_args()
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();
401 let args_lo = self.token.span;
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)
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()?,
418 } else if self.eat(&token::Colon) {
419 AssocTyConstraintKind::Bound {
420 bounds: self.parse_generic_bounds(Some(self.prev_span))?,
426 let span = lo.to(self.prev_span);
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);
433 constraints.push(AssocTyConstraint {
434 id: ast::DUMMY_NODE_ID,
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()
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()?
454 self.fatal("identifiers may currently not be used for const generics")
458 self.parse_literal_maybe_minus()?
460 let value = AnonConst {
461 id: ast::DUMMY_NODE_ID,
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);
474 if !self.eat(&token::Comma) {
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",
487 for span in misplaced_assoc_ty_constraints {
490 "this associated type binding should be moved after the generic parameters",
496 Ok((args, constraints))