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