1use std::mem;
20use std::ops::{Deref, DerefMut};
21
22use itertools::{Either, Itertools};
23use rustc_abi::ExternAbi;
24use rustc_ast::ptr::P;
25use rustc_ast::visit::{AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, walk_list};
26use rustc_ast::*;
27use rustc_ast_pretty::pprust::{self, State};
28use rustc_data_structures::fx::FxIndexMap;
29use rustc_errors::DiagCtxtHandle;
30use rustc_feature::Features;
31use rustc_parse::validate_attr;
32use rustc_session::Session;
33use rustc_session::lint::builtin::{
34 DEPRECATED_WHERE_CLAUSE_LOCATION, MISSING_ABI, MISSING_UNSAFE_ON_EXTERN,
35 PATTERNS_IN_FNS_WITHOUT_BODY,
36};
37use rustc_session::lint::{BuiltinLintDiag, LintBuffer};
38use rustc_span::{Ident, Span, kw, sym};
39use thin_vec::thin_vec;
40
41use crate::errors::{self, TildeConstReason};
42
43enum SelfSemantic {
45 Yes,
46 No,
47}
48
49enum TraitOrTraitImpl {
50 Trait { span: Span, constness: Option<Span> },
51 TraitImpl { constness: Const, polarity: ImplPolarity, trait_ref: Span },
52}
53
54impl TraitOrTraitImpl {
55 fn constness(&self) -> Option<Span> {
56 match self {
57 Self::Trait { constness: Some(span), .. }
58 | Self::TraitImpl { constness: Const::Yes(span), .. } => Some(*span),
59 _ => None,
60 }
61 }
62}
63
64struct AstValidator<'a> {
65 sess: &'a Session,
66 features: &'a Features,
67
68 extern_mod: Option<Span>,
70
71 outer_trait_or_trait_impl: Option<TraitOrTraitImpl>,
72
73 has_proc_macro_decls: bool,
74
75 outer_impl_trait: Option<Span>,
79
80 disallow_tilde_const: Option<TildeConstReason>,
81
82 extern_mod_safety: Option<Safety>,
84
85 lint_buffer: &'a mut LintBuffer,
86}
87
88impl<'a> AstValidator<'a> {
89 fn with_in_trait_impl(
90 &mut self,
91 trait_: Option<(Const, ImplPolarity, &'a TraitRef)>,
92 f: impl FnOnce(&mut Self),
93 ) {
94 let old = mem::replace(
95 &mut self.outer_trait_or_trait_impl,
96 trait_.map(|(constness, polarity, trait_ref)| TraitOrTraitImpl::TraitImpl {
97 constness,
98 polarity,
99 trait_ref: trait_ref.path.span,
100 }),
101 );
102 f(self);
103 self.outer_trait_or_trait_impl = old;
104 }
105
106 fn with_in_trait(&mut self, span: Span, constness: Option<Span>, f: impl FnOnce(&mut Self)) {
107 let old = mem::replace(
108 &mut self.outer_trait_or_trait_impl,
109 Some(TraitOrTraitImpl::Trait { span, constness }),
110 );
111 f(self);
112 self.outer_trait_or_trait_impl = old;
113 }
114
115 fn with_in_extern_mod(&mut self, extern_mod_safety: Safety, f: impl FnOnce(&mut Self)) {
116 let old = mem::replace(&mut self.extern_mod_safety, Some(extern_mod_safety));
117 f(self);
118 self.extern_mod_safety = old;
119 }
120
121 fn with_tilde_const(
122 &mut self,
123 disallowed: Option<TildeConstReason>,
124 f: impl FnOnce(&mut Self),
125 ) {
126 let old = mem::replace(&mut self.disallow_tilde_const, disallowed);
127 f(self);
128 self.disallow_tilde_const = old;
129 }
130
131 fn check_type_alias_where_clause_location(
132 &mut self,
133 ty_alias: &TyAlias,
134 ) -> Result<(), errors::WhereClauseBeforeTypeAlias> {
135 if ty_alias.ty.is_none() || !ty_alias.where_clauses.before.has_where_token {
136 return Ok(());
137 }
138
139 let (before_predicates, after_predicates) =
140 ty_alias.generics.where_clause.predicates.split_at(ty_alias.where_clauses.split);
141 let span = ty_alias.where_clauses.before.span;
142
143 let sugg = if !before_predicates.is_empty() || !ty_alias.where_clauses.after.has_where_token
144 {
145 let mut state = State::new();
146
147 if !ty_alias.where_clauses.after.has_where_token {
148 state.space();
149 state.word_space("where");
150 }
151
152 let mut first = after_predicates.is_empty();
153 for p in before_predicates {
154 if !first {
155 state.word_space(",");
156 }
157 first = false;
158 state.print_where_predicate(p);
159 }
160
161 errors::WhereClauseBeforeTypeAliasSugg::Move {
162 left: span,
163 snippet: state.s.eof(),
164 right: ty_alias.where_clauses.after.span.shrink_to_hi(),
165 }
166 } else {
167 errors::WhereClauseBeforeTypeAliasSugg::Remove { span }
168 };
169
170 Err(errors::WhereClauseBeforeTypeAlias { span, sugg })
171 }
172
173 fn with_impl_trait(&mut self, outer: Option<Span>, f: impl FnOnce(&mut Self)) {
174 let old = mem::replace(&mut self.outer_impl_trait, outer);
175 f(self);
176 self.outer_impl_trait = old;
177 }
178
179 fn walk_ty(&mut self, t: &'a Ty) {
181 match &t.kind {
182 TyKind::ImplTrait(_, bounds) => {
183 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t));
184
185 let mut use_bounds = bounds
189 .iter()
190 .filter_map(|bound| match bound {
191 GenericBound::Use(_, span) => Some(span),
192 _ => None,
193 })
194 .copied();
195 if let Some(bound1) = use_bounds.next()
196 && let Some(bound2) = use_bounds.next()
197 {
198 self.dcx().emit_err(errors::DuplicatePreciseCapturing { bound1, bound2 });
199 }
200 }
201 TyKind::TraitObject(..) => self
202 .with_tilde_const(Some(TildeConstReason::TraitObject), |this| {
203 visit::walk_ty(this, t)
204 }),
205 _ => visit::walk_ty(self, t),
206 }
207 }
208
209 fn visit_struct_field_def(&mut self, field: &'a FieldDef) {
210 if let Some(ref ident) = field.ident
211 && ident.name == kw::Underscore
212 {
213 self.visit_vis(&field.vis);
214 self.visit_ident(ident);
215 self.visit_ty_common(&field.ty);
216 self.walk_ty(&field.ty);
217 walk_list!(self, visit_attribute, &field.attrs);
218 } else {
219 self.visit_field_def(field);
220 }
221 }
222
223 fn dcx(&self) -> DiagCtxtHandle<'a> {
224 self.sess.dcx()
225 }
226
227 fn visibility_not_permitted(&self, vis: &Visibility, note: errors::VisibilityNotPermittedNote) {
228 if let VisibilityKind::Inherited = vis.kind {
229 return;
230 }
231
232 self.dcx().emit_err(errors::VisibilityNotPermitted {
233 span: vis.span,
234 note,
235 remove_qualifier_sugg: vis.span,
236 });
237 }
238
239 fn check_decl_no_pat(decl: &FnDecl, mut report_err: impl FnMut(Span, Option<Ident>, bool)) {
240 for Param { pat, .. } in &decl.inputs {
241 match pat.kind {
242 PatKind::Ident(BindingMode::NONE, _, None) | PatKind::Wild => {}
243 PatKind::Ident(BindingMode::MUT, ident, None) => {
244 report_err(pat.span, Some(ident), true)
245 }
246 _ => report_err(pat.span, None, false),
247 }
248 }
249 }
250
251 fn check_trait_fn_not_const(&self, constness: Const, parent: &TraitOrTraitImpl) {
252 let Const::Yes(span) = constness else {
253 return;
254 };
255
256 let const_trait_impl = self.features.const_trait_impl();
257 let make_impl_const_sugg = if const_trait_impl
258 && let TraitOrTraitImpl::TraitImpl {
259 constness: Const::No,
260 polarity: ImplPolarity::Positive,
261 trait_ref,
262 ..
263 } = parent
264 {
265 Some(trait_ref.shrink_to_lo())
266 } else {
267 None
268 };
269
270 let make_trait_const_sugg =
271 if const_trait_impl && let TraitOrTraitImpl::Trait { span, constness: None } = parent {
272 Some(span.shrink_to_lo())
273 } else {
274 None
275 };
276
277 let parent_constness = parent.constness();
278 self.dcx().emit_err(errors::TraitFnConst {
279 span,
280 in_impl: matches!(parent, TraitOrTraitImpl::TraitImpl { .. }),
281 const_context_label: parent_constness,
282 remove_const_sugg: (
283 self.sess.source_map().span_extend_while_whitespace(span),
284 match parent_constness {
285 Some(_) => rustc_errors::Applicability::MachineApplicable,
286 None => rustc_errors::Applicability::MaybeIncorrect,
287 },
288 ),
289 requires_multiple_changes: make_impl_const_sugg.is_some()
290 || make_trait_const_sugg.is_some(),
291 make_impl_const_sugg,
292 make_trait_const_sugg,
293 });
294 }
295
296 fn check_fn_decl(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) {
297 self.check_decl_num_args(fn_decl);
298 self.check_decl_cvariadic_pos(fn_decl);
299 self.check_decl_attrs(fn_decl);
300 self.check_decl_self_param(fn_decl, self_semantic);
301 }
302
303 fn check_decl_num_args(&self, fn_decl: &FnDecl) {
306 let max_num_args: usize = u16::MAX.into();
307 if fn_decl.inputs.len() > max_num_args {
308 let Param { span, .. } = fn_decl.inputs[0];
309 self.dcx().emit_fatal(errors::FnParamTooMany { span, max_num_args });
310 }
311 }
312
313 fn check_decl_cvariadic_pos(&self, fn_decl: &FnDecl) {
317 match &*fn_decl.inputs {
318 [ps @ .., _] => {
319 for Param { ty, span, .. } in ps {
320 if let TyKind::CVarArgs = ty.kind {
321 self.dcx().emit_err(errors::FnParamCVarArgsNotLast { span: *span });
322 }
323 }
324 }
325 _ => {}
326 }
327 }
328
329 fn check_decl_attrs(&self, fn_decl: &FnDecl) {
330 fn_decl
331 .inputs
332 .iter()
333 .flat_map(|i| i.attrs.as_ref())
334 .filter(|attr| {
335 let arr = [
336 sym::allow,
337 sym::cfg,
338 sym::cfg_attr,
339 sym::cfg_attr_trace,
340 sym::deny,
341 sym::expect,
342 sym::forbid,
343 sym::warn,
344 ];
345 !arr.contains(&attr.name_or_empty()) && rustc_attr_parsing::is_builtin_attr(*attr)
346 })
347 .for_each(|attr| {
348 if attr.is_doc_comment() {
349 self.dcx().emit_err(errors::FnParamDocComment { span: attr.span });
350 } else {
351 self.dcx().emit_err(errors::FnParamForbiddenAttr { span: attr.span });
352 }
353 });
354 }
355
356 fn check_decl_self_param(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) {
357 if let (SelfSemantic::No, [param, ..]) = (self_semantic, &*fn_decl.inputs) {
358 if param.is_self() {
359 self.dcx().emit_err(errors::FnParamForbiddenSelf { span: param.span });
360 }
361 }
362 }
363
364 fn check_item_safety(&self, span: Span, safety: Safety) {
370 match self.extern_mod_safety {
371 Some(extern_safety) => {
372 if matches!(safety, Safety::Unsafe(_) | Safety::Safe(_))
373 && extern_safety == Safety::Default
374 {
375 self.dcx().emit_err(errors::InvalidSafetyOnExtern {
376 item_span: span,
377 block: Some(self.current_extern_span().shrink_to_lo()),
378 });
379 }
380 }
381 None => {
382 if matches!(safety, Safety::Safe(_)) {
383 self.dcx().emit_err(errors::InvalidSafetyOnItem { span });
384 }
385 }
386 }
387 }
388
389 fn check_bare_fn_safety(&self, span: Span, safety: Safety) {
390 if matches!(safety, Safety::Safe(_)) {
391 self.dcx().emit_err(errors::InvalidSafetyOnBareFn { span });
392 }
393 }
394
395 fn check_defaultness(&self, span: Span, defaultness: Defaultness) {
396 if let Defaultness::Default(def_span) = defaultness {
397 let span = self.sess.source_map().guess_head_span(span);
398 self.dcx().emit_err(errors::ForbiddenDefault { span, def_span });
399 }
400 }
401
402 fn ending_semi_or_hi(&self, sp: Span) -> Span {
405 let source_map = self.sess.source_map();
406 let end = source_map.end_point(sp);
407
408 if source_map.span_to_snippet(end).is_ok_and(|s| s == ";") {
409 end
410 } else {
411 sp.shrink_to_hi()
412 }
413 }
414
415 fn check_type_no_bounds(&self, bounds: &[GenericBound], ctx: &str) {
416 let span = match bounds {
417 [] => return,
418 [b0] => b0.span(),
419 [b0, .., bl] => b0.span().to(bl.span()),
420 };
421 self.dcx().emit_err(errors::BoundInContext { span, ctx });
422 }
423
424 fn check_foreign_ty_genericless(
425 &self,
426 generics: &Generics,
427 where_clauses: &TyAliasWhereClauses,
428 ) {
429 let cannot_have = |span, descr, remove_descr| {
430 self.dcx().emit_err(errors::ExternTypesCannotHave {
431 span,
432 descr,
433 remove_descr,
434 block_span: self.current_extern_span(),
435 });
436 };
437
438 if !generics.params.is_empty() {
439 cannot_have(generics.span, "generic parameters", "generic parameters");
440 }
441
442 let check_where_clause = |where_clause: TyAliasWhereClause| {
443 if where_clause.has_where_token {
444 cannot_have(where_clause.span, "`where` clauses", "`where` clause");
445 }
446 };
447
448 check_where_clause(where_clauses.before);
449 check_where_clause(where_clauses.after);
450 }
451
452 fn check_foreign_kind_bodyless(&self, ident: Ident, kind: &str, body: Option<Span>) {
453 let Some(body) = body else {
454 return;
455 };
456 self.dcx().emit_err(errors::BodyInExtern {
457 span: ident.span,
458 body,
459 block: self.current_extern_span(),
460 kind,
461 });
462 }
463
464 fn check_foreign_fn_bodyless(&self, ident: Ident, body: Option<&Block>) {
466 let Some(body) = body else {
467 return;
468 };
469 self.dcx().emit_err(errors::FnBodyInExtern {
470 span: ident.span,
471 body: body.span,
472 block: self.current_extern_span(),
473 });
474 }
475
476 fn current_extern_span(&self) -> Span {
477 self.sess.source_map().guess_head_span(self.extern_mod.unwrap())
478 }
479
480 fn check_foreign_fn_headerless(
482 &self,
483 FnHeader { safety: _, coroutine_kind, constness, ext }: FnHeader,
485 ) {
486 let report_err = |span, kw| {
487 self.dcx().emit_err(errors::FnQualifierInExtern {
488 span,
489 kw,
490 block: self.current_extern_span(),
491 });
492 };
493 match coroutine_kind {
494 Some(kind) => report_err(kind.span(), kind.as_str()),
495 None => (),
496 }
497 match constness {
498 Const::Yes(span) => report_err(span, "const"),
499 Const::No => (),
500 }
501 match ext {
502 Extern::None => (),
503 Extern::Implicit(span) | Extern::Explicit(_, span) => report_err(span, "extern"),
504 }
505 }
506
507 fn check_foreign_item_ascii_only(&self, ident: Ident) {
509 if !ident.as_str().is_ascii() {
510 self.dcx().emit_err(errors::ExternItemAscii {
511 span: ident.span,
512 block: self.current_extern_span(),
513 });
514 }
515 }
516
517 fn check_c_variadic_type(&self, fk: FnKind<'a>) {
523 let variadic_spans: Vec<_> = fk
524 .decl()
525 .inputs
526 .iter()
527 .filter(|arg| matches!(arg.ty.kind, TyKind::CVarArgs))
528 .map(|arg| arg.span)
529 .collect();
530
531 if variadic_spans.is_empty() {
532 return;
533 }
534
535 if let Some(header) = fk.header() {
536 if let Const::Yes(const_span) = header.constness {
537 let mut spans = variadic_spans.clone();
538 spans.push(const_span);
539 self.dcx().emit_err(errors::ConstAndCVariadic {
540 spans,
541 const_span,
542 variadic_spans: variadic_spans.clone(),
543 });
544 }
545 }
546
547 match (fk.ctxt(), fk.header()) {
548 (Some(FnCtxt::Foreign), _) => return,
549 (Some(FnCtxt::Free), Some(header)) => match header.ext {
550 Extern::Explicit(StrLit { symbol_unescaped: sym::C, .. }, _)
551 | Extern::Explicit(StrLit { symbol_unescaped: sym::C_dash_unwind, .. }, _)
552 | Extern::Implicit(_)
553 if matches!(header.safety, Safety::Unsafe(_)) =>
554 {
555 return;
556 }
557 _ => {}
558 },
559 _ => {}
560 };
561
562 self.dcx().emit_err(errors::BadCVariadic { span: variadic_spans });
563 }
564
565 fn check_item_named(&self, ident: Ident, kind: &str) {
566 if ident.name != kw::Underscore {
567 return;
568 }
569 self.dcx().emit_err(errors::ItemUnderscore { span: ident.span, kind });
570 }
571
572 fn check_nomangle_item_asciionly(&self, ident: Ident, item_span: Span) {
573 if ident.name.as_str().is_ascii() {
574 return;
575 }
576 let span = self.sess.source_map().guess_head_span(item_span);
577 self.dcx().emit_err(errors::NoMangleAscii { span });
578 }
579
580 fn check_mod_file_item_asciionly(&self, ident: Ident) {
581 if ident.name.as_str().is_ascii() {
582 return;
583 }
584 self.dcx().emit_err(errors::ModuleNonAscii { span: ident.span, name: ident.name });
585 }
586
587 fn deny_generic_params(&self, generics: &Generics, ident: Span) {
588 if !generics.params.is_empty() {
589 self.dcx().emit_err(errors::AutoTraitGeneric { span: generics.span, ident });
590 }
591 }
592
593 fn deny_super_traits(&self, bounds: &GenericBounds, ident_span: Span) {
594 if let [.., last] = &bounds[..] {
595 let span = ident_span.shrink_to_hi().to(last.span());
596 self.dcx().emit_err(errors::AutoTraitBounds { span, ident: ident_span });
597 }
598 }
599
600 fn deny_where_clause(&self, where_clause: &WhereClause, ident_span: Span) {
601 if !where_clause.predicates.is_empty() {
602 self.dcx()
605 .emit_err(errors::AutoTraitBounds { span: where_clause.span, ident: ident_span });
606 }
607 }
608
609 fn deny_items(&self, trait_items: &[P<AssocItem>], ident: Span) {
610 if !trait_items.is_empty() {
611 let spans: Vec<_> = trait_items.iter().map(|i| i.ident.span).collect();
612 let total = trait_items.first().unwrap().span.to(trait_items.last().unwrap().span);
613 self.dcx().emit_err(errors::AutoTraitItems { spans, total, ident });
614 }
615 }
616
617 fn correct_generic_order_suggestion(&self, data: &AngleBracketedArgs) -> String {
618 let lt_sugg = data.args.iter().filter_map(|arg| match arg {
620 AngleBracketedArg::Arg(lt @ GenericArg::Lifetime(_)) => {
621 Some(pprust::to_string(|s| s.print_generic_arg(lt)))
622 }
623 _ => None,
624 });
625 let args_sugg = data.args.iter().filter_map(|a| match a {
626 AngleBracketedArg::Arg(GenericArg::Lifetime(_)) | AngleBracketedArg::Constraint(_) => {
627 None
628 }
629 AngleBracketedArg::Arg(arg) => Some(pprust::to_string(|s| s.print_generic_arg(arg))),
630 });
631 let constraint_sugg = data.args.iter().filter_map(|a| match a {
633 AngleBracketedArg::Arg(_) => None,
634 AngleBracketedArg::Constraint(c) => {
635 Some(pprust::to_string(|s| s.print_assoc_item_constraint(c)))
636 }
637 });
638 format!(
639 "<{}>",
640 lt_sugg.chain(args_sugg).chain(constraint_sugg).collect::<Vec<String>>().join(", ")
641 )
642 }
643
644 fn check_generic_args_before_constraints(&self, data: &AngleBracketedArgs) {
646 if data.args.iter().is_partitioned(|arg| matches!(arg, AngleBracketedArg::Arg(_))) {
648 return;
649 }
650 let (constraint_spans, arg_spans): (Vec<Span>, Vec<Span>) =
652 data.args.iter().partition_map(|arg| match arg {
653 AngleBracketedArg::Constraint(c) => Either::Left(c.span),
654 AngleBracketedArg::Arg(a) => Either::Right(a.span()),
655 });
656 let args_len = arg_spans.len();
657 let constraint_len = constraint_spans.len();
658 self.dcx().emit_err(errors::ArgsBeforeConstraint {
660 arg_spans: arg_spans.clone(),
661 constraints: constraint_spans[0],
662 args: *arg_spans.iter().last().unwrap(),
663 data: data.span,
664 constraint_spans: errors::EmptyLabelManySpans(constraint_spans),
665 arg_spans2: errors::EmptyLabelManySpans(arg_spans),
666 suggestion: self.correct_generic_order_suggestion(data),
667 constraint_len,
668 args_len,
669 });
670 }
671
672 fn visit_ty_common(&mut self, ty: &'a Ty) {
673 match &ty.kind {
674 TyKind::BareFn(bfty) => {
675 self.check_bare_fn_safety(bfty.decl_span, bfty.safety);
676 self.check_fn_decl(&bfty.decl, SelfSemantic::No);
677 Self::check_decl_no_pat(&bfty.decl, |span, _, _| {
678 self.dcx().emit_err(errors::PatternFnPointer { span });
679 });
680 if let Extern::Implicit(extern_span) = bfty.ext {
681 self.maybe_lint_missing_abi(extern_span, ty.id);
682 }
683 }
684 TyKind::TraitObject(bounds, ..) => {
685 let mut any_lifetime_bounds = false;
686 for bound in bounds {
687 if let GenericBound::Outlives(lifetime) = bound {
688 if any_lifetime_bounds {
689 self.dcx()
690 .emit_err(errors::TraitObjectBound { span: lifetime.ident.span });
691 break;
692 }
693 any_lifetime_bounds = true;
694 }
695 }
696 }
697 TyKind::ImplTrait(_, bounds) => {
698 if let Some(outer_impl_trait_sp) = self.outer_impl_trait {
699 self.dcx().emit_err(errors::NestedImplTrait {
700 span: ty.span,
701 outer: outer_impl_trait_sp,
702 inner: ty.span,
703 });
704 }
705
706 if !bounds.iter().any(|b| matches!(b, GenericBound::Trait(..))) {
707 self.dcx().emit_err(errors::AtLeastOneTrait { span: ty.span });
708 }
709 }
710 _ => {}
711 }
712 }
713
714 fn maybe_lint_missing_abi(&mut self, span: Span, id: NodeId) {
715 if self
718 .sess
719 .source_map()
720 .span_to_snippet(span)
721 .is_ok_and(|snippet| !snippet.starts_with("#["))
722 {
723 self.lint_buffer.buffer_lint(
724 MISSING_ABI,
725 id,
726 span,
727 BuiltinLintDiag::MissingAbi(span, ExternAbi::FALLBACK),
728 )
729 }
730 }
731}
732
733fn validate_generic_param_order(dcx: DiagCtxtHandle<'_>, generics: &[GenericParam], span: Span) {
736 let mut max_param: Option<ParamKindOrd> = None;
737 let mut out_of_order = FxIndexMap::default();
738 let mut param_idents = Vec::with_capacity(generics.len());
739
740 for (idx, param) in generics.iter().enumerate() {
741 let ident = param.ident;
742 let (kind, bounds, span) = (¶m.kind, ¶m.bounds, ident.span);
743 let (ord_kind, ident) = match ¶m.kind {
744 GenericParamKind::Lifetime => (ParamKindOrd::Lifetime, ident.to_string()),
745 GenericParamKind::Type { .. } => (ParamKindOrd::TypeOrConst, ident.to_string()),
746 GenericParamKind::Const { ty, .. } => {
747 let ty = pprust::ty_to_string(ty);
748 (ParamKindOrd::TypeOrConst, format!("const {ident}: {ty}"))
749 }
750 };
751 param_idents.push((kind, ord_kind, bounds, idx, ident));
752 match max_param {
753 Some(max_param) if max_param > ord_kind => {
754 let entry = out_of_order.entry(ord_kind).or_insert((max_param, vec![]));
755 entry.1.push(span);
756 }
757 Some(_) | None => max_param = Some(ord_kind),
758 };
759 }
760
761 if !out_of_order.is_empty() {
762 let mut ordered_params = "<".to_string();
763 param_idents.sort_by_key(|&(_, po, _, i, _)| (po, i));
764 let mut first = true;
765 for (kind, _, bounds, _, ident) in param_idents {
766 if !first {
767 ordered_params += ", ";
768 }
769 ordered_params += &ident;
770
771 if !bounds.is_empty() {
772 ordered_params += ": ";
773 ordered_params += &pprust::bounds_to_string(bounds);
774 }
775
776 match kind {
777 GenericParamKind::Type { default: Some(default) } => {
778 ordered_params += " = ";
779 ordered_params += &pprust::ty_to_string(default);
780 }
781 GenericParamKind::Type { default: None } => (),
782 GenericParamKind::Lifetime => (),
783 GenericParamKind::Const { ty: _, kw_span: _, default: Some(default) } => {
784 ordered_params += " = ";
785 ordered_params += &pprust::expr_to_string(&default.value);
786 }
787 GenericParamKind::Const { ty: _, kw_span: _, default: None } => (),
788 }
789 first = false;
790 }
791
792 ordered_params += ">";
793
794 for (param_ord, (max_param, spans)) in &out_of_order {
795 dcx.emit_err(errors::OutOfOrderParams {
796 spans: spans.clone(),
797 sugg_span: span,
798 param_ord,
799 max_param,
800 ordered_params: &ordered_params,
801 });
802 }
803 }
804}
805
806impl<'a> Visitor<'a> for AstValidator<'a> {
807 fn visit_attribute(&mut self, attr: &Attribute) {
808 validate_attr::check_attr(&self.sess.psess, attr);
809 }
810
811 fn visit_ty(&mut self, ty: &'a Ty) {
812 self.visit_ty_common(ty);
813 self.walk_ty(ty)
814 }
815
816 fn visit_item(&mut self, item: &'a Item) {
817 if item.attrs.iter().any(|attr| attr.is_proc_macro_attr()) {
818 self.has_proc_macro_decls = true;
819 }
820
821 if attr::contains_name(&item.attrs, sym::no_mangle) {
822 self.check_nomangle_item_asciionly(item.ident, item.span);
823 }
824
825 match &item.kind {
826 ItemKind::Impl(box Impl {
827 safety,
828 polarity,
829 defaultness: _,
830 constness,
831 generics,
832 of_trait: Some(t),
833 self_ty,
834 items,
835 }) => {
836 self.with_in_trait_impl(Some((*constness, *polarity, t)), |this| {
837 this.visibility_not_permitted(
838 &item.vis,
839 errors::VisibilityNotPermittedNote::TraitImpl,
840 );
841 if let TyKind::Dummy = self_ty.kind {
842 this.dcx().emit_fatal(errors::ObsoleteAuto { span: item.span });
845 }
846 if let (&Safety::Unsafe(span), &ImplPolarity::Negative(sp)) = (safety, polarity)
847 {
848 this.dcx().emit_err(errors::UnsafeNegativeImpl {
849 span: sp.to(t.path.span),
850 negative: sp,
851 r#unsafe: span,
852 });
853 }
854
855 this.visit_vis(&item.vis);
856 this.visit_ident(&item.ident);
857 let disallowed = matches!(constness, Const::No)
858 .then(|| TildeConstReason::TraitImpl { span: item.span });
859 this.with_tilde_const(disallowed, |this| this.visit_generics(generics));
860 this.visit_trait_ref(t);
861 this.visit_ty(self_ty);
862
863 walk_list!(this, visit_assoc_item, items, AssocCtxt::Impl);
864 });
865 walk_list!(self, visit_attribute, &item.attrs);
866 return; }
868 ItemKind::Impl(box Impl {
869 safety,
870 polarity,
871 defaultness,
872 constness,
873 generics,
874 of_trait: None,
875 self_ty,
876 items,
877 }) => {
878 let error = |annotation_span, annotation, only_trait| errors::InherentImplCannot {
879 span: self_ty.span,
880 annotation_span,
881 annotation,
882 self_ty: self_ty.span,
883 only_trait,
884 };
885
886 self.with_in_trait_impl(None, |this| {
887 this.visibility_not_permitted(
888 &item.vis,
889 errors::VisibilityNotPermittedNote::IndividualImplItems,
890 );
891 if let &Safety::Unsafe(span) = safety {
892 this.dcx().emit_err(errors::InherentImplCannotUnsafe {
893 span: self_ty.span,
894 annotation_span: span,
895 annotation: "unsafe",
896 self_ty: self_ty.span,
897 });
898 }
899 if let &ImplPolarity::Negative(span) = polarity {
900 this.dcx().emit_err(error(span, "negative", false));
901 }
902 if let &Defaultness::Default(def_span) = defaultness {
903 this.dcx().emit_err(error(def_span, "`default`", true));
904 }
905 if let &Const::Yes(span) = constness {
906 this.dcx().emit_err(error(span, "`const`", true));
907 }
908
909 this.visit_vis(&item.vis);
910 this.visit_ident(&item.ident);
911 this.with_tilde_const(
912 Some(TildeConstReason::Impl { span: item.span }),
913 |this| this.visit_generics(generics),
914 );
915 this.visit_ty(self_ty);
916 walk_list!(this, visit_assoc_item, items, AssocCtxt::Impl);
917 });
918 walk_list!(self, visit_attribute, &item.attrs);
919 return; }
921 ItemKind::Fn(
922 func
923 @ box Fn { defaultness, generics: _, sig, contract: _, body, define_opaque: _ },
924 ) => {
925 self.check_defaultness(item.span, *defaultness);
926
927 let is_intrinsic =
928 item.attrs.iter().any(|a| a.name_or_empty() == sym::rustc_intrinsic);
929 if body.is_none() && !is_intrinsic {
930 self.dcx().emit_err(errors::FnWithoutBody {
931 span: item.span,
932 replace_span: self.ending_semi_or_hi(item.span),
933 extern_block_suggestion: match sig.header.ext {
934 Extern::None => None,
935 Extern::Implicit(start_span) => {
936 Some(errors::ExternBlockSuggestion::Implicit {
937 start_span,
938 end_span: item.span.shrink_to_hi(),
939 })
940 }
941 Extern::Explicit(abi, start_span) => {
942 Some(errors::ExternBlockSuggestion::Explicit {
943 start_span,
944 end_span: item.span.shrink_to_hi(),
945 abi: abi.symbol_unescaped,
946 })
947 }
948 },
949 });
950 }
951
952 self.visit_vis(&item.vis);
953 self.visit_ident(&item.ident);
954 let kind = FnKind::Fn(FnCtxt::Free, &item.ident, &item.vis, &*func);
955 self.visit_fn(kind, item.span, item.id);
956 walk_list!(self, visit_attribute, &item.attrs);
957 return; }
959 ItemKind::ForeignMod(ForeignMod { extern_span, abi, safety, .. }) => {
960 self.with_in_extern_mod(*safety, |this| {
961 let old_item = mem::replace(&mut this.extern_mod, Some(item.span));
962 this.visibility_not_permitted(
963 &item.vis,
964 errors::VisibilityNotPermittedNote::IndividualForeignItems,
965 );
966
967 if &Safety::Default == safety {
968 if item.span.at_least_rust_2024() {
969 this.dcx().emit_err(errors::MissingUnsafeOnExtern { span: item.span });
970 } else {
971 this.lint_buffer.buffer_lint(
972 MISSING_UNSAFE_ON_EXTERN,
973 item.id,
974 item.span,
975 BuiltinLintDiag::MissingUnsafeOnExtern {
976 suggestion: item.span.shrink_to_lo(),
977 },
978 );
979 }
980 }
981
982 if abi.is_none() {
983 this.maybe_lint_missing_abi(*extern_span, item.id);
984 }
985 visit::walk_item(this, item);
986 this.extern_mod = old_item;
987 });
988 return; }
990 ItemKind::Enum(def, _) => {
991 for variant in &def.variants {
992 self.visibility_not_permitted(
993 &variant.vis,
994 errors::VisibilityNotPermittedNote::EnumVariant,
995 );
996 for field in variant.data.fields() {
997 self.visibility_not_permitted(
998 &field.vis,
999 errors::VisibilityNotPermittedNote::EnumVariant,
1000 );
1001 }
1002 }
1003 }
1004 ItemKind::Trait(box Trait { is_auto, generics, bounds, items, .. }) => {
1005 let is_const_trait =
1006 attr::find_by_name(&item.attrs, sym::const_trait).map(|attr| attr.span);
1007 self.with_in_trait(item.span, is_const_trait, |this| {
1008 if *is_auto == IsAuto::Yes {
1009 this.deny_generic_params(generics, item.ident.span);
1011 this.deny_super_traits(bounds, item.ident.span);
1012 this.deny_where_clause(&generics.where_clause, item.ident.span);
1013 this.deny_items(items, item.ident.span);
1014 }
1015
1016 this.visit_vis(&item.vis);
1019 this.visit_ident(&item.ident);
1020 let disallowed = is_const_trait
1021 .is_none()
1022 .then(|| TildeConstReason::Trait { span: item.span });
1023 this.with_tilde_const(disallowed, |this| {
1024 this.visit_generics(generics);
1025 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits)
1026 });
1027 walk_list!(this, visit_assoc_item, items, AssocCtxt::Trait);
1028 });
1029 walk_list!(self, visit_attribute, &item.attrs);
1030 return; }
1032 ItemKind::Mod(safety, mod_kind) => {
1033 if let &Safety::Unsafe(span) = safety {
1034 self.dcx().emit_err(errors::UnsafeItem { span, kind: "module" });
1035 }
1036 if !matches!(mod_kind, ModKind::Loaded(_, Inline::Yes, _, _))
1038 && !attr::contains_name(&item.attrs, sym::path)
1039 {
1040 self.check_mod_file_item_asciionly(item.ident);
1041 }
1042 }
1043 ItemKind::Struct(vdata, generics) => match vdata {
1044 VariantData::Struct { fields, .. } => {
1045 self.visit_vis(&item.vis);
1046 self.visit_ident(&item.ident);
1047 self.visit_generics(generics);
1048 walk_list!(self, visit_struct_field_def, fields);
1050 walk_list!(self, visit_attribute, &item.attrs);
1051 return;
1052 }
1053 _ => {}
1054 },
1055 ItemKind::Union(vdata, generics) => {
1056 if vdata.fields().is_empty() {
1057 self.dcx().emit_err(errors::FieldlessUnion { span: item.span });
1058 }
1059 match vdata {
1060 VariantData::Struct { fields, .. } => {
1061 self.visit_vis(&item.vis);
1062 self.visit_ident(&item.ident);
1063 self.visit_generics(generics);
1064 walk_list!(self, visit_struct_field_def, fields);
1066 walk_list!(self, visit_attribute, &item.attrs);
1067 return;
1068 }
1069 _ => {}
1070 }
1071 }
1072 ItemKind::Const(box ConstItem { defaultness, expr, .. }) => {
1073 self.check_defaultness(item.span, *defaultness);
1074 if expr.is_none() {
1075 self.dcx().emit_err(errors::ConstWithoutBody {
1076 span: item.span,
1077 replace_span: self.ending_semi_or_hi(item.span),
1078 });
1079 }
1080 }
1081 ItemKind::Static(box StaticItem { expr, safety, .. }) => {
1082 self.check_item_safety(item.span, *safety);
1083 if matches!(safety, Safety::Unsafe(_)) {
1084 self.dcx().emit_err(errors::UnsafeStatic { span: item.span });
1085 }
1086
1087 if expr.is_none() {
1088 self.dcx().emit_err(errors::StaticWithoutBody {
1089 span: item.span,
1090 replace_span: self.ending_semi_or_hi(item.span),
1091 });
1092 }
1093 }
1094 ItemKind::TyAlias(
1095 ty_alias @ box TyAlias { defaultness, bounds, where_clauses, ty, .. },
1096 ) => {
1097 self.check_defaultness(item.span, *defaultness);
1098 if ty.is_none() {
1099 self.dcx().emit_err(errors::TyAliasWithoutBody {
1100 span: item.span,
1101 replace_span: self.ending_semi_or_hi(item.span),
1102 });
1103 }
1104 self.check_type_no_bounds(bounds, "this context");
1105
1106 if self.features.lazy_type_alias() {
1107 if let Err(err) = self.check_type_alias_where_clause_location(ty_alias) {
1108 self.dcx().emit_err(err);
1109 }
1110 } else if where_clauses.after.has_where_token {
1111 self.dcx().emit_err(errors::WhereClauseAfterTypeAlias {
1112 span: where_clauses.after.span,
1113 help: self.sess.is_nightly_build(),
1114 });
1115 }
1116 }
1117 _ => {}
1118 }
1119
1120 visit::walk_item(self, item);
1121 }
1122
1123 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
1124 match &fi.kind {
1125 ForeignItemKind::Fn(box Fn { defaultness, sig, body, .. }) => {
1126 self.check_defaultness(fi.span, *defaultness);
1127 self.check_foreign_fn_bodyless(fi.ident, body.as_deref());
1128 self.check_foreign_fn_headerless(sig.header);
1129 self.check_foreign_item_ascii_only(fi.ident);
1130 }
1131 ForeignItemKind::TyAlias(box TyAlias {
1132 defaultness,
1133 generics,
1134 where_clauses,
1135 bounds,
1136 ty,
1137 ..
1138 }) => {
1139 self.check_defaultness(fi.span, *defaultness);
1140 self.check_foreign_kind_bodyless(fi.ident, "type", ty.as_ref().map(|b| b.span));
1141 self.check_type_no_bounds(bounds, "`extern` blocks");
1142 self.check_foreign_ty_genericless(generics, where_clauses);
1143 self.check_foreign_item_ascii_only(fi.ident);
1144 }
1145 ForeignItemKind::Static(box StaticItem { expr, safety, .. }) => {
1146 self.check_item_safety(fi.span, *safety);
1147 self.check_foreign_kind_bodyless(fi.ident, "static", expr.as_ref().map(|b| b.span));
1148 self.check_foreign_item_ascii_only(fi.ident);
1149 }
1150 ForeignItemKind::MacCall(..) => {}
1151 }
1152
1153 visit::walk_item(self, fi)
1154 }
1155
1156 fn visit_generic_args(&mut self, generic_args: &'a GenericArgs) {
1158 match generic_args {
1159 GenericArgs::AngleBracketed(data) => {
1160 self.check_generic_args_before_constraints(data);
1161
1162 for arg in &data.args {
1163 match arg {
1164 AngleBracketedArg::Arg(arg) => self.visit_generic_arg(arg),
1165 AngleBracketedArg::Constraint(constraint) => {
1168 self.with_impl_trait(None, |this| {
1169 this.visit_assoc_item_constraint(constraint);
1170 });
1171 }
1172 }
1173 }
1174 }
1175 GenericArgs::Parenthesized(data) => {
1176 walk_list!(self, visit_ty, &data.inputs);
1177 if let FnRetTy::Ty(ty) = &data.output {
1178 self.with_impl_trait(None, |this| this.visit_ty(ty));
1181 }
1182 }
1183 GenericArgs::ParenthesizedElided(_span) => {}
1184 }
1185 }
1186
1187 fn visit_generics(&mut self, generics: &'a Generics) {
1188 let mut prev_param_default = None;
1189 for param in &generics.params {
1190 match param.kind {
1191 GenericParamKind::Lifetime => (),
1192 GenericParamKind::Type { default: Some(_), .. }
1193 | GenericParamKind::Const { default: Some(_), .. } => {
1194 prev_param_default = Some(param.ident.span);
1195 }
1196 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1197 if let Some(span) = prev_param_default {
1198 self.dcx().emit_err(errors::GenericDefaultTrailing { span });
1199 break;
1200 }
1201 }
1202 }
1203 }
1204
1205 validate_generic_param_order(self.dcx(), &generics.params, generics.span);
1206
1207 for predicate in &generics.where_clause.predicates {
1208 let span = predicate.span;
1209 if let WherePredicateKind::EqPredicate(predicate) = &predicate.kind {
1210 deny_equality_constraints(self, predicate, span, generics);
1211 }
1212 }
1213 walk_list!(self, visit_generic_param, &generics.params);
1214 for predicate in &generics.where_clause.predicates {
1215 match &predicate.kind {
1216 WherePredicateKind::BoundPredicate(bound_pred) => {
1217 if !bound_pred.bound_generic_params.is_empty() {
1223 for bound in &bound_pred.bounds {
1224 match bound {
1225 GenericBound::Trait(t) => {
1226 if !t.bound_generic_params.is_empty() {
1227 self.dcx()
1228 .emit_err(errors::NestedLifetimes { span: t.span });
1229 }
1230 }
1231 GenericBound::Outlives(_) => {}
1232 GenericBound::Use(..) => {}
1233 }
1234 }
1235 }
1236 }
1237 _ => {}
1238 }
1239 self.visit_where_predicate(predicate);
1240 }
1241 }
1242
1243 fn visit_param_bound(&mut self, bound: &'a GenericBound, ctxt: BoundKind) {
1244 match bound {
1245 GenericBound::Trait(trait_ref) => {
1246 match (ctxt, trait_ref.modifiers.constness, trait_ref.modifiers.polarity) {
1247 (BoundKind::SuperTraits, BoundConstness::Never, BoundPolarity::Maybe(_))
1248 if !self.features.more_maybe_bounds() =>
1249 {
1250 self.sess
1251 .create_feature_err(
1252 errors::OptionalTraitSupertrait {
1253 span: trait_ref.span,
1254 path_str: pprust::path_to_string(&trait_ref.trait_ref.path),
1255 },
1256 sym::more_maybe_bounds,
1257 )
1258 .emit();
1259 }
1260 (BoundKind::TraitObject, BoundConstness::Never, BoundPolarity::Maybe(_))
1261 if !self.features.more_maybe_bounds() =>
1262 {
1263 self.sess
1264 .create_feature_err(
1265 errors::OptionalTraitObject { span: trait_ref.span },
1266 sym::more_maybe_bounds,
1267 )
1268 .emit();
1269 }
1270 (
1271 BoundKind::TraitObject,
1272 BoundConstness::Always(_),
1273 BoundPolarity::Positive,
1274 ) => {
1275 self.dcx().emit_err(errors::ConstBoundTraitObject { span: trait_ref.span });
1276 }
1277 (_, BoundConstness::Maybe(span), BoundPolarity::Positive)
1278 if let Some(reason) = self.disallow_tilde_const =>
1279 {
1280 self.dcx().emit_err(errors::TildeConstDisallowed { span, reason });
1281 }
1282 _ => {}
1283 }
1284
1285 if let BoundPolarity::Negative(_) = trait_ref.modifiers.polarity
1287 && let Some(segment) = trait_ref.trait_ref.path.segments.last()
1288 {
1289 match segment.args.as_deref() {
1290 Some(ast::GenericArgs::AngleBracketed(args)) => {
1291 for arg in &args.args {
1292 if let ast::AngleBracketedArg::Constraint(constraint) = arg {
1293 self.dcx().emit_err(errors::ConstraintOnNegativeBound {
1294 span: constraint.span,
1295 });
1296 }
1297 }
1298 }
1299 Some(ast::GenericArgs::Parenthesized(args)) => {
1301 self.dcx().emit_err(errors::NegativeBoundWithParentheticalNotation {
1302 span: args.span,
1303 });
1304 }
1305 Some(ast::GenericArgs::ParenthesizedElided(_)) | None => {}
1306 }
1307 }
1308 }
1309 GenericBound::Outlives(_) => {}
1310 GenericBound::Use(_, span) => match ctxt {
1311 BoundKind::Impl => {}
1312 BoundKind::Bound | BoundKind::TraitObject | BoundKind::SuperTraits => {
1313 self.dcx().emit_err(errors::PreciseCapturingNotAllowedHere {
1314 loc: ctxt.descr(),
1315 span: *span,
1316 });
1317 }
1318 },
1319 }
1320
1321 visit::walk_param_bound(self, bound)
1322 }
1323
1324 fn visit_fn(&mut self, fk: FnKind<'a>, span: Span, id: NodeId) {
1325 let self_semantic = match fk.ctxt() {
1327 Some(FnCtxt::Assoc(_)) => SelfSemantic::Yes,
1328 _ => SelfSemantic::No,
1329 };
1330 self.check_fn_decl(fk.decl(), self_semantic);
1331
1332 if let Some(&FnHeader { safety, .. }) = fk.header() {
1333 self.check_item_safety(span, safety);
1334 }
1335
1336 self.check_c_variadic_type(fk);
1337
1338 if let Some(&FnHeader {
1340 constness: Const::Yes(const_span),
1341 coroutine_kind: Some(coroutine_kind),
1342 ..
1343 }) = fk.header()
1344 {
1345 self.dcx().emit_err(errors::ConstAndCoroutine {
1346 spans: vec![coroutine_kind.span(), const_span],
1347 const_span,
1348 coroutine_span: coroutine_kind.span(),
1349 coroutine_kind: coroutine_kind.as_str(),
1350 span,
1351 });
1352 }
1353
1354 if let FnKind::Fn(
1355 _,
1356 _,
1357 _,
1358 Fn {
1359 sig: FnSig { header: FnHeader { ext: Extern::Implicit(extern_span), .. }, .. },
1360 ..
1361 },
1362 ) = fk
1363 {
1364 self.maybe_lint_missing_abi(*extern_span, id);
1365 }
1366
1367 if let FnKind::Fn(ctxt, _, _, Fn { body: None, sig, .. }) = fk {
1369 Self::check_decl_no_pat(&sig.decl, |span, ident, mut_ident| {
1370 if mut_ident && matches!(ctxt, FnCtxt::Assoc(_)) {
1371 if let Some(ident) = ident {
1372 self.lint_buffer.buffer_lint(
1373 PATTERNS_IN_FNS_WITHOUT_BODY,
1374 id,
1375 span,
1376 BuiltinLintDiag::PatternsInFnsWithoutBody {
1377 span,
1378 ident,
1379 is_foreign: matches!(ctxt, FnCtxt::Foreign),
1380 },
1381 )
1382 }
1383 } else {
1384 match ctxt {
1385 FnCtxt::Foreign => self.dcx().emit_err(errors::PatternInForeign { span }),
1386 _ => self.dcx().emit_err(errors::PatternInBodiless { span }),
1387 };
1388 }
1389 });
1390 }
1391
1392 let tilde_const_allowed =
1393 matches!(fk.header(), Some(FnHeader { constness: ast::Const::Yes(_), .. }))
1394 || matches!(fk.ctxt(), Some(FnCtxt::Assoc(_)))
1395 && self
1396 .outer_trait_or_trait_impl
1397 .as_ref()
1398 .and_then(TraitOrTraitImpl::constness)
1399 .is_some();
1400
1401 let disallowed = (!tilde_const_allowed).then(|| match fk {
1402 FnKind::Fn(_, ident, _, _) => TildeConstReason::Function { ident: ident.span },
1403 FnKind::Closure(..) => TildeConstReason::Closure,
1404 });
1405 self.with_tilde_const(disallowed, |this| visit::walk_fn(this, fk));
1406 }
1407
1408 fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
1409 if attr::contains_name(&item.attrs, sym::no_mangle) {
1410 self.check_nomangle_item_asciionly(item.ident, item.span);
1411 }
1412
1413 if ctxt == AssocCtxt::Trait || self.outer_trait_or_trait_impl.is_none() {
1414 self.check_defaultness(item.span, item.kind.defaultness());
1415 }
1416
1417 if ctxt == AssocCtxt::Impl {
1418 match &item.kind {
1419 AssocItemKind::Const(box ConstItem { expr: None, .. }) => {
1420 self.dcx().emit_err(errors::AssocConstWithoutBody {
1421 span: item.span,
1422 replace_span: self.ending_semi_or_hi(item.span),
1423 });
1424 }
1425 AssocItemKind::Fn(box Fn { body, .. }) => {
1426 if body.is_none() {
1427 self.dcx().emit_err(errors::AssocFnWithoutBody {
1428 span: item.span,
1429 replace_span: self.ending_semi_or_hi(item.span),
1430 });
1431 }
1432 }
1433 AssocItemKind::Type(box TyAlias { bounds, ty, .. }) => {
1434 if ty.is_none() {
1435 self.dcx().emit_err(errors::AssocTypeWithoutBody {
1436 span: item.span,
1437 replace_span: self.ending_semi_or_hi(item.span),
1438 });
1439 }
1440 self.check_type_no_bounds(bounds, "`impl`s");
1441 }
1442 _ => {}
1443 }
1444 }
1445
1446 if let AssocItemKind::Type(ty_alias) = &item.kind
1447 && let Err(err) = self.check_type_alias_where_clause_location(ty_alias)
1448 {
1449 let sugg = match err.sugg {
1450 errors::WhereClauseBeforeTypeAliasSugg::Remove { .. } => None,
1451 errors::WhereClauseBeforeTypeAliasSugg::Move { snippet, right, .. } => {
1452 Some((right, snippet))
1453 }
1454 };
1455 self.lint_buffer.buffer_lint(
1456 DEPRECATED_WHERE_CLAUSE_LOCATION,
1457 item.id,
1458 err.span,
1459 BuiltinLintDiag::DeprecatedWhereclauseLocation(err.span, sugg),
1460 );
1461 }
1462
1463 if let Some(parent) = &self.outer_trait_or_trait_impl {
1464 self.visibility_not_permitted(&item.vis, errors::VisibilityNotPermittedNote::TraitImpl);
1465 if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
1466 self.check_trait_fn_not_const(sig.header.constness, parent);
1467 }
1468 }
1469
1470 if let AssocItemKind::Const(..) = item.kind {
1471 self.check_item_named(item.ident, "const");
1472 }
1473
1474 let parent_is_const =
1475 self.outer_trait_or_trait_impl.as_ref().and_then(TraitOrTraitImpl::constness).is_some();
1476
1477 match &item.kind {
1478 AssocItemKind::Fn(func)
1479 if parent_is_const
1480 || ctxt == AssocCtxt::Trait
1481 || matches!(func.sig.header.constness, Const::Yes(_)) =>
1482 {
1483 self.visit_vis(&item.vis);
1484 self.visit_ident(&item.ident);
1485 let kind = FnKind::Fn(FnCtxt::Assoc(ctxt), &item.ident, &item.vis, &*func);
1486 walk_list!(self, visit_attribute, &item.attrs);
1487 self.visit_fn(kind, item.span, item.id);
1488 }
1489 AssocItemKind::Type(_) => {
1490 let disallowed = (!parent_is_const).then(|| match self.outer_trait_or_trait_impl {
1491 Some(TraitOrTraitImpl::Trait { .. }) => {
1492 TildeConstReason::TraitAssocTy { span: item.span }
1493 }
1494 Some(TraitOrTraitImpl::TraitImpl { .. }) => {
1495 TildeConstReason::TraitImplAssocTy { span: item.span }
1496 }
1497 None => TildeConstReason::InherentAssocTy { span: item.span },
1498 });
1499 self.with_tilde_const(disallowed, |this| {
1500 this.with_in_trait_impl(None, |this| visit::walk_assoc_item(this, item, ctxt))
1501 })
1502 }
1503 _ => self.with_in_trait_impl(None, |this| visit::walk_assoc_item(this, item, ctxt)),
1504 }
1505 }
1506}
1507
1508fn deny_equality_constraints(
1511 this: &AstValidator<'_>,
1512 predicate: &WhereEqPredicate,
1513 predicate_span: Span,
1514 generics: &Generics,
1515) {
1516 let mut err = errors::EqualityInWhere { span: predicate_span, assoc: None, assoc2: None };
1517
1518 if let TyKind::Path(Some(qself), full_path) = &predicate.lhs_ty.kind
1520 && let TyKind::Path(None, path) = &qself.ty.kind
1521 && let [PathSegment { ident, args: None, .. }] = &path.segments[..]
1522 {
1523 for param in &generics.params {
1524 if param.ident == *ident
1525 && let [PathSegment { ident, args, .. }] = &full_path.segments[qself.position..]
1526 {
1527 let mut assoc_path = full_path.clone();
1529 assoc_path.segments.pop();
1531 let len = assoc_path.segments.len() - 1;
1532 let gen_args = args.as_deref().cloned();
1533 let arg = AngleBracketedArg::Constraint(AssocItemConstraint {
1535 id: rustc_ast::node_id::DUMMY_NODE_ID,
1536 ident: *ident,
1537 gen_args,
1538 kind: AssocItemConstraintKind::Equality {
1539 term: predicate.rhs_ty.clone().into(),
1540 },
1541 span: ident.span,
1542 });
1543 match &mut assoc_path.segments[len].args {
1545 Some(args) => match args.deref_mut() {
1546 GenericArgs::Parenthesized(_) | GenericArgs::ParenthesizedElided(..) => {
1547 continue;
1548 }
1549 GenericArgs::AngleBracketed(args) => {
1550 args.args.push(arg);
1551 }
1552 },
1553 empty_args => {
1554 *empty_args = Some(
1555 AngleBracketedArgs { span: ident.span, args: thin_vec![arg] }.into(),
1556 );
1557 }
1558 }
1559 err.assoc = Some(errors::AssociatedSuggestion {
1560 span: predicate_span,
1561 ident: *ident,
1562 param: param.ident,
1563 path: pprust::path_to_string(&assoc_path),
1564 })
1565 }
1566 }
1567 }
1568
1569 let mut suggest =
1570 |poly: &PolyTraitRef, potential_assoc: &PathSegment, predicate: &WhereEqPredicate| {
1571 if let [trait_segment] = &poly.trait_ref.path.segments[..] {
1572 let assoc = pprust::path_to_string(&ast::Path::from_ident(potential_assoc.ident));
1573 let ty = pprust::ty_to_string(&predicate.rhs_ty);
1574 let (args, span) = match &trait_segment.args {
1575 Some(args) => match args.deref() {
1576 ast::GenericArgs::AngleBracketed(args) => {
1577 let Some(arg) = args.args.last() else {
1578 return;
1579 };
1580 (format!(", {assoc} = {ty}"), arg.span().shrink_to_hi())
1581 }
1582 _ => return,
1583 },
1584 None => (format!("<{assoc} = {ty}>"), trait_segment.span().shrink_to_hi()),
1585 };
1586 let removal_span = if generics.where_clause.predicates.len() == 1 {
1587 generics.where_clause.span
1589 } else {
1590 let mut span = predicate_span;
1591 let mut prev: Option<Span> = None;
1592 let mut preds = generics.where_clause.predicates.iter().peekable();
1593 while let Some(pred) = preds.next() {
1595 if let WherePredicateKind::EqPredicate(_) = pred.kind
1596 && pred.span == predicate_span
1597 {
1598 if let Some(next) = preds.peek() {
1599 span = span.with_hi(next.span.lo());
1601 } else if let Some(prev) = prev {
1602 span = span.with_lo(prev.hi());
1604 }
1605 }
1606 prev = Some(pred.span);
1607 }
1608 span
1609 };
1610 err.assoc2 = Some(errors::AssociatedSuggestion2 {
1611 span,
1612 args,
1613 predicate: removal_span,
1614 trait_segment: trait_segment.ident,
1615 potential_assoc: potential_assoc.ident,
1616 });
1617 }
1618 };
1619
1620 if let TyKind::Path(None, full_path) = &predicate.lhs_ty.kind {
1621 for bounds in generics.params.iter().map(|p| &p.bounds).chain(
1623 generics.where_clause.predicates.iter().filter_map(|pred| match &pred.kind {
1624 WherePredicateKind::BoundPredicate(p) => Some(&p.bounds),
1625 _ => None,
1626 }),
1627 ) {
1628 for bound in bounds {
1629 if let GenericBound::Trait(poly) = bound
1630 && poly.modifiers == TraitBoundModifiers::NONE
1631 {
1632 if full_path.segments[..full_path.segments.len() - 1]
1633 .iter()
1634 .map(|segment| segment.ident.name)
1635 .zip(poly.trait_ref.path.segments.iter().map(|segment| segment.ident.name))
1636 .all(|(a, b)| a == b)
1637 && let Some(potential_assoc) = full_path.segments.iter().last()
1638 {
1639 suggest(poly, potential_assoc, predicate);
1640 }
1641 }
1642 }
1643 }
1644 if let [potential_param, potential_assoc] = &full_path.segments[..] {
1646 for (ident, bounds) in generics.params.iter().map(|p| (p.ident, &p.bounds)).chain(
1647 generics.where_clause.predicates.iter().filter_map(|pred| match &pred.kind {
1648 WherePredicateKind::BoundPredicate(p)
1649 if let ast::TyKind::Path(None, path) = &p.bounded_ty.kind
1650 && let [segment] = &path.segments[..] =>
1651 {
1652 Some((segment.ident, &p.bounds))
1653 }
1654 _ => None,
1655 }),
1656 ) {
1657 if ident == potential_param.ident {
1658 for bound in bounds {
1659 if let ast::GenericBound::Trait(poly) = bound
1660 && poly.modifiers == TraitBoundModifiers::NONE
1661 {
1662 suggest(poly, potential_assoc, predicate);
1663 }
1664 }
1665 }
1666 }
1667 }
1668 }
1669 this.dcx().emit_err(err);
1670}
1671
1672pub fn check_crate(
1673 sess: &Session,
1674 features: &Features,
1675 krate: &Crate,
1676 lints: &mut LintBuffer,
1677) -> bool {
1678 let mut validator = AstValidator {
1679 sess,
1680 features,
1681 extern_mod: None,
1682 outer_trait_or_trait_impl: None,
1683 has_proc_macro_decls: false,
1684 outer_impl_trait: None,
1685 disallow_tilde_const: Some(TildeConstReason::Item),
1686 extern_mod_safety: None,
1687 lint_buffer: lints,
1688 };
1689 visit::walk_crate(&mut validator, krate);
1690
1691 validator.has_proc_macro_decls
1692}