use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
use super::{Parser, TokenType};
use crate::maybe_whole;
use rustc_ast::ptr::P;
use rustc_ast::token::{self, Token};
use rustc_ast::{self as ast, AngleBracketedArg, AngleBracketedArgs, ParenthesizedArgs};
use rustc_ast::{AnonConst, AssocTyConstraint, AssocTyConstraintKind, BlockCheckMode};
use rustc_ast::{GenericArg, GenericArgs};
use rustc_ast::{Path, PathSegment, QSelf};
use rustc_errors::{pluralize, Applicability, PResult};
use rustc_span::source_map::{BytePos, Span};
use rustc_span::symbol::{kw, sym, Ident};
use std::mem;
use tracing::debug;
#[derive(Copy, Clone, PartialEq)]
pub enum PathStyle {
Expr,
Type,
Mod,
}
impl<'a> Parser<'a> {
pub(super) fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, Path)> {
let lo = self.prev_token.span;
let ty = self.parse_ty()?;
let (mut path, path_span);
if self.eat_keyword(kw::As) {
let path_lo = self.token.span;
path = self.parse_path(PathStyle::Type)?;
path_span = path_lo.to(self.prev_token.span);
} else {
path_span = self.token.span.to(self.token.span);
path = ast::Path { segments: Vec::new(), span: path_span, tokens: None };
}
self.expect(&token::Gt)?;
if self.unmatched_angle_bracket_count > 0 {
self.unmatched_angle_bracket_count -= 1;
debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
}
if !self.recover_colon_before_qpath_proj() {
self.expect(&token::ModSep)?;
}
let qself = QSelf { ty, path_span, position: path.segments.len() };
self.parse_path_segments(&mut path.segments, style)?;
Ok((
qself,
Path { segments: path.segments, span: lo.to(self.prev_token.span), tokens: None },
))
}
fn recover_colon_before_qpath_proj(&mut self) -> bool {
if self.token.kind != token::Colon
|| self.look_ahead(1, |t| !t.is_ident() || t.is_reserved_ident())
{
return false;
}
self.bump();
self.diagnostic()
.struct_span_err(
self.prev_token.span,
"found single colon before projection in qualified path",
)
.span_suggestion(
self.prev_token.span,
"use double colon",
"::".to_string(),
Applicability::MachineApplicable,
)
.emit();
true
}
pub(super) fn parse_path(&mut self, style: PathStyle) -> PResult<'a, Path> {
maybe_whole!(self, NtPath, |path| {
if style == PathStyle::Mod && path.segments.iter().any(|segment| segment.args.is_some())
{
self.struct_span_err(path.span, "unexpected generic arguments in path").emit();
}
path
});
let lo = self.token.span;
let mut segments = Vec::new();
let mod_sep_ctxt = self.token.span.ctxt();
if self.eat(&token::ModSep) {
segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
}
self.parse_path_segments(&mut segments, style)?;
Ok(Path { segments, span: lo.to(self.prev_token.span), tokens: None })
}
pub(super) fn parse_path_segments(
&mut self,
segments: &mut Vec<PathSegment>,
style: PathStyle,
) -> PResult<'a, ()> {
loop {
let segment = self.parse_path_segment(style)?;
if style == PathStyle::Expr {
self.check_trailing_angle_brackets(&segment, &[&token::ModSep]);
}
segments.push(segment);
if self.is_import_coupler() || !self.eat(&token::ModSep) {
return Ok(());
}
}
}
pub(super) fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
let ident = self.parse_path_segment_ident()?;
let is_args_start = |token: &Token| {
matches!(
token.kind,
token::Lt
| token::BinOp(token::Shl)
| token::OpenDelim(token::Paren)
| token::LArrow
)
};
let check_args_start = |this: &mut Self| {
this.expected_tokens.extend_from_slice(&[
TokenType::Token(token::Lt),
TokenType::Token(token::OpenDelim(token::Paren)),
]);
is_args_start(&this.token)
};
Ok(
if style == PathStyle::Type && check_args_start(self)
|| style != PathStyle::Mod
&& self.check(&token::ModSep)
&& self.look_ahead(1, |t| is_args_start(t))
{
if style == PathStyle::Expr {
self.unmatched_angle_bracket_count = 0;
self.max_angle_bracket_count = 0;
}
self.eat(&token::ModSep);
let lo = self.token.span;
let args = if self.eat_lt() {
let args =
self.parse_angle_args_with_leading_angle_bracket_recovery(style, lo)?;
self.expect_gt()?;
let span = lo.to(self.prev_token.span);
AngleBracketedArgs { args, span }.into()
} else {
let (inputs, _) = self.parse_paren_comma_seq(|p| p.parse_ty())?;
let span = ident.span.to(self.prev_token.span);
let output =
self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)?;
ParenthesizedArgs { inputs, output, span }.into()
};
PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
} else {
PathSegment::from_ident(ident)
},
)
}
pub(super) fn parse_path_segment_ident(&mut self) -> PResult<'a, Ident> {
match self.token.ident() {
Some((ident, false)) if ident.is_path_segment_keyword() => {
self.bump();
Ok(ident)
}
_ => self.parse_ident(),
}
}
fn parse_angle_args_with_leading_angle_bracket_recovery(
&mut self,
style: PathStyle,
lo: Span,
) -> PResult<'a, Vec<AngleBracketedArg>> {
let is_first_invocation = style == PathStyle::Expr;
let snapshot = if is_first_invocation { Some(self.clone()) } else { None };
debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
match self.parse_angle_args() {
Ok(args) => Ok(args),
Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
e.cancel();
let snapshot = mem::replace(self, snapshot.unwrap());
debug!(
"parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
snapshot.count={:?}",
snapshot.unmatched_angle_bracket_count,
);
for _ in 0..snapshot.unmatched_angle_bracket_count {
self.eat_lt();
}
let span = lo.with_hi(lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count));
self.struct_span_err(
span,
&format!(
"unmatched angle bracket{}",
pluralize!(snapshot.unmatched_angle_bracket_count)
),
)
.span_suggestion(
span,
&format!(
"remove extra angle bracket{}",
pluralize!(snapshot.unmatched_angle_bracket_count)
),
String::new(),
Applicability::MachineApplicable,
)
.emit();
self.parse_angle_args()
}
Err(e) => Err(e),
}
}
pub(super) fn parse_angle_args(&mut self) -> PResult<'a, Vec<AngleBracketedArg>> {
let mut args = Vec::new();
while let Some(arg) = self.parse_angle_arg()? {
args.push(arg);
if !self.eat(&token::Comma) {
if !self.token.kind.should_end_const_arg() {
if self.handle_ambiguous_unbraced_const_arg(&mut args)? {
continue;
}
}
break;
}
}
Ok(args)
}
fn parse_angle_arg(&mut self) -> PResult<'a, Option<AngleBracketedArg>> {
let lo = self.token.span;
let arg = self.parse_generic_arg()?;
match arg {
Some(arg) => {
if self.check(&token::Colon) | self.check(&token::Eq) {
let (ident, gen_args) = self.get_ident_from_generic_arg(arg, lo)?;
let kind = if self.eat(&token::Colon) {
let bounds = self.parse_generic_bounds(Some(self.prev_token.span))?;
AssocTyConstraintKind::Bound { bounds }
} else if self.eat(&token::Eq) {
let ty = self.parse_assoc_equality_term(ident, self.prev_token.span)?;
AssocTyConstraintKind::Equality { ty }
} else {
unreachable!();
};
let span = lo.to(self.prev_token.span);
if let AssocTyConstraintKind::Bound { .. } = kind {
self.sess.gated_spans.gate(sym::associated_type_bounds, span);
}
let constraint =
AssocTyConstraint { id: ast::DUMMY_NODE_ID, ident, gen_args, kind, span };
Ok(Some(AngleBracketedArg::Constraint(constraint)))
} else {
Ok(Some(AngleBracketedArg::Arg(arg)))
}
}
_ => Ok(None),
}
}
fn parse_assoc_equality_term(&mut self, ident: Ident, eq: Span) -> PResult<'a, P<ast::Ty>> {
let arg = self.parse_generic_arg()?;
let span = ident.span.to(self.prev_token.span);
match arg {
Some(GenericArg::Type(ty)) => return Ok(ty),
Some(GenericArg::Const(expr)) => {
self.struct_span_err(span, "cannot constrain an associated constant to a value")
.span_label(ident.span, "this associated constant...")
.span_label(expr.value.span, "...cannot be constrained to this value")
.emit();
}
Some(GenericArg::Lifetime(lt)) => {
self.struct_span_err(span, "associated lifetimes are not supported")
.span_label(lt.ident.span, "the lifetime is given here")
.help("if you meant to specify a trait object, write `dyn Trait + 'lifetime`")
.emit();
}
None => {
let after_eq = eq.shrink_to_hi();
let before_next = self.token.span.shrink_to_lo();
self.struct_span_err(after_eq.to(before_next), "missing type to the right of `=`")
.span_suggestion(
self.sess.source_map().next_point(eq).to(before_next),
"to constrain the associated type, add a type after `=`",
" TheType".to_string(),
Applicability::HasPlaceholders,
)
.span_suggestion(
eq.to(before_next),
&format!("remove the `=` if `{}` is a type", ident),
String::new(),
Applicability::MaybeIncorrect,
)
.emit();
}
}
Ok(self.mk_ty(span, ast::TyKind::Err))
}
pub(super) fn expr_is_valid_const_arg(&self, expr: &P<rustc_ast::Expr>) -> bool {
match &expr.kind {
ast::ExprKind::Block(_, _) | ast::ExprKind::Lit(_) => true,
ast::ExprKind::Unary(ast::UnOp::Neg, expr) => {
matches!(expr.kind, ast::ExprKind::Lit(_))
}
ast::ExprKind::Path(None, path)
if path.segments.len() == 1 && path.segments[0].args.is_none() =>
{
true
}
_ => false,
}
}
fn parse_generic_arg(&mut self) -> PResult<'a, Option<GenericArg>> {
let start = self.token.span;
let arg = if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
GenericArg::Lifetime(self.expect_lifetime())
} else if self.check_const_arg() {
let value = if let token::OpenDelim(token::Brace) = self.token.kind {
self.parse_block_expr(
None,
self.token.span,
BlockCheckMode::Default,
ast::AttrVec::new(),
)?
} else {
self.handle_unambiguous_unbraced_const_arg()?
};
GenericArg::Const(AnonConst { id: ast::DUMMY_NODE_ID, value })
} else if self.check_type() {
match self.parse_ty() {
Ok(ty) => GenericArg::Type(ty),
Err(err) => {
return self.recover_const_arg(start, err).map(Some);
}
}
} else {
return Ok(None);
};
Ok(Some(arg))
}
fn get_ident_from_generic_arg(
&self,
gen_arg: GenericArg,
lo: Span,
) -> PResult<'a, (Ident, Option<GenericArgs>)> {
let gen_arg_span = gen_arg.span();
match gen_arg {
GenericArg::Type(t) => match t.into_inner().kind {
ast::TyKind::Path(qself, mut path) => {
if let Some(qself) = qself {
let mut err = self.struct_span_err(
gen_arg_span,
"qualified paths cannot be used in associated type constraints",
);
err.span_label(
qself.path_span,
"not allowed in associated type constraints",
);
return Err(err);
}
if path.segments.len() == 1 {
let path_seg = path.segments.remove(0);
let ident = path_seg.ident;
let gen_args = path_seg.args.map(|args| args.into_inner());
return Ok((ident, gen_args));
}
let err = self.struct_span_err(
path.span,
"paths with multiple segments cannot be used in associated type constraints",
);
return Err(err);
}
_ => {
let span = lo.to(self.prev_token.span);
let err = self.struct_span_err(
span,
"only path types can be used in associated type constraints",
);
return Err(err);
}
},
_ => {
let span = lo.to(self.prev_token.span);
let err = self
.struct_span_err(span, "only types can be used in associated type constraints");
return Err(err);
}
}
}
}