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