]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/ast_validation.rs
1e5e39217b7aad346cf0f79fa29e3792bb35af1f
[rust.git] / src / librustc_passes / ast_validation.rs
1 // Validate AST before lowering it to HIR.
2 //
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.
8
9 use errors::{struct_span_err, Applicability, FatalError};
10 use rustc::lint;
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};
16 use rustc_span::Span;
17 use std::mem;
18 use syntax::ast::*;
19 use syntax::attr;
20 use syntax::expand::is_proc_macro_attr;
21 use syntax::print::pprust;
22 use syntax::visit::{self, Visitor};
23 use syntax::walk_list;
24
25 use rustc_error_codes::*;
26
27 #[derive(Clone, Copy)]
28 enum BoundContext {
29     ImplTrait,
30     TraitBounds,
31     TraitObject,
32 }
33
34 impl BoundContext {
35     fn description(&self) -> &'static str {
36         match self {
37             Self::ImplTrait => "`impl Trait`",
38             Self::TraitBounds => "supertraits",
39             Self::TraitObject => "trait objects",
40         }
41     }
42 }
43
44 struct AstValidator<'a> {
45     session: &'a Session,
46     has_proc_macro_decls: bool,
47
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>,
52
53     /// Tracks the context in which a bound can appear.
54     ///
55     /// This is used to forbid `?const Trait` bounds in certain contexts.
56     bound_context_stack: Vec<Option<BoundContext>>,
57
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,
61
62     /// Used to ban associated type bounds (i.e., `Type<AssocType: Bounds>`) in
63     /// certain positions.
64     is_assoc_ty_bound_banned: bool,
65
66     lint_buffer: &'a mut lint::LintBuffer,
67 }
68
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);
72         f(self);
73         self.is_impl_trait_banned = old;
74     }
75
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);
78         f(self);
79         self.is_assoc_ty_bound_banned = old;
80     }
81
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);
85         f(self);
86         self.outer_impl_trait = old;
87         self.bound_context_stack.pop();
88     }
89
90     fn with_bound_context(&mut self, ctx: Option<BoundContext>, f: impl FnOnce(&mut Self)) {
91         self.bound_context_stack.push(ctx);
92         f(self);
93         self.bound_context_stack.pop();
94     }
95
96     fn innermost_bound_context(&mut self) -> Option<BoundContext> {
97         self.bound_context_stack.iter().rev().find(|x| x.is_some()).copied().flatten()
98     }
99
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(
106                         constraint.span,
107                         "associated type bounds are not allowed within structs, enums, or unions",
108                     );
109                 }
110             }
111         }
112         self.visit_assoc_ty_constraint(constraint);
113     }
114
115     // Mirrors `visit::walk_ty`, but tracks relevant state.
116     fn walk_ty(&mut self, t: &'a Ty) {
117         match t.kind {
118             TyKind::ImplTrait(..) => {
119                 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
120             }
121             TyKind::TraitObject(..) => {
122                 self.with_bound_context(Some(BoundContext::TraitObject), |this| {
123                     visit::walk_ty(this, t)
124                 });
125             }
126             TyKind::Path(ref qself, ref path) => {
127                 // We allow these:
128                 //  - `Option<impl Trait>`
129                 //  - `option::Option<impl Trait>`
130                 //  - `option::Option<T>::Foo<impl Trait>
131                 //
132                 // But not these:
133                 //  - `<impl Trait>::Foo`
134                 //  - `option::Option<impl Trait>::Foo`.
135                 //
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));
143                 }
144
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);
152                     } else {
153                         self.with_banned_impl_trait(|this| {
154                             this.visit_path_segment(path.span, segment)
155                         });
156                     }
157                 }
158             }
159             _ => visit::walk_ty(self, t),
160         }
161     }
162
163     fn err_handler(&self) -> &errors::Handler {
164         &self.session.diagnostic()
165     }
166
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");
171         }
172     }
173
174     fn check_label(&self, ident: Ident) {
175         if ident.without_first_quote().is_reserved() {
176             self.err_handler()
177                 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
178         }
179     }
180
181     fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
182         if let VisibilityKind::Inherited = vis.node {
183             return;
184         }
185
186         let mut err =
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");
190         }
191         if let Some(note) = note {
192             err.note(note);
193         }
194         err.emit();
195     }
196
197     fn check_decl_no_pat(decl: &FnDecl, mut report_err: impl FnMut(Span, bool)) {
198         for Param { pat, .. } in &decl.inputs {
199             match pat.kind {
200                 PatKind::Ident(BindingMode::ByValue(Mutability::Not), _, None) | PatKind::Wild => {}
201                 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), _, None) => {
202                     report_err(pat.span, true)
203                 }
204                 _ => report_err(pat.span, false),
205             }
206         }
207     }
208
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")
213                 .note(
214                     "consider using the `async-trait` crate: \
215                        https://crates.io/crates/async-trait",
216                 )
217                 .emit();
218         }
219     }
220
221     fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
222         if constness.node == Constness::Const {
223             struct_span_err!(
224                 self.session,
225                 constness.span,
226                 E0379,
227                 "trait fns cannot be declared const"
228             )
229             .span_label(constness.span, "trait fns cannot be const")
230             .emit();
231         }
232     }
233
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(
240                     poly.span,
241                     &format!("`?Trait` is not permitted in {}", where_),
242                 );
243                 if is_trait {
244                     let path_str = pprust::path_to_string(&poly.trait_ref.path);
245                     err.note(&format!("traits are `?{}` by default", path_str));
246                 }
247                 err.emit();
248             }
249         }
250     }
251
252     /// Matches `'-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus)`,
253     /// or paths for ranges.
254     //
255     // FIXME: do we want to allow `expr -> pattern` conversion to create path expressions?
256     // That means making this work:
257     //
258     // ```rust,ignore (FIXME)
259     // struct S;
260     // macro_rules! m {
261     //     ($a:expr) => {
262     //         let $a = S;
263     //     }
264     // }
265     // m!(S);
266     // ```
267     fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
268         match expr.kind {
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,
274                     _ => false,
275                 } => {}
276             _ => self.err_handler().span_err(
277                 expr.span,
278                 "arbitrary expressions aren't allowed \
279                                                          in patterns",
280             ),
281         }
282     }
283
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
288             .iter()
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();
293                         self.err_handler()
294                             .span_err(spans, "lifetime bounds cannot be used in this context");
295                     }
296                     None
297                 }
298                 _ => Some(param.ident.span),
299             })
300             .collect();
301         if !non_lt_param_spans.is_empty() {
302             self.err_handler().span_err(
303                 non_lt_param_spans,
304                 "only lifetime parameters can be used in this context",
305             );
306         }
307     }
308
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(
314                         *span,
315                         "C-variadic function must be declared with at least one named argument",
316                     );
317                 }
318             }
319             [ps @ .., _] => {
320                 for Param { ty, span, .. } in ps {
321                     if let TyKind::CVarArgs = ty.kind {
322                         self.err_handler().span_err(
323                             *span,
324                             "`...` must be the last argument of a C-variadic function",
325                         );
326                     }
327                 }
328             }
329             _ => {}
330         }
331
332         fn_decl
333             .inputs
334             .iter()
335             .flat_map(|i| i.attrs.as_ref())
336             .filter(|attr| {
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)
339             })
340             .for_each(|attr| {
341                 if attr.is_doc_comment() {
342                     self.err_handler()
343                         .struct_span_err(
344                             attr.span,
345                             "documentation comments cannot be applied to function parameters",
346                         )
347                         .span_label(attr.span, "doc comments are not allowed here")
348                         .emit();
349                 } else {
350                     self.err_handler().span_err(
351                         attr.span,
352                         "allow, cfg, cfg_attr, deny, \
353                 forbid, and warn are the only allowed built-in attributes in function parameters",
354                     )
355                 }
356             });
357     }
358
359     fn check_defaultness(&self, span: Span, defaultness: Defaultness) {
360         if let Defaultness::Default = defaultness {
361             self.err_handler()
362                 .struct_span_err(span, "`default` is only allowed on items in `impl` definitions")
363                 .emit();
364         }
365     }
366
367     fn check_impl_item_provided<T>(&self, sp: Span, body: &Option<T>, ctx: &str, sugg: &str) {
368         if body.is_some() {
369             return;
370         }
371
372         self.err_handler()
373             .struct_span_err(sp, &format!("associated {} in `impl` without body", ctx))
374             .span_suggestion(
375                 self.session.source_map().end_point(sp),
376                 &format!("provide a definition for the {}", ctx),
377                 sugg.to_string(),
378                 Applicability::HasPlaceholders,
379             )
380             .emit();
381     }
382
383     fn check_impl_assoc_type_no_bounds(&self, bounds: &[GenericBound]) {
384         let span = match bounds {
385             [] => return,
386             [b0] => b0.span(),
387             [b0, .., bl] => b0.span().to(bl.span()),
388         };
389         self.err_handler()
390             .struct_span_err(span, "bounds on associated `type`s in `impl`s have no effect")
391             .emit();
392     }
393
394     fn check_c_varadic_type(&self, decl: &FnDecl) {
395         for Param { ty, span, .. } in &decl.inputs {
396             if let TyKind::CVarArgs = ty.kind {
397                 self.err_handler()
398                     .struct_span_err(
399                         *span,
400                         "only foreign or `unsafe extern \"C\" functions may be C-variadic",
401                     )
402                     .emit();
403             }
404         }
405     }
406 }
407
408 enum GenericPosition {
409     Param,
410     Arg,
411 }
412
413 fn validate_generics_order<'a>(
414     sess: &Session,
415     handler: &errors::Handler,
416     generics: impl Iterator<Item = (ParamKindOrd, Option<&'a [GenericBound]>, Span, Option<String>)>,
417     pos: GenericPosition,
418     span: Span,
419 ) {
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;
425
426     for (kind, bounds, span, ident) in generics {
427         if let Some(ident) = ident {
428             param_idents.push((kind, bounds, param_idents.len(), ident));
429         }
430         let max_param = &mut max_param;
431         match max_param {
432             Some(max_param) if *max_param > kind => {
433                 let entry = out_of_order.entry(kind).or_insert((*max_param, vec![]));
434                 entry.1.push(span);
435             }
436             Some(_) | None => *max_param = Some(kind),
437         };
438         match kind {
439             ParamKindOrd::Type => found_type = true,
440             ParamKindOrd::Const => found_const = true,
441             _ => {}
442         }
443     }
444
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 {
450             if !first {
451                 ordered_params += ", ";
452             }
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);
458                 }
459             }
460             first = false;
461         }
462     }
463     ordered_params += ">";
464
465     let pos_str = match pos {
466         GenericPosition::Param => "parameter",
467         GenericPosition::Arg => "argument",
468     };
469
470     for (param_ord, (max_param, spans)) in &out_of_order {
471         let mut err = handler.struct_span_err(
472             spans.clone(),
473             &format!(
474                 "{} {pos}s must be declared prior to {} {pos}s",
475                 param_ord,
476                 max_param,
477                 pos = pos_str,
478             ),
479         );
480         if let GenericPosition::Param = pos {
481             err.span_suggestion(
482                 span,
483                 &format!(
484                     "reorder the {}s: lifetimes, then types{}",
485                     pos_str,
486                     if sess.features_untracked().const_generics { ", then consts" } else { "" },
487                 ),
488                 ordered_params.clone(),
489                 Applicability::MachineApplicable,
490             );
491         }
492         err.emit();
493     }
494
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
497     // are out-of-order.
498     if !out_of_order.is_empty() && found_type && found_const {
499         FatalError.raise();
500     }
501 }
502
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);
506     }
507
508     fn visit_expr(&mut self, expr: &'a Expr) {
509         match &expr.kind {
510             ExprKind::Closure(_, _, _, fn_decl, _, _) => {
511                 self.check_fn_decl(fn_decl);
512             }
513             ExprKind::InlineAsm(..) if !self.session.target.target.options.allow_asm => {
514                 struct_span_err!(
515                     self.session,
516                     expr.span,
517                     E0472,
518                     "asm! is unsupported on this target"
519                 )
520                 .emit();
521             }
522             _ => {}
523         }
524
525         visit::walk_expr(self, expr);
526     }
527
528     fn visit_ty(&mut self, ty: &'a Ty) {
529         match ty.kind {
530             TyKind::BareFn(ref bfty) => {
531                 self.check_fn_decl(&bfty.decl);
532                 Self::check_decl_no_pat(&bfty.decl, |span, _| {
533                     struct_span_err!(
534                         self.session,
535                         span,
536                         E0561,
537                         "patterns aren't allowed in function pointer types"
538                     )
539                     .emit();
540                 });
541                 self.check_late_bound_lifetime_defs(&bfty.generic_params);
542             }
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 {
548                             struct_span_err!(
549                                 self.session,
550                                 lifetime.ident.span,
551                                 E0226,
552                                 "only a single explicit lifetime bound is permitted"
553                             )
554                             .emit();
555                             break;
556                         }
557                         any_lifetime_bounds = true;
558                     }
559                 }
560                 self.no_questions_in_bounds(bounds, "trait object types", false);
561             }
562             TyKind::ImplTrait(_, ref bounds) => {
563                 if self.is_impl_trait_banned {
564                     struct_span_err!(
565                         self.session,
566                         ty.span,
567                         E0667,
568                         "`impl Trait` is not allowed in path parameters"
569                     )
570                     .emit();
571                 }
572
573                 if let Some(outer_impl_trait_sp) = self.outer_impl_trait {
574                     struct_span_err!(
575                         self.session,
576                         ty.span,
577                         E0666,
578                         "nested `impl Trait` is not allowed"
579                     )
580                     .span_label(outer_impl_trait_sp, "outer `impl Trait`")
581                     .span_label(ty.span, "nested `impl Trait` here")
582                     .emit();
583                 }
584
585                 if !bounds
586                     .iter()
587                     .any(|b| if let GenericBound::Trait(..) = *b { true } else { false })
588                 {
589                     self.err_handler().span_err(ty.span, "at least one trait must be specified");
590                 }
591
592                 self.walk_ty(ty);
593                 return;
594             }
595             _ => {}
596         }
597
598         self.walk_ty(ty)
599     }
600
601     fn visit_label(&mut self, label: &'a Label) {
602         self.check_label(label.ident);
603         visit::walk_label(self, label);
604     }
605
606     fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
607         self.check_lifetime(lifetime.ident);
608         visit::walk_lifetime(self, lifetime);
609     }
610
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;
614         }
615
616         match item.kind {
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 {
620                     self.err_handler()
621                         .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
622                         .help("use `auto trait Trait {}` instead")
623                         .emit();
624                 }
625                 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
626                     struct_span_err!(
627                         self.session,
628                         item.span,
629                         E0198,
630                         "negative impls cannot be unsafe"
631                     )
632                     .emit();
633                 }
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);
639                     }
640                 }
641             }
642             ItemKind::Impl(unsafety, polarity, defaultness, _, None, _, _) => {
643                 self.invalid_visibility(
644                     &item.vis,
645                     Some("place qualifiers on individual impl items instead"),
646                 );
647                 if unsafety == Unsafety::Unsafe {
648                     struct_span_err!(
649                         self.session,
650                         item.span,
651                         E0197,
652                         "inherent impls cannot be unsafe"
653                     )
654                     .emit();
655                 }
656                 if polarity == ImplPolarity::Negative {
657                     self.err_handler().span_err(item.span, "inherent impls cannot be negative");
658                 }
659                 if defaultness == Defaultness::Default {
660                     self.err_handler()
661                         .struct_span_err(item.span, "inherent impls cannot be default")
662                         .note("only trait implementations may be annotated with default")
663                         .emit();
664                 }
665             }
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 {
674                         match param.kind {
675                             GenericParamKind::Const { .. } => {
676                                 self.err_handler()
677                                     .struct_span_err(
678                                         item.span,
679                                         "const parameters are not permitted in `const fn`",
680                                     )
681                                     .emit();
682                             }
683                             _ => {}
684                         }
685                     }
686                 }
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, .. })
690                     | Extern::Implicit
691                         if sig.header.unsafety == Unsafety::Unsafe => {}
692                     _ => self.check_c_varadic_type(&sig.decl),
693                 }
694             }
695             ItemKind::ForeignMod(..) => {
696                 self.invalid_visibility(
697                     &item.vis,
698                     Some("place qualifiers on individual foreign items instead"),
699                 );
700             }
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);
706                     }
707                 }
708             }
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() {
713                         struct_span_err!(
714                             self.session,
715                             item.span,
716                             E0567,
717                             "auto traits cannot have generic parameters"
718                         )
719                         .emit();
720                     }
721                     if !bounds.is_empty() {
722                         struct_span_err!(
723                             self.session,
724                             item.span,
725                             E0568,
726                             "auto traits cannot have super traits"
727                         )
728                         .emit();
729                     }
730                     if !trait_items.is_empty() {
731                         struct_span_err!(
732                             self.session,
733                             item.span,
734                             E0380,
735                             "auto traits cannot have methods or associated items"
736                         )
737                         .emit();
738                     }
739                 }
740                 self.no_questions_in_bounds(bounds, "supertraits", true);
741
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);
747                 });
748                 walk_list!(self, visit_trait_item, trait_items);
749                 return;
750             }
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);
754             }
755             ItemKind::Union(ref vdata, _) => {
756                 if let VariantData::Tuple(..) | VariantData::Unit(..) = vdata {
757                     self.err_handler()
758                         .span_err(item.span, "tuple and unit unions are not permitted");
759                 }
760                 if vdata.fields().is_empty() {
761                     self.err_handler().span_err(item.span, "unions cannot have zero fields");
762                 }
763             }
764             _ => {}
765         }
766
767         visit::walk_item(self, item)
768     }
769
770     fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
771         match fi.kind {
772             ForeignItemKind::Fn(ref decl, _) => {
773                 self.check_fn_decl(decl);
774                 Self::check_decl_no_pat(decl, |span, _| {
775                     struct_span_err!(
776                         self.session,
777                         span,
778                         E0130,
779                         "patterns aren't allowed in foreign function declarations"
780                     )
781                     .span_label(span, "pattern not allowed in foreign function")
782                     .emit();
783                 });
784             }
785             ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
786         }
787
788         visit::walk_foreign_item(self, fi)
789     }
790
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(
797                     self.session,
798                     self.err_handler(),
799                     data.args.iter().map(|arg| {
800                         (
801                             match arg {
802                                 GenericArg::Lifetime(..) => ParamKindOrd::Lifetime,
803                                 GenericArg::Type(..) => ParamKindOrd::Type,
804                                 GenericArg::Const(..) => ParamKindOrd::Const,
805                             },
806                             None,
807                             arg.span(),
808                             None,
809                         )
810                     }),
811                     GenericPosition::Arg,
812                     generic_args.span(),
813                 );
814
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| {
818                     walk_list!(
819                         this,
820                         visit_assoc_ty_constraint_from_generic_args,
821                         &data.constraints
822                     );
823                 });
824             }
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));
831                 }
832             }
833         }
834     }
835
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 {
843                     self.err_handler()
844                         .span_err(span, "type parameters with a default must be trailing");
845                     break;
846                 }
847             }
848         }
849
850         validate_generics_order(
851             self.session,
852             self.err_handler(),
853             generics.params.iter().map(|param| {
854                 let ident = Some(param.ident.to_string());
855                 let (kind, ident) = match &param.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)))
861                     }
862                 };
863                 (kind, Some(&*param.bounds), param.ident.span, ident)
864             }),
865             GenericPosition::Param,
866             generics.span,
867         );
868
869         for predicate in &generics.where_clause.predicates {
870             if let WherePredicate::EqPredicate(ref predicate) = *predicate {
871                 self.err_handler()
872                     .struct_span_err(
873                         predicate.span,
874                         "equality constraints are not yet supported in `where` clauses",
875                     )
876                     .span_label(predicate.span, "not supported")
877                     .note(
878                         "for more information, see https://github.com/rust-lang/rust/issues/20041",
879                     )
880                     .emit();
881             }
882         }
883
884         visit::walk_generics(self, generics)
885     }
886
887     fn visit_generic_param(&mut self, param: &'a GenericParam) {
888         if let GenericParamKind::Lifetime { .. } = param.kind {
889             self.check_lifetime(param.ident);
890         }
891         visit::walk_generic_param(self, param);
892     }
893
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 {
899                         self.err_handler()
900                             .span_err(bound.span(), "`?const` and `?` are mutually exclusive");
901                     }
902
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);
906                     }
907                 }
908
909                 Some(Constness::Const) => bug!("Parser should reject bare `const` on bounds"),
910                 None => {}
911             }
912         }
913
914         visit::walk_param_bound(self, bound)
915     }
916
917     fn visit_pat(&mut self, pat: &'a Pat) {
918         match pat.kind {
919             PatKind::Lit(ref expr) => {
920                 self.check_expr_within_pat(expr, false);
921             }
922             PatKind::Range(ref start, ref end, _) => {
923                 self.check_expr_within_pat(start, true);
924                 self.check_expr_within_pat(end, true);
925             }
926             _ => {}
927         }
928
929         visit::walk_pat(self, pat)
930     }
931
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);
936         }
937         visit::walk_where_predicate(self, p);
938     }
939
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);
943     }
944
945     fn visit_variant_data(&mut self, s: &'a VariantData) {
946         self.with_banned_assoc_ty_bound(|this| visit::walk_struct_def(this, s))
947     }
948
949     fn visit_enum_def(
950         &mut self,
951         enum_definition: &'a EnumDef,
952         generics: &'a Generics,
953         item_id: NodeId,
954         _: Span,
955     ) {
956         self.with_banned_assoc_ty_bound(|this| {
957             visit::walk_enum_def(this, enum_definition, generics, item_id)
958         })
959     }
960
961     fn visit_impl_item(&mut self, ii: &'a AssocItem) {
962         match &ii.kind {
963             AssocItemKind::Const(_, body) => {
964                 self.check_impl_item_provided(ii.span, body, "constant", " = <expr>;");
965             }
966             AssocItemKind::Fn(sig, body) => {
967                 self.check_impl_item_provided(ii.span, body, "function", " { <body> }");
968                 self.check_fn_decl(&sig.decl);
969             }
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);
973             }
974             _ => {}
975         }
976         visit::walk_impl_item(self, ii);
977     }
978
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);
982
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);
987             if block.is_none() {
988                 Self::check_decl_no_pat(&sig.decl, |span, mut_ident| {
989                     if mut_ident {
990                         self.lint_buffer.buffer_lint(
991                             lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
992                             ti.id,
993                             span,
994                             "patterns aren't allowed in methods without bodies",
995                         );
996                     } else {
997                         struct_span_err!(
998                             self.session,
999                             span,
1000                             E0642,
1001                             "patterns aren't allowed in methods without bodies"
1002                         )
1003                         .emit();
1004                     }
1005                 });
1006             }
1007         }
1008
1009         visit::walk_trait_item(self, ti);
1010     }
1011
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);
1015         }
1016         visit::walk_assoc_item(self, item);
1017     }
1018 }
1019
1020 pub fn check_crate(session: &Session, krate: &Crate, lints: &mut lint::LintBuffer) -> bool {
1021     let mut validator = AstValidator {
1022         session,
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,
1028         lint_buffer: lints,
1029     };
1030     visit::walk_crate(&mut validator, krate);
1031
1032     validator.has_proc_macro_decls
1033 }