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