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