]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/feature_gate.rs
complete openbsd support for `std::env`
[rust.git] / src / libsyntax / feature_gate.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Feature gating
12 //!
13 //! This modules implements the gating necessary for preventing certain compiler
14 //! features from being used by default. This module will crawl a pre-expanded
15 //! AST to ensure that there are no features which are used that are not
16 //! enabled.
17 //!
18 //! Features are enabled in programs via the crate-level attributes of
19 //! `#![feature(...)]` with a comma-separated list of features.
20 //!
21 //! For the purpose of future feature-tracking, once code for detection of feature
22 //! gate usage is added, *do not remove it again* even once the feature
23 //! becomes stable.
24 use self::Status::*;
25
26 use abi::RustIntrinsic;
27 use ast::NodeId;
28 use ast;
29 use attr;
30 use attr::AttrMetaMethods;
31 use codemap::{CodeMap, Span};
32 use diagnostic::SpanHandler;
33 use visit;
34 use visit::Visitor;
35 use parse::token::{self, InternedString};
36
37 use std::slice;
38 use std::ascii::AsciiExt;
39
40 // If you change this list without updating src/doc/reference.md, @cmr will be sad
41 // Don't ever remove anything from this list; set them to 'Removed'.
42 // The version numbers here correspond to the version in which the current status
43 // was set. This is most important for knowing when a particular feature became
44 // stable (active).
45 // NB: The featureck.py script parses this information directly out of the source
46 // so take care when modifying it.
47 static KNOWN_FEATURES: &'static [(&'static str, &'static str, Status)] = &[
48     ("globs", "1.0.0", Accepted),
49     ("macro_rules", "1.0.0", Accepted),
50     ("struct_variant", "1.0.0", Accepted),
51     ("asm", "1.0.0", Active),
52     ("managed_boxes", "1.0.0", Removed),
53     ("non_ascii_idents", "1.0.0", Active),
54     ("thread_local", "1.0.0", Active),
55     ("link_args", "1.0.0", Active),
56     ("phase", "1.0.0", Removed),
57     ("plugin_registrar", "1.0.0", Active),
58     ("log_syntax", "1.0.0", Active),
59     ("trace_macros", "1.0.0", Active),
60     ("concat_idents", "1.0.0", Active),
61     ("unsafe_destructor", "1.0.0", Active),
62     ("intrinsics", "1.0.0", Active),
63     ("lang_items", "1.0.0", Active),
64
65     ("simd", "1.0.0", Active),
66     ("default_type_params", "1.0.0", Accepted),
67     ("quote", "1.0.0", Active),
68     ("link_llvm_intrinsics", "1.0.0", Active),
69     ("linkage", "1.0.0", Active),
70     ("struct_inherit", "1.0.0", Removed),
71
72     ("quad_precision_float", "1.0.0", Removed),
73
74     ("rustc_diagnostic_macros", "1.0.0", Active),
75     ("unboxed_closures", "1.0.0", Active),
76     ("import_shadowing", "1.0.0", Removed),
77     ("advanced_slice_patterns", "1.0.0", Active),
78     ("tuple_indexing", "1.0.0", Accepted),
79     ("associated_types", "1.0.0", Accepted),
80     ("visible_private_types", "1.0.0", Active),
81     ("slicing_syntax", "1.0.0", Active),
82     ("box_syntax", "1.0.0", Active),
83     ("on_unimplemented", "1.0.0", Active),
84     ("simd_ffi", "1.0.0", Active),
85
86     ("if_let", "1.0.0", Accepted),
87     ("while_let", "1.0.0", Accepted),
88
89     ("plugin", "1.0.0", Active),
90     ("start", "1.0.0", Active),
91     ("main", "1.0.0", Active),
92
93     // A temporary feature gate used to enable parser extensions needed
94     // to bootstrap fix for #5723.
95     ("issue_5723_bootstrap", "1.0.0", Accepted),
96
97     // A way to temporarily opt out of opt in copy. This will *never* be accepted.
98     ("opt_out_copy", "1.0.0", Removed),
99
100     // A way to temporarily opt out of the new orphan rules. This will *never* be accepted.
101     ("old_orphan_check", "1.0.0", Deprecated),
102
103     // A way to temporarily opt out of the new impl rules. This will *never* be accepted.
104     ("old_impl_check", "1.0.0", Deprecated),
105
106     // OIBIT specific features
107     ("optin_builtin_traits", "1.0.0", Active),
108
109     // int and uint are now deprecated
110     ("int_uint", "1.0.0", Active),
111
112     // macro reexport needs more discusion and stabilization
113     ("macro_reexport", "1.0.0", Active),
114
115     // These are used to test this portion of the compiler, they don't actually
116     // mean anything
117     ("test_accepted_feature", "1.0.0", Accepted),
118     ("test_removed_feature", "1.0.0", Removed),
119
120     // Allows use of #[staged_api]
121     ("staged_api", "1.0.0", Active),
122
123     // Allows using items which are missing stability attributes
124     ("unmarked_api", "1.0.0", Active)
125 ];
126
127 enum Status {
128     /// Represents an active feature that is currently being implemented or
129     /// currently being considered for addition/removal.
130     Active,
131
132     /// Represents a feature gate that is temporarily enabling deprecated behavior.
133     /// This gate will never be accepted.
134     Deprecated,
135
136     /// Represents a feature which has since been removed (it was once Active)
137     Removed,
138
139     /// This language feature has since been Accepted (it was once Active)
140     Accepted,
141 }
142
143 /// A set of features to be used by later passes.
144 pub struct Features {
145     pub unboxed_closures: bool,
146     pub rustc_diagnostic_macros: bool,
147     pub visible_private_types: bool,
148     pub quote: bool,
149     pub old_orphan_check: bool,
150     pub simd_ffi: bool,
151     pub unmarked_api: bool,
152     pub lib_features: Vec<(InternedString, Span)>
153 }
154
155 impl Features {
156     pub fn new() -> Features {
157         Features {
158             unboxed_closures: false,
159             rustc_diagnostic_macros: false,
160             visible_private_types: false,
161             quote: false,
162             old_orphan_check: false,
163             simd_ffi: false,
164             unmarked_api: false,
165             lib_features: Vec::new()
166         }
167     }
168 }
169
170 struct Context<'a> {
171     features: Vec<&'static str>,
172     span_handler: &'a SpanHandler,
173     cm: &'a CodeMap,
174 }
175
176 impl<'a> Context<'a> {
177     fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
178         if !self.has_feature(feature) {
179             emit_feature_err(self.span_handler, feature, span, explain);
180         }
181     }
182
183     fn warn_feature(&self, feature: &str, span: Span, explain: &str) {
184         if !self.has_feature(feature) {
185             emit_feature_warn(self.span_handler, feature, span, explain);
186         }
187     }
188     fn has_feature(&self, feature: &str) -> bool {
189         self.features.iter().any(|&n| n == feature)
190     }
191 }
192
193 pub fn emit_feature_err(diag: &SpanHandler, feature: &str, span: Span, explain: &str) {
194     diag.span_err(span, explain);
195     diag.span_help(span, &format!("add #![feature({})] to the \
196                                    crate attributes to enable",
197                                   feature)[]);
198 }
199
200 pub fn emit_feature_warn(diag: &SpanHandler, feature: &str, span: Span, explain: &str) {
201     diag.span_warn(span, explain);
202     if diag.handler.can_emit_warnings {
203         diag.span_help(span, &format!("add #![feature({})] to the \
204                                        crate attributes to silence this warning",
205                                       feature)[]);
206     }
207 }
208
209 struct MacroVisitor<'a> {
210     context: &'a Context<'a>
211 }
212
213 impl<'a, 'v> Visitor<'v> for MacroVisitor<'a> {
214     fn visit_mac(&mut self, mac: &ast::Mac) {
215         let ast::MacInvocTT(ref path, _, _) = mac.node;
216         let id = path.segments.last().unwrap().identifier;
217
218         if id == token::str_to_ident("asm") {
219             self.context.gate_feature("asm", path.span, "inline assembly is not \
220                 stable enough for use and is subject to change");
221         }
222
223         else if id == token::str_to_ident("log_syntax") {
224             self.context.gate_feature("log_syntax", path.span, "`log_syntax!` is not \
225                 stable enough for use and is subject to change");
226         }
227
228         else if id == token::str_to_ident("trace_macros") {
229             self.context.gate_feature("trace_macros", path.span, "`trace_macros` is not \
230                 stable enough for use and is subject to change");
231         }
232
233         else if id == token::str_to_ident("concat_idents") {
234             self.context.gate_feature("concat_idents", path.span, "`concat_idents` is not \
235                 stable enough for use and is subject to change");
236         }
237     }
238 }
239
240 struct PostExpansionVisitor<'a> {
241     context: &'a Context<'a>
242 }
243
244 impl<'a> PostExpansionVisitor<'a> {
245     fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
246         if !self.context.cm.span_is_internal(span) {
247             self.context.gate_feature(feature, span, explain)
248         }
249     }
250 }
251
252 impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
253     fn visit_name(&mut self, sp: Span, name: ast::Name) {
254         if !token::get_name(name).get().is_ascii() {
255             self.gate_feature("non_ascii_idents", sp,
256                               "non-ascii idents are not fully supported.");
257         }
258     }
259
260     fn visit_item(&mut self, i: &ast::Item) {
261         for attr in &i.attrs {
262             if attr.name() == "thread_local" {
263                 self.gate_feature("thread_local", i.span,
264                                   "`#[thread_local]` is an experimental feature, and does not \
265                                   currently handle destructors. There is no corresponding \
266                                   `#[task_local]` mapping to the task model");
267             } else if attr.name() == "linkage" {
268                 self.gate_feature("linkage", i.span,
269                                   "the `linkage` attribute is experimental \
270                                    and not portable across platforms")
271             } else if attr.name() == "rustc_on_unimplemented" {
272                 self.gate_feature("on_unimplemented", i.span,
273                                   "the `#[rustc_on_unimplemented]` attribute \
274                                   is an experimental feature")
275             }
276         }
277         match i.node {
278             ast::ItemExternCrate(_) => {
279                 if attr::contains_name(&i.attrs[], "plugin") {
280                     self.gate_feature("plugin", i.span,
281                                       "compiler plugins are experimental \
282                                        and possibly buggy");
283                 } else if attr::contains_name(&i.attrs[], "macro_reexport") {
284                     self.gate_feature("macro_reexport", i.span,
285                                       "macros reexports are experimental \
286                                        and possibly buggy");
287                 }
288             }
289
290             ast::ItemForeignMod(ref foreign_module) => {
291                 if attr::contains_name(&i.attrs[], "link_args") {
292                     self.gate_feature("link_args", i.span,
293                                       "the `link_args` attribute is not portable \
294                                        across platforms, it is recommended to \
295                                        use `#[link(name = \"foo\")]` instead")
296                 }
297                 if foreign_module.abi == RustIntrinsic {
298                     self.gate_feature("intrinsics",
299                                       i.span,
300                                       "intrinsics are subject to change")
301                 }
302             }
303
304             ast::ItemFn(..) => {
305                 if attr::contains_name(&i.attrs[], "plugin_registrar") {
306                     self.gate_feature("plugin_registrar", i.span,
307                                       "compiler plugins are experimental and possibly buggy");
308                 }
309                 if attr::contains_name(&i.attrs[], "start") {
310                     self.gate_feature("start", i.span,
311                                       "a #[start] function is an experimental \
312                                        feature whose signature may change \
313                                        over time");
314                 }
315                 if attr::contains_name(&i.attrs[], "main") {
316                     self.gate_feature("main", i.span,
317                                       "declaration of a nonstandard #[main] \
318                                        function may change over time, for now \
319                                        a top-level `fn main()` is required");
320                 }
321             }
322
323             ast::ItemStruct(..) => {
324                 if attr::contains_name(&i.attrs[], "simd") {
325                     self.gate_feature("simd", i.span,
326                                       "SIMD types are experimental and possibly buggy");
327                 }
328             }
329
330             ast::ItemImpl(_, polarity, _, _, _, _) => {
331                 match polarity {
332                     ast::ImplPolarity::Negative => {
333                         self.gate_feature("optin_builtin_traits",
334                                           i.span,
335                                           "negative trait bounds are not yet fully implemented; \
336                                           use marker types for now");
337                     },
338                     _ => {}
339                 }
340
341                 if attr::contains_name(i.attrs.as_slice(),
342                                        "unsafe_destructor") {
343                     self.gate_feature("unsafe_destructor",
344                                       i.span,
345                                       "`#[unsafe_destructor]` allows too \
346                                        many unsafe patterns and may be \
347                                        removed in the future");
348                 }
349
350                 if attr::contains_name(&i.attrs[],
351                                        "old_orphan_check") {
352                     self.gate_feature(
353                         "old_orphan_check",
354                         i.span,
355                         "the new orphan check rules will eventually be strictly enforced");
356                 }
357
358                 if attr::contains_name(&i.attrs[],
359                                        "old_impl_check") {
360                     self.gate_feature("old_impl_check",
361                                       i.span,
362                                       "`#[old_impl_check]` will be removed in the future");
363                 }
364             }
365
366             _ => {}
367         }
368
369         visit::walk_item(self, i);
370     }
371
372     fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
373         if attr::contains_name(&i.attrs[], "linkage") {
374             self.gate_feature("linkage", i.span,
375                               "the `linkage` attribute is experimental \
376                                and not portable across platforms")
377         }
378
379         let links_to_llvm = match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
380                                                                      "link_name") {
381             Some(val) => val.get().starts_with("llvm."),
382             _ => false
383         };
384         if links_to_llvm {
385             self.gate_feature("link_llvm_intrinsics", i.span,
386                               "linking to LLVM intrinsics is experimental");
387         }
388
389         visit::walk_foreign_item(self, i)
390     }
391
392     fn visit_ty(&mut self, t: &ast::Ty) {
393         match t.node {
394             ast::TyPath(ref p, _) => {
395                 match &*p.segments {
396
397                     [ast::PathSegment { identifier, .. }] => {
398                         let name = token::get_ident(identifier);
399                         let msg = if name == "int" {
400                             Some("the `int` type is deprecated; \
401                                   use `isize` or a fixed-sized integer")
402                         } else if name == "uint" {
403                             Some("the `uint` type is deprecated; \
404                                   use `usize` or a fixed-sized integer")
405                         } else {
406                             None
407                         };
408
409                         if let Some(msg) = msg {
410                             self.context.warn_feature("int_uint", t.span, msg)
411                         }
412                     }
413                     _ => {}
414                 }
415             }
416             _ => {}
417         }
418         visit::walk_ty(self, t);
419     }
420
421     fn visit_expr(&mut self, e: &ast::Expr) {
422         match e.node {
423             ast::ExprBox(..) | ast::ExprUnary(ast::UnOp::UnUniq, _) => {
424                 self.gate_feature("box_syntax",
425                                   e.span,
426                                   "box expression syntax is experimental in alpha release; \
427                                    you can call `Box::new` instead.");
428             }
429             ast::ExprLit(ref lit) => {
430                 match lit.node {
431                     ast::LitInt(_, ty) => {
432                         let msg = if let ast::SignedIntLit(ast::TyIs(true), _) = ty {
433                             Some("the `i` suffix on integers is deprecated; use `is` \
434                                   or one of the fixed-sized suffixes")
435                         } else if let ast::UnsignedIntLit(ast::TyUs(true)) = ty {
436                             Some("the `u` suffix on integers is deprecated; use `us` \
437                                  or one of the fixed-sized suffixes")
438                         } else {
439                             None
440                         };
441                         if let Some(msg) = msg {
442                             self.context.warn_feature("int_uint", e.span, msg);
443                         }
444                     }
445                     _ => {}
446                 }
447             }
448             _ => {}
449         }
450         visit::walk_expr(self, e);
451     }
452
453     fn visit_attribute(&mut self, attr: &ast::Attribute) {
454         if attr.check_name("staged_api") {
455             self.gate_feature("staged_api", attr.span,
456                               "staged_api is for use by rustc only");
457         }
458
459         if attr::contains_name(slice::ref_slice(attr), "lang") {
460             self.gate_feature("lang_items",
461                               attr.span,
462                               "language items are subject to change");
463         }
464     }
465
466     fn visit_pat(&mut self, pattern: &ast::Pat) {
467         match pattern.node {
468             ast::PatVec(_, Some(_), ref last) if !last.is_empty() => {
469                 self.gate_feature("advanced_slice_patterns",
470                                   pattern.span,
471                                   "multiple-element slice matches anywhere \
472                                    but at the end of a slice (e.g. \
473                                    `[0, ..xs, 0]` are experimental")
474             }
475             ast::PatBox(..) => {
476                 self.gate_feature("box_syntax",
477                                   pattern.span,
478                                   "box pattern syntax is experimental in alpha release");
479             }
480             _ => {}
481         }
482         visit::walk_pat(self, pattern)
483     }
484
485     fn visit_fn(&mut self,
486                 fn_kind: visit::FnKind<'v>,
487                 fn_decl: &'v ast::FnDecl,
488                 block: &'v ast::Block,
489                 span: Span,
490                 _node_id: NodeId) {
491         match fn_kind {
492             visit::FkItemFn(_, _, _, abi) if abi == RustIntrinsic => {
493                 self.gate_feature("intrinsics",
494                                   span,
495                                   "intrinsics are subject to change")
496             }
497             _ => {}
498         }
499         visit::walk_fn(self, fn_kind, fn_decl, block, span);
500     }
501 }
502
503 fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate,
504                         check: F)
505                        -> Features
506     where F: FnOnce(&mut Context, &ast::Crate)
507 {
508     let mut cx = Context {
509         features: Vec::new(),
510         span_handler: span_handler,
511         cm: cm,
512     };
513
514     let mut unknown_features = Vec::new();
515
516     for attr in &krate.attrs {
517         if !attr.check_name("feature") {
518             continue
519         }
520
521         match attr.meta_item_list() {
522             None => {
523                 span_handler.span_err(attr.span, "malformed feature attribute, \
524                                                   expected #![feature(...)]");
525             }
526             Some(list) => {
527                 for mi in list {
528                     let name = match mi.node {
529                         ast::MetaWord(ref word) => (*word).clone(),
530                         _ => {
531                             span_handler.span_err(mi.span,
532                                                   "malformed feature, expected just \
533                                                    one word");
534                             continue
535                         }
536                     };
537                     match KNOWN_FEATURES.iter()
538                                         .find(|& &(n, _, _)| name == n) {
539                         Some(&(name, _, Active)) => {
540                             cx.features.push(name);
541                         }
542                         Some(&(name, _, Deprecated)) => {
543                             cx.features.push(name);
544                             span_handler.span_warn(
545                                 mi.span,
546                                 "feature is deprecated and will only be available \
547                                  for a limited time, please rewrite code that relies on it");
548                         }
549                         Some(&(_, _, Removed)) => {
550                             span_handler.span_err(mi.span, "feature has been removed");
551                         }
552                         Some(&(_, _, Accepted)) => {
553                             span_handler.span_warn(mi.span, "feature has been added to Rust, \
554                                                              directive not necessary");
555                         }
556                         None => {
557                             unknown_features.push((name, mi.span));
558                         }
559                     }
560                 }
561             }
562         }
563     }
564
565     check(&mut cx, krate);
566
567     Features {
568         unboxed_closures: cx.has_feature("unboxed_closures"),
569         rustc_diagnostic_macros: cx.has_feature("rustc_diagnostic_macros"),
570         visible_private_types: cx.has_feature("visible_private_types"),
571         quote: cx.has_feature("quote"),
572         old_orphan_check: cx.has_feature("old_orphan_check"),
573         simd_ffi: cx.has_feature("simd_ffi"),
574         unmarked_api: cx.has_feature("unmarked_api"),
575         lib_features: unknown_features
576     }
577 }
578
579 pub fn check_crate_macros(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
580 -> Features {
581     check_crate_inner(cm, span_handler, krate,
582                       |ctx, krate| visit::walk_crate(&mut MacroVisitor { context: ctx }, krate))
583 }
584
585 pub fn check_crate(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
586 -> Features {
587     check_crate_inner(cm, span_handler, krate,
588                       |ctx, krate| visit::walk_crate(&mut PostExpansionVisitor { context: ctx },
589                                                      krate))
590 }
591