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 #[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 /// Tracks the context in which a bound can appear.
55 /// This is used to forbid `?const Trait` bounds in certain contexts.
56 bound_context_stack: Vec<Option<BoundContext>>,
58 /// Used to ban `impl Trait` in path projections like `<impl Iterator>::Item`
59 /// or `Foo::Bar<impl Trait>`
60 is_impl_trait_banned: bool,
62 /// Used to ban associated type bounds (i.e., `Type<AssocType: Bounds>`) in
63 /// certain positions.
64 is_assoc_ty_bound_banned: bool,
66 lint_buffer: &'a mut lint::LintBuffer,
69 impl<'a> AstValidator<'a> {
70 fn with_banned_impl_trait(&mut self, f: impl FnOnce(&mut Self)) {
71 let old = mem::replace(&mut self.is_impl_trait_banned, true);
73 self.is_impl_trait_banned = old;
76 fn with_banned_assoc_ty_bound(&mut self, f: impl FnOnce(&mut Self)) {
77 let old = mem::replace(&mut self.is_assoc_ty_bound_banned, true);
79 self.is_assoc_ty_bound_banned = old;
82 fn with_impl_trait(&mut self, outer: Option<Span>, f: impl FnOnce(&mut Self)) {
83 self.bound_context_stack.push(outer.map(|_| BoundContext::ImplTrait));
84 let old = mem::replace(&mut self.outer_impl_trait, outer);
86 self.outer_impl_trait = old;
87 self.bound_context_stack.pop();
90 fn with_bound_context(&mut self, ctx: Option<BoundContext>, f: impl FnOnce(&mut Self)) {
91 self.bound_context_stack.push(ctx);
93 self.bound_context_stack.pop();
96 fn innermost_bound_context(&mut self) -> Option<BoundContext> {
97 self.bound_context_stack.iter().rev().find(|x| x.is_some()).copied().flatten()
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(Some(BoundContext::TraitObject), |this| {
123 visit::walk_ty(this, t)
126 TyKind::Path(ref qself, ref path) => {
128 // - `Option<impl Trait>`
129 // - `option::Option<impl Trait>`
130 // - `option::Option<T>::Foo<impl Trait>
133 // - `<impl Trait>::Foo`
134 // - `option::Option<impl Trait>::Foo`.
136 // To implement this, we disallow `impl Trait` from `qself`
137 // (for cases like `<impl Trait>::Foo>`)
138 // but we allow `impl Trait` in `GenericArgs`
139 // iff there are no more PathSegments.
140 if let Some(ref qself) = *qself {
141 // `impl Trait` in `qself` is always illegal
142 self.with_banned_impl_trait(|this| this.visit_ty(&qself.ty));
145 // Note that there should be a call to visit_path here,
146 // so if any logic is added to process `Path`s a call to it should be
147 // added both in visit_path and here. This code mirrors visit::walk_path.
148 for (i, segment) in path.segments.iter().enumerate() {
149 // Allow `impl Trait` iff we're on the final path segment
150 if i == path.segments.len() - 1 {
151 self.visit_path_segment(path.span, segment);
153 self.with_banned_impl_trait(|this| {
154 this.visit_path_segment(path.span, segment)
159 _ => visit::walk_ty(self, t),
163 fn err_handler(&self) -> &errors::Handler {
164 &self.session.diagnostic()
167 fn check_lifetime(&self, ident: Ident) {
168 let valid_names = [kw::UnderscoreLifetime, kw::StaticLifetime, kw::Invalid];
169 if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() {
170 self.err_handler().span_err(ident.span, "lifetimes cannot use keyword names");
174 fn check_label(&self, ident: Ident) {
175 if ident.without_first_quote().is_reserved() {
177 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
181 fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
182 if let VisibilityKind::Inherited = vis.node {
187 struct_span_err!(self.session, vis.span, E0449, "unnecessary visibility qualifier");
188 if vis.node.is_pub() {
189 err.span_label(vis.span, "`pub` not permitted here because it's implied");
191 if let Some(note) = note {
197 fn check_decl_no_pat(decl: &FnDecl, mut report_err: impl FnMut(Span, bool)) {
198 for Param { pat, .. } in &decl.inputs {
200 PatKind::Ident(BindingMode::ByValue(Mutability::Not), _, None) | PatKind::Wild => {}
201 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), _, None) => {
202 report_err(pat.span, true)
204 _ => report_err(pat.span, false),
209 fn check_trait_fn_not_async(&self, span: Span, asyncness: IsAsync) {
210 if asyncness.is_async() {
211 struct_span_err!(self.session, span, E0706, "trait fns cannot be declared `async`")
212 .note("`async` trait functions are not currently supported")
214 "consider using the `async-trait` crate: \
215 https://crates.io/crates/async-trait",
221 fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
222 if constness.node == Constness::Const {
227 "trait fns cannot be declared const"
229 .span_label(constness.span, "trait fns cannot be const")
234 // FIXME(ecstaticmorse): Instead, use the `bound_context_stack` to check this in
235 // `visit_param_bound`.
236 fn no_questions_in_bounds(&self, bounds: &GenericBounds, where_: &str, is_trait: bool) {
237 for bound in bounds {
238 if let GenericBound::Trait(ref poly, TraitBoundModifier::Maybe) = *bound {
239 let mut err = self.err_handler().struct_span_err(
241 &format!("`?Trait` is not permitted in {}", where_),
244 let path_str = pprust::path_to_string(&poly.trait_ref.path);
245 err.note(&format!("traits are `?{}` by default", path_str));
252 /// Matches `'-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus)`,
253 /// or paths for ranges.
255 // FIXME: do we want to allow `expr -> pattern` conversion to create path expressions?
256 // That means making this work:
258 // ```rust,ignore (FIXME)
267 fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
269 ExprKind::Lit(..) | ExprKind::Err => {}
270 ExprKind::Path(..) if allow_paths => {}
271 ExprKind::Unary(UnOp::Neg, ref inner)
272 if match inner.kind {
273 ExprKind::Lit(_) => true,
276 _ => self.err_handler().span_err(
278 "arbitrary expressions aren't allowed \
284 fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) {
285 // Check only lifetime parameters are present and that the lifetime
286 // parameters that are present have no bounds.
287 let non_lt_param_spans: Vec<_> = params
289 .filter_map(|param| match param.kind {
290 GenericParamKind::Lifetime { .. } => {
291 if !param.bounds.is_empty() {
292 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
294 .span_err(spans, "lifetime bounds cannot be used in this context");
298 _ => Some(param.ident.span),
301 if !non_lt_param_spans.is_empty() {
302 self.err_handler().span_err(
304 "only lifetime parameters can be used in this context",
309 fn check_fn_decl(&self, fn_decl: &FnDecl) {
310 match &*fn_decl.inputs {
311 [Param { ty, span, .. }] => {
312 if let TyKind::CVarArgs = ty.kind {
313 self.err_handler().span_err(
315 "C-variadic function must be declared with at least one named argument",
320 for Param { ty, span, .. } in ps {
321 if let TyKind::CVarArgs = ty.kind {
322 self.err_handler().span_err(
324 "`...` must be the last argument of a C-variadic function",
335 .flat_map(|i| i.attrs.as_ref())
337 let arr = [sym::allow, sym::cfg, sym::cfg_attr, sym::deny, sym::forbid, sym::warn];
338 !arr.contains(&attr.name_or_empty()) && attr::is_builtin_attr(attr)
341 if attr.is_doc_comment() {
345 "documentation comments cannot be applied to function parameters",
347 .span_label(attr.span, "doc comments are not allowed here")
350 self.err_handler().span_err(
352 "allow, cfg, cfg_attr, deny, \
353 forbid, and warn are the only allowed built-in attributes in function parameters",
359 fn check_defaultness(&self, span: Span, defaultness: Defaultness) {
360 if let Defaultness::Default = defaultness {
362 .struct_span_err(span, "`default` is only allowed on items in `impl` definitions")
367 fn check_impl_item_provided<T>(&self, sp: Span, body: &Option<T>, ctx: &str, sugg: &str) {
373 .struct_span_err(sp, &format!("associated {} in `impl` without body", ctx))
375 self.session.source_map().end_point(sp),
376 &format!("provide a definition for the {}", ctx),
378 Applicability::HasPlaceholders,
383 fn check_impl_assoc_type_no_bounds(&self, bounds: &[GenericBound]) {
384 let span = match bounds {
387 [b0, .., bl] => b0.span().to(bl.span()),
390 .struct_span_err(span, "bounds on associated `type`s in `impl`s have no effect")
394 fn check_c_varadic_type(&self, decl: &FnDecl) {
395 for Param { ty, span, .. } in &decl.inputs {
396 if let TyKind::CVarArgs = ty.kind {
400 "only foreign or `unsafe extern \"C\" functions may be C-variadic",
408 enum GenericPosition {
413 fn validate_generics_order<'a>(
415 handler: &errors::Handler,
416 generics: impl Iterator<Item = (ParamKindOrd, Option<&'a [GenericBound]>, Span, Option<String>)>,
417 pos: GenericPosition,
420 let mut max_param: Option<ParamKindOrd> = None;
421 let mut out_of_order = FxHashMap::default();
422 let mut param_idents = vec![];
423 let mut found_type = false;
424 let mut found_const = false;
426 for (kind, bounds, span, ident) in generics {
427 if let Some(ident) = ident {
428 param_idents.push((kind, bounds, param_idents.len(), ident));
430 let max_param = &mut max_param;
432 Some(max_param) if *max_param > kind => {
433 let entry = out_of_order.entry(kind).or_insert((*max_param, vec![]));
436 Some(_) | None => *max_param = Some(kind),
439 ParamKindOrd::Type => found_type = true,
440 ParamKindOrd::Const => found_const = true,
445 let mut ordered_params = "<".to_string();
446 if !out_of_order.is_empty() {
447 param_idents.sort_by_key(|&(po, _, i, _)| (po, i));
448 let mut first = true;
449 for (_, bounds, _, ident) in param_idents {
451 ordered_params += ", ";
453 ordered_params += &ident;
454 if let Some(bounds) = bounds {
455 if !bounds.is_empty() {
456 ordered_params += ": ";
457 ordered_params += &pprust::bounds_to_string(&bounds);
463 ordered_params += ">";
465 let pos_str = match pos {
466 GenericPosition::Param => "parameter",
467 GenericPosition::Arg => "argument",
470 for (param_ord, (max_param, spans)) in &out_of_order {
471 let mut err = handler.struct_span_err(
474 "{} {pos}s must be declared prior to {} {pos}s",
480 if let GenericPosition::Param = pos {
484 "reorder the {}s: lifetimes, then types{}",
486 if sess.features_untracked().const_generics { ", then consts" } else { "" },
488 ordered_params.clone(),
489 Applicability::MachineApplicable,
495 // FIXME(const_generics): we shouldn't have to abort here at all, but we currently get ICEs
496 // if we don't. Const parameters and type parameters can currently conflict if they
498 if !out_of_order.is_empty() && found_type && found_const {
503 impl<'a> Visitor<'a> for AstValidator<'a> {
504 fn visit_attribute(&mut self, attr: &Attribute) {
505 validate_attr::check_meta(&self.session.parse_sess, attr);
508 fn visit_expr(&mut self, expr: &'a Expr) {
510 ExprKind::Closure(_, _, _, fn_decl, _, _) => {
511 self.check_fn_decl(fn_decl);
513 ExprKind::InlineAsm(..) if !self.session.target.target.options.allow_asm => {
518 "asm! is unsupported on this target"
525 visit::walk_expr(self, expr);
528 fn visit_ty(&mut self, ty: &'a Ty) {
530 TyKind::BareFn(ref bfty) => {
531 self.check_fn_decl(&bfty.decl);
532 Self::check_decl_no_pat(&bfty.decl, |span, _| {
537 "patterns aren't allowed in function pointer types"
541 self.check_late_bound_lifetime_defs(&bfty.generic_params);
543 TyKind::TraitObject(ref bounds, ..) => {
544 let mut any_lifetime_bounds = false;
545 for bound in bounds {
546 if let GenericBound::Outlives(ref lifetime) = *bound {
547 if any_lifetime_bounds {
552 "only a single explicit lifetime bound is permitted"
557 any_lifetime_bounds = true;
560 self.no_questions_in_bounds(bounds, "trait object types", false);
562 TyKind::ImplTrait(_, ref bounds) => {
563 if self.is_impl_trait_banned {
568 "`impl Trait` is not allowed in path parameters"
573 if let Some(outer_impl_trait_sp) = self.outer_impl_trait {
578 "nested `impl Trait` is not allowed"
580 .span_label(outer_impl_trait_sp, "outer `impl Trait`")
581 .span_label(ty.span, "nested `impl Trait` here")
587 .any(|b| if let GenericBound::Trait(..) = *b { true } else { false })
589 self.err_handler().span_err(ty.span, "at least one trait must be specified");
601 fn visit_label(&mut self, label: &'a Label) {
602 self.check_label(label.ident);
603 visit::walk_label(self, label);
606 fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
607 self.check_lifetime(lifetime.ident);
608 visit::walk_lifetime(self, lifetime);
611 fn visit_item(&mut self, item: &'a Item) {
612 if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)) {
613 self.has_proc_macro_decls = true;
617 ItemKind::Impl(unsafety, polarity, _, _, Some(..), ref ty, ref impl_items) => {
618 self.invalid_visibility(&item.vis, None);
619 if let TyKind::Err = ty.kind {
621 .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
622 .help("use `auto trait Trait {}` instead")
625 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
630 "negative impls cannot be unsafe"
634 for impl_item in impl_items {
635 self.invalid_visibility(&impl_item.vis, None);
636 if let AssocItemKind::Fn(ref sig, _) = impl_item.kind {
637 self.check_trait_fn_not_const(sig.header.constness);
638 self.check_trait_fn_not_async(impl_item.span, sig.header.asyncness.node);
642 ItemKind::Impl(unsafety, polarity, defaultness, _, None, _, _) => {
643 self.invalid_visibility(
645 Some("place qualifiers on individual impl items instead"),
647 if unsafety == Unsafety::Unsafe {
652 "inherent impls cannot be unsafe"
656 if polarity == ImplPolarity::Negative {
657 self.err_handler().span_err(item.span, "inherent impls cannot be negative");
659 if defaultness == Defaultness::Default {
661 .struct_span_err(item.span, "inherent impls cannot be default")
662 .note("only trait implementations may be annotated with default")
666 ItemKind::Fn(ref sig, ref generics, _) => {
667 self.visit_fn_header(&sig.header);
668 self.check_fn_decl(&sig.decl);
669 // We currently do not permit const generics in `const fn`, as
670 // this is tantamount to allowing compile-time dependent typing.
671 if sig.header.constness.node == Constness::Const {
672 // Look for const generics and error if we find any.
673 for param in &generics.params {
675 GenericParamKind::Const { .. } => {
679 "const parameters are not permitted in `const fn`",
687 // Reject C-varadic type unless the function is `unsafe extern "C"` semantically.
688 match sig.header.ext {
689 Extern::Explicit(StrLit { symbol_unescaped: sym::C, .. })
691 if sig.header.unsafety == Unsafety::Unsafe => {}
692 _ => self.check_c_varadic_type(&sig.decl),
695 ItemKind::ForeignMod(..) => {
696 self.invalid_visibility(
698 Some("place qualifiers on individual foreign items instead"),
701 ItemKind::Enum(ref def, _) => {
702 for variant in &def.variants {
703 self.invalid_visibility(&variant.vis, None);
704 for field in variant.data.fields() {
705 self.invalid_visibility(&field.vis, None);
709 ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
710 if is_auto == IsAuto::Yes {
711 // Auto traits cannot have generics, super traits nor contain items.
712 if !generics.params.is_empty() {
717 "auto traits cannot have generic parameters"
721 if !bounds.is_empty() {
726 "auto traits cannot have super traits"
730 if !trait_items.is_empty() {
735 "auto traits cannot have methods or associated items"
740 self.no_questions_in_bounds(bounds, "supertraits", true);
742 // Equivalent of `visit::walk_item` for `ItemKind::Trait` that inserts a bound
743 // context for the supertraits.
744 self.visit_generics(generics);
745 self.with_bound_context(Some(BoundContext::TraitBounds), |this| {
746 walk_list!(this, visit_param_bound, bounds);
748 walk_list!(self, visit_trait_item, trait_items);
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.innermost_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_stack: Vec::new(),
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