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