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