rustc_ast_passes/
ast_validation.rs

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