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_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_trace,
338 sym::cfg_attr_trace,
339 sym::deny,
340 sym::expect,
341 sym::forbid,
342 sym::warn,
343 ];
344 !attr.has_any_name(&arr) && rustc_attr_parsing::is_builtin_attr(*attr)
345 })
346 .for_each(|attr| {
347 if attr.is_doc_comment() {
348 self.dcx().emit_err(errors::FnParamDocComment { span: attr.span });
349 } else {
350 self.dcx().emit_err(errors::FnParamForbiddenAttr { span: attr.span });
351 }
352 });
353 }
354
355 fn check_decl_self_param(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) {
356 if let (SelfSemantic::No, [param, ..]) = (self_semantic, &*fn_decl.inputs) {
357 if param.is_self() {
358 self.dcx().emit_err(errors::FnParamForbiddenSelf { span: param.span });
359 }
360 }
361 }
362
363 fn check_extern_fn_signature(&self, abi: ExternAbi, ctxt: FnCtxt, ident: &Ident, sig: &FnSig) {
365 match AbiMap::from_target(&self.sess.target).canonize_abi(abi, false) {
366 AbiMapping::Direct(canon_abi) | AbiMapping::Deprecated(canon_abi) => {
367 match canon_abi {
368 CanonAbi::C
369 | CanonAbi::Rust
370 | CanonAbi::RustCold
371 | CanonAbi::Arm(_)
372 | CanonAbi::GpuKernel
373 | CanonAbi::X86(_) => { }
374
375 CanonAbi::Custom => {
376 self.reject_safe_fn(abi, ctxt, sig);
378
379 self.reject_coroutine(abi, sig);
381
382 self.reject_params_or_return(abi, ident, sig);
384 }
385
386 CanonAbi::Interrupt(interrupt_kind) => {
387 self.reject_coroutine(abi, sig);
389
390 if let InterruptKind::X86 = interrupt_kind {
391 if let FnRetTy::Ty(ref ret_ty) = sig.decl.output {
394 self.dcx().emit_err(errors::AbiMustNotHaveReturnType {
395 span: ret_ty.span,
396 abi,
397 });
398 }
399 } else {
400 self.reject_params_or_return(abi, ident, sig);
402 }
403 }
404 }
405 }
406 AbiMapping::Invalid => { }
407 }
408 }
409
410 fn reject_safe_fn(&self, abi: ExternAbi, ctxt: FnCtxt, sig: &FnSig) {
411 let dcx = self.dcx();
412
413 match sig.header.safety {
414 Safety::Unsafe(_) => { }
415 Safety::Safe(safe_span) => {
416 let source_map = self.sess.psess.source_map();
417 let safe_span = source_map.span_until_non_whitespace(safe_span.to(sig.span));
418 dcx.emit_err(errors::AbiCustomSafeForeignFunction { span: sig.span, safe_span });
419 }
420 Safety::Default => match ctxt {
421 FnCtxt::Foreign => { }
422 FnCtxt::Free | FnCtxt::Assoc(_) => {
423 dcx.emit_err(errors::AbiCustomSafeFunction {
424 span: sig.span,
425 abi,
426 unsafe_span: sig.span.shrink_to_lo(),
427 });
428 }
429 },
430 }
431 }
432
433 fn reject_coroutine(&self, abi: ExternAbi, sig: &FnSig) {
434 if let Some(coroutine_kind) = sig.header.coroutine_kind {
435 let coroutine_kind_span = self
436 .sess
437 .psess
438 .source_map()
439 .span_until_non_whitespace(coroutine_kind.span().to(sig.span));
440
441 self.dcx().emit_err(errors::AbiCannotBeCoroutine {
442 span: sig.span,
443 abi,
444 coroutine_kind_span,
445 coroutine_kind_str: coroutine_kind.as_str(),
446 });
447 }
448 }
449
450 fn reject_params_or_return(&self, abi: ExternAbi, ident: &Ident, sig: &FnSig) {
451 let mut spans: Vec<_> = sig.decl.inputs.iter().map(|p| p.span).collect();
452 if let FnRetTy::Ty(ref ret_ty) = sig.decl.output {
453 spans.push(ret_ty.span);
454 }
455
456 if !spans.is_empty() {
457 let header_span = sig.header.span().unwrap_or(sig.span.shrink_to_lo());
458 let suggestion_span = header_span.shrink_to_hi().to(sig.decl.output.span());
459 let padding = if header_span.is_empty() { "" } else { " " };
460
461 self.dcx().emit_err(errors::AbiMustNotHaveParametersOrReturnType {
462 spans,
463 symbol: ident.name,
464 suggestion_span,
465 padding,
466 abi,
467 });
468 }
469 }
470
471 fn check_item_safety(&self, span: Span, safety: Safety) {
477 match self.extern_mod_safety {
478 Some(extern_safety) => {
479 if matches!(safety, Safety::Unsafe(_) | Safety::Safe(_))
480 && extern_safety == Safety::Default
481 {
482 self.dcx().emit_err(errors::InvalidSafetyOnExtern {
483 item_span: span,
484 block: Some(self.current_extern_span().shrink_to_lo()),
485 });
486 }
487 }
488 None => {
489 if matches!(safety, Safety::Safe(_)) {
490 self.dcx().emit_err(errors::InvalidSafetyOnItem { span });
491 }
492 }
493 }
494 }
495
496 fn check_fn_ptr_safety(&self, span: Span, safety: Safety) {
497 if matches!(safety, Safety::Safe(_)) {
498 self.dcx().emit_err(errors::InvalidSafetyOnFnPtr { span });
499 }
500 }
501
502 fn check_defaultness(&self, span: Span, defaultness: Defaultness) {
503 if let Defaultness::Default(def_span) = defaultness {
504 let span = self.sess.source_map().guess_head_span(span);
505 self.dcx().emit_err(errors::ForbiddenDefault { span, def_span });
506 }
507 }
508
509 fn ending_semi_or_hi(&self, sp: Span) -> Span {
512 let source_map = self.sess.source_map();
513 let end = source_map.end_point(sp);
514
515 if source_map.span_to_snippet(end).is_ok_and(|s| s == ";") {
516 end
517 } else {
518 sp.shrink_to_hi()
519 }
520 }
521
522 fn check_type_no_bounds(&self, bounds: &[GenericBound], ctx: &str) {
523 let span = match bounds {
524 [] => return,
525 [b0] => b0.span(),
526 [b0, .., bl] => b0.span().to(bl.span()),
527 };
528 self.dcx().emit_err(errors::BoundInContext { span, ctx });
529 }
530
531 fn check_foreign_ty_genericless(
532 &self,
533 generics: &Generics,
534 where_clauses: &TyAliasWhereClauses,
535 ) {
536 let cannot_have = |span, descr, remove_descr| {
537 self.dcx().emit_err(errors::ExternTypesCannotHave {
538 span,
539 descr,
540 remove_descr,
541 block_span: self.current_extern_span(),
542 });
543 };
544
545 if !generics.params.is_empty() {
546 cannot_have(generics.span, "generic parameters", "generic parameters");
547 }
548
549 let check_where_clause = |where_clause: TyAliasWhereClause| {
550 if where_clause.has_where_token {
551 cannot_have(where_clause.span, "`where` clauses", "`where` clause");
552 }
553 };
554
555 check_where_clause(where_clauses.before);
556 check_where_clause(where_clauses.after);
557 }
558
559 fn check_foreign_kind_bodyless(&self, ident: Ident, kind: &str, body_span: Option<Span>) {
560 let Some(body_span) = body_span else {
561 return;
562 };
563 self.dcx().emit_err(errors::BodyInExtern {
564 span: ident.span,
565 body: body_span,
566 block: self.current_extern_span(),
567 kind,
568 });
569 }
570
571 fn check_foreign_fn_bodyless(&self, ident: Ident, body: Option<&Block>) {
573 let Some(body) = body else {
574 return;
575 };
576 self.dcx().emit_err(errors::FnBodyInExtern {
577 span: ident.span,
578 body: body.span,
579 block: self.current_extern_span(),
580 });
581 }
582
583 fn current_extern_span(&self) -> Span {
584 self.sess.source_map().guess_head_span(self.extern_mod_span.unwrap())
585 }
586
587 fn check_foreign_fn_headerless(
589 &self,
590 FnHeader { safety: _, coroutine_kind, constness, ext }: FnHeader,
592 ) {
593 let report_err = |span, kw| {
594 self.dcx().emit_err(errors::FnQualifierInExtern {
595 span,
596 kw,
597 block: self.current_extern_span(),
598 });
599 };
600 match coroutine_kind {
601 Some(kind) => report_err(kind.span(), kind.as_str()),
602 None => (),
603 }
604 match constness {
605 Const::Yes(span) => report_err(span, "const"),
606 Const::No => (),
607 }
608 match ext {
609 Extern::None => (),
610 Extern::Implicit(span) | Extern::Explicit(_, span) => report_err(span, "extern"),
611 }
612 }
613
614 fn check_foreign_item_ascii_only(&self, ident: Ident) {
616 if !ident.as_str().is_ascii() {
617 self.dcx().emit_err(errors::ExternItemAscii {
618 span: ident.span,
619 block: self.current_extern_span(),
620 });
621 }
622 }
623
624 fn check_c_variadic_type(&self, fk: FnKind<'a>) {
630 let variadic_spans: Vec<_> = fk
631 .decl()
632 .inputs
633 .iter()
634 .filter(|arg| matches!(arg.ty.kind, TyKind::CVarArgs))
635 .map(|arg| arg.span)
636 .collect();
637
638 if variadic_spans.is_empty() {
639 return;
640 }
641
642 if let Some(header) = fk.header()
643 && let Const::Yes(const_span) = header.constness
644 {
645 let mut spans = variadic_spans.clone();
646 spans.push(const_span);
647 self.dcx().emit_err(errors::ConstAndCVariadic {
648 spans,
649 const_span,
650 variadic_spans: variadic_spans.clone(),
651 });
652 }
653
654 match (fk.ctxt(), fk.header()) {
655 (Some(FnCtxt::Foreign), _) => return,
656 (Some(FnCtxt::Free), Some(header)) => match header.ext {
657 Extern::Explicit(StrLit { symbol_unescaped: sym::C, .. }, _)
658 | Extern::Explicit(StrLit { symbol_unescaped: sym::C_dash_unwind, .. }, _)
659 | Extern::Implicit(_)
660 if matches!(header.safety, Safety::Unsafe(_)) =>
661 {
662 return;
663 }
664 _ => {}
665 },
666 _ => {}
667 };
668
669 self.dcx().emit_err(errors::BadCVariadic { span: variadic_spans });
670 }
671
672 fn check_item_named(&self, ident: Ident, kind: &str) {
673 if ident.name != kw::Underscore {
674 return;
675 }
676 self.dcx().emit_err(errors::ItemUnderscore { span: ident.span, kind });
677 }
678
679 fn check_nomangle_item_asciionly(&self, ident: Ident, item_span: Span) {
680 if ident.name.as_str().is_ascii() {
681 return;
682 }
683 let span = self.sess.source_map().guess_head_span(item_span);
684 self.dcx().emit_err(errors::NoMangleAscii { span });
685 }
686
687 fn check_mod_file_item_asciionly(&self, ident: Ident) {
688 if ident.name.as_str().is_ascii() {
689 return;
690 }
691 self.dcx().emit_err(errors::ModuleNonAscii { span: ident.span, name: ident.name });
692 }
693
694 fn deny_generic_params(&self, generics: &Generics, ident_span: Span) {
695 if !generics.params.is_empty() {
696 self.dcx()
697 .emit_err(errors::AutoTraitGeneric { span: generics.span, ident: ident_span });
698 }
699 }
700
701 fn deny_super_traits(&self, bounds: &GenericBounds, ident: Span) {
702 if let [.., last] = &bounds[..] {
703 let span = bounds.iter().map(|b| b.span()).collect();
704 let removal = ident.shrink_to_hi().to(last.span());
705 self.dcx().emit_err(errors::AutoTraitBounds { span, removal, ident });
706 }
707 }
708
709 fn deny_where_clause(&self, where_clause: &WhereClause, ident: Span) {
710 if !where_clause.predicates.is_empty() {
711 self.dcx().emit_err(errors::AutoTraitBounds {
714 span: vec![where_clause.span],
715 removal: where_clause.span,
716 ident,
717 });
718 }
719 }
720
721 fn deny_items(&self, trait_items: &[Box<AssocItem>], ident_span: Span) {
722 if !trait_items.is_empty() {
723 let spans: Vec<_> = trait_items.iter().map(|i| i.kind.ident().unwrap().span).collect();
724 let total = trait_items.first().unwrap().span.to(trait_items.last().unwrap().span);
725 self.dcx().emit_err(errors::AutoTraitItems { spans, total, ident: ident_span });
726 }
727 }
728
729 fn correct_generic_order_suggestion(&self, data: &AngleBracketedArgs) -> String {
730 let lt_sugg = data.args.iter().filter_map(|arg| match arg {
732 AngleBracketedArg::Arg(lt @ GenericArg::Lifetime(_)) => {
733 Some(pprust::to_string(|s| s.print_generic_arg(lt)))
734 }
735 _ => None,
736 });
737 let args_sugg = data.args.iter().filter_map(|a| match a {
738 AngleBracketedArg::Arg(GenericArg::Lifetime(_)) | AngleBracketedArg::Constraint(_) => {
739 None
740 }
741 AngleBracketedArg::Arg(arg) => Some(pprust::to_string(|s| s.print_generic_arg(arg))),
742 });
743 let constraint_sugg = data.args.iter().filter_map(|a| match a {
745 AngleBracketedArg::Arg(_) => None,
746 AngleBracketedArg::Constraint(c) => {
747 Some(pprust::to_string(|s| s.print_assoc_item_constraint(c)))
748 }
749 });
750 format!(
751 "<{}>",
752 lt_sugg.chain(args_sugg).chain(constraint_sugg).collect::<Vec<String>>().join(", ")
753 )
754 }
755
756 fn check_generic_args_before_constraints(&self, data: &AngleBracketedArgs) {
758 if data.args.iter().is_partitioned(|arg| matches!(arg, AngleBracketedArg::Arg(_))) {
760 return;
761 }
762 let (constraint_spans, arg_spans): (Vec<Span>, Vec<Span>) =
764 data.args.iter().partition_map(|arg| match arg {
765 AngleBracketedArg::Constraint(c) => Either::Left(c.span),
766 AngleBracketedArg::Arg(a) => Either::Right(a.span()),
767 });
768 let args_len = arg_spans.len();
769 let constraint_len = constraint_spans.len();
770 self.dcx().emit_err(errors::ArgsBeforeConstraint {
772 arg_spans: arg_spans.clone(),
773 constraints: constraint_spans[0],
774 args: *arg_spans.iter().last().unwrap(),
775 data: data.span,
776 constraint_spans: errors::EmptyLabelManySpans(constraint_spans),
777 arg_spans2: errors::EmptyLabelManySpans(arg_spans),
778 suggestion: self.correct_generic_order_suggestion(data),
779 constraint_len,
780 args_len,
781 });
782 }
783
784 fn visit_ty_common(&mut self, ty: &'a Ty) {
785 match &ty.kind {
786 TyKind::FnPtr(bfty) => {
787 self.check_fn_ptr_safety(bfty.decl_span, bfty.safety);
788 self.check_fn_decl(&bfty.decl, SelfSemantic::No);
789 Self::check_decl_no_pat(&bfty.decl, |span, _, _| {
790 self.dcx().emit_err(errors::PatternFnPointer { span });
791 });
792 if let Extern::Implicit(extern_span) = bfty.ext {
793 self.handle_missing_abi(extern_span, ty.id);
794 }
795 }
796 TyKind::TraitObject(bounds, ..) => {
797 let mut any_lifetime_bounds = false;
798 for bound in bounds {
799 if let GenericBound::Outlives(lifetime) = bound {
800 if any_lifetime_bounds {
801 self.dcx()
802 .emit_err(errors::TraitObjectBound { span: lifetime.ident.span });
803 break;
804 }
805 any_lifetime_bounds = true;
806 }
807 }
808 }
809 TyKind::ImplTrait(_, bounds) => {
810 if let Some(outer_impl_trait_sp) = self.outer_impl_trait_span {
811 self.dcx().emit_err(errors::NestedImplTrait {
812 span: ty.span,
813 outer: outer_impl_trait_sp,
814 inner: ty.span,
815 });
816 }
817
818 if !bounds.iter().any(|b| matches!(b, GenericBound::Trait(..))) {
819 self.dcx().emit_err(errors::AtLeastOneTrait { span: ty.span });
820 }
821 }
822 _ => {}
823 }
824 }
825
826 fn handle_missing_abi(&mut self, span: Span, id: NodeId) {
827 if span.edition().at_least_edition_future() && self.features.explicit_extern_abis() {
830 self.dcx().emit_err(errors::MissingAbi { span });
831 } else if self
832 .sess
833 .source_map()
834 .span_to_snippet(span)
835 .is_ok_and(|snippet| !snippet.starts_with("#["))
836 {
837 self.lint_buffer.buffer_lint(
838 MISSING_ABI,
839 id,
840 span,
841 BuiltinLintDiag::MissingAbi(span, ExternAbi::FALLBACK),
842 )
843 }
844 }
845
846 fn visit_attrs_vis(&mut self, attrs: &'a AttrVec, vis: &'a Visibility) {
848 walk_list!(self, visit_attribute, attrs);
849 self.visit_vis(vis);
850 }
851
852 fn visit_attrs_vis_ident(&mut self, attrs: &'a AttrVec, vis: &'a Visibility, ident: &'a Ident) {
854 walk_list!(self, visit_attribute, attrs);
855 self.visit_vis(vis);
856 self.visit_ident(ident);
857 }
858}
859
860fn validate_generic_param_order(dcx: DiagCtxtHandle<'_>, generics: &[GenericParam], span: Span) {
863 let mut max_param: Option<ParamKindOrd> = None;
864 let mut out_of_order = FxIndexMap::default();
865 let mut param_idents = Vec::with_capacity(generics.len());
866
867 for (idx, param) in generics.iter().enumerate() {
868 let ident = param.ident;
869 let (kind, bounds, span) = (¶m.kind, ¶m.bounds, ident.span);
870 let (ord_kind, ident) = match ¶m.kind {
871 GenericParamKind::Lifetime => (ParamKindOrd::Lifetime, ident.to_string()),
872 GenericParamKind::Type { .. } => (ParamKindOrd::TypeOrConst, ident.to_string()),
873 GenericParamKind::Const { ty, .. } => {
874 let ty = pprust::ty_to_string(ty);
875 (ParamKindOrd::TypeOrConst, format!("const {ident}: {ty}"))
876 }
877 };
878 param_idents.push((kind, ord_kind, bounds, idx, ident));
879 match max_param {
880 Some(max_param) if max_param > ord_kind => {
881 let entry = out_of_order.entry(ord_kind).or_insert((max_param, vec![]));
882 entry.1.push(span);
883 }
884 Some(_) | None => max_param = Some(ord_kind),
885 };
886 }
887
888 if !out_of_order.is_empty() {
889 let mut ordered_params = "<".to_string();
890 param_idents.sort_by_key(|&(_, po, _, i, _)| (po, i));
891 let mut first = true;
892 for (kind, _, bounds, _, ident) in param_idents {
893 if !first {
894 ordered_params += ", ";
895 }
896 ordered_params += &ident;
897
898 if !bounds.is_empty() {
899 ordered_params += ": ";
900 ordered_params += &pprust::bounds_to_string(bounds);
901 }
902
903 match kind {
904 GenericParamKind::Type { default: Some(default) } => {
905 ordered_params += " = ";
906 ordered_params += &pprust::ty_to_string(default);
907 }
908 GenericParamKind::Type { default: None } => (),
909 GenericParamKind::Lifetime => (),
910 GenericParamKind::Const { ty: _, span: _, default: Some(default) } => {
911 ordered_params += " = ";
912 ordered_params += &pprust::expr_to_string(&default.value);
913 }
914 GenericParamKind::Const { ty: _, span: _, default: None } => (),
915 }
916 first = false;
917 }
918
919 ordered_params += ">";
920
921 for (param_ord, (max_param, spans)) in &out_of_order {
922 dcx.emit_err(errors::OutOfOrderParams {
923 spans: spans.clone(),
924 sugg_span: span,
925 param_ord,
926 max_param,
927 ordered_params: &ordered_params,
928 });
929 }
930 }
931}
932
933impl<'a> Visitor<'a> for AstValidator<'a> {
934 fn visit_attribute(&mut self, attr: &Attribute) {
935 validate_attr::check_attr(&self.sess.psess, attr, self.lint_node_id);
936 }
937
938 fn visit_ty(&mut self, ty: &'a Ty) {
939 self.visit_ty_common(ty);
940 self.walk_ty(ty)
941 }
942
943 fn visit_item(&mut self, item: &'a Item) {
944 if item.attrs.iter().any(|attr| attr.is_proc_macro_attr()) {
945 self.has_proc_macro_decls = true;
946 }
947
948 let previous_lint_node_id = mem::replace(&mut self.lint_node_id, item.id);
949
950 if let Some(ident) = item.kind.ident()
951 && attr::contains_name(&item.attrs, sym::no_mangle)
952 {
953 self.check_nomangle_item_asciionly(ident, item.span);
954 }
955
956 match &item.kind {
957 ItemKind::Impl(Impl {
958 generics,
959 of_trait:
960 Some(box TraitImplHeader {
961 safety,
962 polarity,
963 defaultness: _,
964 constness,
965 trait_ref: t,
966 }),
967 self_ty,
968 items,
969 }) => {
970 self.visit_attrs_vis(&item.attrs, &item.vis);
971 self.visibility_not_permitted(
972 &item.vis,
973 errors::VisibilityNotPermittedNote::TraitImpl,
974 );
975 if let TyKind::Dummy = self_ty.kind {
976 self.dcx().emit_fatal(errors::ObsoleteAuto { span: item.span });
979 }
980 if let (&Safety::Unsafe(span), &ImplPolarity::Negative(sp)) = (safety, polarity) {
981 self.dcx().emit_err(errors::UnsafeNegativeImpl {
982 span: sp.to(t.path.span),
983 negative: sp,
984 r#unsafe: span,
985 });
986 }
987
988 let disallowed = matches!(constness, Const::No)
989 .then(|| TildeConstReason::TraitImpl { span: item.span });
990 self.with_tilde_const(disallowed, |this| this.visit_generics(generics));
991 self.visit_trait_ref(t);
992 self.visit_ty(self_ty);
993
994 self.with_in_trait_impl(Some((*constness, *polarity, t)), |this| {
995 walk_list!(this, visit_assoc_item, items, AssocCtxt::Impl { of_trait: true });
996 });
997 }
998 ItemKind::Impl(Impl { generics, of_trait: None, self_ty, items }) => {
999 self.visit_attrs_vis(&item.attrs, &item.vis);
1000 self.visibility_not_permitted(
1001 &item.vis,
1002 errors::VisibilityNotPermittedNote::IndividualImplItems,
1003 );
1004
1005 self.with_tilde_const(Some(TildeConstReason::Impl { span: item.span }), |this| {
1006 this.visit_generics(generics)
1007 });
1008 self.visit_ty(self_ty);
1009 self.with_in_trait_impl(None, |this| {
1010 walk_list!(this, visit_assoc_item, items, AssocCtxt::Impl { of_trait: false });
1011 });
1012 }
1013 ItemKind::Fn(
1014 func @ box Fn {
1015 defaultness,
1016 ident,
1017 generics: _,
1018 sig,
1019 contract: _,
1020 body,
1021 define_opaque: _,
1022 },
1023 ) => {
1024 self.visit_attrs_vis_ident(&item.attrs, &item.vis, ident);
1025 self.check_defaultness(item.span, *defaultness);
1026
1027 let is_intrinsic = item.attrs.iter().any(|a| a.has_name(sym::rustc_intrinsic));
1028 if body.is_none() && !is_intrinsic && !self.is_sdylib_interface {
1029 self.dcx().emit_err(errors::FnWithoutBody {
1030 span: item.span,
1031 replace_span: self.ending_semi_or_hi(item.span),
1032 extern_block_suggestion: match sig.header.ext {
1033 Extern::None => None,
1034 Extern::Implicit(start_span) => {
1035 Some(errors::ExternBlockSuggestion::Implicit {
1036 start_span,
1037 end_span: item.span.shrink_to_hi(),
1038 })
1039 }
1040 Extern::Explicit(abi, start_span) => {
1041 Some(errors::ExternBlockSuggestion::Explicit {
1042 start_span,
1043 end_span: item.span.shrink_to_hi(),
1044 abi: abi.symbol_unescaped,
1045 })
1046 }
1047 },
1048 });
1049 }
1050
1051 let kind = FnKind::Fn(FnCtxt::Free, &item.vis, &*func);
1052 self.visit_fn(kind, item.span, item.id);
1053 }
1054 ItemKind::ForeignMod(ForeignMod { extern_span, abi, safety, .. }) => {
1055 let old_item = mem::replace(&mut self.extern_mod_span, Some(item.span));
1056 self.visibility_not_permitted(
1057 &item.vis,
1058 errors::VisibilityNotPermittedNote::IndividualForeignItems,
1059 );
1060
1061 if &Safety::Default == safety {
1062 if item.span.at_least_rust_2024() {
1063 self.dcx().emit_err(errors::MissingUnsafeOnExtern { span: item.span });
1064 } else {
1065 self.lint_buffer.buffer_lint(
1066 MISSING_UNSAFE_ON_EXTERN,
1067 item.id,
1068 item.span,
1069 BuiltinLintDiag::MissingUnsafeOnExtern {
1070 suggestion: item.span.shrink_to_lo(),
1071 },
1072 );
1073 }
1074 }
1075
1076 if abi.is_none() {
1077 self.handle_missing_abi(*extern_span, item.id);
1078 }
1079
1080 let extern_abi = abi.and_then(|abi| ExternAbi::from_str(abi.symbol.as_str()).ok());
1081 self.with_in_extern_mod(*safety, extern_abi, |this| {
1082 visit::walk_item(this, item);
1083 });
1084 self.extern_mod_span = old_item;
1085 }
1086 ItemKind::Enum(_, _, def) => {
1087 for variant in &def.variants {
1088 self.visibility_not_permitted(
1089 &variant.vis,
1090 errors::VisibilityNotPermittedNote::EnumVariant,
1091 );
1092 for field in variant.data.fields() {
1093 self.visibility_not_permitted(
1094 &field.vis,
1095 errors::VisibilityNotPermittedNote::EnumVariant,
1096 );
1097 }
1098 }
1099 self.with_tilde_const(Some(TildeConstReason::Enum { span: item.span }), |this| {
1100 visit::walk_item(this, item)
1101 });
1102 }
1103 ItemKind::Trait(box Trait {
1104 constness,
1105 is_auto,
1106 generics,
1107 ident,
1108 bounds,
1109 items,
1110 ..
1111 }) => {
1112 self.visit_attrs_vis_ident(&item.attrs, &item.vis, ident);
1113 let alt_const_trait_span =
1115 attr::find_by_name(&item.attrs, sym::const_trait).map(|attr| attr.span);
1116 let constness = match (*constness, alt_const_trait_span) {
1117 (Const::Yes(span), _) | (Const::No, Some(span)) => Const::Yes(span),
1118 (Const::No, None) => Const::No,
1119 };
1120 if *is_auto == IsAuto::Yes {
1121 self.deny_generic_params(generics, ident.span);
1123 self.deny_super_traits(bounds, ident.span);
1124 self.deny_where_clause(&generics.where_clause, ident.span);
1125 self.deny_items(items, ident.span);
1126 }
1127
1128 let disallowed = matches!(constness, ast::Const::No)
1131 .then(|| TildeConstReason::Trait { span: item.span });
1132 self.with_tilde_const(disallowed, |this| {
1133 this.visit_generics(generics);
1134 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits)
1135 });
1136 self.with_in_trait(item.span, constness, |this| {
1137 walk_list!(this, visit_assoc_item, items, AssocCtxt::Trait);
1138 });
1139 }
1140 ItemKind::Mod(safety, ident, mod_kind) => {
1141 if let &Safety::Unsafe(span) = safety {
1142 self.dcx().emit_err(errors::UnsafeItem { span, kind: "module" });
1143 }
1144 if !matches!(mod_kind, ModKind::Loaded(_, Inline::Yes, _, _))
1146 && !attr::contains_name(&item.attrs, sym::path)
1147 {
1148 self.check_mod_file_item_asciionly(*ident);
1149 }
1150 visit::walk_item(self, item)
1151 }
1152 ItemKind::Struct(ident, generics, vdata) => {
1153 self.with_tilde_const(Some(TildeConstReason::Struct { span: item.span }), |this| {
1154 match vdata {
1155 VariantData::Struct { fields, .. } => {
1156 this.visit_attrs_vis_ident(&item.attrs, &item.vis, ident);
1157 this.visit_generics(generics);
1158 walk_list!(this, visit_field_def, fields);
1159 }
1160 _ => visit::walk_item(this, item),
1161 }
1162 })
1163 }
1164 ItemKind::Union(ident, generics, vdata) => {
1165 if vdata.fields().is_empty() {
1166 self.dcx().emit_err(errors::FieldlessUnion { span: item.span });
1167 }
1168 self.with_tilde_const(Some(TildeConstReason::Union { span: item.span }), |this| {
1169 match vdata {
1170 VariantData::Struct { fields, .. } => {
1171 this.visit_attrs_vis_ident(&item.attrs, &item.vis, ident);
1172 this.visit_generics(generics);
1173 walk_list!(this, visit_field_def, fields);
1174 }
1175 _ => visit::walk_item(this, item),
1176 }
1177 });
1178 }
1179 ItemKind::Const(box ConstItem { defaultness, expr, .. }) => {
1180 self.check_defaultness(item.span, *defaultness);
1181 if expr.is_none() {
1182 self.dcx().emit_err(errors::ConstWithoutBody {
1183 span: item.span,
1184 replace_span: self.ending_semi_or_hi(item.span),
1185 });
1186 }
1187 visit::walk_item(self, item);
1188 }
1189 ItemKind::Static(box StaticItem { expr, safety, .. }) => {
1190 self.check_item_safety(item.span, *safety);
1191 if matches!(safety, Safety::Unsafe(_)) {
1192 self.dcx().emit_err(errors::UnsafeStatic { span: item.span });
1193 }
1194
1195 if expr.is_none() {
1196 self.dcx().emit_err(errors::StaticWithoutBody {
1197 span: item.span,
1198 replace_span: self.ending_semi_or_hi(item.span),
1199 });
1200 }
1201 visit::walk_item(self, item);
1202 }
1203 ItemKind::TyAlias(
1204 ty_alias @ box TyAlias { defaultness, bounds, where_clauses, ty, .. },
1205 ) => {
1206 self.check_defaultness(item.span, *defaultness);
1207 if ty.is_none() {
1208 self.dcx().emit_err(errors::TyAliasWithoutBody {
1209 span: item.span,
1210 replace_span: self.ending_semi_or_hi(item.span),
1211 });
1212 }
1213 self.check_type_no_bounds(bounds, "this context");
1214
1215 if self.features.lazy_type_alias() {
1216 if let Err(err) = self.check_type_alias_where_clause_location(ty_alias) {
1217 self.dcx().emit_err(err);
1218 }
1219 } else if where_clauses.after.has_where_token {
1220 self.dcx().emit_err(errors::WhereClauseAfterTypeAlias {
1221 span: where_clauses.after.span,
1222 help: self.sess.is_nightly_build(),
1223 });
1224 }
1225 visit::walk_item(self, item);
1226 }
1227 _ => visit::walk_item(self, item),
1228 }
1229
1230 self.lint_node_id = previous_lint_node_id;
1231 }
1232
1233 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
1234 match &fi.kind {
1235 ForeignItemKind::Fn(box Fn { defaultness, ident, sig, body, .. }) => {
1236 self.check_defaultness(fi.span, *defaultness);
1237 self.check_foreign_fn_bodyless(*ident, body.as_deref());
1238 self.check_foreign_fn_headerless(sig.header);
1239 self.check_foreign_item_ascii_only(*ident);
1240 self.check_extern_fn_signature(
1241 self.extern_mod_abi.unwrap_or(ExternAbi::FALLBACK),
1242 FnCtxt::Foreign,
1243 ident,
1244 sig,
1245 );
1246 }
1247 ForeignItemKind::TyAlias(box TyAlias {
1248 defaultness,
1249 ident,
1250 generics,
1251 where_clauses,
1252 bounds,
1253 ty,
1254 ..
1255 }) => {
1256 self.check_defaultness(fi.span, *defaultness);
1257 self.check_foreign_kind_bodyless(*ident, "type", ty.as_ref().map(|b| b.span));
1258 self.check_type_no_bounds(bounds, "`extern` blocks");
1259 self.check_foreign_ty_genericless(generics, where_clauses);
1260 self.check_foreign_item_ascii_only(*ident);
1261 }
1262 ForeignItemKind::Static(box StaticItem { ident, safety, expr, .. }) => {
1263 self.check_item_safety(fi.span, *safety);
1264 self.check_foreign_kind_bodyless(*ident, "static", expr.as_ref().map(|b| b.span));
1265 self.check_foreign_item_ascii_only(*ident);
1266 }
1267 ForeignItemKind::MacCall(..) => {}
1268 }
1269
1270 visit::walk_item(self, fi)
1271 }
1272
1273 fn visit_generic_args(&mut self, generic_args: &'a GenericArgs) {
1275 match generic_args {
1276 GenericArgs::AngleBracketed(data) => {
1277 self.check_generic_args_before_constraints(data);
1278
1279 for arg in &data.args {
1280 match arg {
1281 AngleBracketedArg::Arg(arg) => self.visit_generic_arg(arg),
1282 AngleBracketedArg::Constraint(constraint) => {
1285 self.with_impl_trait(None, |this| {
1286 this.visit_assoc_item_constraint(constraint);
1287 });
1288 }
1289 }
1290 }
1291 }
1292 GenericArgs::Parenthesized(data) => {
1293 walk_list!(self, visit_ty, &data.inputs);
1294 if let FnRetTy::Ty(ty) = &data.output {
1295 self.with_impl_trait(None, |this| this.visit_ty(ty));
1298 }
1299 }
1300 GenericArgs::ParenthesizedElided(_span) => {}
1301 }
1302 }
1303
1304 fn visit_generics(&mut self, generics: &'a Generics) {
1305 let mut prev_param_default = None;
1306 for param in &generics.params {
1307 match param.kind {
1308 GenericParamKind::Lifetime => (),
1309 GenericParamKind::Type { default: Some(_), .. }
1310 | GenericParamKind::Const { default: Some(_), .. } => {
1311 prev_param_default = Some(param.ident.span);
1312 }
1313 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1314 if let Some(span) = prev_param_default {
1315 self.dcx().emit_err(errors::GenericDefaultTrailing { span });
1316 break;
1317 }
1318 }
1319 }
1320 }
1321
1322 validate_generic_param_order(self.dcx(), &generics.params, generics.span);
1323
1324 for predicate in &generics.where_clause.predicates {
1325 let span = predicate.span;
1326 if let WherePredicateKind::EqPredicate(predicate) = &predicate.kind {
1327 deny_equality_constraints(self, predicate, span, generics);
1328 }
1329 }
1330 walk_list!(self, visit_generic_param, &generics.params);
1331 for predicate in &generics.where_clause.predicates {
1332 match &predicate.kind {
1333 WherePredicateKind::BoundPredicate(bound_pred) => {
1334 if !bound_pred.bound_generic_params.is_empty() {
1340 for bound in &bound_pred.bounds {
1341 match bound {
1342 GenericBound::Trait(t) => {
1343 if !t.bound_generic_params.is_empty() {
1344 self.dcx()
1345 .emit_err(errors::NestedLifetimes { span: t.span });
1346 }
1347 }
1348 GenericBound::Outlives(_) => {}
1349 GenericBound::Use(..) => {}
1350 }
1351 }
1352 }
1353 }
1354 _ => {}
1355 }
1356 self.visit_where_predicate(predicate);
1357 }
1358 }
1359
1360 fn visit_param_bound(&mut self, bound: &'a GenericBound, ctxt: BoundKind) {
1361 match bound {
1362 GenericBound::Trait(trait_ref) => {
1363 match (ctxt, trait_ref.modifiers.constness, trait_ref.modifiers.polarity) {
1364 (
1365 BoundKind::TraitObject,
1366 BoundConstness::Always(_),
1367 BoundPolarity::Positive,
1368 ) => {
1369 self.dcx().emit_err(errors::ConstBoundTraitObject { span: trait_ref.span });
1370 }
1371 (_, BoundConstness::Maybe(span), BoundPolarity::Positive)
1372 if let Some(reason) = self.disallow_tilde_const =>
1373 {
1374 self.dcx().emit_err(errors::TildeConstDisallowed { span, reason });
1375 }
1376 _ => {}
1377 }
1378
1379 if let BoundPolarity::Negative(_) = trait_ref.modifiers.polarity
1381 && let Some(segment) = trait_ref.trait_ref.path.segments.last()
1382 {
1383 match segment.args.as_deref() {
1384 Some(ast::GenericArgs::AngleBracketed(args)) => {
1385 for arg in &args.args {
1386 if let ast::AngleBracketedArg::Constraint(constraint) = arg {
1387 self.dcx().emit_err(errors::ConstraintOnNegativeBound {
1388 span: constraint.span,
1389 });
1390 }
1391 }
1392 }
1393 Some(ast::GenericArgs::Parenthesized(args)) => {
1395 self.dcx().emit_err(errors::NegativeBoundWithParentheticalNotation {
1396 span: args.span,
1397 });
1398 }
1399 Some(ast::GenericArgs::ParenthesizedElided(_)) | None => {}
1400 }
1401 }
1402 }
1403 GenericBound::Outlives(_) => {}
1404 GenericBound::Use(_, span) => match ctxt {
1405 BoundKind::Impl => {}
1406 BoundKind::Bound | BoundKind::TraitObject | BoundKind::SuperTraits => {
1407 self.dcx().emit_err(errors::PreciseCapturingNotAllowedHere {
1408 loc: ctxt.descr(),
1409 span: *span,
1410 });
1411 }
1412 },
1413 }
1414
1415 visit::walk_param_bound(self, bound)
1416 }
1417
1418 fn visit_fn(&mut self, fk: FnKind<'a>, span: Span, id: NodeId) {
1419 let self_semantic = match fk.ctxt() {
1421 Some(FnCtxt::Assoc(_)) => SelfSemantic::Yes,
1422 _ => SelfSemantic::No,
1423 };
1424 self.check_fn_decl(fk.decl(), self_semantic);
1425
1426 if let Some(&FnHeader { safety, .. }) = fk.header() {
1427 self.check_item_safety(span, safety);
1428 }
1429
1430 if let FnKind::Fn(ctxt, _, fun) = fk
1431 && let Extern::Explicit(str_lit, _) = fun.sig.header.ext
1432 && let Ok(abi) = ExternAbi::from_str(str_lit.symbol.as_str())
1433 {
1434 self.check_extern_fn_signature(abi, ctxt, &fun.ident, &fun.sig);
1435 }
1436
1437 self.check_c_variadic_type(fk);
1438
1439 if let Some(&FnHeader {
1441 constness: Const::Yes(const_span),
1442 coroutine_kind: Some(coroutine_kind),
1443 ..
1444 }) = fk.header()
1445 {
1446 self.dcx().emit_err(errors::ConstAndCoroutine {
1447 spans: vec![coroutine_kind.span(), const_span],
1448 const_span,
1449 coroutine_span: coroutine_kind.span(),
1450 coroutine_kind: coroutine_kind.as_str(),
1451 span,
1452 });
1453 }
1454
1455 if let FnKind::Fn(
1456 _,
1457 _,
1458 Fn {
1459 sig: FnSig { header: FnHeader { ext: Extern::Implicit(extern_span), .. }, .. },
1460 ..
1461 },
1462 ) = fk
1463 {
1464 self.handle_missing_abi(*extern_span, id);
1465 }
1466
1467 if let FnKind::Fn(ctxt, _, Fn { body: None, sig, .. }) = fk {
1469 Self::check_decl_no_pat(&sig.decl, |span, ident, mut_ident| {
1470 if mut_ident && matches!(ctxt, FnCtxt::Assoc(_)) {
1471 if let Some(ident) = ident {
1472 self.lint_buffer.buffer_lint(
1473 PATTERNS_IN_FNS_WITHOUT_BODY,
1474 id,
1475 span,
1476 BuiltinLintDiag::PatternsInFnsWithoutBody {
1477 span,
1478 ident,
1479 is_foreign: matches!(ctxt, FnCtxt::Foreign),
1480 },
1481 )
1482 }
1483 } else {
1484 match ctxt {
1485 FnCtxt::Foreign => self.dcx().emit_err(errors::PatternInForeign { span }),
1486 _ => self.dcx().emit_err(errors::PatternInBodiless { span }),
1487 };
1488 }
1489 });
1490 }
1491
1492 let tilde_const_allowed =
1493 matches!(fk.header(), Some(FnHeader { constness: ast::Const::Yes(_), .. }))
1494 || matches!(fk.ctxt(), Some(FnCtxt::Assoc(_)))
1495 && self
1496 .outer_trait_or_trait_impl
1497 .as_ref()
1498 .and_then(TraitOrTraitImpl::constness)
1499 .is_some();
1500
1501 let disallowed = (!tilde_const_allowed).then(|| match fk {
1502 FnKind::Fn(_, _, f) => TildeConstReason::Function { ident: f.ident.span },
1503 FnKind::Closure(..) => TildeConstReason::Closure,
1504 });
1505 self.with_tilde_const(disallowed, |this| visit::walk_fn(this, fk));
1506 }
1507
1508 fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
1509 if let Some(ident) = item.kind.ident()
1510 && attr::contains_name(&item.attrs, sym::no_mangle)
1511 {
1512 self.check_nomangle_item_asciionly(ident, item.span);
1513 }
1514
1515 if ctxt == AssocCtxt::Trait || self.outer_trait_or_trait_impl.is_none() {
1516 self.check_defaultness(item.span, item.kind.defaultness());
1517 }
1518
1519 if let AssocCtxt::Impl { .. } = ctxt {
1520 match &item.kind {
1521 AssocItemKind::Const(box ConstItem { expr: None, .. }) => {
1522 self.dcx().emit_err(errors::AssocConstWithoutBody {
1523 span: item.span,
1524 replace_span: self.ending_semi_or_hi(item.span),
1525 });
1526 }
1527 AssocItemKind::Fn(box Fn { body, .. }) => {
1528 if body.is_none() && !self.is_sdylib_interface {
1529 self.dcx().emit_err(errors::AssocFnWithoutBody {
1530 span: item.span,
1531 replace_span: self.ending_semi_or_hi(item.span),
1532 });
1533 }
1534 }
1535 AssocItemKind::Type(box TyAlias { bounds, ty, .. }) => {
1536 if ty.is_none() {
1537 self.dcx().emit_err(errors::AssocTypeWithoutBody {
1538 span: item.span,
1539 replace_span: self.ending_semi_or_hi(item.span),
1540 });
1541 }
1542 self.check_type_no_bounds(bounds, "`impl`s");
1543 }
1544 _ => {}
1545 }
1546 }
1547
1548 if let AssocItemKind::Type(ty_alias) = &item.kind
1549 && let Err(err) = self.check_type_alias_where_clause_location(ty_alias)
1550 {
1551 let sugg = match err.sugg {
1552 errors::WhereClauseBeforeTypeAliasSugg::Remove { .. } => None,
1553 errors::WhereClauseBeforeTypeAliasSugg::Move { snippet, right, .. } => {
1554 Some((right, snippet))
1555 }
1556 };
1557 self.lint_buffer.buffer_lint(
1558 DEPRECATED_WHERE_CLAUSE_LOCATION,
1559 item.id,
1560 err.span,
1561 BuiltinLintDiag::DeprecatedWhereclauseLocation(err.span, sugg),
1562 );
1563 }
1564
1565 if let Some(parent) = &self.outer_trait_or_trait_impl {
1566 self.visibility_not_permitted(&item.vis, errors::VisibilityNotPermittedNote::TraitImpl);
1567 if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
1568 self.check_trait_fn_not_const(sig.header.constness, parent);
1569 }
1570 }
1571
1572 if let AssocItemKind::Const(ci) = &item.kind {
1573 self.check_item_named(ci.ident, "const");
1574 }
1575
1576 let parent_is_const =
1577 self.outer_trait_or_trait_impl.as_ref().and_then(TraitOrTraitImpl::constness).is_some();
1578
1579 match &item.kind {
1580 AssocItemKind::Fn(func)
1581 if parent_is_const
1582 || ctxt == AssocCtxt::Trait
1583 || matches!(func.sig.header.constness, Const::Yes(_)) =>
1584 {
1585 self.visit_attrs_vis_ident(&item.attrs, &item.vis, &func.ident);
1586 let kind = FnKind::Fn(FnCtxt::Assoc(ctxt), &item.vis, &*func);
1587 self.visit_fn(kind, item.span, item.id);
1588 }
1589 AssocItemKind::Type(_) => {
1590 let disallowed = (!parent_is_const).then(|| match self.outer_trait_or_trait_impl {
1591 Some(TraitOrTraitImpl::Trait { .. }) => {
1592 TildeConstReason::TraitAssocTy { span: item.span }
1593 }
1594 Some(TraitOrTraitImpl::TraitImpl { .. }) => {
1595 TildeConstReason::TraitImplAssocTy { span: item.span }
1596 }
1597 None => TildeConstReason::InherentAssocTy { span: item.span },
1598 });
1599 self.with_tilde_const(disallowed, |this| {
1600 this.with_in_trait_impl(None, |this| visit::walk_assoc_item(this, item, ctxt))
1601 })
1602 }
1603 _ => self.with_in_trait_impl(None, |this| visit::walk_assoc_item(this, item, ctxt)),
1604 }
1605 }
1606
1607 fn visit_anon_const(&mut self, anon_const: &'a AnonConst) {
1608 self.with_tilde_const(
1609 Some(TildeConstReason::AnonConst { span: anon_const.value.span }),
1610 |this| visit::walk_anon_const(this, anon_const),
1611 )
1612 }
1613}
1614
1615fn deny_equality_constraints(
1618 this: &AstValidator<'_>,
1619 predicate: &WhereEqPredicate,
1620 predicate_span: Span,
1621 generics: &Generics,
1622) {
1623 let mut err = errors::EqualityInWhere { span: predicate_span, assoc: None, assoc2: None };
1624
1625 if let TyKind::Path(Some(qself), full_path) = &predicate.lhs_ty.kind
1627 && let TyKind::Path(None, path) = &qself.ty.kind
1628 && let [PathSegment { ident, args: None, .. }] = &path.segments[..]
1629 {
1630 for param in &generics.params {
1631 if param.ident == *ident
1632 && let [PathSegment { ident, args, .. }] = &full_path.segments[qself.position..]
1633 {
1634 let mut assoc_path = full_path.clone();
1636 assoc_path.segments.pop();
1638 let len = assoc_path.segments.len() - 1;
1639 let gen_args = args.as_deref().cloned();
1640 let arg = AngleBracketedArg::Constraint(AssocItemConstraint {
1642 id: rustc_ast::node_id::DUMMY_NODE_ID,
1643 ident: *ident,
1644 gen_args,
1645 kind: AssocItemConstraintKind::Equality {
1646 term: predicate.rhs_ty.clone().into(),
1647 },
1648 span: ident.span,
1649 });
1650 match &mut assoc_path.segments[len].args {
1652 Some(args) => match args.deref_mut() {
1653 GenericArgs::Parenthesized(_) | GenericArgs::ParenthesizedElided(..) => {
1654 continue;
1655 }
1656 GenericArgs::AngleBracketed(args) => {
1657 args.args.push(arg);
1658 }
1659 },
1660 empty_args => {
1661 *empty_args = Some(
1662 AngleBracketedArgs { span: ident.span, args: thin_vec![arg] }.into(),
1663 );
1664 }
1665 }
1666 err.assoc = Some(errors::AssociatedSuggestion {
1667 span: predicate_span,
1668 ident: *ident,
1669 param: param.ident,
1670 path: pprust::path_to_string(&assoc_path),
1671 })
1672 }
1673 }
1674 }
1675
1676 let mut suggest =
1677 |poly: &PolyTraitRef, potential_assoc: &PathSegment, predicate: &WhereEqPredicate| {
1678 if let [trait_segment] = &poly.trait_ref.path.segments[..] {
1679 let assoc = pprust::path_to_string(&ast::Path::from_ident(potential_assoc.ident));
1680 let ty = pprust::ty_to_string(&predicate.rhs_ty);
1681 let (args, span) = match &trait_segment.args {
1682 Some(args) => match args.deref() {
1683 ast::GenericArgs::AngleBracketed(args) => {
1684 let Some(arg) = args.args.last() else {
1685 return;
1686 };
1687 (format!(", {assoc} = {ty}"), arg.span().shrink_to_hi())
1688 }
1689 _ => return,
1690 },
1691 None => (format!("<{assoc} = {ty}>"), trait_segment.span().shrink_to_hi()),
1692 };
1693 let removal_span = if generics.where_clause.predicates.len() == 1 {
1694 generics.where_clause.span
1696 } else {
1697 let mut span = predicate_span;
1698 let mut prev_span: Option<Span> = None;
1699 let mut preds = generics.where_clause.predicates.iter().peekable();
1700 while let Some(pred) = preds.next() {
1702 if let WherePredicateKind::EqPredicate(_) = pred.kind
1703 && pred.span == predicate_span
1704 {
1705 if let Some(next) = preds.peek() {
1706 span = span.with_hi(next.span.lo());
1708 } else if let Some(prev_span) = prev_span {
1709 span = span.with_lo(prev_span.hi());
1711 }
1712 }
1713 prev_span = Some(pred.span);
1714 }
1715 span
1716 };
1717 err.assoc2 = Some(errors::AssociatedSuggestion2 {
1718 span,
1719 args,
1720 predicate: removal_span,
1721 trait_segment: trait_segment.ident,
1722 potential_assoc: potential_assoc.ident,
1723 });
1724 }
1725 };
1726
1727 if let TyKind::Path(None, full_path) = &predicate.lhs_ty.kind {
1728 for bounds in generics.params.iter().map(|p| &p.bounds).chain(
1730 generics.where_clause.predicates.iter().filter_map(|pred| match &pred.kind {
1731 WherePredicateKind::BoundPredicate(p) => Some(&p.bounds),
1732 _ => None,
1733 }),
1734 ) {
1735 for bound in bounds {
1736 if let GenericBound::Trait(poly) = bound
1737 && poly.modifiers == TraitBoundModifiers::NONE
1738 {
1739 if full_path.segments[..full_path.segments.len() - 1]
1740 .iter()
1741 .map(|segment| segment.ident.name)
1742 .zip(poly.trait_ref.path.segments.iter().map(|segment| segment.ident.name))
1743 .all(|(a, b)| a == b)
1744 && let Some(potential_assoc) = full_path.segments.iter().last()
1745 {
1746 suggest(poly, potential_assoc, predicate);
1747 }
1748 }
1749 }
1750 }
1751 if let [potential_param, potential_assoc] = &full_path.segments[..] {
1753 for (ident, bounds) in generics.params.iter().map(|p| (p.ident, &p.bounds)).chain(
1754 generics.where_clause.predicates.iter().filter_map(|pred| match &pred.kind {
1755 WherePredicateKind::BoundPredicate(p)
1756 if let ast::TyKind::Path(None, path) = &p.bounded_ty.kind
1757 && let [segment] = &path.segments[..] =>
1758 {
1759 Some((segment.ident, &p.bounds))
1760 }
1761 _ => None,
1762 }),
1763 ) {
1764 if ident == potential_param.ident {
1765 for bound in bounds {
1766 if let ast::GenericBound::Trait(poly) = bound
1767 && poly.modifiers == TraitBoundModifiers::NONE
1768 {
1769 suggest(poly, potential_assoc, predicate);
1770 }
1771 }
1772 }
1773 }
1774 }
1775 }
1776 this.dcx().emit_err(err);
1777}
1778
1779pub fn check_crate(
1780 sess: &Session,
1781 features: &Features,
1782 krate: &Crate,
1783 is_sdylib_interface: bool,
1784 lints: &mut LintBuffer,
1785) -> bool {
1786 let mut validator = AstValidator {
1787 sess,
1788 features,
1789 extern_mod_span: None,
1790 outer_trait_or_trait_impl: None,
1791 has_proc_macro_decls: false,
1792 outer_impl_trait_span: None,
1793 disallow_tilde_const: Some(TildeConstReason::Item),
1794 extern_mod_safety: None,
1795 extern_mod_abi: None,
1796 lint_node_id: CRATE_NODE_ID,
1797 is_sdylib_interface,
1798 lint_buffer: lints,
1799 };
1800 visit::walk_crate(&mut validator, krate);
1801
1802 validator.has_proc_macro_decls
1803}