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