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