Skip to main content

rustc_ast_passes/
ast_validation.rs

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