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