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