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