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