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