]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/feature_gate.rs
Remove morestack support
[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 module 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
25 use self::Status::*;
26 use self::AttributeType::*;
27
28 use abi::Abi;
29 use ast::NodeId;
30 use ast;
31 use attr;
32 use attr::AttrMetaMethods;
33 use codemap::{CodeMap, Span};
34 use diagnostic::SpanHandler;
35 use visit;
36 use visit::Visitor;
37 use parse::token::{self, InternedString};
38
39 use std::ascii::AsciiExt;
40
41 // If you change this list without updating src/doc/reference.md, @cmr will be sad
42 // Don't ever remove anything from this list; set them to 'Removed'.
43 // The version numbers here correspond to the version in which the current status
44 // was set. This is most important for knowing when a particular feature became
45 // stable (active).
46 // NB: The featureck.py script parses this information directly out of the source
47 // so take care when modifying it.
48 const KNOWN_FEATURES: &'static [(&'static str, &'static str, Status)] = &[
49     ("globs", "1.0.0", Accepted),
50     ("macro_rules", "1.0.0", Accepted),
51     ("struct_variant", "1.0.0", Accepted),
52     ("asm", "1.0.0", Active),
53     ("managed_boxes", "1.0.0", Removed),
54     ("non_ascii_idents", "1.0.0", Active),
55     ("thread_local", "1.0.0", Active),
56     ("link_args", "1.0.0", Active),
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     ("intrinsics", "1.0.0", Active),
62     ("lang_items", "1.0.0", Active),
63
64     ("simd", "1.0.0", Active),
65     ("default_type_params", "1.0.0", Accepted),
66     ("quote", "1.0.0", Active),
67     ("link_llvm_intrinsics", "1.0.0", Active),
68     ("linkage", "1.0.0", Active),
69     ("struct_inherit", "1.0.0", Removed),
70
71     ("quad_precision_float", "1.0.0", Removed),
72
73     ("rustc_diagnostic_macros", "1.0.0", Active),
74     ("unboxed_closures", "1.0.0", Active),
75     ("reflect", "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", Accepted),
82     ("box_syntax", "1.0.0", Active),
83     ("placement_in_syntax", "1.0.0", Active),
84     ("pushpop_unsafe", "1.2.0", Active),
85     ("on_unimplemented", "1.0.0", Active),
86     ("simd_ffi", "1.0.0", Active),
87     ("allocator", "1.0.0", Active),
88
89     ("if_let", "1.0.0", Accepted),
90     ("while_let", "1.0.0", Accepted),
91
92     ("plugin", "1.0.0", Active),
93     ("start", "1.0.0", Active),
94     ("main", "1.0.0", Active),
95
96     ("fundamental", "1.0.0", Active),
97
98     // A temporary feature gate used to enable parser extensions needed
99     // to bootstrap fix for #5723.
100     ("issue_5723_bootstrap", "1.0.0", Accepted),
101
102     // A way to temporarily opt out of opt in copy. This will *never* be accepted.
103     ("opt_out_copy", "1.0.0", Removed),
104
105     // OIBIT specific features
106     ("optin_builtin_traits", "1.0.0", Active),
107
108     // macro reexport needs more discussion and stabilization
109     ("macro_reexport", "1.0.0", Active),
110
111     // These are used to test this portion of the compiler, they don't actually
112     // mean anything
113     ("test_accepted_feature", "1.0.0", Accepted),
114     ("test_removed_feature", "1.0.0", Removed),
115
116     // Allows use of #[staged_api]
117     ("staged_api", "1.0.0", Active),
118
119     // Allows using items which are missing stability attributes
120     ("unmarked_api", "1.0.0", Active),
121
122     // Allows using #![no_std]
123     ("no_std", "1.0.0", Active),
124
125     // Allows using #![no_core]
126     ("no_core", "1.3.0", Active),
127
128     // Allows using `box` in patterns; RFC 469
129     ("box_patterns", "1.0.0", Active),
130
131     // Allows using the unsafe_no_drop_flag attribute (unlikely to
132     // switch to Accepted; see RFC 320)
133     ("unsafe_no_drop_flag", "1.0.0", Active),
134
135     // Allows the use of custom attributes; RFC 572
136     ("custom_attribute", "1.0.0", Active),
137
138     // Allows the use of #[derive(Anything)] as sugar for
139     // #[derive_Anything].
140     ("custom_derive", "1.0.0", Active),
141
142     // Allows the use of rustc_* attributes; RFC 572
143     ("rustc_attrs", "1.0.0", Active),
144
145     // Allows the use of #[allow_internal_unstable]. This is an
146     // attribute on macro_rules! and can't use the attribute handling
147     // below (it has to be checked before expansion possibly makes
148     // macros disappear).
149     ("allow_internal_unstable", "1.0.0", Active),
150
151     // #23121. Array patterns have some hazards yet.
152     ("slice_patterns", "1.0.0", Active),
153
154     // Allows use of unary negate on unsigned integers, e.g. -e for e: u8
155     ("negate_unsigned", "1.0.0", Active),
156
157     // Allows the definition of associated constants in `trait` or `impl`
158     // blocks.
159     ("associated_consts", "1.0.0", Active),
160
161     // Allows the definition of `const fn` functions.
162     ("const_fn", "1.2.0", Active),
163
164     // Allows using #[prelude_import] on glob `use` items.
165     ("prelude_import", "1.2.0", Active),
166
167     // Allows the definition recursive static items.
168     ("static_recursion", "1.3.0", Active),
169
170     // Allows default type parameters to influence type inference.
171     ("default_type_parameter_fallback", "1.3.0", Active),
172
173     // Allows associated type defaults
174     ("associated_type_defaults", "1.2.0", Active),
175 ];
176 // (changing above list without updating src/doc/reference.md makes @cmr sad)
177
178 enum Status {
179     /// Represents an active feature that is currently being implemented or
180     /// currently being considered for addition/removal.
181     Active,
182
183     /// Represents a feature which has since been removed (it was once Active)
184     Removed,
185
186     /// This language feature has since been Accepted (it was once Active)
187     Accepted,
188 }
189
190 // Attributes that have a special meaning to rustc or rustdoc
191 pub const KNOWN_ATTRIBUTES: &'static [(&'static str, AttributeType)] = &[
192     // Normal attributes
193
194     ("warn", Normal),
195     ("allow", Normal),
196     ("forbid", Normal),
197     ("deny", Normal),
198
199     ("macro_reexport", Normal),
200     ("macro_use", Normal),
201     ("macro_export", Normal),
202     ("plugin_registrar", Normal),
203
204     ("cfg", Normal),
205     ("cfg_attr", Normal),
206     ("main", Normal),
207     ("start", Normal),
208     ("test", Normal),
209     ("bench", Normal),
210     ("simd", Normal),
211     ("repr", Normal),
212     ("path", Normal),
213     ("abi", Normal),
214     ("automatically_derived", Normal),
215     ("no_mangle", Normal),
216     ("no_link", Normal),
217     ("derive", Normal),
218     ("should_panic", Normal),
219     ("ignore", Normal),
220     ("no_implicit_prelude", Normal),
221     ("reexport_test_harness_main", Normal),
222     ("link_args", Normal),
223     ("macro_escape", Normal),
224
225     // Not used any more, but we can't feature gate it
226     ("no_stack_check", Normal),
227
228     ("staged_api", Gated("staged_api",
229                          "staged_api is for use by rustc only")),
230     ("plugin", Gated("plugin",
231                      "compiler plugins are experimental \
232                       and possibly buggy")),
233     ("no_std", Gated("no_std",
234                      "no_std is experimental")),
235     ("no_core", Gated("no_core",
236                      "no_core is experimental")),
237     ("lang", Gated("lang_items",
238                      "language items are subject to change")),
239     ("linkage", Gated("linkage",
240                       "the `linkage` attribute is experimental \
241                        and not portable across platforms")),
242     ("thread_local", Gated("thread_local",
243                             "`#[thread_local]` is an experimental feature, and does not \
244                              currently handle destructors. There is no corresponding \
245                              `#[task_local]` mapping to the task model")),
246
247     ("rustc_on_unimplemented", Gated("on_unimplemented",
248                                      "the `#[rustc_on_unimplemented]` attribute \
249                                       is an experimental feature")),
250     ("allocator", Gated("allocator",
251                         "the `#[allocator]` attribute is an experimental feature")),
252     ("rustc_variance", Gated("rustc_attrs",
253                              "the `#[rustc_variance]` attribute \
254                               is an experimental feature")),
255     ("rustc_error", Gated("rustc_attrs",
256                           "the `#[rustc_error]` attribute \
257                            is an experimental feature")),
258     ("rustc_move_fragments", Gated("rustc_attrs",
259                                    "the `#[rustc_move_fragments]` attribute \
260                                     is an experimental feature")),
261
262     ("allow_internal_unstable", Gated("allow_internal_unstable",
263                                       EXPLAIN_ALLOW_INTERNAL_UNSTABLE)),
264
265     ("fundamental", Gated("fundamental",
266                           "the `#[fundamental]` attribute \
267                            is an experimental feature")),
268
269     // FIXME: #14408 whitelist docs since rustdoc looks at them
270     ("doc", Whitelisted),
271
272     // FIXME: #14406 these are processed in trans, which happens after the
273     // lint pass
274     ("cold", Whitelisted),
275     ("export_name", Whitelisted),
276     ("inline", Whitelisted),
277     ("link", Whitelisted),
278     ("link_name", Whitelisted),
279     ("link_section", Whitelisted),
280     ("no_builtins", Whitelisted),
281     ("no_mangle", Whitelisted),
282     ("no_debug", Whitelisted),
283     ("omit_gdb_pretty_printer_section", Whitelisted),
284     ("unsafe_no_drop_flag", Gated("unsafe_no_drop_flag",
285                                   "unsafe_no_drop_flag has unstable semantics \
286                                    and may be removed in the future")),
287
288     // used in resolve
289     ("prelude_import", Gated("prelude_import",
290                              "`#[prelude_import]` is for use by rustc only")),
291
292     // FIXME: #14407 these are only looked at on-demand so we can't
293     // guarantee they'll have already been checked
294     ("deprecated", Whitelisted),
295     ("must_use", Whitelisted),
296     ("stable", Whitelisted),
297     ("unstable", Whitelisted),
298
299     ("rustc_paren_sugar", Gated("unboxed_closures",
300                                 "unboxed_closures are still evolving")),
301     ("rustc_reflect_like", Gated("reflect",
302                                  "defining reflective traits is still evolving")),
303
304     // Crate level attributes
305     ("crate_name", CrateLevel),
306     ("crate_type", CrateLevel),
307     ("crate_id", CrateLevel),
308     ("feature", CrateLevel),
309     ("no_start", CrateLevel),
310     ("no_main", CrateLevel),
311     ("no_builtins", CrateLevel),
312     ("recursion_limit", CrateLevel),
313 ];
314
315 #[derive(PartialEq, Copy, Clone, Debug)]
316 pub enum AttributeType {
317     /// Normal, builtin attribute that is consumed
318     /// by the compiler before the unused_attribute check
319     Normal,
320
321     /// Builtin attribute that may not be consumed by the compiler
322     /// before the unused_attribute check. These attributes
323     /// will be ignored by the unused_attribute lint
324     Whitelisted,
325
326     /// Is gated by a given feature gate and reason
327     /// These get whitelisted too
328     Gated(&'static str, &'static str),
329
330     /// Builtin attribute that is only allowed at the crate level
331     CrateLevel,
332 }
333
334 /// A set of features to be used by later passes.
335 pub struct Features {
336     pub unboxed_closures: bool,
337     pub rustc_diagnostic_macros: bool,
338     pub visible_private_types: bool,
339     pub allow_quote: bool,
340     pub allow_asm: bool,
341     pub allow_log_syntax: bool,
342     pub allow_concat_idents: bool,
343     pub allow_trace_macros: bool,
344     pub allow_internal_unstable: bool,
345     pub allow_custom_derive: bool,
346     pub allow_placement_in: bool,
347     pub allow_box: bool,
348     pub allow_pushpop_unsafe: bool,
349     pub simd_ffi: bool,
350     pub unmarked_api: bool,
351     pub negate_unsigned: bool,
352     /// spans of #![feature] attrs for stable language features. for error reporting
353     pub declared_stable_lang_features: Vec<Span>,
354     /// #![feature] attrs for non-language (library) features
355     pub declared_lib_features: Vec<(InternedString, Span)>,
356     pub const_fn: bool,
357     pub static_recursion: bool,
358     pub default_type_parameter_fallback: bool,
359 }
360
361 impl Features {
362     pub fn new() -> Features {
363         Features {
364             unboxed_closures: false,
365             rustc_diagnostic_macros: false,
366             visible_private_types: false,
367             allow_quote: false,
368             allow_asm: false,
369             allow_log_syntax: false,
370             allow_concat_idents: false,
371             allow_trace_macros: false,
372             allow_internal_unstable: false,
373             allow_custom_derive: false,
374             allow_placement_in: false,
375             allow_box: false,
376             allow_pushpop_unsafe: false,
377             simd_ffi: false,
378             unmarked_api: false,
379             negate_unsigned: false,
380             declared_stable_lang_features: Vec::new(),
381             declared_lib_features: Vec::new(),
382             const_fn: false,
383             static_recursion: false,
384             default_type_parameter_fallback: false,
385         }
386     }
387 }
388
389 const EXPLAIN_BOX_SYNTAX: &'static str =
390     "box expression syntax is experimental; you can call `Box::new` instead.";
391
392 const EXPLAIN_PLACEMENT_IN: &'static str =
393     "placement-in expression syntax is experimental and subject to change.";
394
395 const EXPLAIN_PUSHPOP_UNSAFE: &'static str =
396     "push/pop_unsafe macros are experimental and subject to change.";
397
398 pub fn check_for_box_syntax(f: Option<&Features>, diag: &SpanHandler, span: Span) {
399     if let Some(&Features { allow_box: true, .. }) = f {
400         return;
401     }
402     emit_feature_err(diag, "box_syntax", span, EXPLAIN_BOX_SYNTAX);
403 }
404
405 pub fn check_for_placement_in(f: Option<&Features>, diag: &SpanHandler, span: Span) {
406     if let Some(&Features { allow_placement_in: true, .. }) = f {
407         return;
408     }
409     emit_feature_err(diag, "placement_in_syntax", span, EXPLAIN_PLACEMENT_IN);
410 }
411
412 pub fn check_for_pushpop_syntax(f: Option<&Features>, diag: &SpanHandler, span: Span) {
413     if let Some(&Features { allow_pushpop_unsafe: true, .. }) = f {
414         return;
415     }
416     emit_feature_err(diag, "pushpop_unsafe", span, EXPLAIN_PUSHPOP_UNSAFE);
417 }
418
419 struct Context<'a> {
420     features: Vec<&'static str>,
421     span_handler: &'a SpanHandler,
422     cm: &'a CodeMap,
423     plugin_attributes: &'a [(String, AttributeType)],
424 }
425
426 impl<'a> Context<'a> {
427     fn enable_feature(&mut self, feature: &'static str) {
428         debug!("enabling feature: {}", feature);
429         self.features.push(feature);
430     }
431
432     fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
433         let has_feature = self.has_feature(feature);
434         debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", feature, span, has_feature);
435         if !has_feature {
436             emit_feature_err(self.span_handler, feature, span, explain);
437         }
438     }
439     fn has_feature(&self, feature: &str) -> bool {
440         self.features.iter().any(|&n| n == feature)
441     }
442
443     fn check_attribute(&self, attr: &ast::Attribute, is_macro: bool) {
444         debug!("check_attribute(attr = {:?})", attr);
445         let name = &*attr.name();
446         for &(n, ty) in KNOWN_ATTRIBUTES {
447             if n == name {
448                 if let Gated(gate, desc) = ty {
449                     self.gate_feature(gate, attr.span, desc);
450                 }
451                 debug!("check_attribute: {:?} is known, {:?}", name, ty);
452                 return;
453             }
454         }
455         for &(ref n, ref ty) in self.plugin_attributes {
456             if &*n == name {
457                 // Plugins can't gate attributes, so we don't check for it
458                 // unlike the code above; we only use this loop to
459                 // short-circuit to avoid the checks below
460                 debug!("check_attribute: {:?} is registered by a plugin, {:?}", name, ty);
461                 return;
462             }
463         }
464         if name.starts_with("rustc_") {
465             self.gate_feature("rustc_attrs", attr.span,
466                               "unless otherwise specified, attributes \
467                                with the prefix `rustc_` \
468                                are reserved for internal compiler diagnostics");
469         } else if name.starts_with("derive_") {
470             self.gate_feature("custom_derive", attr.span,
471                               "attributes of the form `#[derive_*]` are reserved \
472                                for the compiler");
473         } else {
474             // Only run the custom attribute lint during regular
475             // feature gate checking. Macro gating runs
476             // before the plugin attributes are registered
477             // so we skip this then
478             if !is_macro {
479                 self.gate_feature("custom_attribute", attr.span,
480                            &format!("The attribute `{}` is currently \
481                                     unknown to the compiler and \
482                                     may have meaning \
483                                     added to it in the future",
484                                     name));
485             }
486         }
487     }
488 }
489
490 pub fn emit_feature_err(diag: &SpanHandler, feature: &str, span: Span, explain: &str) {
491     diag.span_err(span, explain);
492
493     // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
494     if option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some() { return; }
495     diag.fileline_help(span, &format!("add #![feature({})] to the \
496                                    crate attributes to enable",
497                                   feature));
498 }
499
500 pub const EXPLAIN_ASM: &'static str =
501     "inline assembly is not stable enough for use and is subject to change";
502
503 pub const EXPLAIN_LOG_SYNTAX: &'static str =
504     "`log_syntax!` is not stable enough for use and is subject to change";
505
506 pub const EXPLAIN_CONCAT_IDENTS: &'static str =
507     "`concat_idents` is not stable enough for use and is subject to change";
508
509 pub const EXPLAIN_TRACE_MACROS: &'static str =
510     "`trace_macros` is not stable enough for use and is subject to change";
511 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &'static str =
512     "allow_internal_unstable side-steps feature gating and stability checks";
513
514 pub const EXPLAIN_CUSTOM_DERIVE: &'static str =
515     "`#[derive]` for custom traits is not stable enough for use and is subject to change";
516
517 struct MacroVisitor<'a> {
518     context: &'a Context<'a>
519 }
520
521 impl<'a, 'v> Visitor<'v> for MacroVisitor<'a> {
522     fn visit_mac(&mut self, mac: &ast::Mac) {
523         let ast::MacInvocTT(ref path, _, _) = mac.node;
524         let id = path.segments.last().unwrap().identifier;
525
526         // Issue 22234: If you add a new case here, make sure to also
527         // add code to catch the macro during or after expansion.
528         //
529         // We still keep this MacroVisitor (rather than *solely*
530         // relying on catching cases during or after expansion) to
531         // catch uses of these macros within conditionally-compiled
532         // code, e.g. `#[cfg]`-guarded functions.
533
534         if id == token::str_to_ident("asm") {
535             self.context.gate_feature("asm", path.span, EXPLAIN_ASM);
536         }
537
538         else if id == token::str_to_ident("log_syntax") {
539             self.context.gate_feature("log_syntax", path.span, EXPLAIN_LOG_SYNTAX);
540         }
541
542         else if id == token::str_to_ident("trace_macros") {
543             self.context.gate_feature("trace_macros", path.span, EXPLAIN_TRACE_MACROS);
544         }
545
546         else if id == token::str_to_ident("concat_idents") {
547             self.context.gate_feature("concat_idents", path.span, EXPLAIN_CONCAT_IDENTS);
548         }
549     }
550
551     fn visit_attribute(&mut self, attr: &'v ast::Attribute) {
552         self.context.check_attribute(attr, true);
553     }
554
555     fn visit_expr(&mut self, e: &ast::Expr) {
556         // Issue 22181: overloaded-`box` and placement-`in` are
557         // implemented via a desugaring expansion, so their feature
558         // gates go into MacroVisitor since that works pre-expansion.
559         //
560         // Issue 22234: we also check during expansion as well.
561         // But we keep these checks as a pre-expansion check to catch
562         // uses in e.g. conditionalized code.
563
564         if let ast::ExprBox(None, _) = e.node {
565             self.context.gate_feature("box_syntax", e.span, EXPLAIN_BOX_SYNTAX);
566         }
567
568         if let ast::ExprBox(Some(_), _) = e.node {
569             self.context.gate_feature("placement_in_syntax", e.span, EXPLAIN_PLACEMENT_IN);
570         }
571
572         visit::walk_expr(self, e);
573     }
574 }
575
576 struct PostExpansionVisitor<'a> {
577     context: &'a Context<'a>
578 }
579
580 impl<'a> PostExpansionVisitor<'a> {
581     fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
582         if !self.context.cm.span_allows_unstable(span) {
583             self.context.gate_feature(feature, span, explain)
584         }
585     }
586 }
587
588 impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
589     fn visit_attribute(&mut self, attr: &ast::Attribute) {
590         if !self.context.cm.span_allows_unstable(attr.span) {
591             self.context.check_attribute(attr, false);
592         }
593     }
594
595     fn visit_name(&mut self, sp: Span, name: ast::Name) {
596         if !name.as_str().is_ascii() {
597             self.gate_feature("non_ascii_idents", sp,
598                               "non-ascii idents are not fully supported.");
599         }
600     }
601
602     fn visit_item(&mut self, i: &ast::Item) {
603         match i.node {
604             ast::ItemExternCrate(_) => {
605                 if attr::contains_name(&i.attrs[..], "macro_reexport") {
606                     self.gate_feature("macro_reexport", i.span,
607                                       "macros reexports are experimental \
608                                        and possibly buggy");
609                 }
610             }
611
612             ast::ItemForeignMod(ref foreign_module) => {
613                 if attr::contains_name(&i.attrs[..], "link_args") {
614                     self.gate_feature("link_args", i.span,
615                                       "the `link_args` attribute is not portable \
616                                        across platforms, it is recommended to \
617                                        use `#[link(name = \"foo\")]` instead")
618                 }
619                 if foreign_module.abi == Abi::RustIntrinsic {
620                     self.gate_feature("intrinsics",
621                                       i.span,
622                                       "intrinsics are subject to change")
623                 }
624             }
625
626             ast::ItemFn(..) => {
627                 if attr::contains_name(&i.attrs[..], "plugin_registrar") {
628                     self.gate_feature("plugin_registrar", i.span,
629                                       "compiler plugins are experimental and possibly buggy");
630                 }
631                 if attr::contains_name(&i.attrs[..], "start") {
632                     self.gate_feature("start", i.span,
633                                       "a #[start] function is an experimental \
634                                        feature whose signature may change \
635                                        over time");
636                 }
637                 if attr::contains_name(&i.attrs[..], "main") {
638                     self.gate_feature("main", i.span,
639                                       "declaration of a nonstandard #[main] \
640                                        function may change over time, for now \
641                                        a top-level `fn main()` is required");
642                 }
643             }
644
645             ast::ItemStruct(..) => {
646                 if attr::contains_name(&i.attrs[..], "simd") {
647                     self.gate_feature("simd", i.span,
648                                       "SIMD types are experimental and possibly buggy");
649                 }
650             }
651
652             ast::ItemDefaultImpl(..) => {
653                 self.gate_feature("optin_builtin_traits",
654                                   i.span,
655                                   "default trait implementations are experimental \
656                                    and possibly buggy");
657             }
658
659             ast::ItemImpl(_, polarity, _, _, _, _) => {
660                 match polarity {
661                     ast::ImplPolarity::Negative => {
662                         self.gate_feature("optin_builtin_traits",
663                                           i.span,
664                                           "negative trait bounds are not yet fully implemented; \
665                                           use marker types for now");
666                     },
667                     _ => {}
668                 }
669             }
670
671             _ => {}
672         }
673
674         visit::walk_item(self, i);
675     }
676
677     fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
678         let links_to_llvm = match attr::first_attr_value_str_by_name(&i.attrs,
679                                                                      "link_name") {
680             Some(val) => val.starts_with("llvm."),
681             _ => false
682         };
683         if links_to_llvm {
684             self.gate_feature("link_llvm_intrinsics", i.span,
685                               "linking to LLVM intrinsics is experimental");
686         }
687
688         visit::walk_foreign_item(self, i)
689     }
690
691     fn visit_expr(&mut self, e: &ast::Expr) {
692         match e.node {
693             ast::ExprBox(..) | ast::ExprUnary(ast::UnOp::UnUniq, _) => {
694                 self.gate_feature("box_syntax",
695                                   e.span,
696                                   "box expression syntax is experimental; \
697                                    you can call `Box::new` instead.");
698             }
699             _ => {}
700         }
701         visit::walk_expr(self, e);
702     }
703
704     fn visit_pat(&mut self, pattern: &ast::Pat) {
705         match pattern.node {
706             ast::PatVec(_, Some(_), ref last) if !last.is_empty() => {
707                 self.gate_feature("advanced_slice_patterns",
708                                   pattern.span,
709                                   "multiple-element slice matches anywhere \
710                                    but at the end of a slice (e.g. \
711                                    `[0, ..xs, 0]`) are experimental")
712             }
713             ast::PatVec(..) => {
714                 self.gate_feature("slice_patterns",
715                                   pattern.span,
716                                   "slice pattern syntax is experimental");
717             }
718             ast::PatBox(..) => {
719                 self.gate_feature("box_patterns",
720                                   pattern.span,
721                                   "box pattern syntax is experimental");
722             }
723             _ => {}
724         }
725         visit::walk_pat(self, pattern)
726     }
727
728     fn visit_fn(&mut self,
729                 fn_kind: visit::FnKind<'v>,
730                 fn_decl: &'v ast::FnDecl,
731                 block: &'v ast::Block,
732                 span: Span,
733                 _node_id: NodeId) {
734         // check for const fn declarations
735         match fn_kind {
736             visit::FkItemFn(_, _, _, ast::Constness::Const, _, _) => {
737                 self.gate_feature("const_fn", span, "const fn is unstable");
738             }
739             _ => {
740                 // stability of const fn methods are covered in
741                 // visit_trait_item and visit_impl_item below; this is
742                 // because default methods don't pass through this
743                 // point.
744             }
745         }
746
747         match fn_kind {
748             visit::FkItemFn(_, _, _, _, abi, _) if abi == Abi::RustIntrinsic => {
749                 self.gate_feature("intrinsics",
750                                   span,
751                                   "intrinsics are subject to change")
752             }
753             visit::FkItemFn(_, _, _, _, abi, _) |
754             visit::FkMethod(_, &ast::MethodSig { abi, .. }, _) if abi == Abi::RustCall => {
755                 self.gate_feature("unboxed_closures",
756                                   span,
757                                   "rust-call ABI is subject to change")
758             }
759             _ => {}
760         }
761         visit::walk_fn(self, fn_kind, fn_decl, block, span);
762     }
763
764     fn visit_trait_item(&mut self, ti: &'v ast::TraitItem) {
765         match ti.node {
766             ast::ConstTraitItem(..) => {
767                 self.gate_feature("associated_consts",
768                                   ti.span,
769                                   "associated constants are experimental")
770             }
771             ast::MethodTraitItem(ref sig, _) => {
772                 if sig.constness == ast::Constness::Const {
773                     self.gate_feature("const_fn", ti.span, "const fn is unstable");
774                 }
775             }
776             ast::TypeTraitItem(_, Some(_)) => {
777                 self.gate_feature("associated_type_defaults", ti.span,
778                                   "associated type defaults are unstable");
779             }
780             _ => {}
781         }
782         visit::walk_trait_item(self, ti);
783     }
784
785     fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
786         match ii.node {
787             ast::ConstImplItem(..) => {
788                 self.gate_feature("associated_consts",
789                                   ii.span,
790                                   "associated constants are experimental")
791             }
792             ast::MethodImplItem(ref sig, _) => {
793                 if sig.constness == ast::Constness::Const {
794                     self.gate_feature("const_fn", ii.span, "const fn is unstable");
795                 }
796             }
797             _ => {}
798         }
799         visit::walk_impl_item(self, ii);
800     }
801 }
802
803 fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler,
804                         krate: &ast::Crate,
805                         plugin_attributes: &[(String, AttributeType)],
806                         check: F)
807                        -> Features
808     where F: FnOnce(&mut Context, &ast::Crate)
809 {
810     let mut cx = Context {
811         features: Vec::new(),
812         span_handler: span_handler,
813         cm: cm,
814         plugin_attributes: plugin_attributes,
815     };
816
817     let mut accepted_features = Vec::new();
818     let mut unknown_features = Vec::new();
819
820     for attr in &krate.attrs {
821         if !attr.check_name("feature") {
822             continue
823         }
824
825         match attr.meta_item_list() {
826             None => {
827                 span_handler.span_err(attr.span, "malformed feature attribute, \
828                                                   expected #![feature(...)]");
829             }
830             Some(list) => {
831                 for mi in list {
832                     let name = match mi.node {
833                         ast::MetaWord(ref word) => (*word).clone(),
834                         _ => {
835                             span_handler.span_err(mi.span,
836                                                   "malformed feature, expected just \
837                                                    one word");
838                             continue
839                         }
840                     };
841                     match KNOWN_FEATURES.iter()
842                                         .find(|& &(n, _, _)| name == n) {
843                         Some(&(name, _, Active)) => {
844                             cx.enable_feature(name);
845                         }
846                         Some(&(_, _, Removed)) => {
847                             span_handler.span_err(mi.span, "feature has been removed");
848                         }
849                         Some(&(_, _, Accepted)) => {
850                             accepted_features.push(mi.span);
851                         }
852                         None => {
853                             unknown_features.push((name, mi.span));
854                         }
855                     }
856                 }
857             }
858         }
859     }
860
861     check(&mut cx, krate);
862
863     // FIXME (pnkfelix): Before adding the 99th entry below, change it
864     // to a single-pass (instead of N calls to `.has_feature`).
865
866     Features {
867         unboxed_closures: cx.has_feature("unboxed_closures"),
868         rustc_diagnostic_macros: cx.has_feature("rustc_diagnostic_macros"),
869         visible_private_types: cx.has_feature("visible_private_types"),
870         allow_quote: cx.has_feature("quote"),
871         allow_asm: cx.has_feature("asm"),
872         allow_log_syntax: cx.has_feature("log_syntax"),
873         allow_concat_idents: cx.has_feature("concat_idents"),
874         allow_trace_macros: cx.has_feature("trace_macros"),
875         allow_internal_unstable: cx.has_feature("allow_internal_unstable"),
876         allow_custom_derive: cx.has_feature("custom_derive"),
877         allow_placement_in: cx.has_feature("placement_in_syntax"),
878         allow_box: cx.has_feature("box_syntax"),
879         allow_pushpop_unsafe: cx.has_feature("pushpop_unsafe"),
880         simd_ffi: cx.has_feature("simd_ffi"),
881         unmarked_api: cx.has_feature("unmarked_api"),
882         negate_unsigned: cx.has_feature("negate_unsigned"),
883         declared_stable_lang_features: accepted_features,
884         declared_lib_features: unknown_features,
885         const_fn: cx.has_feature("const_fn"),
886         static_recursion: cx.has_feature("static_recursion"),
887         default_type_parameter_fallback: cx.has_feature("default_type_parameter_fallback"),
888     }
889 }
890
891 pub fn check_crate_macros(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
892 -> Features {
893     check_crate_inner(cm, span_handler, krate, &[] as &'static [_],
894                       |ctx, krate| visit::walk_crate(&mut MacroVisitor { context: ctx }, krate))
895 }
896
897 pub fn check_crate(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate,
898                    plugin_attributes: &[(String, AttributeType)],
899                    unstable: UnstableFeatures) -> Features
900 {
901     maybe_stage_features(span_handler, krate, unstable);
902
903     check_crate_inner(cm, span_handler, krate, plugin_attributes,
904                       |ctx, krate| visit::walk_crate(&mut PostExpansionVisitor { context: ctx },
905                                                      krate))
906 }
907
908 #[derive(Clone, Copy)]
909 pub enum UnstableFeatures {
910     /// Hard errors for unstable features are active, as on
911     /// beta/stable channels.
912     Disallow,
913     /// Allow features to me activated, as on nightly.
914     Allow,
915     /// Errors are bypassed for bootstrapping. This is required any time
916     /// during the build that feature-related lints are set to warn or above
917     /// because the build turns on warnings-as-errors and uses lots of unstable
918     /// features. As a result, this this is always required for building Rust
919     /// itself.
920     Cheat
921 }
922
923 fn maybe_stage_features(span_handler: &SpanHandler, krate: &ast::Crate,
924                         unstable: UnstableFeatures) {
925     let allow_features = match unstable {
926         UnstableFeatures::Allow => true,
927         UnstableFeatures::Disallow => false,
928         UnstableFeatures::Cheat => true
929     };
930     if !allow_features {
931         for attr in &krate.attrs {
932             if attr.check_name("feature") {
933                 let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)");
934                 let ref msg = format!("#[feature] may not be used on the {} release channel",
935                                       release_channel);
936                 span_handler.span_err(attr.span, msg);
937             }
938         }
939     }
940 }