rustc_ast_passes/
ast_validation.rs

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