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