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