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