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, UNUSED_VISIBILITIES,
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 if !self.sess.target.arch.supports_c_variadic_definitions() {
714 self.dcx().emit_err(errors::CVariadicNotSupported {
715 variadic_span: variadic_param.span,
716 target: &*self.sess.target.llvm_target,
717 });
718 return;
719 }
720
721 match sig.header.ext {
722 Extern::Implicit(_) => {
723 if !matches!(sig.header.safety, Safety::Unsafe(_)) {
724 self.dcx().emit_err(errors::CVariadicMustBeUnsafe {
725 span: variadic_param.span,
726 unsafe_span: sig.safety_span(),
727 });
728 }
729 }
730 Extern::Explicit(StrLit { symbol_unescaped, .. }, _) => {
731 let Ok(abi) = ExternAbi::from_str(symbol_unescaped.as_str()) else {
733 return;
734 };
735
736 self.check_c_variadic_abi(abi, attrs, variadic_param.span, sig);
737
738 if !matches!(sig.header.safety, Safety::Unsafe(_)) {
739 self.dcx().emit_err(errors::CVariadicMustBeUnsafe {
740 span: variadic_param.span,
741 unsafe_span: sig.safety_span(),
742 });
743 }
744 }
745 Extern::None => {
746 let err = errors::CVariadicNoExtern { span: variadic_param.span };
747 self.dcx().emit_err(err);
748 }
749 }
750 }
751 }
752 }
753
754 fn check_c_variadic_abi(
755 &self,
756 abi: ExternAbi,
757 attrs: &'a AttrVec,
758 dotdotdot_span: Span,
759 sig: &FnSig,
760 ) {
761 if attr::contains_name(attrs, sym::naked) {
764 match abi.supports_c_variadic() {
765 CVariadicStatus::Stable if let ExternAbi::C { .. } = abi => {
766 }
768 CVariadicStatus::Stable => {
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 CVariadicStatus::Unstable { feature } => {
777 if !self.features.enabled(sym::c_variadic_naked_functions) {
779 let msg = format!("Naked c-variadic `extern {abi}` functions are unstable");
780 feature_err(&self.sess, sym::c_variadic_naked_functions, sig.span, msg)
781 .emit();
782 }
783
784 if !self.features.enabled(feature) {
785 let msg = format!(
786 "C-variadic functions with the {abi} calling convention are unstable"
787 );
788 feature_err(&self.sess, feature, sig.span, msg).emit();
789 }
790 }
791 CVariadicStatus::NotSupported => {
792 self.dcx().emit_err(errors::CVariadicBadNakedExtern {
794 span: dotdotdot_span,
795 abi: abi.as_str(),
796 extern_span: sig.extern_span(),
797 });
798 }
799 }
800 } else if !matches!(abi, ExternAbi::C { .. }) {
801 self.dcx().emit_err(errors::CVariadicBadExtern {
802 span: dotdotdot_span,
803 abi: abi.as_str(),
804 extern_span: sig.extern_span(),
805 });
806 }
807 }
808
809 fn check_item_named(&self, ident: Ident, kind: &str) {
810 if ident.name != kw::Underscore {
811 return;
812 }
813 self.dcx().emit_err(errors::ItemUnderscore { span: ident.span, kind });
814 }
815
816 fn check_nomangle_item_asciionly(&self, ident: Ident, item_span: Span) {
817 if ident.name.as_str().is_ascii() {
818 return;
819 }
820 let span = self.sess.source_map().guess_head_span(item_span);
821 self.dcx().emit_err(errors::NoMangleAscii { span });
822 }
823
824 fn check_mod_file_item_asciionly(&self, ident: Ident) {
825 if ident.name.as_str().is_ascii() {
826 return;
827 }
828 self.dcx().emit_err(errors::ModuleNonAscii { span: ident.span, name: ident.name });
829 }
830
831 fn deny_const_auto_traits(&self, constness: Const) {
832 if let Const::Yes(span) = constness {
833 self.dcx().emit_err(errors::ConstAutoTrait { span });
834 }
835 }
836
837 fn deny_generic_params(&self, generics: &Generics, ident_span: Span) {
838 if !generics.params.is_empty() {
839 self.dcx()
840 .emit_err(errors::AutoTraitGeneric { span: generics.span, ident: ident_span });
841 }
842 }
843
844 fn deny_super_traits(&self, bounds: &GenericBounds, ident: Span) {
845 if let [.., last] = &bounds[..] {
846 let span = bounds.iter().map(|b| b.span()).collect();
847 let removal = ident.shrink_to_hi().to(last.span());
848 self.dcx().emit_err(errors::AutoTraitBounds { span, removal, ident });
849 }
850 }
851
852 fn deny_where_clause(&self, where_clause: &WhereClause, ident: Span) {
853 if !where_clause.predicates.is_empty() {
854 self.dcx().emit_err(errors::AutoTraitBounds {
857 span: vec![where_clause.span],
858 removal: where_clause.span,
859 ident,
860 });
861 }
862 }
863
864 fn deny_items(&self, trait_items: &[Box<AssocItem>], ident_span: Span) {
865 if !trait_items.is_empty() {
866 let spans: Vec<_> = trait_items.iter().map(|i| i.kind.ident().unwrap().span).collect();
867 let total = trait_items.first().unwrap().span.to(trait_items.last().unwrap().span);
868 self.dcx().emit_err(errors::AutoTraitItems { spans, total, ident: ident_span });
869 }
870 }
871
872 fn correct_generic_order_suggestion(&self, data: &AngleBracketedArgs) -> String {
873 let lt_sugg = data.args.iter().filter_map(|arg| match arg {
875 AngleBracketedArg::Arg(lt @ GenericArg::Lifetime(_)) => {
876 Some(pprust::to_string(|s| s.print_generic_arg(lt)))
877 }
878 _ => None,
879 });
880 let args_sugg = data.args.iter().filter_map(|a| match a {
881 AngleBracketedArg::Arg(GenericArg::Lifetime(_)) | AngleBracketedArg::Constraint(_) => {
882 None
883 }
884 AngleBracketedArg::Arg(arg) => Some(pprust::to_string(|s| s.print_generic_arg(arg))),
885 });
886 let constraint_sugg = data.args.iter().filter_map(|a| match a {
888 AngleBracketedArg::Arg(_) => None,
889 AngleBracketedArg::Constraint(c) => {
890 Some(pprust::to_string(|s| s.print_assoc_item_constraint(c)))
891 }
892 });
893 format!(
894 "<{}>",
895 lt_sugg.chain(args_sugg).chain(constraint_sugg).collect::<Vec<String>>().join(", ")
896 )
897 }
898
899 fn check_generic_args_before_constraints(&self, data: &AngleBracketedArgs) {
901 if data.args.iter().is_partitioned(|arg| matches!(arg, AngleBracketedArg::Arg(_))) {
903 return;
904 }
905 let (constraint_spans, arg_spans): (Vec<Span>, Vec<Span>) =
907 data.args.iter().partition_map(|arg| match arg {
908 AngleBracketedArg::Constraint(c) => Either::Left(c.span),
909 AngleBracketedArg::Arg(a) => Either::Right(a.span()),
910 });
911 let args_len = arg_spans.len();
912 let constraint_len = constraint_spans.len();
913 self.dcx().emit_err(errors::ArgsBeforeConstraint {
915 arg_spans: arg_spans.clone(),
916 constraints: constraint_spans[0],
917 args: *arg_spans.iter().last().unwrap(),
918 data: data.span,
919 constraint_spans: errors::EmptyLabelManySpans(constraint_spans),
920 arg_spans2: errors::EmptyLabelManySpans(arg_spans),
921 suggestion: self.correct_generic_order_suggestion(data),
922 constraint_len,
923 args_len,
924 });
925 }
926
927 fn visit_ty_common(&mut self, ty: &'a Ty) {
928 match &ty.kind {
929 TyKind::FnPtr(bfty) => {
930 self.check_fn_ptr_safety(bfty.decl_span, bfty.safety);
931 self.check_fn_decl(&bfty.decl, SelfSemantic::No);
932 Self::check_decl_no_pat(&bfty.decl, |span, _, _| {
933 self.dcx().emit_err(errors::PatternFnPointer { span });
934 });
935 if let Extern::Implicit(extern_span) = bfty.ext {
936 self.handle_missing_abi(extern_span, ty.id);
937 }
938 }
939 TyKind::TraitObject(bounds, ..) => {
940 let mut any_lifetime_bounds = false;
941 for bound in bounds {
942 if let GenericBound::Outlives(lifetime) = bound {
943 if any_lifetime_bounds {
944 self.dcx()
945 .emit_err(errors::TraitObjectBound { span: lifetime.ident.span });
946 break;
947 }
948 any_lifetime_bounds = true;
949 }
950 }
951 }
952 TyKind::ImplTrait(_, bounds) => {
953 if let Some(outer_impl_trait_sp) = self.outer_impl_trait_span {
954 self.dcx().emit_err(errors::NestedImplTrait {
955 span: ty.span,
956 outer: outer_impl_trait_sp,
957 inner: ty.span,
958 });
959 }
960
961 if !bounds.iter().any(|b| matches!(b, GenericBound::Trait(..))) {
962 self.dcx().emit_err(errors::AtLeastOneTrait { span: ty.span });
963 }
964 }
965 _ => {}
966 }
967 }
968
969 fn handle_missing_abi(&mut self, span: Span, id: NodeId) {
970 if span.edition().at_least_edition_future() && self.features.explicit_extern_abis() {
973 self.dcx().emit_err(errors::MissingAbi { span });
974 } else if self
975 .sess
976 .source_map()
977 .span_to_snippet(span)
978 .is_ok_and(|snippet| !snippet.starts_with("#["))
979 {
980 self.lint_buffer.buffer_lint(
981 MISSING_ABI,
982 id,
983 span,
984 errors::MissingAbiSugg { span, default_abi: ExternAbi::FALLBACK },
985 )
986 }
987 }
988
989 fn visit_attrs_vis(&mut self, attrs: &'a AttrVec, vis: &'a Visibility) {
991 walk_list!(self, visit_attribute, attrs);
992 self.visit_vis(vis);
993 }
994
995 fn visit_attrs_vis_ident(&mut self, attrs: &'a AttrVec, vis: &'a Visibility, ident: &'a Ident) {
997 walk_list!(self, visit_attribute, attrs);
998 self.visit_vis(vis);
999 self.visit_ident(ident);
1000 }
1001}
1002
1003fn validate_generic_param_order(dcx: DiagCtxtHandle<'_>, generics: &[GenericParam], span: Span) {
1006 let mut max_param: Option<ParamKindOrd> = None;
1007 let mut out_of_order = FxIndexMap::default();
1008 let mut param_idents = Vec::with_capacity(generics.len());
1009
1010 for (idx, param) in generics.iter().enumerate() {
1011 let ident = param.ident;
1012 let (kind, bounds, span) = (¶m.kind, ¶m.bounds, ident.span);
1013 let (ord_kind, ident) = match ¶m.kind {
1014 GenericParamKind::Lifetime => (ParamKindOrd::Lifetime, ident.to_string()),
1015 GenericParamKind::Type { .. } => (ParamKindOrd::TypeOrConst, ident.to_string()),
1016 GenericParamKind::Const { ty, .. } => {
1017 let ty = pprust::ty_to_string(ty);
1018 (ParamKindOrd::TypeOrConst, format!("const {ident}: {ty}"))
1019 }
1020 };
1021 param_idents.push((kind, ord_kind, bounds, idx, ident));
1022 match max_param {
1023 Some(max_param) if max_param > ord_kind => {
1024 let entry = out_of_order.entry(ord_kind).or_insert((max_param, vec![]));
1025 entry.1.push(span);
1026 }
1027 Some(_) | None => max_param = Some(ord_kind),
1028 };
1029 }
1030
1031 if !out_of_order.is_empty() {
1032 let mut ordered_params = "<".to_string();
1033 param_idents.sort_by_key(|&(_, po, _, i, _)| (po, i));
1034 let mut first = true;
1035 for (kind, _, bounds, _, ident) in param_idents {
1036 if !first {
1037 ordered_params += ", ";
1038 }
1039 ordered_params += &ident;
1040
1041 if !bounds.is_empty() {
1042 ordered_params += ": ";
1043 ordered_params += &pprust::bounds_to_string(bounds);
1044 }
1045
1046 match kind {
1047 GenericParamKind::Type { default: Some(default) } => {
1048 ordered_params += " = ";
1049 ordered_params += &pprust::ty_to_string(default);
1050 }
1051 GenericParamKind::Type { default: None } => (),
1052 GenericParamKind::Lifetime => (),
1053 GenericParamKind::Const { ty: _, span: _, default: Some(default) } => {
1054 ordered_params += " = ";
1055 ordered_params += &pprust::expr_to_string(&default.value);
1056 }
1057 GenericParamKind::Const { ty: _, span: _, default: None } => (),
1058 }
1059 first = false;
1060 }
1061
1062 ordered_params += ">";
1063
1064 for (param_ord, (max_param, spans)) in &out_of_order {
1065 dcx.emit_err(errors::OutOfOrderParams {
1066 spans: spans.clone(),
1067 sugg_span: span,
1068 param_ord,
1069 max_param,
1070 ordered_params: &ordered_params,
1071 });
1072 }
1073 }
1074}
1075
1076impl<'a> Visitor<'a> for AstValidator<'a> {
1077 fn visit_attribute(&mut self, attr: &Attribute) {
1078 validate_attr::check_attr(&self.sess.psess, attr);
1079 }
1080
1081 fn visit_ty(&mut self, ty: &'a Ty) {
1082 self.visit_ty_common(ty);
1083 self.walk_ty(ty)
1084 }
1085
1086 fn visit_item(&mut self, item: &'a Item) {
1087 if item.attrs.iter().any(|attr| attr.is_proc_macro_attr()) {
1088 self.has_proc_macro_decls = true;
1089 }
1090
1091 let previous_lint_node_id = mem::replace(&mut self.lint_node_id, item.id);
1092
1093 if let Some(ident) = item.kind.ident()
1094 && attr::contains_name(&item.attrs, sym::no_mangle)
1095 {
1096 self.check_nomangle_item_asciionly(ident, item.span);
1097 }
1098
1099 match &item.kind {
1100 ItemKind::Impl(Impl {
1101 generics,
1102 constness,
1103 of_trait:
1104 Some(box TraitImplHeader { safety, polarity, defaultness: _, trait_ref: t }),
1105 self_ty,
1106 items,
1107 }) => {
1108 self.visit_attrs_vis(&item.attrs, &item.vis);
1109 self.visibility_not_permitted(
1110 &item.vis,
1111 errors::VisibilityNotPermittedNote::TraitImpl,
1112 );
1113 if let TyKind::Dummy = self_ty.kind {
1114 self.dcx().emit_fatal(errors::ObsoleteAuto { span: item.span });
1117 }
1118 if let (&Safety::Unsafe(span), &ImplPolarity::Negative(sp)) = (safety, polarity) {
1119 self.dcx().emit_err(errors::UnsafeNegativeImpl {
1120 span: sp.to(t.path.span),
1121 negative: sp,
1122 r#unsafe: span,
1123 });
1124 }
1125
1126 let disallowed = matches!(constness, Const::No)
1127 .then(|| TildeConstReason::TraitImpl { span: item.span });
1128 self.with_tilde_const(disallowed, |this| this.visit_generics(generics));
1129 self.visit_trait_ref(t);
1130 self.visit_ty(self_ty);
1131
1132 self.with_in_trait_or_impl(
1133 Some(TraitOrImpl::TraitImpl {
1134 constness: *constness,
1135 polarity: *polarity,
1136 trait_ref_span: t.path.span,
1137 }),
1138 |this| {
1139 walk_list!(
1140 this,
1141 visit_assoc_item,
1142 items,
1143 AssocCtxt::Impl { of_trait: true }
1144 );
1145 },
1146 );
1147 }
1148 ItemKind::Impl(Impl { generics, of_trait: None, self_ty, items, constness }) => {
1149 self.visit_attrs_vis(&item.attrs, &item.vis);
1150 self.visibility_not_permitted(
1151 &item.vis,
1152 errors::VisibilityNotPermittedNote::IndividualImplItems,
1153 );
1154
1155 let disallowed = matches!(constness, ast::Const::No)
1156 .then(|| TildeConstReason::Impl { span: item.span });
1157
1158 self.with_tilde_const(disallowed, |this| this.visit_generics(generics));
1159
1160 self.visit_ty(self_ty);
1161 self.with_in_trait_or_impl(
1162 Some(TraitOrImpl::Impl { constness: *constness }),
1163 |this| {
1164 walk_list!(
1165 this,
1166 visit_assoc_item,
1167 items,
1168 AssocCtxt::Impl { of_trait: false }
1169 );
1170 },
1171 );
1172 }
1173 ItemKind::Fn(
1174 func @ box Fn {
1175 defaultness,
1176 ident,
1177 generics: _,
1178 sig,
1179 contract: _,
1180 body,
1181 define_opaque: _,
1182 eii_impls,
1183 },
1184 ) => {
1185 self.visit_attrs_vis_ident(&item.attrs, &item.vis, ident);
1186 self.check_defaultness(item.span, *defaultness);
1187
1188 for EiiImpl { eii_macro_path, .. } in eii_impls {
1189 self.visit_path(eii_macro_path);
1190 }
1191
1192 let is_intrinsic = item.attrs.iter().any(|a| a.has_name(sym::rustc_intrinsic));
1193 if body.is_none() && !is_intrinsic && !self.is_sdylib_interface {
1194 self.dcx().emit_err(errors::FnWithoutBody {
1195 span: item.span,
1196 replace_span: self.ending_semi_or_hi(item.span),
1197 extern_block_suggestion: match sig.header.ext {
1198 Extern::None => None,
1199 Extern::Implicit(start_span) => {
1200 Some(errors::ExternBlockSuggestion::Implicit {
1201 start_span,
1202 end_span: item.span.shrink_to_hi(),
1203 })
1204 }
1205 Extern::Explicit(abi, start_span) => {
1206 Some(errors::ExternBlockSuggestion::Explicit {
1207 start_span,
1208 end_span: item.span.shrink_to_hi(),
1209 abi: abi.symbol_unescaped,
1210 })
1211 }
1212 },
1213 });
1214 }
1215
1216 let kind = FnKind::Fn(FnCtxt::Free, &item.vis, &*func);
1217 self.visit_fn(kind, &item.attrs, item.span, item.id);
1218 }
1219 ItemKind::ForeignMod(ForeignMod { extern_span, abi, safety, .. }) => {
1220 let old_item = mem::replace(&mut self.extern_mod_span, Some(item.span));
1221 self.visibility_not_permitted(
1222 &item.vis,
1223 errors::VisibilityNotPermittedNote::IndividualForeignItems,
1224 );
1225
1226 if &Safety::Default == safety {
1227 if item.span.at_least_rust_2024() {
1228 self.dcx().emit_err(errors::MissingUnsafeOnExtern { span: item.span });
1229 } else {
1230 self.lint_buffer.buffer_lint(
1231 MISSING_UNSAFE_ON_EXTERN,
1232 item.id,
1233 item.span,
1234 errors::MissingUnsafeOnExternLint {
1235 suggestion: item.span.shrink_to_lo(),
1236 },
1237 );
1238 }
1239 }
1240
1241 if abi.is_none() {
1242 self.handle_missing_abi(*extern_span, item.id);
1243 }
1244
1245 let extern_abi = abi.and_then(|abi| ExternAbi::from_str(abi.symbol.as_str()).ok());
1246 self.with_in_extern_mod(*safety, extern_abi, |this| {
1247 visit::walk_item(this, item);
1248 });
1249 self.extern_mod_span = old_item;
1250 }
1251 ItemKind::Enum(_, _, def) => {
1252 for variant in &def.variants {
1253 self.visibility_not_permitted(
1254 &variant.vis,
1255 errors::VisibilityNotPermittedNote::EnumVariant,
1256 );
1257 for field in variant.data.fields() {
1258 self.visibility_not_permitted(
1259 &field.vis,
1260 errors::VisibilityNotPermittedNote::EnumVariant,
1261 );
1262 }
1263 }
1264 self.with_tilde_const(Some(TildeConstReason::Enum { span: item.span }), |this| {
1265 visit::walk_item(this, item)
1266 });
1267 }
1268 ItemKind::Trait(box Trait {
1269 constness,
1270 is_auto,
1271 generics,
1272 ident,
1273 bounds,
1274 items,
1275 ..
1276 }) => {
1277 self.visit_attrs_vis_ident(&item.attrs, &item.vis, ident);
1278 if *is_auto == IsAuto::Yes {
1279 self.deny_const_auto_traits(*constness);
1281 self.deny_generic_params(generics, ident.span);
1283 self.deny_super_traits(bounds, ident.span);
1284 self.deny_where_clause(&generics.where_clause, ident.span);
1285 self.deny_items(items, ident.span);
1286 }
1287
1288 let disallowed = matches!(constness, ast::Const::No)
1291 .then(|| TildeConstReason::Trait { span: item.span });
1292 self.with_tilde_const(disallowed, |this| {
1293 this.visit_generics(generics);
1294 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits)
1295 });
1296 self.with_in_trait(item.span, *constness, |this| {
1297 walk_list!(this, visit_assoc_item, items, AssocCtxt::Trait);
1298 });
1299 }
1300 ItemKind::TraitAlias(box TraitAlias { constness, generics, bounds, .. }) => {
1301 let disallowed = matches!(constness, ast::Const::No)
1302 .then(|| TildeConstReason::Trait { span: item.span });
1303 self.with_tilde_const(disallowed, |this| {
1304 this.visit_generics(generics);
1305 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits)
1306 });
1307 }
1308 ItemKind::Mod(safety, ident, mod_kind) => {
1309 if let &Safety::Unsafe(span) = safety {
1310 self.dcx().emit_err(errors::UnsafeItem { span, kind: "module" });
1311 }
1312 if !matches!(mod_kind, ModKind::Loaded(_, Inline::Yes, _))
1314 && !attr::contains_name(&item.attrs, sym::path)
1315 {
1316 self.check_mod_file_item_asciionly(*ident);
1317 }
1318 visit::walk_item(self, item)
1319 }
1320 ItemKind::Struct(ident, generics, vdata) => {
1321 self.with_tilde_const(Some(TildeConstReason::Struct { span: item.span }), |this| {
1322 let is_scalable_vector =
1324 item.attrs.iter().any(|attr| attr.has_name(sym::rustc_scalable_vector));
1325 if is_scalable_vector && !matches!(vdata, VariantData::Tuple(..)) {
1326 this.dcx()
1327 .emit_err(errors::ScalableVectorNotTupleStruct { span: item.span });
1328 }
1329
1330 match vdata {
1331 VariantData::Struct { fields, .. } => {
1332 this.visit_attrs_vis_ident(&item.attrs, &item.vis, ident);
1333 this.visit_generics(generics);
1334 walk_list!(this, visit_field_def, fields);
1335 }
1336 _ => visit::walk_item(this, item),
1337 }
1338 })
1339 }
1340 ItemKind::Union(ident, generics, vdata) => {
1341 if vdata.fields().is_empty() {
1342 self.dcx().emit_err(errors::FieldlessUnion { span: item.span });
1343 }
1344 self.with_tilde_const(Some(TildeConstReason::Union { span: item.span }), |this| {
1345 match vdata {
1346 VariantData::Struct { fields, .. } => {
1347 this.visit_attrs_vis_ident(&item.attrs, &item.vis, ident);
1348 this.visit_generics(generics);
1349 walk_list!(this, visit_field_def, fields);
1350 }
1351 _ => visit::walk_item(this, item),
1352 }
1353 });
1354 }
1355 ItemKind::Const(box ConstItem { defaultness, ident, rhs, .. }) => {
1356 self.check_defaultness(item.span, *defaultness);
1357 if rhs.is_none() {
1358 self.dcx().emit_err(errors::ConstWithoutBody {
1359 span: item.span,
1360 replace_span: self.ending_semi_or_hi(item.span),
1361 });
1362 }
1363 if ident.name == kw::Underscore
1364 && !matches!(item.vis.kind, VisibilityKind::Inherited)
1365 && ident.span.eq_ctxt(item.vis.span)
1366 {
1367 self.lint_buffer.buffer_lint(
1368 UNUSED_VISIBILITIES,
1369 item.id,
1370 item.vis.span,
1371 BuiltinLintDiag::UnusedVisibility(item.vis.span),
1372 )
1373 }
1374
1375 visit::walk_item(self, item);
1376 }
1377 ItemKind::Static(box StaticItem { expr, safety, .. }) => {
1378 self.check_item_safety(item.span, *safety);
1379 if matches!(safety, Safety::Unsafe(_)) {
1380 self.dcx().emit_err(errors::UnsafeStatic { span: item.span });
1381 }
1382
1383 if expr.is_none() {
1384 self.dcx().emit_err(errors::StaticWithoutBody {
1385 span: item.span,
1386 replace_span: self.ending_semi_or_hi(item.span),
1387 });
1388 }
1389 visit::walk_item(self, item);
1390 }
1391 ItemKind::TyAlias(
1392 ty_alias @ box TyAlias { defaultness, bounds, after_where_clause, ty, .. },
1393 ) => {
1394 self.check_defaultness(item.span, *defaultness);
1395 if ty.is_none() {
1396 self.dcx().emit_err(errors::TyAliasWithoutBody {
1397 span: item.span,
1398 replace_span: self.ending_semi_or_hi(item.span),
1399 });
1400 }
1401 self.check_type_no_bounds(bounds, "this context");
1402
1403 if self.features.lazy_type_alias() {
1404 if let Err(err) = self.check_type_alias_where_clause_location(ty_alias) {
1405 self.dcx().emit_err(err);
1406 }
1407 } else if after_where_clause.has_where_token {
1408 self.dcx().emit_err(errors::WhereClauseAfterTypeAlias {
1409 span: after_where_clause.span,
1410 help: self.sess.is_nightly_build(),
1411 });
1412 }
1413 visit::walk_item(self, item);
1414 }
1415 _ => visit::walk_item(self, item),
1416 }
1417
1418 self.lint_node_id = previous_lint_node_id;
1419 }
1420
1421 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
1422 match &fi.kind {
1423 ForeignItemKind::Fn(box Fn { defaultness, ident, sig, body, .. }) => {
1424 self.check_defaultness(fi.span, *defaultness);
1425 self.check_foreign_fn_bodyless(*ident, body.as_deref());
1426 self.check_foreign_fn_headerless(sig.header);
1427 self.check_foreign_item_ascii_only(*ident);
1428 self.check_extern_fn_signature(
1429 self.extern_mod_abi.unwrap_or(ExternAbi::FALLBACK),
1430 FnCtxt::Foreign,
1431 ident,
1432 sig,
1433 );
1434 }
1435 ForeignItemKind::TyAlias(box TyAlias {
1436 defaultness,
1437 ident,
1438 generics,
1439 after_where_clause,
1440 bounds,
1441 ty,
1442 ..
1443 }) => {
1444 self.check_defaultness(fi.span, *defaultness);
1445 self.check_foreign_kind_bodyless(*ident, "type", ty.as_ref().map(|b| b.span));
1446 self.check_type_no_bounds(bounds, "`extern` blocks");
1447 self.check_foreign_ty_genericless(generics, after_where_clause);
1448 self.check_foreign_item_ascii_only(*ident);
1449 }
1450 ForeignItemKind::Static(box StaticItem { ident, safety, expr, .. }) => {
1451 self.check_item_safety(fi.span, *safety);
1452 self.check_foreign_kind_bodyless(*ident, "static", expr.as_ref().map(|b| b.span));
1453 self.check_foreign_item_ascii_only(*ident);
1454 }
1455 ForeignItemKind::MacCall(..) => {}
1456 }
1457
1458 visit::walk_item(self, fi)
1459 }
1460
1461 fn visit_generic_args(&mut self, generic_args: &'a GenericArgs) {
1463 match generic_args {
1464 GenericArgs::AngleBracketed(data) => {
1465 self.check_generic_args_before_constraints(data);
1466
1467 for arg in &data.args {
1468 match arg {
1469 AngleBracketedArg::Arg(arg) => self.visit_generic_arg(arg),
1470 AngleBracketedArg::Constraint(constraint) => {
1473 self.with_impl_trait(None, |this| {
1474 this.visit_assoc_item_constraint(constraint);
1475 });
1476 }
1477 }
1478 }
1479 }
1480 GenericArgs::Parenthesized(data) => {
1481 walk_list!(self, visit_ty, &data.inputs);
1482 if let FnRetTy::Ty(ty) = &data.output {
1483 self.with_impl_trait(None, |this| this.visit_ty(ty));
1486 }
1487 }
1488 GenericArgs::ParenthesizedElided(_span) => {}
1489 }
1490 }
1491
1492 fn visit_generics(&mut self, generics: &'a Generics) {
1493 let mut prev_param_default = None;
1494 for param in &generics.params {
1495 match param.kind {
1496 GenericParamKind::Lifetime => (),
1497 GenericParamKind::Type { default: Some(_), .. }
1498 | GenericParamKind::Const { default: Some(_), .. } => {
1499 prev_param_default = Some(param.ident.span);
1500 }
1501 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1502 if let Some(span) = prev_param_default {
1503 self.dcx().emit_err(errors::GenericDefaultTrailing { span });
1504 break;
1505 }
1506 }
1507 }
1508 }
1509
1510 validate_generic_param_order(self.dcx(), &generics.params, generics.span);
1511
1512 for predicate in &generics.where_clause.predicates {
1513 let span = predicate.span;
1514 if let WherePredicateKind::EqPredicate(predicate) = &predicate.kind {
1515 deny_equality_constraints(self, predicate, span, generics);
1516 }
1517 }
1518 walk_list!(self, visit_generic_param, &generics.params);
1519 for predicate in &generics.where_clause.predicates {
1520 match &predicate.kind {
1521 WherePredicateKind::BoundPredicate(bound_pred) => {
1522 if !bound_pred.bound_generic_params.is_empty() {
1528 for bound in &bound_pred.bounds {
1529 match bound {
1530 GenericBound::Trait(t) => {
1531 if !t.bound_generic_params.is_empty() {
1532 self.dcx()
1533 .emit_err(errors::NestedLifetimes { span: t.span });
1534 }
1535 }
1536 GenericBound::Outlives(_) => {}
1537 GenericBound::Use(..) => {}
1538 }
1539 }
1540 }
1541 }
1542 _ => {}
1543 }
1544 self.visit_where_predicate(predicate);
1545 }
1546 }
1547
1548 fn visit_param_bound(&mut self, bound: &'a GenericBound, ctxt: BoundKind) {
1549 match bound {
1550 GenericBound::Trait(trait_ref) => {
1551 match (ctxt, trait_ref.modifiers.constness, trait_ref.modifiers.polarity) {
1552 (
1553 BoundKind::TraitObject,
1554 BoundConstness::Always(_),
1555 BoundPolarity::Positive,
1556 ) => {
1557 self.dcx().emit_err(errors::ConstBoundTraitObject { span: trait_ref.span });
1558 }
1559 (_, BoundConstness::Maybe(span), BoundPolarity::Positive)
1560 if let Some(reason) = self.disallow_tilde_const =>
1561 {
1562 self.dcx().emit_err(errors::TildeConstDisallowed { span, reason });
1563 }
1564 _ => {}
1565 }
1566
1567 if let BoundPolarity::Negative(_) = trait_ref.modifiers.polarity
1569 && let Some(segment) = trait_ref.trait_ref.path.segments.last()
1570 {
1571 match segment.args.as_deref() {
1572 Some(ast::GenericArgs::AngleBracketed(args)) => {
1573 for arg in &args.args {
1574 if let ast::AngleBracketedArg::Constraint(constraint) = arg {
1575 self.dcx().emit_err(errors::ConstraintOnNegativeBound {
1576 span: constraint.span,
1577 });
1578 }
1579 }
1580 }
1581 Some(ast::GenericArgs::Parenthesized(args)) => {
1583 self.dcx().emit_err(errors::NegativeBoundWithParentheticalNotation {
1584 span: args.span,
1585 });
1586 }
1587 Some(ast::GenericArgs::ParenthesizedElided(_)) | None => {}
1588 }
1589 }
1590 }
1591 GenericBound::Outlives(_) => {}
1592 GenericBound::Use(_, span) => match ctxt {
1593 BoundKind::Impl => {}
1594 BoundKind::Bound | BoundKind::TraitObject | BoundKind::SuperTraits => {
1595 self.dcx().emit_err(errors::PreciseCapturingNotAllowedHere {
1596 loc: ctxt.descr(),
1597 span: *span,
1598 });
1599 }
1600 },
1601 }
1602
1603 visit::walk_param_bound(self, bound)
1604 }
1605
1606 fn visit_fn(&mut self, fk: FnKind<'a>, attrs: &AttrVec, span: Span, id: NodeId) {
1607 let self_semantic = match fk.ctxt() {
1609 Some(FnCtxt::Assoc(_)) => SelfSemantic::Yes,
1610 _ => SelfSemantic::No,
1611 };
1612 self.check_fn_decl(fk.decl(), self_semantic);
1613
1614 if let Some(&FnHeader { safety, .. }) = fk.header() {
1615 self.check_item_safety(span, safety);
1616 }
1617
1618 if let FnKind::Fn(ctxt, _, fun) = fk
1619 && let Extern::Explicit(str_lit, _) = fun.sig.header.ext
1620 && let Ok(abi) = ExternAbi::from_str(str_lit.symbol.as_str())
1621 {
1622 self.check_extern_fn_signature(abi, ctxt, &fun.ident, &fun.sig);
1623 }
1624
1625 self.check_c_variadic_type(fk, attrs);
1626
1627 if let Some(&FnHeader {
1629 constness: Const::Yes(const_span),
1630 coroutine_kind: Some(coroutine_kind),
1631 ..
1632 }) = fk.header()
1633 {
1634 self.dcx().emit_err(errors::ConstAndCoroutine {
1635 spans: vec![coroutine_kind.span(), const_span],
1636 const_span,
1637 coroutine_span: coroutine_kind.span(),
1638 coroutine_kind: coroutine_kind.as_str(),
1639 span,
1640 });
1641 }
1642
1643 if let FnKind::Fn(
1644 _,
1645 _,
1646 Fn {
1647 sig: FnSig { header: FnHeader { ext: Extern::Implicit(extern_span), .. }, .. },
1648 ..
1649 },
1650 ) = fk
1651 {
1652 self.handle_missing_abi(*extern_span, id);
1653 }
1654
1655 if let FnKind::Fn(ctxt, _, Fn { body: None, sig, .. }) = fk {
1657 Self::check_decl_no_pat(&sig.decl, |span, ident, mut_ident| {
1658 if mut_ident && matches!(ctxt, FnCtxt::Assoc(_)) {
1659 if let Some(ident) = ident {
1660 self.lint_buffer.buffer_lint(
1661 PATTERNS_IN_FNS_WITHOUT_BODY,
1662 id,
1663 span,
1664 BuiltinLintDiag::PatternsInFnsWithoutBody {
1665 span,
1666 ident,
1667 is_foreign: matches!(ctxt, FnCtxt::Foreign),
1668 },
1669 )
1670 }
1671 } else {
1672 match ctxt {
1673 FnCtxt::Foreign => self.dcx().emit_err(errors::PatternInForeign { span }),
1674 _ => self.dcx().emit_err(errors::PatternInBodiless { span }),
1675 };
1676 }
1677 });
1678 }
1679
1680 let tilde_const_allowed =
1681 matches!(fk.header(), Some(FnHeader { constness: ast::Const::Yes(_), .. }))
1682 || matches!(fk.ctxt(), Some(FnCtxt::Assoc(_)))
1683 && self
1684 .outer_trait_or_trait_impl
1685 .as_ref()
1686 .and_then(TraitOrImpl::constness)
1687 .is_some();
1688
1689 let disallowed = (!tilde_const_allowed).then(|| match fk {
1690 FnKind::Fn(_, _, f) => TildeConstReason::Function { ident: f.ident.span },
1691 FnKind::Closure(..) => TildeConstReason::Closure,
1692 });
1693 self.with_tilde_const(disallowed, |this| visit::walk_fn(this, fk));
1694 }
1695
1696 fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
1697 if let Some(ident) = item.kind.ident()
1698 && attr::contains_name(&item.attrs, sym::no_mangle)
1699 {
1700 self.check_nomangle_item_asciionly(ident, item.span);
1701 }
1702
1703 if ctxt == AssocCtxt::Trait || self.outer_trait_or_trait_impl.is_none() {
1704 self.check_defaultness(item.span, item.kind.defaultness());
1705 }
1706
1707 if let AssocCtxt::Impl { .. } = ctxt {
1708 match &item.kind {
1709 AssocItemKind::Const(box ConstItem { rhs: None, .. }) => {
1710 self.dcx().emit_err(errors::AssocConstWithoutBody {
1711 span: item.span,
1712 replace_span: self.ending_semi_or_hi(item.span),
1713 });
1714 }
1715 AssocItemKind::Fn(box Fn { body, .. }) => {
1716 if body.is_none() && !self.is_sdylib_interface {
1717 self.dcx().emit_err(errors::AssocFnWithoutBody {
1718 span: item.span,
1719 replace_span: self.ending_semi_or_hi(item.span),
1720 });
1721 }
1722 }
1723 AssocItemKind::Type(box TyAlias { bounds, ty, .. }) => {
1724 if ty.is_none() {
1725 self.dcx().emit_err(errors::AssocTypeWithoutBody {
1726 span: item.span,
1727 replace_span: self.ending_semi_or_hi(item.span),
1728 });
1729 }
1730 self.check_type_no_bounds(bounds, "`impl`s");
1731 }
1732 _ => {}
1733 }
1734 }
1735
1736 if let AssocItemKind::Type(ty_alias) = &item.kind
1737 && let Err(err) = self.check_type_alias_where_clause_location(ty_alias)
1738 {
1739 let sugg = match err.sugg {
1740 errors::WhereClauseBeforeTypeAliasSugg::Remove { .. } => None,
1741 errors::WhereClauseBeforeTypeAliasSugg::Move { snippet, right, .. } => {
1742 Some((right, snippet))
1743 }
1744 };
1745 self.lint_buffer.buffer_lint(
1746 DEPRECATED_WHERE_CLAUSE_LOCATION,
1747 item.id,
1748 err.span,
1749 BuiltinLintDiag::DeprecatedWhereclauseLocation(err.span, sugg),
1750 );
1751 }
1752
1753 match &self.outer_trait_or_trait_impl {
1754 Some(parent @ (TraitOrImpl::Trait { .. } | TraitOrImpl::TraitImpl { .. })) => {
1755 self.visibility_not_permitted(
1756 &item.vis,
1757 errors::VisibilityNotPermittedNote::TraitImpl,
1758 );
1759 if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
1760 self.check_trait_fn_not_const(sig.header.constness, parent);
1761 self.check_async_fn_in_const_trait_or_impl(sig, parent);
1762 }
1763 }
1764 Some(parent @ TraitOrImpl::Impl { constness }) => {
1765 if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
1766 self.check_impl_fn_not_const(sig.header.constness, *constness);
1767 self.check_async_fn_in_const_trait_or_impl(sig, parent);
1768 }
1769 }
1770 None => {}
1771 }
1772
1773 if let AssocItemKind::Const(ci) = &item.kind {
1774 self.check_item_named(ci.ident, "const");
1775 }
1776
1777 let parent_is_const =
1778 self.outer_trait_or_trait_impl.as_ref().and_then(TraitOrImpl::constness).is_some();
1779
1780 match &item.kind {
1781 AssocItemKind::Fn(func)
1782 if parent_is_const
1783 || ctxt == AssocCtxt::Trait
1784 || matches!(func.sig.header.constness, Const::Yes(_)) =>
1785 {
1786 self.visit_attrs_vis_ident(&item.attrs, &item.vis, &func.ident);
1787 let kind = FnKind::Fn(FnCtxt::Assoc(ctxt), &item.vis, &*func);
1788 self.visit_fn(kind, &item.attrs, item.span, item.id);
1789 }
1790 AssocItemKind::Type(_) => {
1791 let disallowed = (!parent_is_const).then(|| match self.outer_trait_or_trait_impl {
1792 Some(TraitOrImpl::Trait { .. }) => {
1793 TildeConstReason::TraitAssocTy { span: item.span }
1794 }
1795 Some(TraitOrImpl::TraitImpl { .. }) => {
1796 TildeConstReason::TraitImplAssocTy { span: item.span }
1797 }
1798 Some(TraitOrImpl::Impl { .. }) | None => {
1799 TildeConstReason::InherentAssocTy { span: item.span }
1800 }
1801 });
1802 self.with_tilde_const(disallowed, |this| {
1803 this.with_in_trait_or_impl(None, |this| {
1804 visit::walk_assoc_item(this, item, ctxt)
1805 })
1806 })
1807 }
1808 _ => self.with_in_trait_or_impl(None, |this| visit::walk_assoc_item(this, item, ctxt)),
1809 }
1810 }
1811
1812 fn visit_anon_const(&mut self, anon_const: &'a AnonConst) {
1813 self.with_tilde_const(
1814 Some(TildeConstReason::AnonConst { span: anon_const.value.span }),
1815 |this| visit::walk_anon_const(this, anon_const),
1816 )
1817 }
1818}
1819
1820fn deny_equality_constraints(
1823 this: &AstValidator<'_>,
1824 predicate: &WhereEqPredicate,
1825 predicate_span: Span,
1826 generics: &Generics,
1827) {
1828 let mut err = errors::EqualityInWhere { span: predicate_span, assoc: None, assoc2: None };
1829
1830 if let TyKind::Path(Some(qself), full_path) = &predicate.lhs_ty.kind
1832 && let TyKind::Path(None, path) = &qself.ty.kind
1833 && let [PathSegment { ident, args: None, .. }] = &path.segments[..]
1834 {
1835 for param in &generics.params {
1836 if param.ident == *ident
1837 && let [PathSegment { ident, args, .. }] = &full_path.segments[qself.position..]
1838 {
1839 let mut assoc_path = full_path.clone();
1841 assoc_path.segments.pop();
1843 let len = assoc_path.segments.len() - 1;
1844 let gen_args = args.as_deref().cloned();
1845 let arg = AngleBracketedArg::Constraint(AssocItemConstraint {
1847 id: rustc_ast::node_id::DUMMY_NODE_ID,
1848 ident: *ident,
1849 gen_args,
1850 kind: AssocItemConstraintKind::Equality {
1851 term: predicate.rhs_ty.clone().into(),
1852 },
1853 span: ident.span,
1854 });
1855 match &mut assoc_path.segments[len].args {
1857 Some(args) => match args.deref_mut() {
1858 GenericArgs::Parenthesized(_) | GenericArgs::ParenthesizedElided(..) => {
1859 continue;
1860 }
1861 GenericArgs::AngleBracketed(args) => {
1862 args.args.push(arg);
1863 }
1864 },
1865 empty_args => {
1866 *empty_args = Some(
1867 AngleBracketedArgs { span: ident.span, args: thin_vec![arg] }.into(),
1868 );
1869 }
1870 }
1871 err.assoc = Some(errors::AssociatedSuggestion {
1872 span: predicate_span,
1873 ident: *ident,
1874 param: param.ident,
1875 path: pprust::path_to_string(&assoc_path),
1876 })
1877 }
1878 }
1879 }
1880
1881 let mut suggest =
1882 |poly: &PolyTraitRef, potential_assoc: &PathSegment, predicate: &WhereEqPredicate| {
1883 if let [trait_segment] = &poly.trait_ref.path.segments[..] {
1884 let assoc = pprust::path_to_string(&ast::Path::from_ident(potential_assoc.ident));
1885 let ty = pprust::ty_to_string(&predicate.rhs_ty);
1886 let (args, span) = match &trait_segment.args {
1887 Some(args) => match args.deref() {
1888 ast::GenericArgs::AngleBracketed(args) => {
1889 let Some(arg) = args.args.last() else {
1890 return;
1891 };
1892 (format!(", {assoc} = {ty}"), arg.span().shrink_to_hi())
1893 }
1894 _ => return,
1895 },
1896 None => (format!("<{assoc} = {ty}>"), trait_segment.span().shrink_to_hi()),
1897 };
1898 let removal_span = if generics.where_clause.predicates.len() == 1 {
1899 generics.where_clause.span
1901 } else {
1902 let mut span = predicate_span;
1903 let mut prev_span: Option<Span> = None;
1904 let mut preds = generics.where_clause.predicates.iter().peekable();
1905 while let Some(pred) = preds.next() {
1907 if let WherePredicateKind::EqPredicate(_) = pred.kind
1908 && pred.span == predicate_span
1909 {
1910 if let Some(next) = preds.peek() {
1911 span = span.with_hi(next.span.lo());
1913 } else if let Some(prev_span) = prev_span {
1914 span = span.with_lo(prev_span.hi());
1916 }
1917 }
1918 prev_span = Some(pred.span);
1919 }
1920 span
1921 };
1922 err.assoc2 = Some(errors::AssociatedSuggestion2 {
1923 span,
1924 args,
1925 predicate: removal_span,
1926 trait_segment: trait_segment.ident,
1927 potential_assoc: potential_assoc.ident,
1928 });
1929 }
1930 };
1931
1932 if let TyKind::Path(None, full_path) = &predicate.lhs_ty.kind {
1933 for bounds in generics.params.iter().map(|p| &p.bounds).chain(
1935 generics.where_clause.predicates.iter().filter_map(|pred| match &pred.kind {
1936 WherePredicateKind::BoundPredicate(p) => Some(&p.bounds),
1937 _ => None,
1938 }),
1939 ) {
1940 for bound in bounds {
1941 if let GenericBound::Trait(poly) = bound
1942 && poly.modifiers == TraitBoundModifiers::NONE
1943 {
1944 if full_path.segments[..full_path.segments.len() - 1]
1945 .iter()
1946 .map(|segment| segment.ident.name)
1947 .zip(poly.trait_ref.path.segments.iter().map(|segment| segment.ident.name))
1948 .all(|(a, b)| a == b)
1949 && let Some(potential_assoc) = full_path.segments.last()
1950 {
1951 suggest(poly, potential_assoc, predicate);
1952 }
1953 }
1954 }
1955 }
1956 if let [potential_param, potential_assoc] = &full_path.segments[..] {
1958 for (ident, bounds) in generics.params.iter().map(|p| (p.ident, &p.bounds)).chain(
1959 generics.where_clause.predicates.iter().filter_map(|pred| match &pred.kind {
1960 WherePredicateKind::BoundPredicate(p)
1961 if let ast::TyKind::Path(None, path) = &p.bounded_ty.kind
1962 && let [segment] = &path.segments[..] =>
1963 {
1964 Some((segment.ident, &p.bounds))
1965 }
1966 _ => None,
1967 }),
1968 ) {
1969 if ident == potential_param.ident {
1970 for bound in bounds {
1971 if let ast::GenericBound::Trait(poly) = bound
1972 && poly.modifiers == TraitBoundModifiers::NONE
1973 {
1974 suggest(poly, potential_assoc, predicate);
1975 }
1976 }
1977 }
1978 }
1979 }
1980 }
1981 this.dcx().emit_err(err);
1982}
1983
1984pub fn check_crate(
1985 sess: &Session,
1986 features: &Features,
1987 krate: &Crate,
1988 is_sdylib_interface: bool,
1989 lints: &mut LintBuffer,
1990) -> bool {
1991 let mut validator = AstValidator {
1992 sess,
1993 features,
1994 extern_mod_span: None,
1995 outer_trait_or_trait_impl: None,
1996 has_proc_macro_decls: false,
1997 outer_impl_trait_span: None,
1998 disallow_tilde_const: Some(TildeConstReason::Item),
1999 extern_mod_safety: None,
2000 extern_mod_abi: None,
2001 lint_node_id: CRATE_NODE_ID,
2002 is_sdylib_interface,
2003 lint_buffer: lints,
2004 };
2005 visit::walk_crate(&mut validator, krate);
2006
2007 validator.has_proc_macro_decls
2008}