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