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