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 errors::{struct_span_err, Applicability, FatalError};
11 use rustc::session::Session;
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_parse::validate_attr;
14 use rustc_span::source_map::Spanned;
15 use rustc_span::symbol::{kw, sym};
20 use syntax::expand::is_proc_macro_attr;
21 use syntax::print::pprust;
22 use syntax::visit::{self, Visitor};
23 use syntax::walk_list;
25 use rustc_error_codes::*;
27 /// A syntactic context that disallows certain kinds of bounds (e.g., `?Trait` or `?const Trait`).
28 #[derive(Clone, Copy)]
36 fn description(&self) -> &'static str {
38 Self::ImplTrait => "`impl Trait`",
39 Self::TraitBounds => "supertraits",
40 Self::TraitObject => "trait objects",
45 struct AstValidator<'a> {
47 has_proc_macro_decls: bool,
49 /// Used to ban nested `impl Trait`, e.g., `impl Into<impl Debug>`.
50 /// Nested `impl Trait` _is_ allowed in associated type position,
51 /// e.g., `impl Iterator<Item = impl Debug>`.
52 outer_impl_trait: Option<Span>,
54 /// Keeps track of the `BoundContext` as we recurse.
56 /// This is used to forbid `?const Trait` bounds in, e.g.,
57 /// `impl Iterator<Item = Box<dyn ?const Trait>`.
58 bound_context: Option<BoundContext>,
60 /// Used to ban `impl Trait` in path projections like `<impl Iterator>::Item`
61 /// or `Foo::Bar<impl Trait>`
62 is_impl_trait_banned: bool,
64 /// Used to ban associated type bounds (i.e., `Type<AssocType: Bounds>`) in
65 /// certain positions.
66 is_assoc_ty_bound_banned: bool,
68 lint_buffer: &'a mut lint::LintBuffer,
71 impl<'a> AstValidator<'a> {
72 fn with_banned_impl_trait(&mut self, f: impl FnOnce(&mut Self)) {
73 let old = mem::replace(&mut self.is_impl_trait_banned, true);
75 self.is_impl_trait_banned = old;
78 fn with_banned_assoc_ty_bound(&mut self, f: impl FnOnce(&mut Self)) {
79 let old = mem::replace(&mut self.is_assoc_ty_bound_banned, true);
81 self.is_assoc_ty_bound_banned = old;
84 fn with_impl_trait(&mut self, outer: Option<Span>, f: impl FnOnce(&mut Self)) {
85 let old = mem::replace(&mut self.outer_impl_trait, outer);
87 self.with_bound_context(BoundContext::ImplTrait, |this| f(this));
91 self.outer_impl_trait = old;
94 fn with_bound_context(&mut self, ctx: BoundContext, f: impl FnOnce(&mut Self)) {
95 let old = self.bound_context.replace(ctx);
97 self.bound_context = old;
100 fn visit_assoc_ty_constraint_from_generic_args(&mut self, constraint: &'a AssocTyConstraint) {
101 match constraint.kind {
102 AssocTyConstraintKind::Equality { .. } => {}
103 AssocTyConstraintKind::Bound { .. } => {
104 if self.is_assoc_ty_bound_banned {
105 self.err_handler().span_err(
107 "associated type bounds are not allowed within structs, enums, or unions",
112 self.visit_assoc_ty_constraint(constraint);
115 // Mirrors `visit::walk_ty`, but tracks relevant state.
116 fn walk_ty(&mut self, t: &'a Ty) {
118 TyKind::ImplTrait(..) => {
119 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
121 TyKind::TraitObject(..) => {
122 self.with_bound_context(BoundContext::TraitObject, |this| visit::walk_ty(this, t));
124 TyKind::Path(ref qself, ref path) => {
126 // - `Option<impl Trait>`
127 // - `option::Option<impl Trait>`
128 // - `option::Option<T>::Foo<impl Trait>
131 // - `<impl Trait>::Foo`
132 // - `option::Option<impl Trait>::Foo`.
134 // To implement this, we disallow `impl Trait` from `qself`
135 // (for cases like `<impl Trait>::Foo>`)
136 // but we allow `impl Trait` in `GenericArgs`
137 // iff there are no more PathSegments.
138 if let Some(ref qself) = *qself {
139 // `impl Trait` in `qself` is always illegal
140 self.with_banned_impl_trait(|this| this.visit_ty(&qself.ty));
143 // Note that there should be a call to visit_path here,
144 // so if any logic is added to process `Path`s a call to it should be
145 // added both in visit_path and here. This code mirrors visit::walk_path.
146 for (i, segment) in path.segments.iter().enumerate() {
147 // Allow `impl Trait` iff we're on the final path segment
148 if i == path.segments.len() - 1 {
149 self.visit_path_segment(path.span, segment);
151 self.with_banned_impl_trait(|this| {
152 this.visit_path_segment(path.span, segment)
157 _ => visit::walk_ty(self, t),
161 fn err_handler(&self) -> &errors::Handler {
162 &self.session.diagnostic()
165 fn check_lifetime(&self, ident: Ident) {
166 let valid_names = [kw::UnderscoreLifetime, kw::StaticLifetime, kw::Invalid];
167 if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() {
168 self.err_handler().span_err(ident.span, "lifetimes cannot use keyword names");
172 fn check_label(&self, ident: Ident) {
173 if ident.without_first_quote().is_reserved() {
175 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
179 fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
180 if let VisibilityKind::Inherited = vis.node {
185 struct_span_err!(self.session, vis.span, E0449, "unnecessary visibility qualifier");
186 if vis.node.is_pub() {
187 err.span_label(vis.span, "`pub` not permitted here because it's implied");
189 if let Some(note) = note {
195 fn check_decl_no_pat(decl: &FnDecl, mut report_err: impl FnMut(Span, bool)) {
196 for Param { pat, .. } in &decl.inputs {
198 PatKind::Ident(BindingMode::ByValue(Mutability::Not), _, None) | PatKind::Wild => {}
199 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), _, None) => {
200 report_err(pat.span, true)
202 _ => report_err(pat.span, false),
207 fn check_trait_fn_not_async(&self, span: Span, asyncness: IsAsync) {
208 if asyncness.is_async() {
209 struct_span_err!(self.session, span, E0706, "trait fns cannot be declared `async`")
210 .note("`async` trait functions are not currently supported")
212 "consider using the `async-trait` crate: \
213 https://crates.io/crates/async-trait",
219 fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
220 if constness.node == Constness::Const {
225 "trait fns cannot be declared const"
227 .span_label(constness.span, "trait fns cannot be const")
232 // FIXME(ecstaticmorse): Instead, use `bound_context` to check this in `visit_param_bound`.
233 fn no_questions_in_bounds(&self, bounds: &GenericBounds, where_: &str, is_trait: bool) {
234 for bound in bounds {
235 if let GenericBound::Trait(ref poly, TraitBoundModifier::Maybe) = *bound {
236 let mut err = self.err_handler().struct_span_err(
238 &format!("`?Trait` is not permitted in {}", where_),
241 let path_str = pprust::path_to_string(&poly.trait_ref.path);
242 err.note(&format!("traits are `?{}` by default", path_str));
249 /// Matches `'-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus)`,
250 /// or paths for ranges.
252 // FIXME: do we want to allow `expr -> pattern` conversion to create path expressions?
253 // That means making this work:
255 // ```rust,ignore (FIXME)
264 fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
266 ExprKind::Lit(..) | ExprKind::Err => {}
267 ExprKind::Path(..) if allow_paths => {}
268 ExprKind::Unary(UnOp::Neg, ref inner)
269 if match inner.kind {
270 ExprKind::Lit(_) => true,
273 _ => self.err_handler().span_err(
275 "arbitrary expressions aren't allowed \
281 fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) {
282 // Check only lifetime parameters are present and that the lifetime
283 // parameters that are present have no bounds.
284 let non_lt_param_spans: Vec<_> = params
286 .filter_map(|param| match param.kind {
287 GenericParamKind::Lifetime { .. } => {
288 if !param.bounds.is_empty() {
289 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
291 .span_err(spans, "lifetime bounds cannot be used in this context");
295 _ => Some(param.ident.span),
298 if !non_lt_param_spans.is_empty() {
299 self.err_handler().span_err(
301 "only lifetime parameters can be used in this context",
306 fn check_fn_decl(&self, fn_decl: &FnDecl) {
307 match &*fn_decl.inputs {
308 [Param { ty, span, .. }] => {
309 if let TyKind::CVarArgs = ty.kind {
310 self.err_handler().span_err(
312 "C-variadic function must be declared with at least one named argument",
317 for Param { ty, span, .. } in ps {
318 if let TyKind::CVarArgs = ty.kind {
319 self.err_handler().span_err(
321 "`...` must be the last argument of a C-variadic function",
332 .flat_map(|i| i.attrs.as_ref())
334 let arr = [sym::allow, sym::cfg, sym::cfg_attr, sym::deny, sym::forbid, sym::warn];
335 !arr.contains(&attr.name_or_empty()) && attr::is_builtin_attr(attr)
338 if attr.is_doc_comment() {
342 "documentation comments cannot be applied to function parameters",
344 .span_label(attr.span, "doc comments are not allowed here")
347 self.err_handler().span_err(
349 "allow, cfg, cfg_attr, deny, \
350 forbid, and warn are the only allowed built-in attributes in function parameters",
356 fn check_defaultness(&self, span: Span, defaultness: Defaultness) {
357 if let Defaultness::Default = defaultness {
359 .struct_span_err(span, "`default` is only allowed on items in `impl` definitions")
364 fn check_impl_item_provided<T>(&self, sp: Span, body: &Option<T>, ctx: &str, sugg: &str) {
370 .struct_span_err(sp, &format!("associated {} in `impl` without body", ctx))
372 self.session.source_map().end_point(sp),
373 &format!("provide a definition for the {}", ctx),
375 Applicability::HasPlaceholders,
380 fn check_impl_assoc_type_no_bounds(&self, bounds: &[GenericBound]) {
381 let span = match bounds {
384 [b0, .., bl] => b0.span().to(bl.span()),
387 .struct_span_err(span, "bounds on associated `type`s in `impl`s have no effect")
391 fn check_c_varadic_type(&self, decl: &FnDecl) {
392 for Param { ty, span, .. } in &decl.inputs {
393 if let TyKind::CVarArgs = ty.kind {
397 "only foreign or `unsafe extern \"C\" functions may be C-variadic",
405 enum GenericPosition {
410 fn validate_generics_order<'a>(
412 handler: &errors::Handler,
413 generics: impl Iterator<Item = (ParamKindOrd, Option<&'a [GenericBound]>, Span, Option<String>)>,
414 pos: GenericPosition,
417 let mut max_param: Option<ParamKindOrd> = None;
418 let mut out_of_order = FxHashMap::default();
419 let mut param_idents = vec![];
420 let mut found_type = false;
421 let mut found_const = false;
423 for (kind, bounds, span, ident) in generics {
424 if let Some(ident) = ident {
425 param_idents.push((kind, bounds, param_idents.len(), ident));
427 let max_param = &mut max_param;
429 Some(max_param) if *max_param > kind => {
430 let entry = out_of_order.entry(kind).or_insert((*max_param, vec![]));
433 Some(_) | None => *max_param = Some(kind),
436 ParamKindOrd::Type => found_type = true,
437 ParamKindOrd::Const => found_const = true,
442 let mut ordered_params = "<".to_string();
443 if !out_of_order.is_empty() {
444 param_idents.sort_by_key(|&(po, _, i, _)| (po, i));
445 let mut first = true;
446 for (_, bounds, _, ident) in param_idents {
448 ordered_params += ", ";
450 ordered_params += &ident;
451 if let Some(bounds) = bounds {
452 if !bounds.is_empty() {
453 ordered_params += ": ";
454 ordered_params += &pprust::bounds_to_string(&bounds);
460 ordered_params += ">";
462 let pos_str = match pos {
463 GenericPosition::Param => "parameter",
464 GenericPosition::Arg => "argument",
467 for (param_ord, (max_param, spans)) in &out_of_order {
468 let mut err = handler.struct_span_err(
471 "{} {pos}s must be declared prior to {} {pos}s",
477 if let GenericPosition::Param = pos {
481 "reorder the {}s: lifetimes, then types{}",
483 if sess.features_untracked().const_generics { ", then consts" } else { "" },
485 ordered_params.clone(),
486 Applicability::MachineApplicable,
492 // FIXME(const_generics): we shouldn't have to abort here at all, but we currently get ICEs
493 // if we don't. Const parameters and type parameters can currently conflict if they
495 if !out_of_order.is_empty() && found_type && found_const {
500 impl<'a> Visitor<'a> for AstValidator<'a> {
501 fn visit_attribute(&mut self, attr: &Attribute) {
502 validate_attr::check_meta(&self.session.parse_sess, attr);
505 fn visit_expr(&mut self, expr: &'a Expr) {
507 ExprKind::Closure(_, _, _, fn_decl, _, _) => {
508 self.check_fn_decl(fn_decl);
510 ExprKind::InlineAsm(..) if !self.session.target.target.options.allow_asm => {
515 "asm! is unsupported on this target"
522 visit::walk_expr(self, expr);
525 fn visit_ty(&mut self, ty: &'a Ty) {
527 TyKind::BareFn(ref bfty) => {
528 self.check_fn_decl(&bfty.decl);
529 Self::check_decl_no_pat(&bfty.decl, |span, _| {
534 "patterns aren't allowed in function pointer types"
538 self.check_late_bound_lifetime_defs(&bfty.generic_params);
540 TyKind::TraitObject(ref bounds, ..) => {
541 let mut any_lifetime_bounds = false;
542 for bound in bounds {
543 if let GenericBound::Outlives(ref lifetime) = *bound {
544 if any_lifetime_bounds {
549 "only a single explicit lifetime bound is permitted"
554 any_lifetime_bounds = true;
557 self.no_questions_in_bounds(bounds, "trait object types", false);
559 TyKind::ImplTrait(_, ref bounds) => {
560 if self.is_impl_trait_banned {
565 "`impl Trait` is not allowed in path parameters"
570 if let Some(outer_impl_trait_sp) = self.outer_impl_trait {
575 "nested `impl Trait` is not allowed"
577 .span_label(outer_impl_trait_sp, "outer `impl Trait`")
578 .span_label(ty.span, "nested `impl Trait` here")
584 .any(|b| if let GenericBound::Trait(..) = *b { true } else { false })
586 self.err_handler().span_err(ty.span, "at least one trait must be specified");
598 fn visit_label(&mut self, label: &'a Label) {
599 self.check_label(label.ident);
600 visit::walk_label(self, label);
603 fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
604 self.check_lifetime(lifetime.ident);
605 visit::walk_lifetime(self, lifetime);
608 fn visit_item(&mut self, item: &'a Item) {
609 if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)) {
610 self.has_proc_macro_decls = true;
614 ItemKind::Impl(unsafety, polarity, _, _, Some(..), ref ty, ref impl_items) => {
615 self.invalid_visibility(&item.vis, None);
616 if let TyKind::Err = ty.kind {
618 .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
619 .help("use `auto trait Trait {}` instead")
622 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
627 "negative impls cannot be unsafe"
631 for impl_item in impl_items {
632 self.invalid_visibility(&impl_item.vis, None);
633 if let AssocItemKind::Fn(ref sig, _) = impl_item.kind {
634 self.check_trait_fn_not_const(sig.header.constness);
635 self.check_trait_fn_not_async(impl_item.span, sig.header.asyncness.node);
639 ItemKind::Impl(unsafety, polarity, defaultness, _, None, _, _) => {
640 self.invalid_visibility(
642 Some("place qualifiers on individual impl items instead"),
644 if unsafety == Unsafety::Unsafe {
649 "inherent impls cannot be unsafe"
653 if polarity == ImplPolarity::Negative {
654 self.err_handler().span_err(item.span, "inherent impls cannot be negative");
656 if defaultness == Defaultness::Default {
658 .struct_span_err(item.span, "inherent impls cannot be default")
659 .note("only trait implementations may be annotated with default")
663 ItemKind::Fn(ref sig, ref generics, _) => {
664 self.visit_fn_header(&sig.header);
665 self.check_fn_decl(&sig.decl);
666 // We currently do not permit const generics in `const fn`, as
667 // this is tantamount to allowing compile-time dependent typing.
668 if sig.header.constness.node == Constness::Const {
669 // Look for const generics and error if we find any.
670 for param in &generics.params {
672 GenericParamKind::Const { .. } => {
676 "const parameters are not permitted in `const fn`",
684 // Reject C-varadic type unless the function is `unsafe extern "C"` semantically.
685 match sig.header.ext {
686 Extern::Explicit(StrLit { symbol_unescaped: sym::C, .. })
688 if sig.header.unsafety == Unsafety::Unsafe => {}
689 _ => self.check_c_varadic_type(&sig.decl),
692 ItemKind::ForeignMod(..) => {
693 self.invalid_visibility(
695 Some("place qualifiers on individual foreign items instead"),
698 ItemKind::Enum(ref def, _) => {
699 for variant in &def.variants {
700 self.invalid_visibility(&variant.vis, None);
701 for field in variant.data.fields() {
702 self.invalid_visibility(&field.vis, None);
706 ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
707 if is_auto == IsAuto::Yes {
708 // Auto traits cannot have generics, super traits nor contain items.
709 if !generics.params.is_empty() {
714 "auto traits cannot have generic parameters"
718 if !bounds.is_empty() {
723 "auto traits cannot have super traits"
727 if !trait_items.is_empty() {
732 "auto traits cannot have methods or associated items"
737 self.no_questions_in_bounds(bounds, "supertraits", true);
739 // Equivalent of `visit::walk_item` for `ItemKind::Trait` that inserts a bound
740 // context for the supertraits.
741 self.visit_vis(&item.vis);
742 self.visit_ident(item.ident);
743 self.visit_generics(generics);
744 self.with_bound_context(BoundContext::TraitBounds, |this| {
745 walk_list!(this, visit_param_bound, bounds);
747 walk_list!(self, visit_trait_item, trait_items);
748 walk_list!(self, visit_attribute, &item.attrs);
751 ItemKind::Mod(_) => {
752 // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
753 attr::first_attr_value_str_by_name(&item.attrs, sym::path);
755 ItemKind::Union(ref vdata, _) => {
756 if let VariantData::Tuple(..) | VariantData::Unit(..) = vdata {
758 .span_err(item.span, "tuple and unit unions are not permitted");
760 if vdata.fields().is_empty() {
761 self.err_handler().span_err(item.span, "unions cannot have zero fields");
767 visit::walk_item(self, item)
770 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
772 ForeignItemKind::Fn(ref decl, _) => {
773 self.check_fn_decl(decl);
774 Self::check_decl_no_pat(decl, |span, _| {
779 "patterns aren't allowed in foreign function declarations"
781 .span_label(span, "pattern not allowed in foreign function")
785 ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
788 visit::walk_foreign_item(self, fi)
791 // Mirrors `visit::walk_generic_args`, but tracks relevant state.
792 fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
793 match *generic_args {
794 GenericArgs::AngleBracketed(ref data) => {
795 walk_list!(self, visit_generic_arg, &data.args);
796 validate_generics_order(
799 data.args.iter().map(|arg| {
802 GenericArg::Lifetime(..) => ParamKindOrd::Lifetime,
803 GenericArg::Type(..) => ParamKindOrd::Type,
804 GenericArg::Const(..) => ParamKindOrd::Const,
811 GenericPosition::Arg,
815 // Type bindings such as `Item = impl Debug` in `Iterator<Item = Debug>`
816 // are allowed to contain nested `impl Trait`.
817 self.with_impl_trait(None, |this| {
820 visit_assoc_ty_constraint_from_generic_args,
825 GenericArgs::Parenthesized(ref data) => {
826 walk_list!(self, visit_ty, &data.inputs);
827 if let FunctionRetTy::Ty(ty) = &data.output {
828 // `-> Foo` syntax is essentially an associated type binding,
829 // so it is also allowed to contain nested `impl Trait`.
830 self.with_impl_trait(None, |this| this.visit_ty(ty));
836 fn visit_generics(&mut self, generics: &'a Generics) {
837 let mut prev_ty_default = None;
838 for param in &generics.params {
839 if let GenericParamKind::Type { ref default, .. } = param.kind {
840 if default.is_some() {
841 prev_ty_default = Some(param.ident.span);
842 } else if let Some(span) = prev_ty_default {
844 .span_err(span, "type parameters with a default must be trailing");
850 validate_generics_order(
853 generics.params.iter().map(|param| {
854 let ident = Some(param.ident.to_string());
855 let (kind, ident) = match ¶m.kind {
856 GenericParamKind::Lifetime { .. } => (ParamKindOrd::Lifetime, ident),
857 GenericParamKind::Type { .. } => (ParamKindOrd::Type, ident),
858 GenericParamKind::Const { ref ty } => {
859 let ty = pprust::ty_to_string(ty);
860 (ParamKindOrd::Const, Some(format!("const {}: {}", param.ident, ty)))
863 (kind, Some(&*param.bounds), param.ident.span, ident)
865 GenericPosition::Param,
869 for predicate in &generics.where_clause.predicates {
870 if let WherePredicate::EqPredicate(ref predicate) = *predicate {
874 "equality constraints are not yet supported in `where` clauses",
876 .span_label(predicate.span, "not supported")
878 "for more information, see https://github.com/rust-lang/rust/issues/20041",
884 visit::walk_generics(self, generics)
887 fn visit_generic_param(&mut self, param: &'a GenericParam) {
888 if let GenericParamKind::Lifetime { .. } = param.kind {
889 self.check_lifetime(param.ident);
891 visit::walk_generic_param(self, param);
894 fn visit_param_bound(&mut self, bound: &'a GenericBound) {
895 if let GenericBound::Trait(poly, maybe_bound) = bound {
896 match poly.trait_ref.constness {
897 Some(Constness::NotConst) => {
898 if *maybe_bound == TraitBoundModifier::Maybe {
900 .span_err(bound.span(), "`?const` and `?` are mutually exclusive");
903 if let Some(ctx) = self.bound_context {
904 let msg = format!("`?const` is not permitted in {}", ctx.description());
905 self.err_handler().span_err(bound.span(), &msg);
909 Some(Constness::Const) => bug!("Parser should reject bare `const` on bounds"),
914 visit::walk_param_bound(self, bound)
917 fn visit_pat(&mut self, pat: &'a Pat) {
919 PatKind::Lit(ref expr) => {
920 self.check_expr_within_pat(expr, false);
922 PatKind::Range(ref start, ref end, _) => {
923 self.check_expr_within_pat(start, true);
924 self.check_expr_within_pat(end, true);
929 visit::walk_pat(self, pat)
932 fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
933 if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
934 // A type binding, eg `for<'c> Foo: Send+Clone+'c`
935 self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
937 visit::walk_where_predicate(self, p);
940 fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
941 self.check_late_bound_lifetime_defs(&t.bound_generic_params);
942 visit::walk_poly_trait_ref(self, t, m);
945 fn visit_variant_data(&mut self, s: &'a VariantData) {
946 self.with_banned_assoc_ty_bound(|this| visit::walk_struct_def(this, s))
951 enum_definition: &'a EnumDef,
952 generics: &'a Generics,
956 self.with_banned_assoc_ty_bound(|this| {
957 visit::walk_enum_def(this, enum_definition, generics, item_id)
961 fn visit_impl_item(&mut self, ii: &'a AssocItem) {
963 AssocItemKind::Const(_, body) => {
964 self.check_impl_item_provided(ii.span, body, "constant", " = <expr>;");
966 AssocItemKind::Fn(sig, body) => {
967 self.check_impl_item_provided(ii.span, body, "function", " { <body> }");
968 self.check_fn_decl(&sig.decl);
970 AssocItemKind::TyAlias(bounds, body) => {
971 self.check_impl_item_provided(ii.span, body, "type", " = <type>;");
972 self.check_impl_assoc_type_no_bounds(bounds);
976 visit::walk_impl_item(self, ii);
979 fn visit_trait_item(&mut self, ti: &'a AssocItem) {
980 self.invalid_visibility(&ti.vis, None);
981 self.check_defaultness(ti.span, ti.defaultness);
983 if let AssocItemKind::Fn(sig, block) = &ti.kind {
984 self.check_fn_decl(&sig.decl);
985 self.check_trait_fn_not_async(ti.span, sig.header.asyncness.node);
986 self.check_trait_fn_not_const(sig.header.constness);
988 Self::check_decl_no_pat(&sig.decl, |span, mut_ident| {
990 self.lint_buffer.buffer_lint(
991 lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
994 "patterns aren't allowed in methods without bodies",
1001 "patterns aren't allowed in methods without bodies"
1009 visit::walk_trait_item(self, ti);
1012 fn visit_assoc_item(&mut self, item: &'a AssocItem) {
1013 if let AssocItemKind::Fn(sig, _) = &item.kind {
1014 self.check_c_varadic_type(&sig.decl);
1016 visit::walk_assoc_item(self, item);
1020 pub fn check_crate(session: &Session, krate: &Crate, lints: &mut lint::LintBuffer) -> bool {
1021 let mut validator = AstValidator {
1023 has_proc_macro_decls: false,
1024 outer_impl_trait: None,
1025 bound_context: None,
1026 is_impl_trait_banned: false,
1027 is_assoc_ty_bound_banned: false,
1030 visit::walk_crate(&mut validator, krate);
1032 validator.has_proc_macro_decls