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