1use rustc_ast::{
2 self as ast, AttrVec, DUMMY_NODE_ID, GenericBounds, GenericParam, GenericParamKind, TyKind,
3 WhereClause, token,
4};
5use rustc_errors::{Applicability, PResult};
6use rustc_span::{Ident, Span, kw, sym};
7use thin_vec::ThinVec;
8
9use super::{ForceCollect, Parser, Trailing, UsePreAttrPos};
10use crate::errors::{
11 self, MultipleWhereClauses, UnexpectedDefaultValueForLifetimeInGenericParameters,
12 UnexpectedSelfInGenericParameters, WhereClauseBeforeTupleStructBody,
13 WhereClauseBeforeTupleStructBodySugg,
14};
15use crate::exp;
16
17enum PredicateKindOrStructBody {
18 PredicateKind(ast::WherePredicateKind),
19 StructBody(ThinVec<ast::FieldDef>),
20}
21
22impl<'a> Parser<'a> {
23 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
29 let mut lifetimes = Vec::new();
30 while self.check_lifetime() {
31 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
32
33 if !self.eat_plus() {
34 break;
35 }
36 }
37 lifetimes
38 }
39
40 fn parse_ty_param(&mut self, preceding_attrs: AttrVec) -> PResult<'a, GenericParam> {
42 let ident = self.parse_ident()?;
43
44 if self.may_recover()
46 && ident.name.as_str().to_ascii_lowercase() == kw::Const.as_str()
47 && self.check_ident()
48 {
50 return self.recover_const_param_with_mistyped_const(preceding_attrs, ident);
51 }
52
53 let mut colon_span = None;
55 let bounds = if self.eat(exp!(Colon)) {
56 colon_span = Some(self.prev_token.span);
57 if self.token.is_keyword(kw::Impl) {
59 let impl_span = self.token.span;
60 let snapshot = self.create_snapshot_for_diagnostic();
61 match self.parse_ty() {
62 Ok(p) => {
63 if let TyKind::ImplTrait(_, bounds) = &p.kind {
64 let span = impl_span.to(self.token.span.shrink_to_lo());
65 let mut err = self.dcx().struct_span_err(
66 span,
67 "expected trait bound, found `impl Trait` type",
68 );
69 err.span_label(span, "not a trait");
70 if let [bound, ..] = &bounds[..] {
71 err.span_suggestion_verbose(
72 impl_span.until(bound.span()),
73 "use the trait bounds directly",
74 String::new(),
75 Applicability::MachineApplicable,
76 );
77 }
78 return Err(err);
79 }
80 }
81 Err(err) => {
82 err.cancel();
83 }
84 }
85 self.restore_snapshot(snapshot);
86 }
87 self.parse_generic_bounds()?
88 } else {
89 Vec::new()
90 };
91
92 let default = if self.eat(exp!(Eq)) { Some(self.parse_ty()?) } else { None };
93 Ok(GenericParam {
94 ident,
95 id: ast::DUMMY_NODE_ID,
96 attrs: preceding_attrs,
97 bounds,
98 kind: GenericParamKind::Type { default },
99 is_placeholder: false,
100 colon_span,
101 })
102 }
103
104 pub(crate) fn parse_const_param(
105 &mut self,
106 preceding_attrs: AttrVec,
107 ) -> PResult<'a, GenericParam> {
108 let const_span = self.token.span;
109
110 self.expect_keyword(exp!(Const))?;
111 let ident = self.parse_ident()?;
112 self.expect(exp!(Colon))?;
113 let ty = self.parse_ty()?;
114
115 let default = if self.eat(exp!(Eq)) { Some(self.parse_const_arg()?) } else { None };
117 let span = if let Some(ref default) = default {
118 const_span.to(default.value.span)
119 } else {
120 const_span.to(ty.span)
121 };
122
123 Ok(GenericParam {
124 ident,
125 id: ast::DUMMY_NODE_ID,
126 attrs: preceding_attrs,
127 bounds: Vec::new(),
128 kind: GenericParamKind::Const { ty, span, default },
129 is_placeholder: false,
130 colon_span: None,
131 })
132 }
133
134 pub(crate) fn recover_const_param_with_mistyped_const(
135 &mut self,
136 preceding_attrs: AttrVec,
137 mistyped_const_ident: Ident,
138 ) -> PResult<'a, GenericParam> {
139 let ident = self.parse_ident()?;
140 self.expect(exp!(Colon))?;
141 let ty = self.parse_ty()?;
142
143 let default = if self.eat(exp!(Eq)) { Some(self.parse_const_arg()?) } else { None };
145 let span = if let Some(ref default) = default {
146 mistyped_const_ident.span.to(default.value.span)
147 } else {
148 mistyped_const_ident.span.to(ty.span)
149 };
150
151 self.dcx()
152 .struct_span_err(
153 mistyped_const_ident.span,
154 format!("`const` keyword was mistyped as `{}`", mistyped_const_ident.as_str()),
155 )
156 .with_span_suggestion_verbose(
157 mistyped_const_ident.span,
158 "use the `const` keyword",
159 kw::Const,
160 Applicability::MachineApplicable,
161 )
162 .emit();
163
164 Ok(GenericParam {
165 ident,
166 id: ast::DUMMY_NODE_ID,
167 attrs: preceding_attrs,
168 bounds: Vec::new(),
169 kind: GenericParamKind::Const { ty, span, default },
170 is_placeholder: false,
171 colon_span: None,
172 })
173 }
174
175 pub(super) fn parse_generic_params(&mut self) -> PResult<'a, ThinVec<ast::GenericParam>> {
178 let mut params = ThinVec::new();
179 let mut done = false;
180 while !done {
181 let attrs = self.parse_outer_attributes()?;
182 let param = self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
183 if this.eat_keyword_noexpect(kw::SelfUpper) {
184 this.dcx()
187 .emit_err(UnexpectedSelfInGenericParameters { span: this.prev_token.span });
188
189 let _ = this.eat(exp!(Comma));
191 }
192
193 let param = if this.check_lifetime() {
194 let lifetime = this.expect_lifetime();
195 let (colon_span, bounds) = if this.eat(exp!(Colon)) {
197 (Some(this.prev_token.span), this.parse_lt_param_bounds())
198 } else {
199 (None, Vec::new())
200 };
201
202 if this.check_noexpect(&token::Eq) && this.look_ahead(1, |t| t.is_lifetime()) {
203 let lo = this.token.span;
204 this.bump(); this.bump(); let span = lo.to(this.prev_token.span);
208 this.dcx().emit_err(UnexpectedDefaultValueForLifetimeInGenericParameters {
209 span,
210 });
211 }
212
213 Some(ast::GenericParam {
214 ident: lifetime.ident,
215 id: lifetime.id,
216 attrs,
217 bounds,
218 kind: ast::GenericParamKind::Lifetime,
219 is_placeholder: false,
220 colon_span,
221 })
222 } else if this.check_keyword(exp!(Const)) {
223 Some(this.parse_const_param(attrs)?)
225 } else if this.check_ident() {
226 Some(this.parse_ty_param(attrs)?)
228 } else if this.token.can_begin_type() {
229 let snapshot = this.create_snapshot_for_diagnostic();
231 let lo = this.token.span;
232 match this.parse_ty_where_predicate_kind() {
233 Ok(_) => {
234 this.dcx().emit_err(errors::BadAssocTypeBounds {
235 span: lo.to(this.prev_token.span),
236 });
237 }
239 Err(err) => {
240 err.cancel();
241 this.restore_snapshot(snapshot);
243 }
244 }
245 return Ok((None, Trailing::No, UsePreAttrPos::No));
246 } else {
247 if !attrs.is_empty() {
249 if !params.is_empty() {
250 this.dcx().emit_err(errors::AttrAfterGeneric { span: attrs[0].span });
251 } else {
252 this.dcx()
253 .emit_err(errors::AttrWithoutGenerics { span: attrs[0].span });
254 }
255 }
256 return Ok((None, Trailing::No, UsePreAttrPos::No));
257 };
258
259 if !this.eat(exp!(Comma)) {
260 done = true;
261 }
262 Ok((param, Trailing::No, UsePreAttrPos::No))
264 })?;
265
266 if let Some(param) = param {
267 params.push(param);
268 } else {
269 break;
270 }
271 }
272 Ok(params)
273 }
274
275 pub(super) fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
283 if self.eat_noexpect(&token::PathSep) {
286 self.dcx()
287 .emit_err(errors::InvalidPathSepInFnDefinition { span: self.prev_token.span });
288 }
289
290 let span_lo = self.token.span;
291 let (params, span) = if self.eat_lt() {
292 let params = self.parse_generic_params()?;
293 self.expect_gt_or_maybe_suggest_closing_generics(¶ms)?;
294 (params, span_lo.to(self.prev_token.span))
295 } else {
296 (ThinVec::new(), self.prev_token.span.shrink_to_hi())
297 };
298 Ok(ast::Generics {
299 params,
300 where_clause: WhereClause {
301 has_where_token: false,
302 predicates: ThinVec::new(),
303 span: self.prev_token.span.shrink_to_hi(),
304 },
305 span,
306 })
307 }
308
309 pub(super) fn parse_contract(
312 &mut self,
313 ) -> PResult<'a, Option<rustc_ast::ptr::P<ast::FnContract>>> {
314 let requires = if self.eat_keyword_noexpect(exp!(ContractRequires).kw) {
315 self.psess.gated_spans.gate(sym::contracts_internals, self.prev_token.span);
316 let precond = self.parse_expr()?;
317 Some(precond)
318 } else {
319 None
320 };
321 let ensures = if self.eat_keyword_noexpect(exp!(ContractEnsures).kw) {
322 self.psess.gated_spans.gate(sym::contracts_internals, self.prev_token.span);
323 let postcond = self.parse_expr()?;
324 Some(postcond)
325 } else {
326 None
327 };
328 if requires.is_none() && ensures.is_none() {
329 Ok(None)
330 } else {
331 Ok(Some(rustc_ast::ptr::P(ast::FnContract { requires, ensures })))
332 }
333 }
334
335 pub(super) fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
341 self.parse_where_clause_common(None).map(|(clause, _)| clause)
342 }
343
344 pub(super) fn parse_struct_where_clause(
345 &mut self,
346 struct_name: Ident,
347 body_insertion_point: Span,
348 ) -> PResult<'a, (WhereClause, Option<ThinVec<ast::FieldDef>>)> {
349 self.parse_where_clause_common(Some((struct_name, body_insertion_point)))
350 }
351
352 fn parse_where_clause_common(
353 &mut self,
354 struct_: Option<(Ident, Span)>,
355 ) -> PResult<'a, (WhereClause, Option<ThinVec<ast::FieldDef>>)> {
356 let mut where_clause = WhereClause {
357 has_where_token: false,
358 predicates: ThinVec::new(),
359 span: self.prev_token.span.shrink_to_hi(),
360 };
361 let mut tuple_struct_body = None;
362
363 if !self.eat_keyword(exp!(Where)) {
364 return Ok((where_clause, None));
365 }
366
367 if self.eat_noexpect(&token::Colon) {
368 let colon_span = self.prev_token.span;
369 self.dcx()
370 .struct_span_err(colon_span, "unexpected colon after `where`")
371 .with_span_suggestion_short(
372 colon_span,
373 "remove the colon",
374 "",
375 Applicability::MachineApplicable,
376 )
377 .emit();
378 }
379
380 where_clause.has_where_token = true;
381 let where_lo = self.prev_token.span;
382
383 if self.choose_generics_over_qpath(0) {
387 let generics = self.parse_generics()?;
388 self.dcx().emit_err(errors::WhereOnGenerics { span: generics.span });
389 }
390
391 loop {
392 let where_sp = where_lo.to(self.prev_token.span);
393 let attrs = self.parse_outer_attributes()?;
394 let pred_lo = self.token.span;
395 let predicate = self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
396 for attr in &attrs {
397 self.psess.gated_spans.gate(sym::where_clause_attrs, attr.span);
398 }
399 let kind = if this.check_lifetime() && this.look_ahead(1, |t| !t.is_like_plus()) {
400 let lifetime = this.expect_lifetime();
401 this.expect(exp!(Colon))?;
403 let bounds = this.parse_lt_param_bounds();
404 Some(ast::WherePredicateKind::RegionPredicate(ast::WhereRegionPredicate {
405 lifetime,
406 bounds,
407 }))
408 } else if this.check_type() {
409 match this.parse_ty_where_predicate_kind_or_recover_tuple_struct_body(
410 struct_, pred_lo, where_sp,
411 )? {
412 PredicateKindOrStructBody::PredicateKind(kind) => Some(kind),
413 PredicateKindOrStructBody::StructBody(body) => {
414 tuple_struct_body = Some(body);
415 None
416 }
417 }
418 } else {
419 None
420 };
421 let predicate = kind.map(|kind| ast::WherePredicate {
422 attrs,
423 kind,
424 id: DUMMY_NODE_ID,
425 span: pred_lo.to(this.prev_token.span),
426 is_placeholder: false,
427 });
428 Ok((predicate, Trailing::No, UsePreAttrPos::No))
429 })?;
430 match predicate {
431 Some(predicate) => where_clause.predicates.push(predicate),
432 None => break,
433 }
434
435 let prev_token = self.prev_token.span;
436 let ate_comma = self.eat(exp!(Comma));
437
438 if self.eat_keyword_noexpect(kw::Where) {
439 self.dcx().emit_err(MultipleWhereClauses {
440 span: self.token.span,
441 previous: pred_lo,
442 between: prev_token.shrink_to_hi().to(self.prev_token.span),
443 });
444 } else if !ate_comma {
445 break;
446 }
447 }
448
449 where_clause.span = where_lo.to(self.prev_token.span);
450 Ok((where_clause, tuple_struct_body))
451 }
452
453 fn parse_ty_where_predicate_kind_or_recover_tuple_struct_body(
454 &mut self,
455 struct_: Option<(Ident, Span)>,
456 pred_lo: Span,
457 where_sp: Span,
458 ) -> PResult<'a, PredicateKindOrStructBody> {
459 let mut snapshot = None;
460
461 if let Some(struct_) = struct_
462 && self.may_recover()
463 && self.token == token::OpenParen
464 {
465 snapshot = Some((struct_, self.create_snapshot_for_diagnostic()));
466 };
467
468 match self.parse_ty_where_predicate_kind() {
469 Ok(pred) => Ok(PredicateKindOrStructBody::PredicateKind(pred)),
470 Err(type_err) => {
471 let Some(((struct_name, body_insertion_point), mut snapshot)) = snapshot else {
472 return Err(type_err);
473 };
474
475 match snapshot.parse_tuple_struct_body() {
477 Ok(body)
483 if matches!(snapshot.token.kind, token::Semi | token::Eof)
484 || snapshot.token.can_begin_item() =>
485 {
486 type_err.cancel();
487
488 let body_sp = pred_lo.to(snapshot.prev_token.span);
489 let map = self.psess.source_map();
490
491 self.dcx().emit_err(WhereClauseBeforeTupleStructBody {
492 span: where_sp,
493 name: struct_name.span,
494 body: body_sp,
495 sugg: map.span_to_snippet(body_sp).ok().map(|body| {
496 WhereClauseBeforeTupleStructBodySugg {
497 left: body_insertion_point.shrink_to_hi(),
498 snippet: body,
499 right: map.end_point(where_sp).to(body_sp),
500 }
501 }),
502 });
503
504 self.restore_snapshot(snapshot);
505 Ok(PredicateKindOrStructBody::StructBody(body))
506 }
507 Ok(_) => Err(type_err),
508 Err(body_err) => {
509 body_err.cancel();
510 Err(type_err)
511 }
512 }
513 }
514 }
515 }
516
517 fn parse_ty_where_predicate_kind(&mut self) -> PResult<'a, ast::WherePredicateKind> {
518 let (lifetime_defs, _) = self.parse_late_bound_lifetime_defs()?;
526
527 let ty = self.parse_ty_for_where_clause()?;
530 if self.eat(exp!(Colon)) {
531 let bounds = self.parse_generic_bounds()?;
532 Ok(ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
533 bound_generic_params: lifetime_defs,
534 bounded_ty: ty,
535 bounds,
536 }))
537 } else if self.eat(exp!(Eq)) || self.eat(exp!(EqEq)) {
540 let rhs_ty = self.parse_ty()?;
541 Ok(ast::WherePredicateKind::EqPredicate(ast::WhereEqPredicate { lhs_ty: ty, rhs_ty }))
542 } else {
543 self.maybe_recover_bounds_doubled_colon(&ty)?;
544 self.unexpected_any()
545 }
546 }
547
548 pub(super) fn choose_generics_over_qpath(&self, start: usize) -> bool {
549 self.look_ahead(start, |t| t == &token::Lt)
568 && (self.look_ahead(start + 1, |t| t == &token::Pound || t == &token::Gt)
569 || self.look_ahead(start + 1, |t| t.is_lifetime() || t.is_ident())
570 && self.look_ahead(start + 2, |t| {
571 matches!(t.kind, token::Gt | token::Comma | token::Colon | token::Eq)
572 || t.kind == token::Question
575 })
576 || self.is_keyword_ahead(start + 1, &[kw::Const]))
577 }
578}