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