rustc_ast_passes/
ast_validation.rs

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