1 // Validate AST before lowering it to HIR.
3 // This pass is supposed to catch things that fit into AST data structures,
4 // but not permitted by the language. It runs after expansion when AST is frozen,
5 // so it can check for erroneous constructions produced by syntax extensions.
6 // This pass is supposed to perform only simple checks not requiring name resolution
7 // or type checking or some other kind of complex analysis.
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_errors::{struct_span_err, Applicability, FatalError};
11 use rustc_parse::validate_attr;
12 use rustc_session::lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY;
13 use rustc_session::lint::LintBuffer;
14 use rustc_session::Session;
15 use rustc_span::source_map::Spanned;
16 use rustc_span::symbol::{kw, sym};
21 use syntax::expand::is_proc_macro_attr;
22 use syntax::print::pprust;
23 use syntax::visit::{self, Visitor};
24 use syntax::walk_list;
26 /// A syntactic context that disallows certain kinds of bounds (e.g., `?Trait` or `?const Trait`).
27 #[derive(Clone, Copy)]
35 fn description(&self) -> &'static str {
37 Self::ImplTrait => "`impl Trait`",
38 Self::TraitBounds => "supertraits",
39 Self::TraitObject => "trait objects",
44 struct AstValidator<'a> {
46 has_proc_macro_decls: bool,
48 /// Used to ban nested `impl Trait`, e.g., `impl Into<impl Debug>`.
49 /// Nested `impl Trait` _is_ allowed in associated type position,
50 /// e.g., `impl Iterator<Item = impl Debug>`.
51 outer_impl_trait: Option<Span>,
53 /// Keeps track of the `BoundContext` as we recurse.
55 /// This is used to forbid `?const Trait` bounds in, e.g.,
56 /// `impl Iterator<Item = Box<dyn ?const Trait>`.
57 bound_context: Option<BoundContext>,
59 /// Used to ban `impl Trait` in path projections like `<impl Iterator>::Item`
60 /// or `Foo::Bar<impl Trait>`
61 is_impl_trait_banned: bool,
63 /// Used to ban associated type bounds (i.e., `Type<AssocType: Bounds>`) in
64 /// certain positions.
65 is_assoc_ty_bound_banned: bool,
67 lint_buffer: &'a mut LintBuffer,
70 impl<'a> AstValidator<'a> {
71 fn with_banned_impl_trait(&mut self, f: impl FnOnce(&mut Self)) {
72 let old = mem::replace(&mut self.is_impl_trait_banned, true);
74 self.is_impl_trait_banned = old;
77 fn with_banned_assoc_ty_bound(&mut self, f: impl FnOnce(&mut Self)) {
78 let old = mem::replace(&mut self.is_assoc_ty_bound_banned, true);
80 self.is_assoc_ty_bound_banned = old;
83 fn with_impl_trait(&mut self, outer: Option<Span>, f: impl FnOnce(&mut Self)) {
84 let old = mem::replace(&mut self.outer_impl_trait, outer);
86 self.with_bound_context(BoundContext::ImplTrait, |this| f(this));
90 self.outer_impl_trait = old;
93 fn with_bound_context(&mut self, ctx: BoundContext, f: impl FnOnce(&mut Self)) {
94 let old = self.bound_context.replace(ctx);
96 self.bound_context = old;
99 fn visit_assoc_ty_constraint_from_generic_args(&mut self, constraint: &'a AssocTyConstraint) {
100 match constraint.kind {
101 AssocTyConstraintKind::Equality { .. } => {}
102 AssocTyConstraintKind::Bound { .. } => {
103 if self.is_assoc_ty_bound_banned {
104 self.err_handler().span_err(
106 "associated type bounds are not allowed within structs, enums, or unions",
111 self.visit_assoc_ty_constraint(constraint);
114 // Mirrors `visit::walk_ty`, but tracks relevant state.
115 fn walk_ty(&mut self, t: &'a Ty) {
117 TyKind::ImplTrait(..) => {
118 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
120 TyKind::TraitObject(..) => {
121 self.with_bound_context(BoundContext::TraitObject, |this| visit::walk_ty(this, t));
123 TyKind::Path(ref qself, ref path) => {
125 // - `Option<impl Trait>`
126 // - `option::Option<impl Trait>`
127 // - `option::Option<T>::Foo<impl Trait>
130 // - `<impl Trait>::Foo`
131 // - `option::Option<impl Trait>::Foo`.
133 // To implement this, we disallow `impl Trait` from `qself`
134 // (for cases like `<impl Trait>::Foo>`)
135 // but we allow `impl Trait` in `GenericArgs`
136 // iff there are no more PathSegments.
137 if let Some(ref qself) = *qself {
138 // `impl Trait` in `qself` is always illegal
139 self.with_banned_impl_trait(|this| this.visit_ty(&qself.ty));
142 // Note that there should be a call to visit_path here,
143 // so if any logic is added to process `Path`s a call to it should be
144 // added both in visit_path and here. This code mirrors visit::walk_path.
145 for (i, segment) in path.segments.iter().enumerate() {
146 // Allow `impl Trait` iff we're on the final path segment
147 if i == path.segments.len() - 1 {
148 self.visit_path_segment(path.span, segment);
150 self.with_banned_impl_trait(|this| {
151 this.visit_path_segment(path.span, segment)
156 _ => visit::walk_ty(self, t),
160 fn err_handler(&self) -> &rustc_errors::Handler {
161 &self.session.diagnostic()
164 fn check_lifetime(&self, ident: Ident) {
165 let valid_names = [kw::UnderscoreLifetime, kw::StaticLifetime, kw::Invalid];
166 if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() {
167 self.err_handler().span_err(ident.span, "lifetimes cannot use keyword names");
171 fn check_label(&self, ident: Ident) {
172 if ident.without_first_quote().is_reserved() {
174 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
178 fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
179 if let VisibilityKind::Inherited = vis.node {
184 struct_span_err!(self.session, vis.span, E0449, "unnecessary visibility qualifier");
185 if vis.node.is_pub() {
186 err.span_label(vis.span, "`pub` not permitted here because it's implied");
188 if let Some(note) = note {
194 fn check_decl_no_pat(decl: &FnDecl, mut report_err: impl FnMut(Span, bool)) {
195 for Param { pat, .. } in &decl.inputs {
197 PatKind::Ident(BindingMode::ByValue(Mutability::Not), _, None) | PatKind::Wild => {}
198 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), _, None) => {
199 report_err(pat.span, true)
201 _ => report_err(pat.span, false),
206 fn check_trait_fn_not_async(&self, span: Span, asyncness: IsAsync) {
207 if asyncness.is_async() {
208 struct_span_err!(self.session, span, E0706, "trait fns cannot be declared `async`")
209 .note("`async` trait functions are not currently supported")
211 "consider using the `async-trait` crate: \
212 https://crates.io/crates/async-trait",
218 fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
219 if constness.node == Constness::Const {
224 "trait fns cannot be declared const"
226 .span_label(constness.span, "trait fns cannot be const")
231 // FIXME(ecstaticmorse): Instead, use `bound_context` to check this in `visit_param_bound`.
232 fn no_questions_in_bounds(&self, bounds: &GenericBounds, where_: &str, is_trait: bool) {
233 for bound in bounds {
234 if let GenericBound::Trait(ref poly, TraitBoundModifier::Maybe) = *bound {
235 let mut err = self.err_handler().struct_span_err(
237 &format!("`?Trait` is not permitted in {}", where_),
240 let path_str = pprust::path_to_string(&poly.trait_ref.path);
241 err.note(&format!("traits are `?{}` by default", path_str));
248 /// Matches `'-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus)`,
249 /// or paths for ranges.
251 // FIXME: do we want to allow `expr -> pattern` conversion to create path expressions?
252 // That means making this work:
254 // ```rust,ignore (FIXME)
263 fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
265 ExprKind::Lit(..) | ExprKind::Err => {}
266 ExprKind::Path(..) if allow_paths => {}
267 ExprKind::Unary(UnOp::Neg, ref inner)
268 if match inner.kind {
269 ExprKind::Lit(_) => true,
272 _ => self.err_handler().span_err(
274 "arbitrary expressions aren't allowed \
280 fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) {
281 // Check only lifetime parameters are present and that the lifetime
282 // parameters that are present have no bounds.
283 let non_lt_param_spans: Vec<_> = params
285 .filter_map(|param| match param.kind {
286 GenericParamKind::Lifetime { .. } => {
287 if !param.bounds.is_empty() {
288 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
290 .span_err(spans, "lifetime bounds cannot be used in this context");
294 _ => Some(param.ident.span),
297 if !non_lt_param_spans.is_empty() {
298 self.err_handler().span_err(
300 "only lifetime parameters can be used in this context",
305 fn check_fn_decl(&self, fn_decl: &FnDecl) {
306 match &*fn_decl.inputs {
307 [Param { ty, span, .. }] => {
308 if let TyKind::CVarArgs = ty.kind {
309 self.err_handler().span_err(
311 "C-variadic function must be declared with at least one named argument",
316 for Param { ty, span, .. } in ps {
317 if let TyKind::CVarArgs = ty.kind {
318 self.err_handler().span_err(
320 "`...` must be the last argument of a C-variadic function",
331 .flat_map(|i| i.attrs.as_ref())
333 let arr = [sym::allow, sym::cfg, sym::cfg_attr, sym::deny, sym::forbid, sym::warn];
334 !arr.contains(&attr.name_or_empty()) && attr::is_builtin_attr(attr)
337 if attr.is_doc_comment() {
341 "documentation comments cannot be applied to function parameters",
343 .span_label(attr.span, "doc comments are not allowed here")
346 self.err_handler().span_err(
348 "allow, cfg, cfg_attr, deny, \
349 forbid, and warn are the only allowed built-in attributes in function parameters",
355 fn check_defaultness(&self, span: Span, defaultness: Defaultness) {
356 if let Defaultness::Default = defaultness {
358 .struct_span_err(span, "`default` is only allowed on items in `impl` definitions")
363 fn check_impl_item_provided<T>(&self, sp: Span, body: &Option<T>, ctx: &str, sugg: &str) {
369 .struct_span_err(sp, &format!("associated {} in `impl` without body", ctx))
371 self.session.source_map().end_point(sp),
372 &format!("provide a definition for the {}", ctx),
374 Applicability::HasPlaceholders,
379 fn check_impl_assoc_type_no_bounds(&self, bounds: &[GenericBound]) {
380 let span = match bounds {
383 [b0, .., bl] => b0.span().to(bl.span()),
386 .struct_span_err(span, "bounds on associated `type`s in `impl`s have no effect")
390 fn check_c_varadic_type(&self, decl: &FnDecl) {
391 for Param { ty, span, .. } in &decl.inputs {
392 if let TyKind::CVarArgs = ty.kind {
396 "only foreign or `unsafe extern \"C\" functions may be C-variadic",
404 enum GenericPosition {
409 fn validate_generics_order<'a>(
411 handler: &rustc_errors::Handler,
412 generics: impl Iterator<Item = (ParamKindOrd, Option<&'a [GenericBound]>, Span, Option<String>)>,
413 pos: GenericPosition,
416 let mut max_param: Option<ParamKindOrd> = None;
417 let mut out_of_order = FxHashMap::default();
418 let mut param_idents = vec![];
419 let mut found_type = false;
420 let mut found_const = false;
422 for (kind, bounds, span, ident) in generics {
423 if let Some(ident) = ident {
424 param_idents.push((kind, bounds, param_idents.len(), ident));
426 let max_param = &mut max_param;
428 Some(max_param) if *max_param > kind => {
429 let entry = out_of_order.entry(kind).or_insert((*max_param, vec![]));
432 Some(_) | None => *max_param = Some(kind),
435 ParamKindOrd::Type => found_type = true,
436 ParamKindOrd::Const => found_const = true,
441 let mut ordered_params = "<".to_string();
442 if !out_of_order.is_empty() {
443 param_idents.sort_by_key(|&(po, _, i, _)| (po, i));
444 let mut first = true;
445 for (_, bounds, _, ident) in param_idents {
447 ordered_params += ", ";
449 ordered_params += &ident;
450 if let Some(bounds) = bounds {
451 if !bounds.is_empty() {
452 ordered_params += ": ";
453 ordered_params += &pprust::bounds_to_string(&bounds);
459 ordered_params += ">";
461 let pos_str = match pos {
462 GenericPosition::Param => "parameter",
463 GenericPosition::Arg => "argument",
466 for (param_ord, (max_param, spans)) in &out_of_order {
467 let mut err = handler.struct_span_err(
470 "{} {pos}s must be declared prior to {} {pos}s",
476 if let GenericPosition::Param = pos {
480 "reorder the {}s: lifetimes, then types{}",
482 if sess.features_untracked().const_generics { ", then consts" } else { "" },
484 ordered_params.clone(),
485 Applicability::MachineApplicable,
491 // FIXME(const_generics): we shouldn't have to abort here at all, but we currently get ICEs
492 // if we don't. Const parameters and type parameters can currently conflict if they
494 if !out_of_order.is_empty() && found_type && found_const {
499 impl<'a> Visitor<'a> for AstValidator<'a> {
500 fn visit_attribute(&mut self, attr: &Attribute) {
501 validate_attr::check_meta(&self.session.parse_sess, attr);
504 fn visit_expr(&mut self, expr: &'a Expr) {
506 ExprKind::Closure(_, _, _, fn_decl, _, _) => {
507 self.check_fn_decl(fn_decl);
509 ExprKind::InlineAsm(..) if !self.session.target.target.options.allow_asm => {
514 "asm! is unsupported on this target"
521 visit::walk_expr(self, expr);
524 fn visit_ty(&mut self, ty: &'a Ty) {
526 TyKind::BareFn(ref bfty) => {
527 self.check_fn_decl(&bfty.decl);
528 Self::check_decl_no_pat(&bfty.decl, |span, _| {
533 "patterns aren't allowed in function pointer types"
537 self.check_late_bound_lifetime_defs(&bfty.generic_params);
539 TyKind::TraitObject(ref bounds, ..) => {
540 let mut any_lifetime_bounds = false;
541 for bound in bounds {
542 if let GenericBound::Outlives(ref lifetime) = *bound {
543 if any_lifetime_bounds {
548 "only a single explicit lifetime bound is permitted"
553 any_lifetime_bounds = true;
556 self.no_questions_in_bounds(bounds, "trait object types", false);
558 TyKind::ImplTrait(_, ref bounds) => {
559 if self.is_impl_trait_banned {
564 "`impl Trait` is not allowed in path parameters"
569 if let Some(outer_impl_trait_sp) = self.outer_impl_trait {
574 "nested `impl Trait` is not allowed"
576 .span_label(outer_impl_trait_sp, "outer `impl Trait`")
577 .span_label(ty.span, "nested `impl Trait` here")
583 .any(|b| if let GenericBound::Trait(..) = *b { true } else { false })
585 self.err_handler().span_err(ty.span, "at least one trait must be specified");
597 fn visit_label(&mut self, label: &'a Label) {
598 self.check_label(label.ident);
599 visit::walk_label(self, label);
602 fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
603 self.check_lifetime(lifetime.ident);
604 visit::walk_lifetime(self, lifetime);
607 fn visit_item(&mut self, item: &'a Item) {
608 if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)) {
609 self.has_proc_macro_decls = true;
622 self.invalid_visibility(&item.vis, None);
623 if let TyKind::Err = self_ty.kind {
625 .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
626 .help("use `auto trait Trait {}` instead")
629 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
634 "negative impls cannot be unsafe"
638 for impl_item in items {
639 self.invalid_visibility(&impl_item.vis, None);
640 if let AssocItemKind::Fn(ref sig, _) = impl_item.kind {
641 self.check_trait_fn_not_const(sig.header.constness);
642 self.check_trait_fn_not_async(impl_item.span, sig.header.asyncness.node);
655 self.invalid_visibility(
657 Some("place qualifiers on individual impl items instead"),
659 if unsafety == Unsafety::Unsafe {
664 "inherent impls cannot be unsafe"
668 if polarity == ImplPolarity::Negative {
669 self.err_handler().span_err(item.span, "inherent impls cannot be negative");
671 if defaultness == Defaultness::Default {
673 .struct_span_err(item.span, "inherent impls cannot be default")
674 .note("only trait implementations may be annotated with default")
678 ItemKind::Fn(ref sig, ref generics, _) => {
679 self.visit_fn_header(&sig.header);
680 self.check_fn_decl(&sig.decl);
681 // We currently do not permit const generics in `const fn`, as
682 // this is tantamount to allowing compile-time dependent typing.
683 if sig.header.constness.node == Constness::Const {
684 // Look for const generics and error if we find any.
685 for param in &generics.params {
687 GenericParamKind::Const { .. } => {
691 "const parameters are not permitted in `const fn`",
699 // Reject C-varadic type unless the function is `unsafe extern "C"` semantically.
700 match sig.header.ext {
701 Extern::Explicit(StrLit { symbol_unescaped: sym::C, .. })
703 if sig.header.unsafety == Unsafety::Unsafe => {}
704 _ => self.check_c_varadic_type(&sig.decl),
707 ItemKind::ForeignMod(..) => {
708 self.invalid_visibility(
710 Some("place qualifiers on individual foreign items instead"),
713 ItemKind::Enum(ref def, _) => {
714 for variant in &def.variants {
715 self.invalid_visibility(&variant.vis, None);
716 for field in variant.data.fields() {
717 self.invalid_visibility(&field.vis, None);
721 ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
722 if is_auto == IsAuto::Yes {
723 // Auto traits cannot have generics, super traits nor contain items.
724 if !generics.params.is_empty() {
729 "auto traits cannot have generic parameters"
733 if !bounds.is_empty() {
738 "auto traits cannot have super traits"
742 if !trait_items.is_empty() {
747 "auto traits cannot have methods or associated items"
752 self.no_questions_in_bounds(bounds, "supertraits", true);
754 // Equivalent of `visit::walk_item` for `ItemKind::Trait` that inserts a bound
755 // context for the supertraits.
756 self.visit_vis(&item.vis);
757 self.visit_ident(item.ident);
758 self.visit_generics(generics);
759 self.with_bound_context(BoundContext::TraitBounds, |this| {
760 walk_list!(this, visit_param_bound, bounds);
762 walk_list!(self, visit_trait_item, trait_items);
763 walk_list!(self, visit_attribute, &item.attrs);
766 ItemKind::Mod(_) => {
767 // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
768 attr::first_attr_value_str_by_name(&item.attrs, sym::path);
770 ItemKind::Union(ref vdata, _) => {
771 if let VariantData::Tuple(..) | VariantData::Unit(..) = vdata {
773 .span_err(item.span, "tuple and unit unions are not permitted");
775 if vdata.fields().is_empty() {
776 self.err_handler().span_err(item.span, "unions cannot have zero fields");
782 visit::walk_item(self, item)
785 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
787 ForeignItemKind::Fn(ref decl, _) => {
788 self.check_fn_decl(decl);
789 Self::check_decl_no_pat(decl, |span, _| {
794 "patterns aren't allowed in foreign function declarations"
796 .span_label(span, "pattern not allowed in foreign function")
800 ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
803 visit::walk_foreign_item(self, fi)
806 // Mirrors `visit::walk_generic_args`, but tracks relevant state.
807 fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
808 match *generic_args {
809 GenericArgs::AngleBracketed(ref data) => {
810 walk_list!(self, visit_generic_arg, &data.args);
811 validate_generics_order(
814 data.args.iter().map(|arg| {
817 GenericArg::Lifetime(..) => ParamKindOrd::Lifetime,
818 GenericArg::Type(..) => ParamKindOrd::Type,
819 GenericArg::Const(..) => ParamKindOrd::Const,
826 GenericPosition::Arg,
830 // Type bindings such as `Item = impl Debug` in `Iterator<Item = Debug>`
831 // are allowed to contain nested `impl Trait`.
832 self.with_impl_trait(None, |this| {
835 visit_assoc_ty_constraint_from_generic_args,
840 GenericArgs::Parenthesized(ref data) => {
841 walk_list!(self, visit_ty, &data.inputs);
842 if let FunctionRetTy::Ty(ty) = &data.output {
843 // `-> Foo` syntax is essentially an associated type binding,
844 // so it is also allowed to contain nested `impl Trait`.
845 self.with_impl_trait(None, |this| this.visit_ty(ty));
851 fn visit_generics(&mut self, generics: &'a Generics) {
852 let mut prev_ty_default = None;
853 for param in &generics.params {
854 if let GenericParamKind::Type { ref default, .. } = param.kind {
855 if default.is_some() {
856 prev_ty_default = Some(param.ident.span);
857 } else if let Some(span) = prev_ty_default {
859 .span_err(span, "type parameters with a default must be trailing");
865 validate_generics_order(
868 generics.params.iter().map(|param| {
869 let ident = Some(param.ident.to_string());
870 let (kind, ident) = match ¶m.kind {
871 GenericParamKind::Lifetime { .. } => (ParamKindOrd::Lifetime, ident),
872 GenericParamKind::Type { .. } => (ParamKindOrd::Type, ident),
873 GenericParamKind::Const { ref ty } => {
874 let ty = pprust::ty_to_string(ty);
875 (ParamKindOrd::Const, Some(format!("const {}: {}", param.ident, ty)))
878 (kind, Some(&*param.bounds), param.ident.span, ident)
880 GenericPosition::Param,
884 for predicate in &generics.where_clause.predicates {
885 if let WherePredicate::EqPredicate(ref predicate) = *predicate {
889 "equality constraints are not yet supported in `where` clauses",
891 .span_label(predicate.span, "not supported")
893 "for more information, see https://github.com/rust-lang/rust/issues/20041",
899 visit::walk_generics(self, generics)
902 fn visit_generic_param(&mut self, param: &'a GenericParam) {
903 if let GenericParamKind::Lifetime { .. } = param.kind {
904 self.check_lifetime(param.ident);
906 visit::walk_generic_param(self, param);
909 fn visit_param_bound(&mut self, bound: &'a GenericBound) {
910 if let GenericBound::Trait(poly, maybe_bound) = bound {
911 match poly.trait_ref.constness {
912 Some(Constness::NotConst) => {
913 if *maybe_bound == TraitBoundModifier::Maybe {
915 .span_err(bound.span(), "`?const` and `?` are mutually exclusive");
918 if let Some(ctx) = self.bound_context {
919 let msg = format!("`?const` is not permitted in {}", ctx.description());
920 self.err_handler().span_err(bound.span(), &msg);
924 Some(Constness::Const) => panic!("Parser should reject bare `const` on bounds"),
929 visit::walk_param_bound(self, bound)
932 fn visit_pat(&mut self, pat: &'a Pat) {
934 PatKind::Lit(ref expr) => {
935 self.check_expr_within_pat(expr, false);
937 PatKind::Range(ref start, ref end, _) => {
938 if let Some(expr) = start {
939 self.check_expr_within_pat(expr, true);
941 if let Some(expr) = end {
942 self.check_expr_within_pat(expr, true);
948 visit::walk_pat(self, pat)
951 fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
952 if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
953 // A type binding, eg `for<'c> Foo: Send+Clone+'c`
954 self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
956 visit::walk_where_predicate(self, p);
959 fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
960 self.check_late_bound_lifetime_defs(&t.bound_generic_params);
961 visit::walk_poly_trait_ref(self, t, m);
964 fn visit_variant_data(&mut self, s: &'a VariantData) {
965 self.with_banned_assoc_ty_bound(|this| visit::walk_struct_def(this, s))
970 enum_definition: &'a EnumDef,
971 generics: &'a Generics,
975 self.with_banned_assoc_ty_bound(|this| {
976 visit::walk_enum_def(this, enum_definition, generics, item_id)
980 fn visit_impl_item(&mut self, ii: &'a AssocItem) {
982 AssocItemKind::Const(_, body) => {
983 self.check_impl_item_provided(ii.span, body, "constant", " = <expr>;");
985 AssocItemKind::Fn(sig, body) => {
986 self.check_impl_item_provided(ii.span, body, "function", " { <body> }");
987 self.check_fn_decl(&sig.decl);
989 AssocItemKind::TyAlias(bounds, body) => {
990 self.check_impl_item_provided(ii.span, body, "type", " = <type>;");
991 self.check_impl_assoc_type_no_bounds(bounds);
995 visit::walk_impl_item(self, ii);
998 fn visit_trait_item(&mut self, ti: &'a AssocItem) {
999 self.invalid_visibility(&ti.vis, None);
1000 self.check_defaultness(ti.span, ti.defaultness);
1002 if let AssocItemKind::Fn(sig, block) = &ti.kind {
1003 self.check_fn_decl(&sig.decl);
1004 self.check_trait_fn_not_async(ti.span, sig.header.asyncness.node);
1005 self.check_trait_fn_not_const(sig.header.constness);
1006 if block.is_none() {
1007 Self::check_decl_no_pat(&sig.decl, |span, mut_ident| {
1009 self.lint_buffer.buffer_lint(
1010 PATTERNS_IN_FNS_WITHOUT_BODY,
1013 "patterns aren't allowed in methods without bodies",
1020 "patterns aren't allowed in methods without bodies"
1028 visit::walk_trait_item(self, ti);
1031 fn visit_assoc_item(&mut self, item: &'a AssocItem) {
1032 if let AssocItemKind::Fn(sig, _) = &item.kind {
1033 self.check_c_varadic_type(&sig.decl);
1035 visit::walk_assoc_item(self, item);
1039 pub fn check_crate(session: &Session, krate: &Crate, lints: &mut LintBuffer) -> bool {
1040 let mut validator = AstValidator {
1042 has_proc_macro_decls: false,
1043 outer_impl_trait: None,
1044 bound_context: None,
1045 is_impl_trait_banned: false,
1046 is_assoc_ty_bound_banned: false,
1049 visit::walk_crate(&mut validator, krate);
1051 validator.has_proc_macro_decls