]> git.lizzy.rs Git - rust.git/blob - src/librustc_ast_passes/ast_validation.rs
Auto merge of #69242 - cjgillot:object_violations, r=Zoxc
[rust.git] / src / librustc_ast_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 rustc_ast_pretty::pprust;
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_errors::{error_code, struct_span_err, Applicability, FatalError};
12 use rustc_parse::validate_attr;
13 use rustc_session::lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY;
14 use rustc_session::lint::LintBuffer;
15 use rustc_session::Session;
16 use rustc_span::symbol::{kw, sym};
17 use rustc_span::Span;
18 use std::mem;
19 use syntax::ast::*;
20 use syntax::attr;
21 use syntax::expand::is_proc_macro_attr;
22 use syntax::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
23 use syntax::walk_list;
24
25 const MORE_EXTERN: &str =
26     "for more information, visit https://doc.rust-lang.org/std/keyword.extern.html";
27
28 /// Is `self` allowed semantically as the first parameter in an `FnDecl`?
29 enum SelfSemantic {
30     Yes,
31     No,
32 }
33
34 /// A syntactic context that disallows certain kinds of bounds (e.g., `?Trait` or `?const Trait`).
35 #[derive(Clone, Copy)]
36 enum BoundContext {
37     ImplTrait,
38     TraitBounds,
39     TraitObject,
40 }
41
42 impl BoundContext {
43     fn description(&self) -> &'static str {
44         match self {
45             Self::ImplTrait => "`impl Trait`",
46             Self::TraitBounds => "supertraits",
47             Self::TraitObject => "trait objects",
48         }
49     }
50 }
51
52 struct AstValidator<'a> {
53     session: &'a Session,
54
55     /// The span of the `extern` in an `extern { ... }` block, if any.
56     extern_mod: Option<&'a Item>,
57
58     /// Are we inside a trait impl?
59     in_trait_impl: bool,
60
61     has_proc_macro_decls: bool,
62
63     /// Used to ban nested `impl Trait`, e.g., `impl Into<impl Debug>`.
64     /// Nested `impl Trait` _is_ allowed in associated type position,
65     /// e.g., `impl Iterator<Item = impl Debug>`.
66     outer_impl_trait: Option<Span>,
67
68     /// Keeps track of the `BoundContext` as we recurse.
69     ///
70     /// This is used to forbid `?const Trait` bounds in, e.g.,
71     /// `impl Iterator<Item = Box<dyn ?const Trait>`.
72     bound_context: Option<BoundContext>,
73
74     /// Used to ban `impl Trait` in path projections like `<impl Iterator>::Item`
75     /// or `Foo::Bar<impl Trait>`
76     is_impl_trait_banned: bool,
77
78     /// Used to ban associated type bounds (i.e., `Type<AssocType: Bounds>`) in
79     /// certain positions.
80     is_assoc_ty_bound_banned: bool,
81
82     lint_buffer: &'a mut LintBuffer,
83 }
84
85 impl<'a> AstValidator<'a> {
86     fn with_in_trait_impl(&mut self, is_in: bool, f: impl FnOnce(&mut Self)) {
87         let old = mem::replace(&mut self.in_trait_impl, is_in);
88         f(self);
89         self.in_trait_impl = old;
90     }
91
92     fn with_banned_impl_trait(&mut self, f: impl FnOnce(&mut Self)) {
93         let old = mem::replace(&mut self.is_impl_trait_banned, true);
94         f(self);
95         self.is_impl_trait_banned = old;
96     }
97
98     fn with_banned_assoc_ty_bound(&mut self, f: impl FnOnce(&mut Self)) {
99         let old = mem::replace(&mut self.is_assoc_ty_bound_banned, true);
100         f(self);
101         self.is_assoc_ty_bound_banned = old;
102     }
103
104     fn with_impl_trait(&mut self, outer: Option<Span>, f: impl FnOnce(&mut Self)) {
105         let old = mem::replace(&mut self.outer_impl_trait, outer);
106         if outer.is_some() {
107             self.with_bound_context(BoundContext::ImplTrait, |this| f(this));
108         } else {
109             f(self)
110         }
111         self.outer_impl_trait = old;
112     }
113
114     fn with_bound_context(&mut self, ctx: BoundContext, f: impl FnOnce(&mut Self)) {
115         let old = self.bound_context.replace(ctx);
116         f(self);
117         self.bound_context = old;
118     }
119
120     fn visit_assoc_ty_constraint_from_generic_args(&mut self, constraint: &'a AssocTyConstraint) {
121         match constraint.kind {
122             AssocTyConstraintKind::Equality { .. } => {}
123             AssocTyConstraintKind::Bound { .. } => {
124                 if self.is_assoc_ty_bound_banned {
125                     self.err_handler().span_err(
126                         constraint.span,
127                         "associated type bounds are not allowed within structs, enums, or unions",
128                     );
129                 }
130             }
131         }
132         self.visit_assoc_ty_constraint(constraint);
133     }
134
135     // Mirrors `visit::walk_ty`, but tracks relevant state.
136     fn walk_ty(&mut self, t: &'a Ty) {
137         match t.kind {
138             TyKind::ImplTrait(..) => {
139                 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
140             }
141             TyKind::TraitObject(..) => {
142                 self.with_bound_context(BoundContext::TraitObject, |this| visit::walk_ty(this, t));
143             }
144             TyKind::Path(ref qself, ref path) => {
145                 // We allow these:
146                 //  - `Option<impl Trait>`
147                 //  - `option::Option<impl Trait>`
148                 //  - `option::Option<T>::Foo<impl Trait>
149                 //
150                 // But not these:
151                 //  - `<impl Trait>::Foo`
152                 //  - `option::Option<impl Trait>::Foo`.
153                 //
154                 // To implement this, we disallow `impl Trait` from `qself`
155                 // (for cases like `<impl Trait>::Foo>`)
156                 // but we allow `impl Trait` in `GenericArgs`
157                 // iff there are no more PathSegments.
158                 if let Some(ref qself) = *qself {
159                     // `impl Trait` in `qself` is always illegal
160                     self.with_banned_impl_trait(|this| this.visit_ty(&qself.ty));
161                 }
162
163                 // Note that there should be a call to visit_path here,
164                 // so if any logic is added to process `Path`s a call to it should be
165                 // added both in visit_path and here. This code mirrors visit::walk_path.
166                 for (i, segment) in path.segments.iter().enumerate() {
167                     // Allow `impl Trait` iff we're on the final path segment
168                     if i == path.segments.len() - 1 {
169                         self.visit_path_segment(path.span, segment);
170                     } else {
171                         self.with_banned_impl_trait(|this| {
172                             this.visit_path_segment(path.span, segment)
173                         });
174                     }
175                 }
176             }
177             _ => visit::walk_ty(self, t),
178         }
179     }
180
181     fn err_handler(&self) -> &rustc_errors::Handler {
182         &self.session.diagnostic()
183     }
184
185     fn check_lifetime(&self, ident: Ident) {
186         let valid_names = [kw::UnderscoreLifetime, kw::StaticLifetime, kw::Invalid];
187         if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() {
188             self.err_handler().span_err(ident.span, "lifetimes cannot use keyword names");
189         }
190     }
191
192     fn check_label(&self, ident: Ident) {
193         if ident.without_first_quote().is_reserved() {
194             self.err_handler()
195                 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
196         }
197     }
198
199     fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
200         if let VisibilityKind::Inherited = vis.node {
201             return;
202         }
203
204         let mut err =
205             struct_span_err!(self.session, vis.span, E0449, "unnecessary visibility qualifier");
206         if vis.node.is_pub() {
207             err.span_label(vis.span, "`pub` not permitted here because it's implied");
208         }
209         if let Some(note) = note {
210             err.note(note);
211         }
212         err.emit();
213     }
214
215     fn check_decl_no_pat(decl: &FnDecl, mut report_err: impl FnMut(Span, bool)) {
216         for Param { pat, .. } in &decl.inputs {
217             match pat.kind {
218                 PatKind::Ident(BindingMode::ByValue(Mutability::Not), _, None) | PatKind::Wild => {}
219                 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), _, None) => {
220                     report_err(pat.span, true)
221                 }
222                 _ => report_err(pat.span, false),
223             }
224         }
225     }
226
227     fn check_trait_fn_not_async(&self, fn_span: Span, asyncness: Async) {
228         if let Async::Yes { span, .. } = asyncness {
229             struct_span_err!(
230                 self.session,
231                 fn_span,
232                 E0706,
233                 "functions in traits cannot be declared `async`"
234             )
235             .span_label(span, "`async` because of this")
236             .note("`async` trait functions are not currently supported")
237             .note("consider using the `async-trait` crate: https://crates.io/crates/async-trait")
238             .emit();
239         }
240     }
241
242     fn check_trait_fn_not_const(&self, constness: Const) {
243         if let Const::Yes(span) = constness {
244             struct_span_err!(
245                 self.session,
246                 span,
247                 E0379,
248                 "functions in traits cannot be declared const"
249             )
250             .span_label(span, "functions in traits cannot be const")
251             .emit();
252         }
253     }
254
255     // FIXME(ecstaticmorse): Instead, use `bound_context` to check this in `visit_param_bound`.
256     fn no_questions_in_bounds(&self, bounds: &GenericBounds, where_: &str, is_trait: bool) {
257         for bound in bounds {
258             if let GenericBound::Trait(ref poly, TraitBoundModifier::Maybe) = *bound {
259                 let mut err = self.err_handler().struct_span_err(
260                     poly.span,
261                     &format!("`?Trait` is not permitted in {}", where_),
262                 );
263                 if is_trait {
264                     let path_str = pprust::path_to_string(&poly.trait_ref.path);
265                     err.note(&format!("traits are `?{}` by default", path_str));
266                 }
267                 err.emit();
268             }
269         }
270     }
271
272     /// Matches `'-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus)`,
273     /// or paths for ranges.
274     //
275     // FIXME: do we want to allow `expr -> pattern` conversion to create path expressions?
276     // That means making this work:
277     //
278     // ```rust,ignore (FIXME)
279     // struct S;
280     // macro_rules! m {
281     //     ($a:expr) => {
282     //         let $a = S;
283     //     }
284     // }
285     // m!(S);
286     // ```
287     fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
288         match expr.kind {
289             ExprKind::Lit(..) | ExprKind::Err => {}
290             ExprKind::Path(..) if allow_paths => {}
291             ExprKind::Unary(UnOp::Neg, ref inner)
292                 if match inner.kind {
293                     ExprKind::Lit(_) => true,
294                     _ => false,
295                 } => {}
296             _ => self.err_handler().span_err(
297                 expr.span,
298                 "arbitrary expressions aren't allowed \
299                                                          in patterns",
300             ),
301         }
302     }
303
304     fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) {
305         // Check only lifetime parameters are present and that the lifetime
306         // parameters that are present have no bounds.
307         let non_lt_param_spans: Vec<_> = params
308             .iter()
309             .filter_map(|param| match param.kind {
310                 GenericParamKind::Lifetime { .. } => {
311                     if !param.bounds.is_empty() {
312                         let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
313                         self.err_handler()
314                             .span_err(spans, "lifetime bounds cannot be used in this context");
315                     }
316                     None
317                 }
318                 _ => Some(param.ident.span),
319             })
320             .collect();
321         if !non_lt_param_spans.is_empty() {
322             self.err_handler().span_err(
323                 non_lt_param_spans,
324                 "only lifetime parameters can be used in this context",
325             );
326         }
327     }
328
329     fn check_fn_decl(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) {
330         self.check_decl_cvaradic_pos(fn_decl);
331         self.check_decl_attrs(fn_decl);
332         self.check_decl_self_param(fn_decl, self_semantic);
333     }
334
335     fn check_decl_cvaradic_pos(&self, fn_decl: &FnDecl) {
336         match &*fn_decl.inputs {
337             [Param { ty, span, .. }] => {
338                 if let TyKind::CVarArgs = ty.kind {
339                     self.err_handler().span_err(
340                         *span,
341                         "C-variadic function must be declared with at least one named argument",
342                     );
343                 }
344             }
345             [ps @ .., _] => {
346                 for Param { ty, span, .. } in ps {
347                     if let TyKind::CVarArgs = ty.kind {
348                         self.err_handler().span_err(
349                             *span,
350                             "`...` must be the last argument of a C-variadic function",
351                         );
352                     }
353                 }
354             }
355             _ => {}
356         }
357     }
358
359     fn check_decl_attrs(&self, fn_decl: &FnDecl) {
360         fn_decl
361             .inputs
362             .iter()
363             .flat_map(|i| i.attrs.as_ref())
364             .filter(|attr| {
365                 let arr = [sym::allow, sym::cfg, sym::cfg_attr, sym::deny, sym::forbid, sym::warn];
366                 !arr.contains(&attr.name_or_empty()) && rustc_attr::is_builtin_attr(attr)
367             })
368             .for_each(|attr| {
369                 if attr.is_doc_comment() {
370                     self.err_handler()
371                         .struct_span_err(
372                             attr.span,
373                             "documentation comments cannot be applied to function parameters",
374                         )
375                         .span_label(attr.span, "doc comments are not allowed here")
376                         .emit();
377                 } else {
378                     self.err_handler().span_err(
379                         attr.span,
380                         "allow, cfg, cfg_attr, deny, \
381                 forbid, and warn are the only allowed built-in attributes in function parameters",
382                     )
383                 }
384             });
385     }
386
387     fn check_decl_self_param(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) {
388         if let (SelfSemantic::No, [param, ..]) = (self_semantic, &*fn_decl.inputs) {
389             if param.is_self() {
390                 self.err_handler()
391                     .struct_span_err(
392                         param.span,
393                         "`self` parameter is only allowed in associated functions",
394                     )
395                     .span_label(param.span, "not semantically valid as function parameter")
396                     .note("associated functions are those in `impl` or `trait` definitions")
397                     .emit();
398             }
399         }
400     }
401
402     fn check_defaultness(&self, span: Span, defaultness: Defaultness) {
403         if let Defaultness::Default = defaultness {
404             self.err_handler()
405                 .struct_span_err(span, "`default` is only allowed on items in `impl` definitions")
406                 .emit();
407         }
408     }
409
410     fn error_item_without_body(&self, sp: Span, ctx: &str, msg: &str, sugg: &str) {
411         self.err_handler()
412             .struct_span_err(sp, msg)
413             .span_suggestion(
414                 self.session.source_map().end_point(sp),
415                 &format!("provide a definition for the {}", ctx),
416                 sugg.to_string(),
417                 Applicability::HasPlaceholders,
418             )
419             .emit();
420     }
421
422     fn check_impl_item_provided<T>(&self, sp: Span, body: &Option<T>, ctx: &str, sugg: &str) {
423         if body.is_none() {
424             let msg = format!("associated {} in `impl` without body", ctx);
425             self.error_item_without_body(sp, ctx, &msg, sugg);
426         }
427     }
428
429     fn check_type_no_bounds(&self, bounds: &[GenericBound], ctx: &str) {
430         let span = match bounds {
431             [] => return,
432             [b0] => b0.span(),
433             [b0, .., bl] => b0.span().to(bl.span()),
434         };
435         self.err_handler()
436             .struct_span_err(span, &format!("bounds on `type`s in {} have no effect", ctx))
437             .emit();
438     }
439
440     fn check_foreign_ty_genericless(&self, generics: &Generics) {
441         let cannot_have = |span, descr, remove_descr| {
442             self.err_handler()
443                 .struct_span_err(
444                     span,
445                     &format!("`type`s inside `extern` blocks cannot have {}", descr),
446                 )
447                 .span_suggestion(
448                     span,
449                     &format!("remove the {}", remove_descr),
450                     String::new(),
451                     Applicability::MaybeIncorrect,
452                 )
453                 .span_label(self.current_extern_span(), "`extern` block begins here")
454                 .note(MORE_EXTERN)
455                 .emit();
456         };
457
458         if !generics.params.is_empty() {
459             cannot_have(generics.span, "generic parameters", "generic parameters");
460         }
461
462         if !generics.where_clause.predicates.is_empty() {
463             cannot_have(generics.where_clause.span, "`where` clauses", "`where` clause");
464         }
465     }
466
467     fn check_foreign_kind_bodyless(&self, ident: Ident, kind: &str, body: Option<Span>) {
468         let body = match body {
469             None => return,
470             Some(body) => body,
471         };
472         self.err_handler()
473             .struct_span_err(ident.span, &format!("incorrect `{}` inside `extern` block", kind))
474             .span_label(ident.span, "cannot have a body")
475             .span_label(body, "the invalid body")
476             .span_label(
477                 self.current_extern_span(),
478                 format!(
479                     "`extern` blocks define existing foreign {0}s and {0}s \
480                     inside of them cannot have a body",
481                     kind
482                 ),
483             )
484             .note(MORE_EXTERN)
485             .emit();
486     }
487
488     /// An `fn` in `extern { ... }` cannot have a body `{ ... }`.
489     fn check_foreign_fn_bodyless(&self, ident: Ident, body: Option<&Block>) {
490         let body = match body {
491             None => return,
492             Some(body) => body,
493         };
494         self.err_handler()
495             .struct_span_err(ident.span, "incorrect function inside `extern` block")
496             .span_label(ident.span, "cannot have a body")
497             .span_suggestion(
498                 body.span,
499                 "remove the invalid body",
500                 ";".to_string(),
501                 Applicability::MaybeIncorrect,
502             )
503             .help(
504                 "you might have meant to write a function accessible through FFI, \
505                 which can be done by writing `extern fn` outside of the `extern` block",
506             )
507             .span_label(
508                 self.current_extern_span(),
509                 "`extern` blocks define existing foreign functions and functions \
510                 inside of them cannot have a body",
511             )
512             .note(MORE_EXTERN)
513             .emit();
514     }
515
516     fn current_extern_span(&self) -> Span {
517         self.session.source_map().def_span(self.extern_mod.unwrap().span)
518     }
519
520     /// An `fn` in `extern { ... }` cannot have qualfiers, e.g. `async fn`.
521     fn check_foreign_fn_headerless(&self, ident: Ident, span: Span, header: FnHeader) {
522         if header.has_qualifiers() {
523             self.err_handler()
524                 .struct_span_err(ident.span, "functions in `extern` blocks cannot have qualifiers")
525                 .span_label(self.current_extern_span(), "in this `extern` block")
526                 .span_suggestion(
527                     span.until(ident.span.shrink_to_lo()),
528                     "remove the qualifiers",
529                     "fn ".to_string(),
530                     Applicability::MaybeIncorrect,
531                 )
532                 .emit();
533         }
534     }
535
536     /// Reject C-varadic type unless the function is foreign,
537     /// or free and `unsafe extern "C"` semantically.
538     fn check_c_varadic_type(&self, fk: FnKind<'a>) {
539         match (fk.ctxt(), fk.header()) {
540             (Some(FnCtxt::Foreign), _) => return,
541             (Some(FnCtxt::Free), Some(header)) => match header.ext {
542                 Extern::Explicit(StrLit { symbol_unescaped: sym::C, .. }) | Extern::Implicit
543                     if matches!(header.unsafety, Unsafe::Yes(_)) =>
544                 {
545                     return;
546                 }
547                 _ => {}
548             },
549             _ => {}
550         };
551
552         for Param { ty, span, .. } in &fk.decl().inputs {
553             if let TyKind::CVarArgs = ty.kind {
554                 self.err_handler()
555                     .struct_span_err(
556                         *span,
557                         "only foreign or `unsafe extern \"C\" functions may be C-variadic",
558                     )
559                     .emit();
560             }
561         }
562     }
563
564     /// We currently do not permit const generics in `const fn`,
565     /// as this is tantamount to allowing compile-time dependent typing.
566     ///
567     /// FIXME(const_generics): Is this really true / necessary? Discuss with @varkor.
568     /// At any rate, the restriction feels too syntactic. Consider moving it to e.g. typeck.
569     fn check_const_fn_const_generic(&self, span: Span, sig: &FnSig, generics: &Generics) {
570         if let Const::Yes(const_span) = sig.header.constness {
571             // Look for const generics and error if we find any.
572             for param in &generics.params {
573                 if let GenericParamKind::Const { .. } = param.kind {
574                     self.err_handler()
575                         .struct_span_err(
576                             span,
577                             "const parameters are not permitted in const functions",
578                         )
579                         .span_label(const_span, "`const` because of this")
580                         .emit();
581                 }
582             }
583         }
584     }
585
586     fn check_item_named(&self, ident: Ident, kind: &str) {
587         if ident.name != kw::Underscore {
588             return;
589         }
590         self.err_handler()
591             .struct_span_err(ident.span, &format!("`{}` items in this context need a name", kind))
592             .span_label(ident.span, format!("`_` is not a valid name for this `{}` item", kind))
593             .emit();
594     }
595 }
596
597 enum GenericPosition {
598     Param,
599     Arg,
600 }
601
602 fn validate_generics_order<'a>(
603     sess: &Session,
604     handler: &rustc_errors::Handler,
605     generics: impl Iterator<Item = (ParamKindOrd, Option<&'a [GenericBound]>, Span, Option<String>)>,
606     pos: GenericPosition,
607     span: Span,
608 ) {
609     let mut max_param: Option<ParamKindOrd> = None;
610     let mut out_of_order = FxHashMap::default();
611     let mut param_idents = vec![];
612     let mut found_type = false;
613     let mut found_const = false;
614
615     for (kind, bounds, span, ident) in generics {
616         if let Some(ident) = ident {
617             param_idents.push((kind, bounds, param_idents.len(), ident));
618         }
619         let max_param = &mut max_param;
620         match max_param {
621             Some(max_param) if *max_param > kind => {
622                 let entry = out_of_order.entry(kind).or_insert((*max_param, vec![]));
623                 entry.1.push(span);
624             }
625             Some(_) | None => *max_param = Some(kind),
626         };
627         match kind {
628             ParamKindOrd::Type => found_type = true,
629             ParamKindOrd::Const => found_const = true,
630             _ => {}
631         }
632     }
633
634     let mut ordered_params = "<".to_string();
635     if !out_of_order.is_empty() {
636         param_idents.sort_by_key(|&(po, _, i, _)| (po, i));
637         let mut first = true;
638         for (_, bounds, _, ident) in param_idents {
639             if !first {
640                 ordered_params += ", ";
641             }
642             ordered_params += &ident;
643             if let Some(bounds) = bounds {
644                 if !bounds.is_empty() {
645                     ordered_params += ": ";
646                     ordered_params += &pprust::bounds_to_string(&bounds);
647                 }
648             }
649             first = false;
650         }
651     }
652     ordered_params += ">";
653
654     let pos_str = match pos {
655         GenericPosition::Param => "parameter",
656         GenericPosition::Arg => "argument",
657     };
658
659     for (param_ord, (max_param, spans)) in &out_of_order {
660         let mut err = handler.struct_span_err(
661             spans.clone(),
662             &format!(
663                 "{} {pos}s must be declared prior to {} {pos}s",
664                 param_ord,
665                 max_param,
666                 pos = pos_str,
667             ),
668         );
669         if let GenericPosition::Param = pos {
670             err.span_suggestion(
671                 span,
672                 &format!(
673                     "reorder the {}s: lifetimes, then types{}",
674                     pos_str,
675                     if sess.features_untracked().const_generics { ", then consts" } else { "" },
676                 ),
677                 ordered_params.clone(),
678                 Applicability::MachineApplicable,
679             );
680         }
681         err.emit();
682     }
683
684     // FIXME(const_generics): we shouldn't have to abort here at all, but we currently get ICEs
685     // if we don't. Const parameters and type parameters can currently conflict if they
686     // are out-of-order.
687     if !out_of_order.is_empty() && found_type && found_const {
688         FatalError.raise();
689     }
690 }
691
692 impl<'a> Visitor<'a> for AstValidator<'a> {
693     fn visit_attribute(&mut self, attr: &Attribute) {
694         validate_attr::check_meta(&self.session.parse_sess, attr);
695     }
696
697     fn visit_expr(&mut self, expr: &'a Expr) {
698         match &expr.kind {
699             ExprKind::InlineAsm(..) if !self.session.target.target.options.allow_asm => {
700                 struct_span_err!(
701                     self.session,
702                     expr.span,
703                     E0472,
704                     "asm! is unsupported on this target"
705                 )
706                 .emit();
707             }
708             _ => {}
709         }
710
711         visit::walk_expr(self, expr);
712     }
713
714     fn visit_ty(&mut self, ty: &'a Ty) {
715         match ty.kind {
716             TyKind::BareFn(ref bfty) => {
717                 self.check_fn_decl(&bfty.decl, SelfSemantic::No);
718                 Self::check_decl_no_pat(&bfty.decl, |span, _| {
719                     struct_span_err!(
720                         self.session,
721                         span,
722                         E0561,
723                         "patterns aren't allowed in function pointer types"
724                     )
725                     .emit();
726                 });
727                 self.check_late_bound_lifetime_defs(&bfty.generic_params);
728             }
729             TyKind::TraitObject(ref bounds, ..) => {
730                 let mut any_lifetime_bounds = false;
731                 for bound in bounds {
732                     if let GenericBound::Outlives(ref lifetime) = *bound {
733                         if any_lifetime_bounds {
734                             struct_span_err!(
735                                 self.session,
736                                 lifetime.ident.span,
737                                 E0226,
738                                 "only a single explicit lifetime bound is permitted"
739                             )
740                             .emit();
741                             break;
742                         }
743                         any_lifetime_bounds = true;
744                     }
745                 }
746                 self.no_questions_in_bounds(bounds, "trait object types", false);
747             }
748             TyKind::ImplTrait(_, ref bounds) => {
749                 if self.is_impl_trait_banned {
750                     struct_span_err!(
751                         self.session,
752                         ty.span,
753                         E0667,
754                         "`impl Trait` is not allowed in path parameters"
755                     )
756                     .emit();
757                 }
758
759                 if let Some(outer_impl_trait_sp) = self.outer_impl_trait {
760                     struct_span_err!(
761                         self.session,
762                         ty.span,
763                         E0666,
764                         "nested `impl Trait` is not allowed"
765                     )
766                     .span_label(outer_impl_trait_sp, "outer `impl Trait`")
767                     .span_label(ty.span, "nested `impl Trait` here")
768                     .emit();
769                 }
770
771                 if !bounds
772                     .iter()
773                     .any(|b| if let GenericBound::Trait(..) = *b { true } else { false })
774                 {
775                     self.err_handler().span_err(ty.span, "at least one trait must be specified");
776                 }
777
778                 self.walk_ty(ty);
779                 return;
780             }
781             _ => {}
782         }
783
784         self.walk_ty(ty)
785     }
786
787     fn visit_label(&mut self, label: &'a Label) {
788         self.check_label(label.ident);
789         visit::walk_label(self, label);
790     }
791
792     fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
793         self.check_lifetime(lifetime.ident);
794         visit::walk_lifetime(self, lifetime);
795     }
796
797     fn visit_item(&mut self, item: &'a Item) {
798         if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)) {
799             self.has_proc_macro_decls = true;
800         }
801
802         match item.kind {
803             ItemKind::Impl {
804                 unsafety,
805                 polarity,
806                 defaultness: _,
807                 constness: _,
808                 generics: _,
809                 of_trait: Some(_),
810                 ref self_ty,
811                 items: _,
812             } => {
813                 self.with_in_trait_impl(true, |this| {
814                     this.invalid_visibility(&item.vis, None);
815                     if let TyKind::Err = self_ty.kind {
816                         this.err_handler()
817                             .struct_span_err(
818                                 item.span,
819                                 "`impl Trait for .. {}` is an obsolete syntax",
820                             )
821                             .help("use `auto trait Trait {}` instead")
822                             .emit();
823                     }
824                     if let (Unsafe::Yes(span), ImplPolarity::Negative) = (unsafety, polarity) {
825                         struct_span_err!(
826                             this.session,
827                             item.span,
828                             E0198,
829                             "negative impls cannot be unsafe"
830                         )
831                         .span_label(span, "unsafe because of this")
832                         .emit();
833                     }
834
835                     visit::walk_item(this, item);
836                 });
837                 return; // Avoid visiting again.
838             }
839             ItemKind::Impl {
840                 unsafety,
841                 polarity,
842                 defaultness,
843                 constness,
844                 generics: _,
845                 of_trait: None,
846                 self_ty: _,
847                 items: _,
848             } => {
849                 self.invalid_visibility(
850                     &item.vis,
851                     Some("place qualifiers on individual impl items instead"),
852                 );
853                 if let Unsafe::Yes(span) = unsafety {
854                     struct_span_err!(
855                         self.session,
856                         item.span,
857                         E0197,
858                         "inherent impls cannot be unsafe"
859                     )
860                     .span_label(span, "unsafe because of this")
861                     .emit();
862                 }
863                 if polarity == ImplPolarity::Negative {
864                     self.err_handler().span_err(item.span, "inherent impls cannot be negative");
865                 }
866                 if defaultness == Defaultness::Default {
867                     self.err_handler()
868                         .struct_span_err(item.span, "inherent impls cannot be default")
869                         .note("only trait implementations may be annotated with default")
870                         .emit();
871                 }
872                 if let Const::Yes(span) = constness {
873                     self.err_handler()
874                         .struct_span_err(item.span, "inherent impls cannot be `const`")
875                         .span_label(span, "`const` because of this")
876                         .note("only trait implementations may be annotated with `const`")
877                         .emit();
878                 }
879             }
880             ItemKind::Fn(ref sig, ref generics, ref body) => {
881                 self.check_const_fn_const_generic(item.span, sig, generics);
882
883                 if body.is_none() {
884                     let msg = "free function without a body";
885                     self.error_item_without_body(item.span, "function", msg, " { <body> }");
886                 }
887             }
888             ItemKind::ForeignMod(_) => {
889                 let old_item = mem::replace(&mut self.extern_mod, Some(item));
890                 self.invalid_visibility(
891                     &item.vis,
892                     Some("place qualifiers on individual foreign items instead"),
893                 );
894                 visit::walk_item(self, item);
895                 self.extern_mod = old_item;
896                 return; // Avoid visiting again.
897             }
898             ItemKind::Enum(ref def, _) => {
899                 for variant in &def.variants {
900                     self.invalid_visibility(&variant.vis, None);
901                     for field in variant.data.fields() {
902                         self.invalid_visibility(&field.vis, None);
903                     }
904                 }
905             }
906             ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
907                 if is_auto == IsAuto::Yes {
908                     // Auto traits cannot have generics, super traits nor contain items.
909                     if !generics.params.is_empty() {
910                         struct_span_err!(
911                             self.session,
912                             item.span,
913                             E0567,
914                             "auto traits cannot have generic parameters"
915                         )
916                         .emit();
917                     }
918                     if !bounds.is_empty() {
919                         struct_span_err!(
920                             self.session,
921                             item.span,
922                             E0568,
923                             "auto traits cannot have super traits"
924                         )
925                         .emit();
926                     }
927                     if !trait_items.is_empty() {
928                         struct_span_err!(
929                             self.session,
930                             item.span,
931                             E0380,
932                             "auto traits cannot have methods or associated items"
933                         )
934                         .emit();
935                     }
936                 }
937                 self.no_questions_in_bounds(bounds, "supertraits", true);
938
939                 // Equivalent of `visit::walk_item` for `ItemKind::Trait` that inserts a bound
940                 // context for the supertraits.
941                 self.visit_vis(&item.vis);
942                 self.visit_ident(item.ident);
943                 self.visit_generics(generics);
944                 self.with_bound_context(BoundContext::TraitBounds, |this| {
945                     walk_list!(this, visit_param_bound, bounds);
946                 });
947                 walk_list!(self, visit_assoc_item, trait_items, AssocCtxt::Trait);
948                 walk_list!(self, visit_attribute, &item.attrs);
949                 return;
950             }
951             ItemKind::Mod(_) => {
952                 // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
953                 attr::first_attr_value_str_by_name(&item.attrs, sym::path);
954             }
955             ItemKind::Union(ref vdata, _) => {
956                 if let VariantData::Tuple(..) | VariantData::Unit(..) = vdata {
957                     self.err_handler()
958                         .span_err(item.span, "tuple and unit unions are not permitted");
959                 }
960                 if vdata.fields().is_empty() {
961                     self.err_handler().span_err(item.span, "unions cannot have zero fields");
962                 }
963             }
964             ItemKind::Const(.., None) => {
965                 let msg = "free constant item without body";
966                 self.error_item_without_body(item.span, "constant", msg, " = <expr>;");
967             }
968             ItemKind::Static(.., None) => {
969                 let msg = "free static item without body";
970                 self.error_item_without_body(item.span, "static", msg, " = <expr>;");
971             }
972             _ => {}
973         }
974
975         visit::walk_item(self, item)
976     }
977
978     fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
979         match &fi.kind {
980             ForeignItemKind::Fn(sig, _, body) => {
981                 self.check_foreign_fn_bodyless(fi.ident, body.as_deref());
982                 self.check_foreign_fn_headerless(fi.ident, fi.span, sig.header);
983             }
984             ForeignItemKind::TyAlias(generics, bounds, body) => {
985                 self.check_foreign_kind_bodyless(fi.ident, "type", body.as_ref().map(|b| b.span));
986                 self.check_type_no_bounds(bounds, "`extern` blocks");
987                 self.check_foreign_ty_genericless(generics);
988             }
989             ForeignItemKind::Static(_, _, body) => {
990                 self.check_foreign_kind_bodyless(fi.ident, "static", body.as_ref().map(|b| b.span));
991             }
992             ForeignItemKind::Const(..) | ForeignItemKind::Macro(..) => {}
993         }
994
995         visit::walk_foreign_item(self, fi)
996     }
997
998     // Mirrors `visit::walk_generic_args`, but tracks relevant state.
999     fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
1000         match *generic_args {
1001             GenericArgs::AngleBracketed(ref data) => {
1002                 walk_list!(self, visit_generic_arg, &data.args);
1003                 validate_generics_order(
1004                     self.session,
1005                     self.err_handler(),
1006                     data.args.iter().map(|arg| {
1007                         (
1008                             match arg {
1009                                 GenericArg::Lifetime(..) => ParamKindOrd::Lifetime,
1010                                 GenericArg::Type(..) => ParamKindOrd::Type,
1011                                 GenericArg::Const(..) => ParamKindOrd::Const,
1012                             },
1013                             None,
1014                             arg.span(),
1015                             None,
1016                         )
1017                     }),
1018                     GenericPosition::Arg,
1019                     generic_args.span(),
1020                 );
1021
1022                 // Type bindings such as `Item = impl Debug` in `Iterator<Item = Debug>`
1023                 // are allowed to contain nested `impl Trait`.
1024                 self.with_impl_trait(None, |this| {
1025                     walk_list!(
1026                         this,
1027                         visit_assoc_ty_constraint_from_generic_args,
1028                         &data.constraints
1029                     );
1030                 });
1031             }
1032             GenericArgs::Parenthesized(ref data) => {
1033                 walk_list!(self, visit_ty, &data.inputs);
1034                 if let FnRetTy::Ty(ty) = &data.output {
1035                     // `-> Foo` syntax is essentially an associated type binding,
1036                     // so it is also allowed to contain nested `impl Trait`.
1037                     self.with_impl_trait(None, |this| this.visit_ty(ty));
1038                 }
1039             }
1040         }
1041     }
1042
1043     fn visit_generics(&mut self, generics: &'a Generics) {
1044         let mut prev_ty_default = None;
1045         for param in &generics.params {
1046             if let GenericParamKind::Type { ref default, .. } = param.kind {
1047                 if default.is_some() {
1048                     prev_ty_default = Some(param.ident.span);
1049                 } else if let Some(span) = prev_ty_default {
1050                     self.err_handler()
1051                         .span_err(span, "type parameters with a default must be trailing");
1052                     break;
1053                 }
1054             }
1055         }
1056
1057         validate_generics_order(
1058             self.session,
1059             self.err_handler(),
1060             generics.params.iter().map(|param| {
1061                 let ident = Some(param.ident.to_string());
1062                 let (kind, ident) = match &param.kind {
1063                     GenericParamKind::Lifetime { .. } => (ParamKindOrd::Lifetime, ident),
1064                     GenericParamKind::Type { .. } => (ParamKindOrd::Type, ident),
1065                     GenericParamKind::Const { ref ty } => {
1066                         let ty = pprust::ty_to_string(ty);
1067                         (ParamKindOrd::Const, Some(format!("const {}: {}", param.ident, ty)))
1068                     }
1069                 };
1070                 (kind, Some(&*param.bounds), param.ident.span, ident)
1071             }),
1072             GenericPosition::Param,
1073             generics.span,
1074         );
1075
1076         for predicate in &generics.where_clause.predicates {
1077             if let WherePredicate::EqPredicate(ref predicate) = *predicate {
1078                 self.err_handler()
1079                     .struct_span_err(
1080                         predicate.span,
1081                         "equality constraints are not yet supported in `where` clauses",
1082                     )
1083                     .span_label(predicate.span, "not supported")
1084                     .note(
1085                         "see issue #20041 <https://github.com/rust-lang/rust/issues/20041> \
1086                          for more information",
1087                     )
1088                     .emit();
1089             }
1090         }
1091
1092         visit::walk_generics(self, generics)
1093     }
1094
1095     fn visit_generic_param(&mut self, param: &'a GenericParam) {
1096         if let GenericParamKind::Lifetime { .. } = param.kind {
1097             self.check_lifetime(param.ident);
1098         }
1099         visit::walk_generic_param(self, param);
1100     }
1101
1102     fn visit_param_bound(&mut self, bound: &'a GenericBound) {
1103         match bound {
1104             GenericBound::Trait(_, TraitBoundModifier::MaybeConst) => {
1105                 if let Some(ctx) = self.bound_context {
1106                     let msg = format!("`?const` is not permitted in {}", ctx.description());
1107                     self.err_handler().span_err(bound.span(), &msg);
1108                 }
1109             }
1110
1111             GenericBound::Trait(_, TraitBoundModifier::MaybeConstMaybe) => {
1112                 self.err_handler()
1113                     .span_err(bound.span(), "`?const` and `?` are mutually exclusive");
1114             }
1115
1116             _ => {}
1117         }
1118
1119         visit::walk_param_bound(self, bound)
1120     }
1121
1122     fn visit_pat(&mut self, pat: &'a Pat) {
1123         match pat.kind {
1124             PatKind::Lit(ref expr) => {
1125                 self.check_expr_within_pat(expr, false);
1126             }
1127             PatKind::Range(ref start, ref end, _) => {
1128                 if let Some(expr) = start {
1129                     self.check_expr_within_pat(expr, true);
1130                 }
1131                 if let Some(expr) = end {
1132                     self.check_expr_within_pat(expr, true);
1133                 }
1134             }
1135             _ => {}
1136         }
1137
1138         visit::walk_pat(self, pat)
1139     }
1140
1141     fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
1142         if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
1143             // A type binding, eg `for<'c> Foo: Send+Clone+'c`
1144             self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
1145         }
1146         visit::walk_where_predicate(self, p);
1147     }
1148
1149     fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
1150         self.check_late_bound_lifetime_defs(&t.bound_generic_params);
1151         visit::walk_poly_trait_ref(self, t, m);
1152     }
1153
1154     fn visit_variant_data(&mut self, s: &'a VariantData) {
1155         self.with_banned_assoc_ty_bound(|this| visit::walk_struct_def(this, s))
1156     }
1157
1158     fn visit_enum_def(
1159         &mut self,
1160         enum_definition: &'a EnumDef,
1161         generics: &'a Generics,
1162         item_id: NodeId,
1163         _: Span,
1164     ) {
1165         self.with_banned_assoc_ty_bound(|this| {
1166             visit::walk_enum_def(this, enum_definition, generics, item_id)
1167         })
1168     }
1169
1170     fn visit_fn(&mut self, fk: FnKind<'a>, span: Span, id: NodeId) {
1171         // Only associated `fn`s can have `self` parameters.
1172         let self_semantic = match fk.ctxt() {
1173             Some(FnCtxt::Assoc(_)) => SelfSemantic::Yes,
1174             _ => SelfSemantic::No,
1175         };
1176         self.check_fn_decl(fk.decl(), self_semantic);
1177
1178         self.check_c_varadic_type(fk);
1179
1180         // Functions cannot both be `const async`
1181         if let Some(FnHeader {
1182             constness: Const::Yes(cspan),
1183             asyncness: Async::Yes { span: aspan, .. },
1184             ..
1185         }) = fk.header()
1186         {
1187             self.err_handler()
1188                 .struct_span_err(span, "functions cannot be both `const` and `async`")
1189                 .span_label(*cspan, "`const` because of this")
1190                 .span_label(*aspan, "`async` because of this")
1191                 .emit();
1192         }
1193
1194         // Functions without bodies cannot have patterns.
1195         if let FnKind::Fn(ctxt, _, sig, _, None) = fk {
1196             Self::check_decl_no_pat(&sig.decl, |span, mut_ident| {
1197                 let (code, msg, label) = match ctxt {
1198                     FnCtxt::Foreign => (
1199                         error_code!(E0130),
1200                         "patterns aren't allowed in foreign function declarations",
1201                         "pattern not allowed in foreign function",
1202                     ),
1203                     _ => (
1204                         error_code!(E0642),
1205                         "patterns aren't allowed in functions without bodies",
1206                         "pattern not allowed in function without body",
1207                     ),
1208                 };
1209                 if mut_ident && matches!(ctxt, FnCtxt::Assoc(_)) {
1210                     self.lint_buffer.buffer_lint(PATTERNS_IN_FNS_WITHOUT_BODY, id, span, msg);
1211                 } else {
1212                     self.err_handler()
1213                         .struct_span_err(span, msg)
1214                         .span_label(span, label)
1215                         .code(code)
1216                         .emit();
1217                 }
1218             });
1219         }
1220
1221         visit::walk_fn(self, fk, span);
1222     }
1223
1224     fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
1225         if ctxt == AssocCtxt::Trait {
1226             self.check_defaultness(item.span, item.defaultness);
1227         }
1228
1229         if ctxt == AssocCtxt::Impl {
1230             match &item.kind {
1231                 AssocItemKind::Const(_, body) => {
1232                     self.check_impl_item_provided(item.span, body, "constant", " = <expr>;");
1233                 }
1234                 AssocItemKind::Fn(_, _, body) => {
1235                     self.check_impl_item_provided(item.span, body, "function", " { <body> }");
1236                 }
1237                 AssocItemKind::TyAlias(_, bounds, body) => {
1238                     self.check_impl_item_provided(item.span, body, "type", " = <type>;");
1239                     self.check_type_no_bounds(bounds, "`impl`s");
1240                 }
1241                 _ => {}
1242             }
1243         }
1244
1245         if ctxt == AssocCtxt::Trait || self.in_trait_impl {
1246             self.invalid_visibility(&item.vis, None);
1247             if let AssocItemKind::Fn(sig, _, _) = &item.kind {
1248                 self.check_trait_fn_not_const(sig.header.constness);
1249                 self.check_trait_fn_not_async(item.span, sig.header.asyncness);
1250             }
1251         }
1252
1253         if let AssocItemKind::Const(..) = item.kind {
1254             self.check_item_named(item.ident, "const");
1255         }
1256
1257         self.with_in_trait_impl(false, |this| visit::walk_assoc_item(this, item, ctxt));
1258     }
1259 }
1260
1261 pub fn check_crate(session: &Session, krate: &Crate, lints: &mut LintBuffer) -> bool {
1262     let mut validator = AstValidator {
1263         session,
1264         extern_mod: None,
1265         in_trait_impl: false,
1266         has_proc_macro_decls: false,
1267         outer_impl_trait: None,
1268         bound_context: None,
1269         is_impl_trait_banned: false,
1270         is_assoc_ty_bound_banned: false,
1271         lint_buffer: lints,
1272     };
1273     visit::walk_crate(&mut validator, krate);
1274
1275     validator.has_proc_macro_decls
1276 }