]> git.lizzy.rs Git - rust.git/blob - src/librustc_ast_passes/feature_gate.rs
Auto merge of #72705 - Lucretiel:stdio-forwarding, r=Amanieu
[rust.git] / src / librustc_ast_passes / feature_gate.rs
1 use rustc_ast::ast::{self, AssocTyConstraint, AssocTyConstraintKind, NodeId};
2 use rustc_ast::ast::{GenericParam, GenericParamKind, PatKind, RangeEnd, VariantData};
3 use rustc_ast::attr;
4 use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
5 use rustc_errors::{struct_span_err, Handler};
6 use rustc_feature::{AttributeGate, BUILTIN_ATTRIBUTE_MAP};
7 use rustc_feature::{Features, GateIssue, UnstableFeatures};
8 use rustc_session::parse::{feature_err, feature_err_issue, ParseSess};
9 use rustc_span::source_map::Spanned;
10 use rustc_span::symbol::{sym, Symbol};
11 use rustc_span::Span;
12
13 use log::debug;
14
15 macro_rules! gate_feature_fn {
16     ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr) => {{
17         let (cx, has_feature, span, name, explain) = (&*$cx, $has_feature, $span, $name, $explain);
18         let has_feature: bool = has_feature(&$cx.features);
19         debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
20         if !has_feature && !span.allows_unstable($name) {
21             feature_err_issue(cx.parse_sess, name, span, GateIssue::Language, explain).emit();
22         }
23     }};
24 }
25
26 macro_rules! gate_feature_post {
27     ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
28         gate_feature_fn!($cx, |x: &Features| x.$feature, $span, sym::$feature, $explain)
29     };
30 }
31
32 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
33     PostExpansionVisitor { parse_sess, features }.visit_attribute(attr)
34 }
35
36 struct PostExpansionVisitor<'a> {
37     parse_sess: &'a ParseSess,
38     features: &'a Features,
39 }
40
41 impl<'a> PostExpansionVisitor<'a> {
42     fn check_abi(&self, abi: ast::StrLit) {
43         let ast::StrLit { symbol_unescaped, span, .. } = abi;
44
45         match &*symbol_unescaped.as_str() {
46             // Stable
47             "Rust" | "C" | "cdecl" | "stdcall" | "fastcall" | "aapcs" | "win64" | "sysv64"
48             | "system" => {}
49             "rust-intrinsic" => {
50                 gate_feature_post!(&self, intrinsics, span, "intrinsics are subject to change");
51             }
52             "platform-intrinsic" => {
53                 gate_feature_post!(
54                     &self,
55                     platform_intrinsics,
56                     span,
57                     "platform intrinsics are experimental and possibly buggy"
58                 );
59             }
60             "vectorcall" => {
61                 gate_feature_post!(
62                     &self,
63                     abi_vectorcall,
64                     span,
65                     "vectorcall is experimental and subject to change"
66                 );
67             }
68             "thiscall" => {
69                 gate_feature_post!(
70                     &self,
71                     abi_thiscall,
72                     span,
73                     "thiscall is experimental and subject to change"
74                 );
75             }
76             "rust-call" => {
77                 gate_feature_post!(
78                     &self,
79                     unboxed_closures,
80                     span,
81                     "rust-call ABI is subject to change"
82                 );
83             }
84             "ptx-kernel" => {
85                 gate_feature_post!(
86                     &self,
87                     abi_ptx,
88                     span,
89                     "PTX ABIs are experimental and subject to change"
90                 );
91             }
92             "unadjusted" => {
93                 gate_feature_post!(
94                     &self,
95                     abi_unadjusted,
96                     span,
97                     "unadjusted ABI is an implementation detail and perma-unstable"
98                 );
99             }
100             "msp430-interrupt" => {
101                 gate_feature_post!(
102                     &self,
103                     abi_msp430_interrupt,
104                     span,
105                     "msp430-interrupt ABI is experimental and subject to change"
106                 );
107             }
108             "x86-interrupt" => {
109                 gate_feature_post!(
110                     &self,
111                     abi_x86_interrupt,
112                     span,
113                     "x86-interrupt ABI is experimental and subject to change"
114                 );
115             }
116             "amdgpu-kernel" => {
117                 gate_feature_post!(
118                     &self,
119                     abi_amdgpu_kernel,
120                     span,
121                     "amdgpu-kernel ABI is experimental and subject to change"
122                 );
123             }
124             "avr-interrupt" | "avr-non-blocking-interrupt" => {
125                 gate_feature_post!(
126                     &self,
127                     abi_avr_interrupt,
128                     span,
129                     "avr-interrupt and avr-non-blocking-interrupt ABIs are experimental and subject to change"
130                 );
131             }
132             "efiapi" => {
133                 gate_feature_post!(
134                     &self,
135                     abi_efiapi,
136                     span,
137                     "efiapi ABI is experimental and subject to change"
138                 );
139             }
140             abi => self
141                 .parse_sess
142                 .span_diagnostic
143                 .delay_span_bug(span, &format!("unrecognized ABI not caught in lowering: {}", abi)),
144         }
145     }
146
147     fn check_extern(&self, ext: ast::Extern) {
148         if let ast::Extern::Explicit(abi) = ext {
149             self.check_abi(abi);
150         }
151     }
152
153     fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
154         let has_fields = variants.iter().any(|variant| match variant.data {
155             VariantData::Tuple(..) | VariantData::Struct(..) => true,
156             VariantData::Unit(..) => false,
157         });
158
159         let discriminant_spans = variants
160             .iter()
161             .filter(|variant| match variant.data {
162                 VariantData::Tuple(..) | VariantData::Struct(..) => false,
163                 VariantData::Unit(..) => true,
164             })
165             .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
166             .collect::<Vec<_>>();
167
168         if !discriminant_spans.is_empty() && has_fields {
169             let mut err = feature_err(
170                 self.parse_sess,
171                 sym::arbitrary_enum_discriminant,
172                 discriminant_spans.clone(),
173                 "custom discriminant values are not allowed in enums with tuple or struct variants",
174             );
175             for sp in discriminant_spans {
176                 err.span_label(sp, "disallowed custom discriminant");
177             }
178             for variant in variants.iter() {
179                 match &variant.data {
180                     VariantData::Struct(..) => {
181                         err.span_label(variant.span, "struct variant defined here");
182                     }
183                     VariantData::Tuple(..) => {
184                         err.span_label(variant.span, "tuple variant defined here");
185                     }
186                     VariantData::Unit(..) => {}
187                 }
188             }
189             err.emit();
190         }
191     }
192
193     fn check_gat(&self, generics: &ast::Generics, span: Span) {
194         if !generics.params.is_empty() {
195             gate_feature_post!(
196                 &self,
197                 generic_associated_types,
198                 span,
199                 "generic associated types are unstable"
200             );
201         }
202         if !generics.where_clause.predicates.is_empty() {
203             gate_feature_post!(
204                 &self,
205                 generic_associated_types,
206                 span,
207                 "where clauses on associated types are unstable"
208             );
209         }
210     }
211
212     /// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
213     fn check_impl_trait(&self, ty: &ast::Ty) {
214         struct ImplTraitVisitor<'a> {
215             vis: &'a PostExpansionVisitor<'a>,
216         }
217         impl Visitor<'_> for ImplTraitVisitor<'_> {
218             fn visit_ty(&mut self, ty: &ast::Ty) {
219                 if let ast::TyKind::ImplTrait(..) = ty.kind {
220                     gate_feature_post!(
221                         &self.vis,
222                         type_alias_impl_trait,
223                         ty.span,
224                         "`impl Trait` in type aliases is unstable"
225                     );
226                 }
227                 visit::walk_ty(self, ty);
228             }
229         }
230         ImplTraitVisitor { vis: self }.visit_ty(ty);
231     }
232 }
233
234 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
235     fn visit_attribute(&mut self, attr: &ast::Attribute) {
236         let attr_info =
237             attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).map(|a| **a);
238         // Check feature gates for built-in attributes.
239         if let Some((.., AttributeGate::Gated(_, name, descr, has_feature))) = attr_info {
240             gate_feature_fn!(self, has_feature, attr.span, name, descr);
241         }
242         // Check unstable flavors of the `#[doc]` attribute.
243         if attr.check_name(sym::doc) {
244             for nested_meta in attr.meta_item_list().unwrap_or_default() {
245                 macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
246                     $(if nested_meta.check_name(sym::$name) {
247                         let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
248                         gate_feature_post!(self, $feature, attr.span, msg);
249                     })*
250                 }}
251
252                 gate_doc!(
253                     include => external_doc
254                     cfg => doc_cfg
255                     masked => doc_masked
256                     alias => doc_alias
257                     keyword => doc_keyword
258                 );
259             }
260         }
261     }
262
263     fn visit_name(&mut self, sp: Span, name: Symbol) {
264         if !name.as_str().is_ascii() {
265             gate_feature_post!(
266                 &self,
267                 non_ascii_idents,
268                 self.parse_sess.source_map().guess_head_span(sp),
269                 "non-ascii idents are not fully supported"
270             );
271         }
272     }
273
274     fn visit_item(&mut self, i: &'a ast::Item) {
275         match i.kind {
276             ast::ItemKind::ForeignMod(ref foreign_module) => {
277                 if let Some(abi) = foreign_module.abi {
278                     self.check_abi(abi);
279                 }
280             }
281
282             ast::ItemKind::Fn(..) => {
283                 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
284                     gate_feature_post!(
285                         &self,
286                         plugin_registrar,
287                         i.span,
288                         "compiler plugins are experimental and possibly buggy"
289                     );
290                 }
291                 if attr::contains_name(&i.attrs[..], sym::start) {
292                     gate_feature_post!(
293                         &self,
294                         start,
295                         i.span,
296                         "`#[start]` functions are experimental \
297                          and their signature may change \
298                          over time"
299                     );
300                 }
301                 if attr::contains_name(&i.attrs[..], sym::main) {
302                     gate_feature_post!(
303                         &self,
304                         main,
305                         i.span,
306                         "declaration of a non-standard `#[main]` \
307                          function may change over time, for now \
308                          a top-level `fn main()` is required"
309                     );
310                 }
311             }
312
313             ast::ItemKind::Struct(..) => {
314                 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
315                     for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
316                         if item.check_name(sym::simd) {
317                             gate_feature_post!(
318                                 &self,
319                                 repr_simd,
320                                 attr.span,
321                                 "SIMD types are experimental and possibly buggy"
322                             );
323                         }
324                     }
325                 }
326             }
327
328             ast::ItemKind::Enum(ast::EnumDef { ref variants, .. }, ..) => {
329                 for variant in variants {
330                     match (&variant.data, &variant.disr_expr) {
331                         (ast::VariantData::Unit(..), _) => {}
332                         (_, Some(disr_expr)) => gate_feature_post!(
333                             &self,
334                             arbitrary_enum_discriminant,
335                             disr_expr.value.span,
336                             "discriminants on non-unit variants are experimental"
337                         ),
338                         _ => {}
339                     }
340                 }
341
342                 let has_feature = self.features.arbitrary_enum_discriminant;
343                 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
344                     self.maybe_report_invalid_custom_discriminants(&variants);
345                 }
346             }
347
348             ast::ItemKind::Impl { polarity, defaultness, ref of_trait, .. } => {
349                 if let ast::ImplPolarity::Negative(span) = polarity {
350                     gate_feature_post!(
351                         &self,
352                         negative_impls,
353                         span.to(of_trait.as_ref().map(|t| t.path.span).unwrap_or(span)),
354                         "negative trait bounds are not yet fully implemented; \
355                          use marker types for now"
356                     );
357                 }
358
359                 if let ast::Defaultness::Default(_) = defaultness {
360                     gate_feature_post!(&self, specialization, i.span, "specialization is unstable");
361                 }
362             }
363
364             ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
365                 gate_feature_post!(
366                     &self,
367                     optin_builtin_traits,
368                     i.span,
369                     "auto traits are experimental and possibly buggy"
370                 );
371             }
372
373             ast::ItemKind::TraitAlias(..) => {
374                 gate_feature_post!(&self, trait_alias, i.span, "trait aliases are experimental");
375             }
376
377             ast::ItemKind::MacroDef(ast::MacroDef { macro_rules: false, .. }) => {
378                 let msg = "`macro` is experimental";
379                 gate_feature_post!(&self, decl_macro, i.span, msg);
380             }
381
382             ast::ItemKind::TyAlias(_, _, _, Some(ref ty)) => self.check_impl_trait(&ty),
383
384             _ => {}
385         }
386
387         visit::walk_item(self, i);
388     }
389
390     fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
391         match i.kind {
392             ast::ForeignItemKind::Fn(..) | ast::ForeignItemKind::Static(..) => {
393                 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
394                 let links_to_llvm = match link_name {
395                     Some(val) => val.as_str().starts_with("llvm."),
396                     _ => false,
397                 };
398                 if links_to_llvm {
399                     gate_feature_post!(
400                         &self,
401                         link_llvm_intrinsics,
402                         i.span,
403                         "linking to LLVM intrinsics is experimental"
404                     );
405                 }
406             }
407             ast::ForeignItemKind::TyAlias(..) => {
408                 gate_feature_post!(&self, extern_types, i.span, "extern types are experimental");
409             }
410             ast::ForeignItemKind::MacCall(..) => {}
411         }
412
413         visit::walk_foreign_item(self, i)
414     }
415
416     fn visit_ty(&mut self, ty: &'a ast::Ty) {
417         match ty.kind {
418             ast::TyKind::BareFn(ref bare_fn_ty) => {
419                 self.check_extern(bare_fn_ty.ext);
420             }
421             ast::TyKind::Never => {
422                 gate_feature_post!(&self, never_type, ty.span, "the `!` type is experimental");
423             }
424             _ => {}
425         }
426         visit::walk_ty(self, ty)
427     }
428
429     fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FnRetTy) {
430         if let ast::FnRetTy::Ty(ref output_ty) = *ret_ty {
431             if let ast::TyKind::Never = output_ty.kind {
432                 // Do nothing.
433             } else {
434                 self.visit_ty(output_ty)
435             }
436         }
437     }
438
439     fn visit_expr(&mut self, e: &'a ast::Expr) {
440         match e.kind {
441             ast::ExprKind::Box(_) => {
442                 gate_feature_post!(
443                     &self,
444                     box_syntax,
445                     e.span,
446                     "box expression syntax is experimental; you can call `Box::new` instead"
447                 );
448             }
449             ast::ExprKind::Type(..) => {
450                 // To avoid noise about type ascription in common syntax errors, only emit if it
451                 // is the *only* error.
452                 if self.parse_sess.span_diagnostic.err_count() == 0 {
453                     gate_feature_post!(
454                         &self,
455                         type_ascription,
456                         e.span,
457                         "type ascription is experimental"
458                     );
459                 }
460             }
461             ast::ExprKind::TryBlock(_) => {
462                 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
463             }
464             ast::ExprKind::Block(_, opt_label) => {
465                 if let Some(label) = opt_label {
466                     gate_feature_post!(
467                         &self,
468                         label_break_value,
469                         label.ident.span,
470                         "labels on blocks are unstable"
471                     );
472                 }
473             }
474             _ => {}
475         }
476         visit::walk_expr(self, e)
477     }
478
479     fn visit_pat(&mut self, pattern: &'a ast::Pat) {
480         match &pattern.kind {
481             PatKind::Box(..) => {
482                 gate_feature_post!(
483                     &self,
484                     box_patterns,
485                     pattern.span,
486                     "box pattern syntax is experimental"
487                 );
488             }
489             PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
490                 gate_feature_post!(
491                     &self,
492                     exclusive_range_pattern,
493                     pattern.span,
494                     "exclusive range pattern syntax is experimental"
495                 );
496             }
497             _ => {}
498         }
499         visit::walk_pat(self, pattern)
500     }
501
502     fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) {
503         if let Some(header) = fn_kind.header() {
504             // Stability of const fn methods are covered in `visit_assoc_item` below.
505             self.check_extern(header.ext);
506
507             if let (ast::Const::Yes(_), ast::Extern::Implicit)
508             | (ast::Const::Yes(_), ast::Extern::Explicit(_)) = (header.constness, header.ext)
509             {
510                 gate_feature_post!(
511                     &self,
512                     const_extern_fn,
513                     span,
514                     "`const extern fn` definitions are unstable"
515                 );
516             }
517         }
518
519         if fn_kind.ctxt() != Some(FnCtxt::Foreign) && fn_kind.decl().c_variadic() {
520             gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
521         }
522
523         visit::walk_fn(self, fn_kind, span)
524     }
525
526     fn visit_generic_param(&mut self, param: &'a GenericParam) {
527         if let GenericParamKind::Const { .. } = param.kind {
528             gate_feature_post!(
529                 &self,
530                 const_generics,
531                 param.ident.span,
532                 "const generics are unstable"
533             )
534         }
535         visit::walk_generic_param(self, param)
536     }
537
538     fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
539         if let AssocTyConstraintKind::Bound { .. } = constraint.kind {
540             gate_feature_post!(
541                 &self,
542                 associated_type_bounds,
543                 constraint.span,
544                 "associated type bounds are unstable"
545             )
546         }
547         visit::walk_assoc_ty_constraint(self, constraint)
548     }
549
550     fn visit_assoc_item(&mut self, i: &'a ast::AssocItem, ctxt: AssocCtxt) {
551         let is_fn = match i.kind {
552             ast::AssocItemKind::Fn(_, ref sig, _, _) => {
553                 if let (ast::Const::Yes(_), AssocCtxt::Trait) = (sig.header.constness, ctxt) {
554                     gate_feature_post!(&self, const_fn, i.span, "const fn is unstable");
555                 }
556                 true
557             }
558             ast::AssocItemKind::TyAlias(_, ref generics, _, ref ty) => {
559                 if let (Some(_), AssocCtxt::Trait) = (ty, ctxt) {
560                     gate_feature_post!(
561                         &self,
562                         associated_type_defaults,
563                         i.span,
564                         "associated type defaults are unstable"
565                     );
566                 }
567                 if let Some(ty) = ty {
568                     self.check_impl_trait(ty);
569                 }
570                 self.check_gat(generics, i.span);
571                 false
572             }
573             _ => false,
574         };
575         if let ast::Defaultness::Default(_) = i.kind.defaultness() {
576             // Limit `min_specialization` to only specializing functions.
577             gate_feature_fn!(
578                 &self,
579                 |x: &Features| x.specialization || (is_fn && x.min_specialization),
580                 i.span,
581                 sym::specialization,
582                 "specialization is unstable"
583             );
584         }
585         visit::walk_assoc_item(self, i, ctxt)
586     }
587
588     fn visit_vis(&mut self, vis: &'a ast::Visibility) {
589         if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
590             gate_feature_post!(
591                 &self,
592                 crate_visibility_modifier,
593                 vis.span,
594                 "`crate` visibility modifier is experimental"
595             );
596         }
597         visit::walk_vis(self, vis)
598     }
599 }
600
601 pub fn check_crate(
602     krate: &ast::Crate,
603     parse_sess: &ParseSess,
604     features: &Features,
605     unstable: UnstableFeatures,
606 ) {
607     maybe_stage_features(&parse_sess.span_diagnostic, krate, unstable);
608     let mut visitor = PostExpansionVisitor { parse_sess, features };
609
610     let spans = parse_sess.gated_spans.spans.borrow();
611     macro_rules! gate_all {
612         ($gate:ident, $msg:literal) => {
613             for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
614                 gate_feature_post!(&visitor, $gate, *span, $msg);
615             }
616         };
617     }
618     gate_all!(let_chains, "`let` expressions in this position are experimental");
619     gate_all!(async_closure, "async closures are unstable");
620     gate_all!(generators, "yield syntax is experimental");
621     gate_all!(or_patterns, "or-patterns syntax is experimental");
622     gate_all!(raw_ref_op, "raw address of syntax is experimental");
623     gate_all!(const_trait_bound_opt_out, "`?const` on trait bounds is experimental");
624     gate_all!(const_trait_impl, "const trait impls are experimental");
625     gate_all!(half_open_range_patterns, "half-open range patterns are unstable");
626
627     // All uses of `gate_all!` below this point were added in #65742,
628     // and subsequently disabled (with the non-early gating readded).
629     macro_rules! gate_all {
630         ($gate:ident, $msg:literal) => {
631             // FIXME(eddyb) do something more useful than always
632             // disabling these uses of early feature-gatings.
633             if false {
634                 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
635                     gate_feature_post!(&visitor, $gate, *span, $msg);
636                 }
637             }
638         };
639     }
640
641     gate_all!(trait_alias, "trait aliases are experimental");
642     gate_all!(associated_type_bounds, "associated type bounds are unstable");
643     gate_all!(crate_visibility_modifier, "`crate` visibility modifier is experimental");
644     gate_all!(const_generics, "const generics are unstable");
645     gate_all!(decl_macro, "`macro` is experimental");
646     gate_all!(box_patterns, "box pattern syntax is experimental");
647     gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
648     gate_all!(try_blocks, "`try` blocks are unstable");
649     gate_all!(label_break_value, "labels on blocks are unstable");
650     gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
651     // To avoid noise about type ascription in common syntax errors,
652     // only emit if it is the *only* error. (Also check it last.)
653     if parse_sess.span_diagnostic.err_count() == 0 {
654         gate_all!(type_ascription, "type ascription is experimental");
655     }
656
657     visit::walk_crate(&mut visitor, krate);
658 }
659
660 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate, unstable: UnstableFeatures) {
661     if !unstable.is_nightly_build() {
662         for attr in krate.attrs.iter().filter(|attr| attr.check_name(sym::feature)) {
663             struct_span_err!(
664                 span_handler,
665                 attr.span,
666                 E0554,
667                 "`#![feature]` may not be used on the {} release channel",
668                 option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")
669             )
670             .emit();
671         }
672     }
673 }