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