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