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_trace,
338                    sym::cfg_attr_trace,
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 { of_trait: true });
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 { of_trait: false });
916                });
917                walk_list!(self, visit_attribute, &item.attrs);
918                return; // Avoid visiting again.
919            }
920            ItemKind::Fn(
921                func
922                @ box Fn { defaultness, generics: _, sig, contract: _, body, define_opaque: _ },
923            ) => {
924                self.check_defaultness(item.span, *defaultness);
925
926                let is_intrinsic =
927                    item.attrs.iter().any(|a| a.name_or_empty() == sym::rustc_intrinsic);
928                if body.is_none() && !is_intrinsic {
929                    self.dcx().emit_err(errors::FnWithoutBody {
930                        span: item.span,
931                        replace_span: self.ending_semi_or_hi(item.span),
932                        extern_block_suggestion: match sig.header.ext {
933                            Extern::None => None,
934                            Extern::Implicit(start_span) => {
935                                Some(errors::ExternBlockSuggestion::Implicit {
936                                    start_span,
937                                    end_span: item.span.shrink_to_hi(),
938                                })
939                            }
940                            Extern::Explicit(abi, start_span) => {
941                                Some(errors::ExternBlockSuggestion::Explicit {
942                                    start_span,
943                                    end_span: item.span.shrink_to_hi(),
944                                    abi: abi.symbol_unescaped,
945                                })
946                            }
947                        },
948                    });
949                }
950
951                self.visit_vis(&item.vis);
952                self.visit_ident(&item.ident);
953                let kind = FnKind::Fn(FnCtxt::Free, &item.ident, &item.vis, &*func);
954                self.visit_fn(kind, item.span, item.id);
955                walk_list!(self, visit_attribute, &item.attrs);
956                return; // Avoid visiting again.
957            }
958            ItemKind::ForeignMod(ForeignMod { extern_span, abi, safety, .. }) => {
959                self.with_in_extern_mod(*safety, |this| {
960                    let old_item = mem::replace(&mut this.extern_mod, Some(item.span));
961                    this.visibility_not_permitted(
962                        &item.vis,
963                        errors::VisibilityNotPermittedNote::IndividualForeignItems,
964                    );
965
966                    if &Safety::Default == safety {
967                        if item.span.at_least_rust_2024() {
968                            this.dcx().emit_err(errors::MissingUnsafeOnExtern { span: item.span });
969                        } else {
970                            this.lint_buffer.buffer_lint(
971                                MISSING_UNSAFE_ON_EXTERN,
972                                item.id,
973                                item.span,
974                                BuiltinLintDiag::MissingUnsafeOnExtern {
975                                    suggestion: item.span.shrink_to_lo(),
976                                },
977                            );
978                        }
979                    }
980
981                    if abi.is_none() {
982                        this.maybe_lint_missing_abi(*extern_span, item.id);
983                    }
984                    visit::walk_item(this, item);
985                    this.extern_mod = old_item;
986                });
987                return; // Avoid visiting again.
988            }
989            ItemKind::Enum(def, _) => {
990                for variant in &def.variants {
991                    self.visibility_not_permitted(
992                        &variant.vis,
993                        errors::VisibilityNotPermittedNote::EnumVariant,
994                    );
995                    for field in variant.data.fields() {
996                        self.visibility_not_permitted(
997                            &field.vis,
998                            errors::VisibilityNotPermittedNote::EnumVariant,
999                        );
1000                    }
1001                }
1002            }
1003            ItemKind::Trait(box Trait { is_auto, generics, bounds, items, .. }) => {
1004                let is_const_trait =
1005                    attr::find_by_name(&item.attrs, sym::const_trait).map(|attr| attr.span);
1006                self.with_in_trait(item.span, is_const_trait, |this| {
1007                    if *is_auto == IsAuto::Yes {
1008                        // Auto traits cannot have generics, super traits nor contain items.
1009                        this.deny_generic_params(generics, item.ident.span);
1010                        this.deny_super_traits(bounds, item.ident.span);
1011                        this.deny_where_clause(&generics.where_clause, item.ident.span);
1012                        this.deny_items(items, item.ident.span);
1013                    }
1014
1015                    // Equivalent of `visit::walk_item` for `ItemKind::Trait` that inserts a bound
1016                    // context for the supertraits.
1017                    this.visit_vis(&item.vis);
1018                    this.visit_ident(&item.ident);
1019                    let disallowed = is_const_trait
1020                        .is_none()
1021                        .then(|| TildeConstReason::Trait { span: item.span });
1022                    this.with_tilde_const(disallowed, |this| {
1023                        this.visit_generics(generics);
1024                        walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits)
1025                    });
1026                    walk_list!(this, visit_assoc_item, items, AssocCtxt::Trait);
1027                });
1028                walk_list!(self, visit_attribute, &item.attrs);
1029                return; // Avoid visiting again
1030            }
1031            ItemKind::Mod(safety, mod_kind) => {
1032                if let &Safety::Unsafe(span) = safety {
1033                    self.dcx().emit_err(errors::UnsafeItem { span, kind: "module" });
1034                }
1035                // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
1036                if !matches!(mod_kind, ModKind::Loaded(_, Inline::Yes, _, _))
1037                    && !attr::contains_name(&item.attrs, sym::path)
1038                {
1039                    self.check_mod_file_item_asciionly(item.ident);
1040                }
1041            }
1042            ItemKind::Struct(vdata, generics) => match vdata {
1043                VariantData::Struct { fields, .. } => {
1044                    self.visit_vis(&item.vis);
1045                    self.visit_ident(&item.ident);
1046                    self.visit_generics(generics);
1047                    // Permit `Anon{Struct,Union}` as field type.
1048                    walk_list!(self, visit_struct_field_def, fields);
1049                    walk_list!(self, visit_attribute, &item.attrs);
1050                    return;
1051                }
1052                _ => {}
1053            },
1054            ItemKind::Union(vdata, generics) => {
1055                if vdata.fields().is_empty() {
1056                    self.dcx().emit_err(errors::FieldlessUnion { span: item.span });
1057                }
1058                match vdata {
1059                    VariantData::Struct { fields, .. } => {
1060                        self.visit_vis(&item.vis);
1061                        self.visit_ident(&item.ident);
1062                        self.visit_generics(generics);
1063                        // Permit `Anon{Struct,Union}` as field type.
1064                        walk_list!(self, visit_struct_field_def, fields);
1065                        walk_list!(self, visit_attribute, &item.attrs);
1066                        return;
1067                    }
1068                    _ => {}
1069                }
1070            }
1071            ItemKind::Const(box ConstItem { defaultness, expr, .. }) => {
1072                self.check_defaultness(item.span, *defaultness);
1073                if expr.is_none() {
1074                    self.dcx().emit_err(errors::ConstWithoutBody {
1075                        span: item.span,
1076                        replace_span: self.ending_semi_or_hi(item.span),
1077                    });
1078                }
1079            }
1080            ItemKind::Static(box StaticItem { expr, safety, .. }) => {
1081                self.check_item_safety(item.span, *safety);
1082                if matches!(safety, Safety::Unsafe(_)) {
1083                    self.dcx().emit_err(errors::UnsafeStatic { span: item.span });
1084                }
1085
1086                if expr.is_none() {
1087                    self.dcx().emit_err(errors::StaticWithoutBody {
1088                        span: item.span,
1089                        replace_span: self.ending_semi_or_hi(item.span),
1090                    });
1091                }
1092            }
1093            ItemKind::TyAlias(
1094                ty_alias @ box TyAlias { defaultness, bounds, where_clauses, ty, .. },
1095            ) => {
1096                self.check_defaultness(item.span, *defaultness);
1097                if ty.is_none() {
1098                    self.dcx().emit_err(errors::TyAliasWithoutBody {
1099                        span: item.span,
1100                        replace_span: self.ending_semi_or_hi(item.span),
1101                    });
1102                }
1103                self.check_type_no_bounds(bounds, "this context");
1104
1105                if self.features.lazy_type_alias() {
1106                    if let Err(err) = self.check_type_alias_where_clause_location(ty_alias) {
1107                        self.dcx().emit_err(err);
1108                    }
1109                } else if where_clauses.after.has_where_token {
1110                    self.dcx().emit_err(errors::WhereClauseAfterTypeAlias {
1111                        span: where_clauses.after.span,
1112                        help: self.sess.is_nightly_build(),
1113                    });
1114                }
1115            }
1116            _ => {}
1117        }
1118
1119        visit::walk_item(self, item);
1120    }
1121
1122    fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
1123        match &fi.kind {
1124            ForeignItemKind::Fn(box Fn { defaultness, sig, body, .. }) => {
1125                self.check_defaultness(fi.span, *defaultness);
1126                self.check_foreign_fn_bodyless(fi.ident, body.as_deref());
1127                self.check_foreign_fn_headerless(sig.header);
1128                self.check_foreign_item_ascii_only(fi.ident);
1129            }
1130            ForeignItemKind::TyAlias(box TyAlias {
1131                defaultness,
1132                generics,
1133                where_clauses,
1134                bounds,
1135                ty,
1136                ..
1137            }) => {
1138                self.check_defaultness(fi.span, *defaultness);
1139                self.check_foreign_kind_bodyless(fi.ident, "type", ty.as_ref().map(|b| b.span));
1140                self.check_type_no_bounds(bounds, "`extern` blocks");
1141                self.check_foreign_ty_genericless(generics, where_clauses);
1142                self.check_foreign_item_ascii_only(fi.ident);
1143            }
1144            ForeignItemKind::Static(box StaticItem { expr, safety, .. }) => {
1145                self.check_item_safety(fi.span, *safety);
1146                self.check_foreign_kind_bodyless(fi.ident, "static", expr.as_ref().map(|b| b.span));
1147                self.check_foreign_item_ascii_only(fi.ident);
1148            }
1149            ForeignItemKind::MacCall(..) => {}
1150        }
1151
1152        visit::walk_item(self, fi)
1153    }
1154
1155    // Mirrors `visit::walk_generic_args`, but tracks relevant state.
1156    fn visit_generic_args(&mut self, generic_args: &'a GenericArgs) {
1157        match generic_args {
1158            GenericArgs::AngleBracketed(data) => {
1159                self.check_generic_args_before_constraints(data);
1160
1161                for arg in &data.args {
1162                    match arg {
1163                        AngleBracketedArg::Arg(arg) => self.visit_generic_arg(arg),
1164                        // Associated type bindings such as `Item = impl Debug` in
1165                        // `Iterator<Item = Debug>` are allowed to contain nested `impl Trait`.
1166                        AngleBracketedArg::Constraint(constraint) => {
1167                            self.with_impl_trait(None, |this| {
1168                                this.visit_assoc_item_constraint(constraint);
1169                            });
1170                        }
1171                    }
1172                }
1173            }
1174            GenericArgs::Parenthesized(data) => {
1175                walk_list!(self, visit_ty, &data.inputs);
1176                if let FnRetTy::Ty(ty) = &data.output {
1177                    // `-> Foo` syntax is essentially an associated type binding,
1178                    // so it is also allowed to contain nested `impl Trait`.
1179                    self.with_impl_trait(None, |this| this.visit_ty(ty));
1180                }
1181            }
1182            GenericArgs::ParenthesizedElided(_span) => {}
1183        }
1184    }
1185
1186    fn visit_generics(&mut self, generics: &'a Generics) {
1187        let mut prev_param_default = None;
1188        for param in &generics.params {
1189            match param.kind {
1190                GenericParamKind::Lifetime => (),
1191                GenericParamKind::Type { default: Some(_), .. }
1192                | GenericParamKind::Const { default: Some(_), .. } => {
1193                    prev_param_default = Some(param.ident.span);
1194                }
1195                GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1196                    if let Some(span) = prev_param_default {
1197                        self.dcx().emit_err(errors::GenericDefaultTrailing { span });
1198                        break;
1199                    }
1200                }
1201            }
1202        }
1203
1204        validate_generic_param_order(self.dcx(), &generics.params, generics.span);
1205
1206        for predicate in &generics.where_clause.predicates {
1207            let span = predicate.span;
1208            if let WherePredicateKind::EqPredicate(predicate) = &predicate.kind {
1209                deny_equality_constraints(self, predicate, span, generics);
1210            }
1211        }
1212        walk_list!(self, visit_generic_param, &generics.params);
1213        for predicate in &generics.where_clause.predicates {
1214            match &predicate.kind {
1215                WherePredicateKind::BoundPredicate(bound_pred) => {
1216                    // This is slightly complicated. Our representation for poly-trait-refs contains a single
1217                    // binder and thus we only allow a single level of quantification. However,
1218                    // the syntax of Rust permits quantification in two places in where clauses,
1219                    // e.g., `T: for <'a> Foo<'a>` and `for <'a, 'b> &'b T: Foo<'a>`. If both are
1220                    // defined, then error.
1221                    if !bound_pred.bound_generic_params.is_empty() {
1222                        for bound in &bound_pred.bounds {
1223                            match bound {
1224                                GenericBound::Trait(t) => {
1225                                    if !t.bound_generic_params.is_empty() {
1226                                        self.dcx()
1227                                            .emit_err(errors::NestedLifetimes { span: t.span });
1228                                    }
1229                                }
1230                                GenericBound::Outlives(_) => {}
1231                                GenericBound::Use(..) => {}
1232                            }
1233                        }
1234                    }
1235                }
1236                _ => {}
1237            }
1238            self.visit_where_predicate(predicate);
1239        }
1240    }
1241
1242    fn visit_param_bound(&mut self, bound: &'a GenericBound, ctxt: BoundKind) {
1243        match bound {
1244            GenericBound::Trait(trait_ref) => {
1245                match (ctxt, trait_ref.modifiers.constness, trait_ref.modifiers.polarity) {
1246                    (BoundKind::SuperTraits, BoundConstness::Never, BoundPolarity::Maybe(_))
1247                        if !self.features.more_maybe_bounds() =>
1248                    {
1249                        self.sess
1250                            .create_feature_err(
1251                                errors::OptionalTraitSupertrait {
1252                                    span: trait_ref.span,
1253                                    path_str: pprust::path_to_string(&trait_ref.trait_ref.path),
1254                                },
1255                                sym::more_maybe_bounds,
1256                            )
1257                            .emit();
1258                    }
1259                    (BoundKind::TraitObject, BoundConstness::Never, BoundPolarity::Maybe(_))
1260                        if !self.features.more_maybe_bounds() =>
1261                    {
1262                        self.sess
1263                            .create_feature_err(
1264                                errors::OptionalTraitObject { span: trait_ref.span },
1265                                sym::more_maybe_bounds,
1266                            )
1267                            .emit();
1268                    }
1269                    (
1270                        BoundKind::TraitObject,
1271                        BoundConstness::Always(_),
1272                        BoundPolarity::Positive,
1273                    ) => {
1274                        self.dcx().emit_err(errors::ConstBoundTraitObject { span: trait_ref.span });
1275                    }
1276                    (_, BoundConstness::Maybe(span), BoundPolarity::Positive)
1277                        if let Some(reason) = self.disallow_tilde_const =>
1278                    {
1279                        self.dcx().emit_err(errors::TildeConstDisallowed { span, reason });
1280                    }
1281                    _ => {}
1282                }
1283
1284                // Negative trait bounds are not allowed to have associated constraints
1285                if let BoundPolarity::Negative(_) = trait_ref.modifiers.polarity
1286                    && let Some(segment) = trait_ref.trait_ref.path.segments.last()
1287                {
1288                    match segment.args.as_deref() {
1289                        Some(ast::GenericArgs::AngleBracketed(args)) => {
1290                            for arg in &args.args {
1291                                if let ast::AngleBracketedArg::Constraint(constraint) = arg {
1292                                    self.dcx().emit_err(errors::ConstraintOnNegativeBound {
1293                                        span: constraint.span,
1294                                    });
1295                                }
1296                            }
1297                        }
1298                        // The lowered form of parenthesized generic args contains an associated type binding.
1299                        Some(ast::GenericArgs::Parenthesized(args)) => {
1300                            self.dcx().emit_err(errors::NegativeBoundWithParentheticalNotation {
1301                                span: args.span,
1302                            });
1303                        }
1304                        Some(ast::GenericArgs::ParenthesizedElided(_)) | None => {}
1305                    }
1306                }
1307            }
1308            GenericBound::Outlives(_) => {}
1309            GenericBound::Use(_, span) => match ctxt {
1310                BoundKind::Impl => {}
1311                BoundKind::Bound | BoundKind::TraitObject | BoundKind::SuperTraits => {
1312                    self.dcx().emit_err(errors::PreciseCapturingNotAllowedHere {
1313                        loc: ctxt.descr(),
1314                        span: *span,
1315                    });
1316                }
1317            },
1318        }
1319
1320        visit::walk_param_bound(self, bound)
1321    }
1322
1323    fn visit_fn(&mut self, fk: FnKind<'a>, span: Span, id: NodeId) {
1324        // Only associated `fn`s can have `self` parameters.
1325        let self_semantic = match fk.ctxt() {
1326            Some(FnCtxt::Assoc(_)) => SelfSemantic::Yes,
1327            _ => SelfSemantic::No,
1328        };
1329        self.check_fn_decl(fk.decl(), self_semantic);
1330
1331        if let Some(&FnHeader { safety, .. }) = fk.header() {
1332            self.check_item_safety(span, safety);
1333        }
1334
1335        self.check_c_variadic_type(fk);
1336
1337        // Functions cannot both be `const async` or `const gen`
1338        if let Some(&FnHeader {
1339            constness: Const::Yes(const_span),
1340            coroutine_kind: Some(coroutine_kind),
1341            ..
1342        }) = fk.header()
1343        {
1344            self.dcx().emit_err(errors::ConstAndCoroutine {
1345                spans: vec![coroutine_kind.span(), const_span],
1346                const_span,
1347                coroutine_span: coroutine_kind.span(),
1348                coroutine_kind: coroutine_kind.as_str(),
1349                span,
1350            });
1351        }
1352
1353        if let FnKind::Fn(
1354            _,
1355            _,
1356            _,
1357            Fn {
1358                sig: FnSig { header: FnHeader { ext: Extern::Implicit(extern_span), .. }, .. },
1359                ..
1360            },
1361        ) = fk
1362        {
1363            self.maybe_lint_missing_abi(*extern_span, id);
1364        }
1365
1366        // Functions without bodies cannot have patterns.
1367        if let FnKind::Fn(ctxt, _, _, Fn { body: None, sig, .. }) = fk {
1368            Self::check_decl_no_pat(&sig.decl, |span, ident, mut_ident| {
1369                if mut_ident && matches!(ctxt, FnCtxt::Assoc(_)) {
1370                    if let Some(ident) = ident {
1371                        self.lint_buffer.buffer_lint(
1372                            PATTERNS_IN_FNS_WITHOUT_BODY,
1373                            id,
1374                            span,
1375                            BuiltinLintDiag::PatternsInFnsWithoutBody {
1376                                span,
1377                                ident,
1378                                is_foreign: matches!(ctxt, FnCtxt::Foreign),
1379                            },
1380                        )
1381                    }
1382                } else {
1383                    match ctxt {
1384                        FnCtxt::Foreign => self.dcx().emit_err(errors::PatternInForeign { span }),
1385                        _ => self.dcx().emit_err(errors::PatternInBodiless { span }),
1386                    };
1387                }
1388            });
1389        }
1390
1391        let tilde_const_allowed =
1392            matches!(fk.header(), Some(FnHeader { constness: ast::Const::Yes(_), .. }))
1393                || matches!(fk.ctxt(), Some(FnCtxt::Assoc(_)))
1394                    && self
1395                        .outer_trait_or_trait_impl
1396                        .as_ref()
1397                        .and_then(TraitOrTraitImpl::constness)
1398                        .is_some();
1399
1400        let disallowed = (!tilde_const_allowed).then(|| match fk {
1401            FnKind::Fn(_, ident, _, _) => TildeConstReason::Function { ident: ident.span },
1402            FnKind::Closure(..) => TildeConstReason::Closure,
1403        });
1404        self.with_tilde_const(disallowed, |this| visit::walk_fn(this, fk));
1405    }
1406
1407    fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
1408        if attr::contains_name(&item.attrs, sym::no_mangle) {
1409            self.check_nomangle_item_asciionly(item.ident, item.span);
1410        }
1411
1412        if ctxt == AssocCtxt::Trait || self.outer_trait_or_trait_impl.is_none() {
1413            self.check_defaultness(item.span, item.kind.defaultness());
1414        }
1415
1416        if let AssocCtxt::Impl { .. } = ctxt {
1417            match &item.kind {
1418                AssocItemKind::Const(box ConstItem { expr: None, .. }) => {
1419                    self.dcx().emit_err(errors::AssocConstWithoutBody {
1420                        span: item.span,
1421                        replace_span: self.ending_semi_or_hi(item.span),
1422                    });
1423                }
1424                AssocItemKind::Fn(box Fn { body, .. }) => {
1425                    if body.is_none() {
1426                        self.dcx().emit_err(errors::AssocFnWithoutBody {
1427                            span: item.span,
1428                            replace_span: self.ending_semi_or_hi(item.span),
1429                        });
1430                    }
1431                }
1432                AssocItemKind::Type(box TyAlias { bounds, ty, .. }) => {
1433                    if ty.is_none() {
1434                        self.dcx().emit_err(errors::AssocTypeWithoutBody {
1435                            span: item.span,
1436                            replace_span: self.ending_semi_or_hi(item.span),
1437                        });
1438                    }
1439                    self.check_type_no_bounds(bounds, "`impl`s");
1440                }
1441                _ => {}
1442            }
1443        }
1444
1445        if let AssocItemKind::Type(ty_alias) = &item.kind
1446            && let Err(err) = self.check_type_alias_where_clause_location(ty_alias)
1447        {
1448            let sugg = match err.sugg {
1449                errors::WhereClauseBeforeTypeAliasSugg::Remove { .. } => None,
1450                errors::WhereClauseBeforeTypeAliasSugg::Move { snippet, right, .. } => {
1451                    Some((right, snippet))
1452                }
1453            };
1454            self.lint_buffer.buffer_lint(
1455                DEPRECATED_WHERE_CLAUSE_LOCATION,
1456                item.id,
1457                err.span,
1458                BuiltinLintDiag::DeprecatedWhereclauseLocation(err.span, sugg),
1459            );
1460        }
1461
1462        if let Some(parent) = &self.outer_trait_or_trait_impl {
1463            self.visibility_not_permitted(&item.vis, errors::VisibilityNotPermittedNote::TraitImpl);
1464            if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
1465                self.check_trait_fn_not_const(sig.header.constness, parent);
1466            }
1467        }
1468
1469        if let AssocItemKind::Const(..) = item.kind {
1470            self.check_item_named(item.ident, "const");
1471        }
1472
1473        let parent_is_const =
1474            self.outer_trait_or_trait_impl.as_ref().and_then(TraitOrTraitImpl::constness).is_some();
1475
1476        match &item.kind {
1477            AssocItemKind::Fn(func)
1478                if parent_is_const
1479                    || ctxt == AssocCtxt::Trait
1480                    || matches!(func.sig.header.constness, Const::Yes(_)) =>
1481            {
1482                self.visit_vis(&item.vis);
1483                self.visit_ident(&item.ident);
1484                let kind = FnKind::Fn(FnCtxt::Assoc(ctxt), &item.ident, &item.vis, &*func);
1485                walk_list!(self, visit_attribute, &item.attrs);
1486                self.visit_fn(kind, item.span, item.id);
1487            }
1488            AssocItemKind::Type(_) => {
1489                let disallowed = (!parent_is_const).then(|| match self.outer_trait_or_trait_impl {
1490                    Some(TraitOrTraitImpl::Trait { .. }) => {
1491                        TildeConstReason::TraitAssocTy { span: item.span }
1492                    }
1493                    Some(TraitOrTraitImpl::TraitImpl { .. }) => {
1494                        TildeConstReason::TraitImplAssocTy { span: item.span }
1495                    }
1496                    None => TildeConstReason::InherentAssocTy { span: item.span },
1497                });
1498                self.with_tilde_const(disallowed, |this| {
1499                    this.with_in_trait_impl(None, |this| visit::walk_assoc_item(this, item, ctxt))
1500                })
1501            }
1502            _ => self.with_in_trait_impl(None, |this| visit::walk_assoc_item(this, item, ctxt)),
1503        }
1504    }
1505}
1506
1507/// When encountering an equality constraint in a `where` clause, emit an error. If the code seems
1508/// like it's setting an associated type, provide an appropriate suggestion.
1509fn deny_equality_constraints(
1510    this: &AstValidator<'_>,
1511    predicate: &WhereEqPredicate,
1512    predicate_span: Span,
1513    generics: &Generics,
1514) {
1515    let mut err = errors::EqualityInWhere { span: predicate_span, assoc: None, assoc2: None };
1516
1517    // Given `<A as Foo>::Bar = RhsTy`, suggest `A: Foo<Bar = RhsTy>`.
1518    if let TyKind::Path(Some(qself), full_path) = &predicate.lhs_ty.kind
1519        && let TyKind::Path(None, path) = &qself.ty.kind
1520        && let [PathSegment { ident, args: None, .. }] = &path.segments[..]
1521    {
1522        for param in &generics.params {
1523            if param.ident == *ident
1524                && let [PathSegment { ident, args, .. }] = &full_path.segments[qself.position..]
1525            {
1526                // Make a new `Path` from `foo::Bar` to `Foo<Bar = RhsTy>`.
1527                let mut assoc_path = full_path.clone();
1528                // Remove `Bar` from `Foo::Bar`.
1529                assoc_path.segments.pop();
1530                let len = assoc_path.segments.len() - 1;
1531                let gen_args = args.as_deref().cloned();
1532                // Build `<Bar = RhsTy>`.
1533                let arg = AngleBracketedArg::Constraint(AssocItemConstraint {
1534                    id: rustc_ast::node_id::DUMMY_NODE_ID,
1535                    ident: *ident,
1536                    gen_args,
1537                    kind: AssocItemConstraintKind::Equality {
1538                        term: predicate.rhs_ty.clone().into(),
1539                    },
1540                    span: ident.span,
1541                });
1542                // Add `<Bar = RhsTy>` to `Foo`.
1543                match &mut assoc_path.segments[len].args {
1544                    Some(args) => match args.deref_mut() {
1545                        GenericArgs::Parenthesized(_) | GenericArgs::ParenthesizedElided(..) => {
1546                            continue;
1547                        }
1548                        GenericArgs::AngleBracketed(args) => {
1549                            args.args.push(arg);
1550                        }
1551                    },
1552                    empty_args => {
1553                        *empty_args = Some(
1554                            AngleBracketedArgs { span: ident.span, args: thin_vec![arg] }.into(),
1555                        );
1556                    }
1557                }
1558                err.assoc = Some(errors::AssociatedSuggestion {
1559                    span: predicate_span,
1560                    ident: *ident,
1561                    param: param.ident,
1562                    path: pprust::path_to_string(&assoc_path),
1563                })
1564            }
1565        }
1566    }
1567
1568    let mut suggest =
1569        |poly: &PolyTraitRef, potential_assoc: &PathSegment, predicate: &WhereEqPredicate| {
1570            if let [trait_segment] = &poly.trait_ref.path.segments[..] {
1571                let assoc = pprust::path_to_string(&ast::Path::from_ident(potential_assoc.ident));
1572                let ty = pprust::ty_to_string(&predicate.rhs_ty);
1573                let (args, span) = match &trait_segment.args {
1574                    Some(args) => match args.deref() {
1575                        ast::GenericArgs::AngleBracketed(args) => {
1576                            let Some(arg) = args.args.last() else {
1577                                return;
1578                            };
1579                            (format!(", {assoc} = {ty}"), arg.span().shrink_to_hi())
1580                        }
1581                        _ => return,
1582                    },
1583                    None => (format!("<{assoc} = {ty}>"), trait_segment.span().shrink_to_hi()),
1584                };
1585                let removal_span = if generics.where_clause.predicates.len() == 1 {
1586                    // We're removing th eonly where bound left, remove the whole thing.
1587                    generics.where_clause.span
1588                } else {
1589                    let mut span = predicate_span;
1590                    let mut prev: Option<Span> = None;
1591                    let mut preds = generics.where_clause.predicates.iter().peekable();
1592                    // Find the predicate that shouldn't have been in the where bound list.
1593                    while let Some(pred) = preds.next() {
1594                        if let WherePredicateKind::EqPredicate(_) = pred.kind
1595                            && pred.span == predicate_span
1596                        {
1597                            if let Some(next) = preds.peek() {
1598                                // This is the first predicate, remove the trailing comma as well.
1599                                span = span.with_hi(next.span.lo());
1600                            } else if let Some(prev) = prev {
1601                                // Remove the previous comma as well.
1602                                span = span.with_lo(prev.hi());
1603                            }
1604                        }
1605                        prev = Some(pred.span);
1606                    }
1607                    span
1608                };
1609                err.assoc2 = Some(errors::AssociatedSuggestion2 {
1610                    span,
1611                    args,
1612                    predicate: removal_span,
1613                    trait_segment: trait_segment.ident,
1614                    potential_assoc: potential_assoc.ident,
1615                });
1616            }
1617        };
1618
1619    if let TyKind::Path(None, full_path) = &predicate.lhs_ty.kind {
1620        // Given `A: Foo, Foo::Bar = RhsTy`, suggest `A: Foo<Bar = RhsTy>`.
1621        for bounds in generics.params.iter().map(|p| &p.bounds).chain(
1622            generics.where_clause.predicates.iter().filter_map(|pred| match &pred.kind {
1623                WherePredicateKind::BoundPredicate(p) => Some(&p.bounds),
1624                _ => None,
1625            }),
1626        ) {
1627            for bound in bounds {
1628                if let GenericBound::Trait(poly) = bound
1629                    && poly.modifiers == TraitBoundModifiers::NONE
1630                {
1631                    if full_path.segments[..full_path.segments.len() - 1]
1632                        .iter()
1633                        .map(|segment| segment.ident.name)
1634                        .zip(poly.trait_ref.path.segments.iter().map(|segment| segment.ident.name))
1635                        .all(|(a, b)| a == b)
1636                        && let Some(potential_assoc) = full_path.segments.iter().last()
1637                    {
1638                        suggest(poly, potential_assoc, predicate);
1639                    }
1640                }
1641            }
1642        }
1643        // Given `A: Foo, A::Bar = RhsTy`, suggest `A: Foo<Bar = RhsTy>`.
1644        if let [potential_param, potential_assoc] = &full_path.segments[..] {
1645            for (ident, bounds) in generics.params.iter().map(|p| (p.ident, &p.bounds)).chain(
1646                generics.where_clause.predicates.iter().filter_map(|pred| match &pred.kind {
1647                    WherePredicateKind::BoundPredicate(p)
1648                        if let ast::TyKind::Path(None, path) = &p.bounded_ty.kind
1649                            && let [segment] = &path.segments[..] =>
1650                    {
1651                        Some((segment.ident, &p.bounds))
1652                    }
1653                    _ => None,
1654                }),
1655            ) {
1656                if ident == potential_param.ident {
1657                    for bound in bounds {
1658                        if let ast::GenericBound::Trait(poly) = bound
1659                            && poly.modifiers == TraitBoundModifiers::NONE
1660                        {
1661                            suggest(poly, potential_assoc, predicate);
1662                        }
1663                    }
1664                }
1665            }
1666        }
1667    }
1668    this.dcx().emit_err(err);
1669}
1670
1671pub fn check_crate(
1672    sess: &Session,
1673    features: &Features,
1674    krate: &Crate,
1675    lints: &mut LintBuffer,
1676) -> bool {
1677    let mut validator = AstValidator {
1678        sess,
1679        features,
1680        extern_mod: None,
1681        outer_trait_or_trait_impl: None,
1682        has_proc_macro_decls: false,
1683        outer_impl_trait: None,
1684        disallow_tilde_const: Some(TildeConstReason::Item),
1685        extern_mod_safety: None,
1686        lint_buffer: lints,
1687    };
1688    visit::walk_crate(&mut validator, krate);
1689
1690    validator.has_proc_macro_decls
1691}