]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_passes/src/feature_gate.rs
Stablize `const_extern_fn` for "Rust" and "C"
[rust.git] / compiler / rustc_ast_passes / src / feature_gate.rs
1 use rustc_ast as ast;
2 use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
3 use rustc_ast::{AssocConstraint, AssocConstraintKind, NodeId};
4 use rustc_ast::{PatKind, RangeEnd, VariantData};
5 use rustc_errors::struct_span_err;
6 use rustc_feature::{AttributeGate, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
7 use rustc_feature::{Features, GateIssue};
8 use rustc_session::parse::{feature_err, feature_err_issue};
9 use rustc_session::Session;
10 use rustc_span::source_map::Spanned;
11 use rustc_span::symbol::sym;
12 use rustc_span::Span;
13
14 use tracing::debug;
15
16 macro_rules! gate_feature_fn {
17     ($visitor: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $help: expr) => {{
18         let (visitor, has_feature, span, name, explain, help) =
19             (&*$visitor, $has_feature, $span, $name, $explain, $help);
20         let has_feature: bool = has_feature(visitor.features);
21         debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
22         if !has_feature && !span.allows_unstable($name) {
23             feature_err_issue(&visitor.sess.parse_sess, name, span, GateIssue::Language, explain)
24                 .help(help)
25                 .emit();
26         }
27     }};
28     ($visitor: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr) => {{
29         let (visitor, has_feature, span, name, explain) =
30             (&*$visitor, $has_feature, $span, $name, $explain);
31         let has_feature: bool = has_feature(visitor.features);
32         debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
33         if !has_feature && !span.allows_unstable($name) {
34             feature_err_issue(&visitor.sess.parse_sess, name, span, GateIssue::Language, explain)
35                 .emit();
36         }
37     }};
38 }
39
40 macro_rules! gate_feature_post {
41     ($visitor: expr, $feature: ident, $span: expr, $explain: expr, $help: expr) => {
42         gate_feature_fn!($visitor, |x: &Features| x.$feature, $span, sym::$feature, $explain, $help)
43     };
44     ($visitor: expr, $feature: ident, $span: expr, $explain: expr) => {
45         gate_feature_fn!($visitor, |x: &Features| x.$feature, $span, sym::$feature, $explain)
46     };
47 }
48
49 pub fn check_attribute(attr: &ast::Attribute, sess: &Session, features: &Features) {
50     PostExpansionVisitor { sess, features }.visit_attribute(attr)
51 }
52
53 struct PostExpansionVisitor<'a> {
54     sess: &'a Session,
55
56     // `sess` contains a `Features`, but this might not be that one.
57     features: &'a Features,
58 }
59
60 impl<'a> PostExpansionVisitor<'a> {
61     fn check_abi(&self, abi: ast::StrLit, constness: ast::Const) {
62         let ast::StrLit { symbol_unescaped, span, .. } = abi;
63
64         if let ast::Const::Yes(_) = constness {
65             match symbol_unescaped.as_str() {
66                 // Stable
67                 "Rust" | "C" => {}
68                 abi => gate_feature_post!(
69                     &self,
70                     const_extern_fn,
71                     span,
72                     &format!("`{}` as a `const fn` ABI is unstable", abi)
73                 ),
74             }
75         }
76
77         match symbol_unescaped.as_str() {
78             // Stable
79             "Rust" | "C" | "cdecl" | "stdcall" | "fastcall" | "aapcs" | "win64" | "sysv64"
80             | "system" => {}
81             "rust-intrinsic" => {
82                 gate_feature_post!(&self, intrinsics, span, "intrinsics are subject to change");
83             }
84             "platform-intrinsic" => {
85                 gate_feature_post!(
86                     &self,
87                     platform_intrinsics,
88                     span,
89                     "platform intrinsics are experimental and possibly buggy"
90                 );
91             }
92             "vectorcall" => {
93                 gate_feature_post!(
94                     &self,
95                     abi_vectorcall,
96                     span,
97                     "vectorcall is experimental and subject to change"
98                 );
99             }
100             "thiscall" => {
101                 gate_feature_post!(
102                     &self,
103                     abi_thiscall,
104                     span,
105                     "thiscall is experimental and subject to change"
106                 );
107             }
108             "rust-call" => {
109                 gate_feature_post!(
110                     &self,
111                     unboxed_closures,
112                     span,
113                     "rust-call ABI is subject to change"
114                 );
115             }
116             "ptx-kernel" => {
117                 gate_feature_post!(
118                     &self,
119                     abi_ptx,
120                     span,
121                     "PTX ABIs are experimental and subject to change"
122                 );
123             }
124             "unadjusted" => {
125                 gate_feature_post!(
126                     &self,
127                     abi_unadjusted,
128                     span,
129                     "unadjusted ABI is an implementation detail and perma-unstable"
130                 );
131             }
132             "msp430-interrupt" => {
133                 gate_feature_post!(
134                     &self,
135                     abi_msp430_interrupt,
136                     span,
137                     "msp430-interrupt ABI is experimental and subject to change"
138                 );
139             }
140             "x86-interrupt" => {
141                 gate_feature_post!(
142                     &self,
143                     abi_x86_interrupt,
144                     span,
145                     "x86-interrupt ABI is experimental and subject to change"
146                 );
147             }
148             "amdgpu-kernel" => {
149                 gate_feature_post!(
150                     &self,
151                     abi_amdgpu_kernel,
152                     span,
153                     "amdgpu-kernel ABI is experimental and subject to change"
154                 );
155             }
156             "avr-interrupt" | "avr-non-blocking-interrupt" => {
157                 gate_feature_post!(
158                     &self,
159                     abi_avr_interrupt,
160                     span,
161                     "avr-interrupt and avr-non-blocking-interrupt ABIs are experimental and subject to change"
162                 );
163             }
164             "efiapi" => {
165                 gate_feature_post!(
166                     &self,
167                     abi_efiapi,
168                     span,
169                     "efiapi ABI is experimental and subject to change"
170                 );
171             }
172             "C-cmse-nonsecure-call" => {
173                 gate_feature_post!(
174                     &self,
175                     abi_c_cmse_nonsecure_call,
176                     span,
177                     "C-cmse-nonsecure-call ABI is experimental and subject to change"
178                 );
179             }
180             "C-unwind" => {
181                 gate_feature_post!(
182                     &self,
183                     c_unwind,
184                     span,
185                     "C-unwind ABI is experimental and subject to change"
186                 );
187             }
188             "stdcall-unwind" => {
189                 gate_feature_post!(
190                     &self,
191                     c_unwind,
192                     span,
193                     "stdcall-unwind ABI is experimental and subject to change"
194                 );
195             }
196             "system-unwind" => {
197                 gate_feature_post!(
198                     &self,
199                     c_unwind,
200                     span,
201                     "system-unwind ABI is experimental and subject to change"
202                 );
203             }
204             "thiscall-unwind" => {
205                 gate_feature_post!(
206                     &self,
207                     c_unwind,
208                     span,
209                     "thiscall-unwind ABI is experimental and subject to change"
210                 );
211             }
212             "cdecl-unwind" => {
213                 gate_feature_post!(
214                     &self,
215                     c_unwind,
216                     span,
217                     "cdecl-unwind ABI is experimental and subject to change"
218                 );
219             }
220             "fastcall-unwind" => {
221                 gate_feature_post!(
222                     &self,
223                     c_unwind,
224                     span,
225                     "fastcall-unwind ABI is experimental and subject to change"
226                 );
227             }
228             "vectorcall-unwind" => {
229                 gate_feature_post!(
230                     &self,
231                     c_unwind,
232                     span,
233                     "vectorcall-unwind ABI is experimental and subject to change"
234                 );
235             }
236             "aapcs-unwind" => {
237                 gate_feature_post!(
238                     &self,
239                     c_unwind,
240                     span,
241                     "aapcs-unwind ABI is experimental and subject to change"
242                 );
243             }
244             "win64-unwind" => {
245                 gate_feature_post!(
246                     &self,
247                     c_unwind,
248                     span,
249                     "win64-unwind ABI is experimental and subject to change"
250                 );
251             }
252             "sysv64-unwind" => {
253                 gate_feature_post!(
254                     &self,
255                     c_unwind,
256                     span,
257                     "sysv64-unwind ABI is experimental and subject to change"
258                 );
259             }
260             "wasm" => {
261                 gate_feature_post!(
262                     &self,
263                     wasm_abi,
264                     span,
265                     "wasm ABI is experimental and subject to change"
266                 );
267             }
268             abi => {
269                 self.sess.parse_sess.span_diagnostic.delay_span_bug(
270                     span,
271                     &format!("unrecognized ABI not caught in lowering: {}", abi),
272                 );
273             }
274         }
275     }
276
277     fn check_extern(&self, ext: ast::Extern, constness: ast::Const) {
278         if let ast::Extern::Explicit(abi) = ext {
279             self.check_abi(abi, constness);
280         }
281     }
282
283     fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
284         let has_fields = variants.iter().any(|variant| match variant.data {
285             VariantData::Tuple(..) | VariantData::Struct(..) => true,
286             VariantData::Unit(..) => false,
287         });
288
289         let discriminant_spans = variants
290             .iter()
291             .filter(|variant| match variant.data {
292                 VariantData::Tuple(..) | VariantData::Struct(..) => false,
293                 VariantData::Unit(..) => true,
294             })
295             .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
296             .collect::<Vec<_>>();
297
298         if !discriminant_spans.is_empty() && has_fields {
299             let mut err = feature_err(
300                 &self.sess.parse_sess,
301                 sym::arbitrary_enum_discriminant,
302                 discriminant_spans.clone(),
303                 "custom discriminant values are not allowed in enums with tuple or struct variants",
304             );
305             for sp in discriminant_spans {
306                 err.span_label(sp, "disallowed custom discriminant");
307             }
308             for variant in variants.iter() {
309                 match &variant.data {
310                     VariantData::Struct(..) => {
311                         err.span_label(variant.span, "struct variant defined here");
312                     }
313                     VariantData::Tuple(..) => {
314                         err.span_label(variant.span, "tuple variant defined here");
315                     }
316                     VariantData::Unit(..) => {}
317                 }
318             }
319             err.emit();
320         }
321     }
322
323     fn check_gat(&self, generics: &ast::Generics, span: Span) {
324         if !generics.params.is_empty() {
325             gate_feature_post!(
326                 &self,
327                 generic_associated_types,
328                 span,
329                 "generic associated types are unstable"
330             );
331         }
332         if !generics.where_clause.predicates.is_empty() {
333             gate_feature_post!(
334                 &self,
335                 generic_associated_types,
336                 span,
337                 "where clauses on associated types are unstable"
338             );
339         }
340     }
341
342     /// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
343     fn check_impl_trait(&self, ty: &ast::Ty) {
344         struct ImplTraitVisitor<'a> {
345             vis: &'a PostExpansionVisitor<'a>,
346         }
347         impl Visitor<'_> for ImplTraitVisitor<'_> {
348             fn visit_ty(&mut self, ty: &ast::Ty) {
349                 if let ast::TyKind::ImplTrait(..) = ty.kind {
350                     gate_feature_post!(
351                         &self.vis,
352                         type_alias_impl_trait,
353                         ty.span,
354                         "`impl Trait` in type aliases is unstable"
355                     );
356                 }
357                 visit::walk_ty(self, ty);
358             }
359         }
360         ImplTraitVisitor { vis: self }.visit_ty(ty);
361     }
362 }
363
364 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
365     fn visit_attribute(&mut self, attr: &ast::Attribute) {
366         let attr_info = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
367         // Check feature gates for built-in attributes.
368         if let Some(BuiltinAttribute {
369             gate: AttributeGate::Gated(_, name, descr, has_feature),
370             ..
371         }) = attr_info
372         {
373             gate_feature_fn!(self, has_feature, attr.span, *name, descr);
374         }
375         // Check unstable flavors of the `#[doc]` attribute.
376         if attr.has_name(sym::doc) {
377             for nested_meta in attr.meta_item_list().unwrap_or_default() {
378                 macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
379                     $(if nested_meta.has_name(sym::$name) {
380                         let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
381                         gate_feature_post!(self, $feature, attr.span, msg);
382                     })*
383                 }}
384
385                 gate_doc!(
386                     cfg => doc_cfg
387                     cfg_hide => doc_cfg_hide
388                     masked => doc_masked
389                     notable_trait => doc_notable_trait
390                 );
391
392                 if nested_meta.has_name(sym::keyword) {
393                     let msg = "`#[doc(keyword)]` is meant for internal use only";
394                     gate_feature_post!(self, rustdoc_internals, attr.span, msg);
395                 }
396             }
397         }
398
399         // Check for unstable modifiers on `#[link(..)]` attribute
400         if attr.has_name(sym::link) {
401             for nested_meta in attr.meta_item_list().unwrap_or_default() {
402                 if nested_meta.has_name(sym::modifiers) {
403                     gate_feature_post!(
404                         self,
405                         native_link_modifiers,
406                         nested_meta.span(),
407                         "native link modifiers are experimental"
408                     );
409
410                     if let Some(modifiers) = nested_meta.value_str() {
411                         for modifier in modifiers.as_str().split(',') {
412                             if let Some(modifier) = modifier.strip_prefix(&['+', '-']) {
413                                 macro_rules! gate_modifier { ($($name:literal => $feature:ident)*) => {
414                                     $(if modifier == $name {
415                                         let msg = concat!("`#[link(modifiers=\"", $name, "\")]` is unstable");
416                                         gate_feature_post!(
417                                             self,
418                                             $feature,
419                                             nested_meta.name_value_literal_span().unwrap(),
420                                             msg
421                                         );
422                                     })*
423                                 }}
424
425                                 gate_modifier!(
426                                     "bundle" => native_link_modifiers_bundle
427                                     "verbatim" => native_link_modifiers_verbatim
428                                     "whole-archive" => native_link_modifiers_whole_archive
429                                     "as-needed" => native_link_modifiers_as_needed
430                                 );
431                             }
432                         }
433                     }
434                 }
435             }
436         }
437
438         // Emit errors for non-staged-api crates.
439         if !self.features.staged_api {
440             if attr.has_name(sym::rustc_deprecated)
441                 || attr.has_name(sym::unstable)
442                 || attr.has_name(sym::stable)
443                 || attr.has_name(sym::rustc_const_unstable)
444                 || attr.has_name(sym::rustc_const_stable)
445             {
446                 struct_span_err!(
447                     self.sess,
448                     attr.span,
449                     E0734,
450                     "stability attributes may not be used outside of the standard library",
451                 )
452                 .emit();
453             }
454         }
455     }
456
457     fn visit_item(&mut self, i: &'a ast::Item) {
458         match i.kind {
459             ast::ItemKind::ForeignMod(ref foreign_module) => {
460                 if let Some(abi) = foreign_module.abi {
461                     self.check_abi(abi, ast::Const::No);
462                 }
463             }
464
465             ast::ItemKind::Fn(..) => {
466                 if self.sess.contains_name(&i.attrs, sym::start) {
467                     gate_feature_post!(
468                         &self,
469                         start,
470                         i.span,
471                         "`#[start]` functions are experimental \
472                          and their signature may change \
473                          over time"
474                     );
475                 }
476             }
477
478             ast::ItemKind::Struct(..) => {
479                 for attr in self.sess.filter_by_name(&i.attrs, sym::repr) {
480                     for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
481                         if item.has_name(sym::simd) {
482                             gate_feature_post!(
483                                 &self,
484                                 repr_simd,
485                                 attr.span,
486                                 "SIMD types are experimental and possibly buggy"
487                             );
488                         }
489                     }
490                 }
491             }
492
493             ast::ItemKind::Enum(ast::EnumDef { ref variants, .. }, ..) => {
494                 for variant in variants {
495                     match (&variant.data, &variant.disr_expr) {
496                         (ast::VariantData::Unit(..), _) => {}
497                         (_, Some(disr_expr)) => gate_feature_post!(
498                             &self,
499                             arbitrary_enum_discriminant,
500                             disr_expr.value.span,
501                             "discriminants on non-unit variants are experimental"
502                         ),
503                         _ => {}
504                     }
505                 }
506
507                 let has_feature = self.features.arbitrary_enum_discriminant;
508                 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
509                     self.maybe_report_invalid_custom_discriminants(&variants);
510                 }
511             }
512
513             ast::ItemKind::Impl(box ast::Impl { polarity, defaultness, ref of_trait, .. }) => {
514                 if let ast::ImplPolarity::Negative(span) = polarity {
515                     gate_feature_post!(
516                         &self,
517                         negative_impls,
518                         span.to(of_trait.as_ref().map_or(span, |t| t.path.span)),
519                         "negative trait bounds are not yet fully implemented; \
520                          use marker types for now"
521                     );
522                 }
523
524                 if let ast::Defaultness::Default(_) = defaultness {
525                     gate_feature_post!(&self, specialization, i.span, "specialization is unstable");
526                 }
527             }
528
529             ast::ItemKind::Trait(box ast::Trait { is_auto: ast::IsAuto::Yes, .. }) => {
530                 gate_feature_post!(
531                     &self,
532                     auto_traits,
533                     i.span,
534                     "auto traits are experimental and possibly buggy"
535                 );
536             }
537
538             ast::ItemKind::TraitAlias(..) => {
539                 gate_feature_post!(&self, trait_alias, i.span, "trait aliases are experimental");
540             }
541
542             ast::ItemKind::MacroDef(ast::MacroDef { macro_rules: false, .. }) => {
543                 let msg = "`macro` is experimental";
544                 gate_feature_post!(&self, decl_macro, i.span, msg);
545             }
546
547             ast::ItemKind::TyAlias(box ast::TyAlias { ty: Some(ref ty), .. }) => {
548                 self.check_impl_trait(&ty)
549             }
550
551             _ => {}
552         }
553
554         visit::walk_item(self, i);
555     }
556
557     fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
558         match i.kind {
559             ast::ForeignItemKind::Fn(..) | ast::ForeignItemKind::Static(..) => {
560                 let link_name = self.sess.first_attr_value_str_by_name(&i.attrs, sym::link_name);
561                 let links_to_llvm =
562                     link_name.map_or(false, |val| val.as_str().starts_with("llvm."));
563                 if links_to_llvm {
564                     gate_feature_post!(
565                         &self,
566                         link_llvm_intrinsics,
567                         i.span,
568                         "linking to LLVM intrinsics is experimental"
569                     );
570                 }
571             }
572             ast::ForeignItemKind::TyAlias(..) => {
573                 gate_feature_post!(&self, extern_types, i.span, "extern types are experimental");
574             }
575             ast::ForeignItemKind::MacCall(..) => {}
576         }
577
578         visit::walk_foreign_item(self, i)
579     }
580
581     fn visit_ty(&mut self, ty: &'a ast::Ty) {
582         match ty.kind {
583             ast::TyKind::BareFn(ref bare_fn_ty) => {
584                 // Function pointers cannot be `const`
585                 self.check_extern(bare_fn_ty.ext, ast::Const::No);
586             }
587             ast::TyKind::Never => {
588                 gate_feature_post!(&self, never_type, ty.span, "the `!` type is experimental");
589             }
590             _ => {}
591         }
592         visit::walk_ty(self, ty)
593     }
594
595     fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FnRetTy) {
596         if let ast::FnRetTy::Ty(ref output_ty) = *ret_ty {
597             if let ast::TyKind::Never = output_ty.kind {
598                 // Do nothing.
599             } else {
600                 self.visit_ty(output_ty)
601             }
602         }
603     }
604
605     fn visit_expr(&mut self, e: &'a ast::Expr) {
606         match e.kind {
607             ast::ExprKind::Box(_) => {
608                 gate_feature_post!(
609                     &self,
610                     box_syntax,
611                     e.span,
612                     "box expression syntax is experimental; you can call `Box::new` instead"
613                 );
614             }
615             ast::ExprKind::Type(..) => {
616                 // To avoid noise about type ascription in common syntax errors, only emit if it
617                 // is the *only* error.
618                 if self.sess.parse_sess.span_diagnostic.err_count() == 0 {
619                     gate_feature_post!(
620                         &self,
621                         type_ascription,
622                         e.span,
623                         "type ascription is experimental"
624                     );
625                 }
626             }
627             ast::ExprKind::TryBlock(_) => {
628                 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
629             }
630             ast::ExprKind::Block(_, Some(label)) => {
631                 gate_feature_post!(
632                     &self,
633                     label_break_value,
634                     label.ident.span,
635                     "labels on blocks are unstable"
636                 );
637             }
638             _ => {}
639         }
640         visit::walk_expr(self, e)
641     }
642
643     fn visit_pat(&mut self, pattern: &'a ast::Pat) {
644         match &pattern.kind {
645             PatKind::Slice(pats) => {
646                 for pat in pats {
647                     let inner_pat = match &pat.kind {
648                         PatKind::Ident(.., Some(pat)) => pat,
649                         _ => pat,
650                     };
651                     if let PatKind::Range(Some(_), None, Spanned { .. }) = inner_pat.kind {
652                         gate_feature_post!(
653                             &self,
654                             half_open_range_patterns,
655                             pat.span,
656                             "`X..` patterns in slices are experimental"
657                         );
658                     }
659                 }
660             }
661             PatKind::Box(..) => {
662                 gate_feature_post!(
663                     &self,
664                     box_patterns,
665                     pattern.span,
666                     "box pattern syntax is experimental"
667                 );
668             }
669             PatKind::Range(_, Some(_), Spanned { node: RangeEnd::Excluded, .. }) => {
670                 gate_feature_post!(
671                     &self,
672                     exclusive_range_pattern,
673                     pattern.span,
674                     "exclusive range pattern syntax is experimental"
675                 );
676             }
677             _ => {}
678         }
679         visit::walk_pat(self, pattern)
680     }
681
682     fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) {
683         if let Some(header) = fn_kind.header() {
684             // Stability of const fn methods are covered in `visit_assoc_item` below.
685             self.check_extern(header.ext, header.constness);
686         }
687
688         if fn_kind.ctxt() != Some(FnCtxt::Foreign) && fn_kind.decl().c_variadic() {
689             gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
690         }
691
692         visit::walk_fn(self, fn_kind, span)
693     }
694
695     fn visit_assoc_constraint(&mut self, constraint: &'a AssocConstraint) {
696         if let AssocConstraintKind::Bound { .. } = constraint.kind {
697             gate_feature_post!(
698                 &self,
699                 associated_type_bounds,
700                 constraint.span,
701                 "associated type bounds are unstable"
702             )
703         }
704         visit::walk_assoc_constraint(self, constraint)
705     }
706
707     fn visit_assoc_item(&mut self, i: &'a ast::AssocItem, ctxt: AssocCtxt) {
708         let is_fn = match i.kind {
709             ast::AssocItemKind::Fn(_) => true,
710             ast::AssocItemKind::TyAlias(box ast::TyAlias { ref generics, ref ty, .. }) => {
711                 if let (Some(_), AssocCtxt::Trait) = (ty, ctxt) {
712                     gate_feature_post!(
713                         &self,
714                         associated_type_defaults,
715                         i.span,
716                         "associated type defaults are unstable"
717                     );
718                 }
719                 if let Some(ty) = ty {
720                     self.check_impl_trait(ty);
721                 }
722                 self.check_gat(generics, i.span);
723                 false
724             }
725             _ => false,
726         };
727         if let ast::Defaultness::Default(_) = i.kind.defaultness() {
728             // Limit `min_specialization` to only specializing functions.
729             gate_feature_fn!(
730                 &self,
731                 |x: &Features| x.specialization || (is_fn && x.min_specialization),
732                 i.span,
733                 sym::specialization,
734                 "specialization is unstable"
735             );
736         }
737         visit::walk_assoc_item(self, i, ctxt)
738     }
739
740     fn visit_vis(&mut self, vis: &'a ast::Visibility) {
741         if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.kind {
742             gate_feature_post!(
743                 &self,
744                 crate_visibility_modifier,
745                 vis.span,
746                 "`crate` visibility modifier is experimental"
747             );
748         }
749         visit::walk_vis(self, vis)
750     }
751 }
752
753 pub fn check_crate(krate: &ast::Crate, sess: &Session) {
754     maybe_stage_features(sess, krate);
755     check_incompatible_features(sess);
756     let mut visitor = PostExpansionVisitor { sess, features: &sess.features_untracked() };
757
758     let spans = sess.parse_sess.gated_spans.spans.borrow();
759     macro_rules! gate_all {
760         ($gate:ident, $msg:literal, $help:literal) => {
761             if let Some(spans) = spans.get(&sym::$gate) {
762                 for span in spans {
763                     gate_feature_post!(&visitor, $gate, *span, $msg, $help);
764                 }
765             }
766         };
767         ($gate:ident, $msg:literal) => {
768             if let Some(spans) = spans.get(&sym::$gate) {
769                 for span in spans {
770                     gate_feature_post!(&visitor, $gate, *span, $msg);
771                 }
772             }
773         };
774     }
775     gate_all!(
776         if_let_guard,
777         "`if let` guards are experimental",
778         "you can write `if matches!(<expr>, <pattern>)` instead of `if let <pattern> = <expr>`"
779     );
780     gate_all!(let_chains, "`let` expressions in this position are unstable");
781     gate_all!(
782         async_closure,
783         "async closures are unstable",
784         "to use an async block, remove the `||`: `async {`"
785     );
786     gate_all!(more_qualified_paths, "usage of qualified paths in this context is experimental");
787     gate_all!(generators, "yield syntax is experimental");
788     gate_all!(raw_ref_op, "raw address of syntax is experimental");
789     gate_all!(const_trait_impl, "const trait impls are experimental");
790     gate_all!(half_open_range_patterns, "half-open range patterns are unstable");
791     gate_all!(inline_const, "inline-const is experimental");
792     gate_all!(inline_const_pat, "inline-const in pattern position is experimental");
793     gate_all!(associated_const_equality, "associated const equality is incomplete");
794
795     // All uses of `gate_all!` below this point were added in #65742,
796     // and subsequently disabled (with the non-early gating readded).
797     macro_rules! gate_all {
798         ($gate:ident, $msg:literal) => {
799             // FIXME(eddyb) do something more useful than always
800             // disabling these uses of early feature-gatings.
801             if false {
802                 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
803                     gate_feature_post!(&visitor, $gate, *span, $msg);
804                 }
805             }
806         };
807     }
808
809     gate_all!(trait_alias, "trait aliases are experimental");
810     gate_all!(associated_type_bounds, "associated type bounds are unstable");
811     gate_all!(crate_visibility_modifier, "`crate` visibility modifier is experimental");
812     gate_all!(decl_macro, "`macro` is experimental");
813     gate_all!(box_patterns, "box pattern syntax is experimental");
814     gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
815     gate_all!(try_blocks, "`try` blocks are unstable");
816     gate_all!(label_break_value, "labels on blocks are unstable");
817     gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
818     // To avoid noise about type ascription in common syntax errors,
819     // only emit if it is the *only* error. (Also check it last.)
820     if sess.parse_sess.span_diagnostic.err_count() == 0 {
821         gate_all!(type_ascription, "type ascription is experimental");
822     }
823
824     visit::walk_crate(&mut visitor, krate);
825 }
826
827 fn maybe_stage_features(sess: &Session, krate: &ast::Crate) {
828     // checks if `#![feature]` has been used to enable any lang feature
829     // does not check the same for lib features unless there's at least one
830     // declared lang feature
831     use rustc_errors::Applicability;
832
833     if !sess.opts.unstable_features.is_nightly_build() {
834         let lang_features = &sess.features_untracked().declared_lang_features;
835         if lang_features.len() == 0 {
836             return;
837         }
838         for attr in krate.attrs.iter().filter(|attr| attr.has_name(sym::feature)) {
839             let mut err = struct_span_err!(
840                 sess.parse_sess.span_diagnostic,
841                 attr.span,
842                 E0554,
843                 "`#![feature]` may not be used on the {} release channel",
844                 option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")
845             );
846             let mut all_stable = true;
847             for ident in
848                 attr.meta_item_list().into_iter().flatten().flat_map(|nested| nested.ident())
849             {
850                 let name = ident.name;
851                 let stable_since = lang_features
852                     .iter()
853                     .flat_map(|&(feature, _, since)| if feature == name { since } else { None })
854                     .next();
855                 if let Some(since) = stable_since {
856                     err.help(&format!(
857                         "the feature `{}` has been stable since {} and no longer requires \
858                                   an attribute to enable",
859                         name, since
860                     ));
861                 } else {
862                     all_stable = false;
863                 }
864             }
865             if all_stable {
866                 err.span_suggestion(
867                     attr.span,
868                     "remove the attribute",
869                     String::new(),
870                     Applicability::MachineApplicable,
871                 );
872             }
873             err.emit();
874         }
875     }
876 }
877
878 fn check_incompatible_features(sess: &Session) {
879     let features = sess.features_untracked();
880
881     let declared_features = features
882         .declared_lang_features
883         .iter()
884         .copied()
885         .map(|(name, span, _)| (name, span))
886         .chain(features.declared_lib_features.iter().copied());
887
888     for (f1, f2) in rustc_feature::INCOMPATIBLE_FEATURES
889         .iter()
890         .filter(|&&(f1, f2)| features.enabled(f1) && features.enabled(f2))
891     {
892         if let Some((f1_name, f1_span)) = declared_features.clone().find(|(name, _)| name == f1) {
893             if let Some((f2_name, f2_span)) = declared_features.clone().find(|(name, _)| name == f2)
894             {
895                 let spans = vec![f1_span, f2_span];
896                 sess.struct_span_err(
897                     spans.clone(),
898                     &format!(
899                         "features `{}` and `{}` are incompatible, using them at the same time \
900                         is not allowed",
901                         f1_name, f2_name
902                     ),
903                 )
904                 .help("remove one of these features")
905                 .emit();
906             }
907         }
908     }
909 }