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;
623 self.invalid_visibility(&item.vis, None);
624 if let TyKind::Err = self_ty.kind {
626 .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
627 .help("use `auto trait Trait {}` instead")
630 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
635 "negative impls cannot be unsafe"
639 for impl_item in items {
640 self.invalid_visibility(&impl_item.vis, None);
641 if let AssocItemKind::Fn(ref sig, _) = impl_item.kind {
642 self.check_trait_fn_not_const(sig.header.constness);
643 self.check_trait_fn_not_async(impl_item.span, sig.header.asyncness.node);
657 self.invalid_visibility(
659 Some("place qualifiers on individual impl items instead"),
661 if unsafety == Unsafety::Unsafe {
666 "inherent impls cannot be unsafe"
670 if polarity == ImplPolarity::Negative {
671 self.err_handler().span_err(item.span, "inherent impls cannot be negative");
673 if defaultness == Defaultness::Default {
675 .struct_span_err(item.span, "inherent impls cannot be default")
676 .note("only trait implementations may be annotated with default")
679 if constness == Constness::Const {
681 .struct_span_err(item.span, "inherent impls cannot be `const`")
682 .note("only trait implementations may be annotated with `const`")
686 ItemKind::Fn(ref sig, ref generics, _) => {
687 self.visit_fn_header(&sig.header);
688 self.check_fn_decl(&sig.decl);
689 // We currently do not permit const generics in `const fn`, as
690 // this is tantamount to allowing compile-time dependent typing.
691 if sig.header.constness.node == Constness::Const {
692 // Look for const generics and error if we find any.
693 for param in &generics.params {
695 GenericParamKind::Const { .. } => {
699 "const parameters are not permitted in `const fn`",
707 // Reject C-varadic type unless the function is `unsafe extern "C"` semantically.
708 match sig.header.ext {
709 Extern::Explicit(StrLit { symbol_unescaped: sym::C, .. })
711 if sig.header.unsafety == Unsafety::Unsafe => {}
712 _ => self.check_c_varadic_type(&sig.decl),
715 ItemKind::ForeignMod(..) => {
716 self.invalid_visibility(
718 Some("place qualifiers on individual foreign items instead"),
721 ItemKind::Enum(ref def, _) => {
722 for variant in &def.variants {
723 self.invalid_visibility(&variant.vis, None);
724 for field in variant.data.fields() {
725 self.invalid_visibility(&field.vis, None);
729 ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
730 if is_auto == IsAuto::Yes {
731 // Auto traits cannot have generics, super traits nor contain items.
732 if !generics.params.is_empty() {
737 "auto traits cannot have generic parameters"
741 if !bounds.is_empty() {
746 "auto traits cannot have super traits"
750 if !trait_items.is_empty() {
755 "auto traits cannot have methods or associated items"
760 self.no_questions_in_bounds(bounds, "supertraits", true);
762 // Equivalent of `visit::walk_item` for `ItemKind::Trait` that inserts a bound
763 // context for the supertraits.
764 self.visit_vis(&item.vis);
765 self.visit_ident(item.ident);
766 self.visit_generics(generics);
767 self.with_bound_context(BoundContext::TraitBounds, |this| {
768 walk_list!(this, visit_param_bound, bounds);
770 walk_list!(self, visit_trait_item, trait_items);
771 walk_list!(self, visit_attribute, &item.attrs);
774 ItemKind::Mod(_) => {
775 // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
776 attr::first_attr_value_str_by_name(&item.attrs, sym::path);
778 ItemKind::Union(ref vdata, _) => {
779 if let VariantData::Tuple(..) | VariantData::Unit(..) = vdata {
781 .span_err(item.span, "tuple and unit unions are not permitted");
783 if vdata.fields().is_empty() {
784 self.err_handler().span_err(item.span, "unions cannot have zero fields");
790 visit::walk_item(self, item)
793 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
795 ForeignItemKind::Fn(ref decl, _) => {
796 self.check_fn_decl(decl);
797 Self::check_decl_no_pat(decl, |span, _| {
802 "patterns aren't allowed in foreign function declarations"
804 .span_label(span, "pattern not allowed in foreign function")
808 ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
811 visit::walk_foreign_item(self, fi)
814 // Mirrors `visit::walk_generic_args`, but tracks relevant state.
815 fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
816 match *generic_args {
817 GenericArgs::AngleBracketed(ref data) => {
818 walk_list!(self, visit_generic_arg, &data.args);
819 validate_generics_order(
822 data.args.iter().map(|arg| {
825 GenericArg::Lifetime(..) => ParamKindOrd::Lifetime,
826 GenericArg::Type(..) => ParamKindOrd::Type,
827 GenericArg::Const(..) => ParamKindOrd::Const,
834 GenericPosition::Arg,
838 // Type bindings such as `Item = impl Debug` in `Iterator<Item = Debug>`
839 // are allowed to contain nested `impl Trait`.
840 self.with_impl_trait(None, |this| {
843 visit_assoc_ty_constraint_from_generic_args,
848 GenericArgs::Parenthesized(ref data) => {
849 walk_list!(self, visit_ty, &data.inputs);
850 if let FunctionRetTy::Ty(ty) = &data.output {
851 // `-> Foo` syntax is essentially an associated type binding,
852 // so it is also allowed to contain nested `impl Trait`.
853 self.with_impl_trait(None, |this| this.visit_ty(ty));
859 fn visit_generics(&mut self, generics: &'a Generics) {
860 let mut prev_ty_default = None;
861 for param in &generics.params {
862 if let GenericParamKind::Type { ref default, .. } = param.kind {
863 if default.is_some() {
864 prev_ty_default = Some(param.ident.span);
865 } else if let Some(span) = prev_ty_default {
867 .span_err(span, "type parameters with a default must be trailing");
873 validate_generics_order(
876 generics.params.iter().map(|param| {
877 let ident = Some(param.ident.to_string());
878 let (kind, ident) = match ¶m.kind {
879 GenericParamKind::Lifetime { .. } => (ParamKindOrd::Lifetime, ident),
880 GenericParamKind::Type { .. } => (ParamKindOrd::Type, ident),
881 GenericParamKind::Const { ref ty } => {
882 let ty = pprust::ty_to_string(ty);
883 (ParamKindOrd::Const, Some(format!("const {}: {}", param.ident, ty)))
886 (kind, Some(&*param.bounds), param.ident.span, ident)
888 GenericPosition::Param,
892 for predicate in &generics.where_clause.predicates {
893 if let WherePredicate::EqPredicate(ref predicate) = *predicate {
897 "equality constraints are not yet supported in `where` clauses",
899 .span_label(predicate.span, "not supported")
901 "for more information, see https://github.com/rust-lang/rust/issues/20041",
907 visit::walk_generics(self, generics)
910 fn visit_generic_param(&mut self, param: &'a GenericParam) {
911 if let GenericParamKind::Lifetime { .. } = param.kind {
912 self.check_lifetime(param.ident);
914 visit::walk_generic_param(self, param);
917 fn visit_param_bound(&mut self, bound: &'a GenericBound) {
919 GenericBound::Trait(_, TraitBoundModifier::MaybeConst) => {
920 if let Some(ctx) = self.bound_context {
921 let msg = format!("`?const` is not permitted in {}", ctx.description());
922 self.err_handler().span_err(bound.span(), &msg);
926 GenericBound::Trait(_, TraitBoundModifier::MaybeConstMaybe) => {
928 .span_err(bound.span(), "`?const` and `?` are mutually exclusive");
934 visit::walk_param_bound(self, bound)
937 fn visit_pat(&mut self, pat: &'a Pat) {
939 PatKind::Lit(ref expr) => {
940 self.check_expr_within_pat(expr, false);
942 PatKind::Range(ref start, ref end, _) => {
943 if let Some(expr) = start {
944 self.check_expr_within_pat(expr, true);
946 if let Some(expr) = end {
947 self.check_expr_within_pat(expr, true);
953 visit::walk_pat(self, pat)
956 fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
957 if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
958 // A type binding, eg `for<'c> Foo: Send+Clone+'c`
959 self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
961 visit::walk_where_predicate(self, p);
964 fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
965 self.check_late_bound_lifetime_defs(&t.bound_generic_params);
966 visit::walk_poly_trait_ref(self, t, m);
969 fn visit_variant_data(&mut self, s: &'a VariantData) {
970 self.with_banned_assoc_ty_bound(|this| visit::walk_struct_def(this, s))
975 enum_definition: &'a EnumDef,
976 generics: &'a Generics,
980 self.with_banned_assoc_ty_bound(|this| {
981 visit::walk_enum_def(this, enum_definition, generics, item_id)
985 fn visit_impl_item(&mut self, ii: &'a AssocItem) {
987 AssocItemKind::Const(_, body) => {
988 self.check_impl_item_provided(ii.span, body, "constant", " = <expr>;");
990 AssocItemKind::Fn(sig, body) => {
991 self.check_impl_item_provided(ii.span, body, "function", " { <body> }");
992 self.check_fn_decl(&sig.decl);
994 AssocItemKind::TyAlias(bounds, body) => {
995 self.check_impl_item_provided(ii.span, body, "type", " = <type>;");
996 self.check_impl_assoc_type_no_bounds(bounds);
1000 visit::walk_impl_item(self, ii);
1003 fn visit_trait_item(&mut self, ti: &'a AssocItem) {
1004 self.invalid_visibility(&ti.vis, None);
1005 self.check_defaultness(ti.span, ti.defaultness);
1007 if let AssocItemKind::Fn(sig, block) = &ti.kind {
1008 self.check_fn_decl(&sig.decl);
1009 self.check_trait_fn_not_async(ti.span, sig.header.asyncness.node);
1010 self.check_trait_fn_not_const(sig.header.constness);
1011 if block.is_none() {
1012 Self::check_decl_no_pat(&sig.decl, |span, mut_ident| {
1014 self.lint_buffer.buffer_lint(
1015 PATTERNS_IN_FNS_WITHOUT_BODY,
1018 "patterns aren't allowed in methods without bodies",
1025 "patterns aren't allowed in methods without bodies"
1033 visit::walk_trait_item(self, ti);
1036 fn visit_assoc_item(&mut self, item: &'a AssocItem) {
1037 if let AssocItemKind::Fn(sig, _) = &item.kind {
1038 self.check_c_varadic_type(&sig.decl);
1040 visit::walk_assoc_item(self, item);
1044 pub fn check_crate(session: &Session, krate: &Crate, lints: &mut LintBuffer) -> bool {
1045 let mut validator = AstValidator {
1047 has_proc_macro_decls: false,
1048 outer_impl_trait: None,
1049 bound_context: None,
1050 is_impl_trait_banned: false,
1051 is_assoc_ty_bound_banned: false,
1054 visit::walk_crate(&mut validator, krate);
1056 validator.has_proc_macro_decls