Skip to main content

rustc_ast_passes/
ast_validation.rs

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