]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/feature_gate.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[rust.git] / src / libsyntax / feature_gate.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Feature gating
12 //!
13 //! This modules implements the gating necessary for preventing certain compiler
14 //! features from being used by default. This module will crawl a pre-expanded
15 //! AST to ensure that there are no features which are used that are not
16 //! enabled.
17 //!
18 //! Features are enabled in programs via the crate-level attributes of
19 //! `#![feature(...)]` with a comma-separated list of features.
20 //!
21 //! For the purpose of future feature-tracking, once code for detection of feature
22 //! gate usage is added, *do not remove it again* even once the feature
23 //! becomes stable.
24
25 use self::Status::*;
26 use self::AttributeType::*;
27
28 use abi::RustIntrinsic;
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 static 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     ("phase", "1.0.0", Removed),
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     ("unsafe_destructor", "1.0.0", Active),
63     ("intrinsics", "1.0.0", Active),
64     ("lang_items", "1.0.0", Active),
65
66     ("simd", "1.0.0", Active),
67     ("default_type_params", "1.0.0", Accepted),
68     ("quote", "1.0.0", Active),
69     ("link_llvm_intrinsics", "1.0.0", Active),
70     ("linkage", "1.0.0", Active),
71     ("struct_inherit", "1.0.0", Removed),
72
73     ("quad_precision_float", "1.0.0", Removed),
74
75     ("rustc_diagnostic_macros", "1.0.0", Active),
76     ("unboxed_closures", "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     ("on_unimplemented", "1.0.0", Active),
85     ("simd_ffi", "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     // A temporary feature gate used to enable parser extensions needed
95     // to bootstrap fix for #5723.
96     ("issue_5723_bootstrap", "1.0.0", Accepted),
97
98     // A way to temporarily opt out of opt in copy. This will *never* be accepted.
99     ("opt_out_copy", "1.0.0", Removed),
100
101     // A way to temporarily opt out of the new orphan rules. This will *never* be accepted.
102     ("old_orphan_check", "1.0.0", Deprecated),
103
104     // A way to temporarily opt out of the new impl rules. This will *never* be accepted.
105     ("old_impl_check", "1.0.0", Deprecated),
106
107     // OIBIT specific features
108     ("optin_builtin_traits", "1.0.0", Active),
109
110     // int and uint are now deprecated
111     ("int_uint", "1.0.0", Active),
112
113     // macro reexport needs more discussion and stabilization
114     ("macro_reexport", "1.0.0", Active),
115
116     // These are used to test this portion of the compiler, they don't actually
117     // mean anything
118     ("test_accepted_feature", "1.0.0", Accepted),
119     ("test_removed_feature", "1.0.0", Removed),
120
121     // Allows use of #[staged_api]
122     ("staged_api", "1.0.0", Active),
123
124     // Allows using items which are missing stability attributes
125     ("unmarked_api", "1.0.0", Active),
126
127     // Allows using #![no_std]
128     ("no_std", "1.0.0", Active),
129
130     // Allows using `box` in patterns; RFC 469
131     ("box_patterns", "1.0.0", Active),
132
133     // Allows using the unsafe_no_drop_flag attribute (unlikely to
134     // switch to Accepted; see RFC 320)
135     ("unsafe_no_drop_flag", "1.0.0", Active),
136
137     // Allows the use of custom attributes; RFC 572
138     ("custom_attribute", "1.0.0", Active),
139
140     // Allows the use of rustc_* attributes; RFC 572
141     ("rustc_attrs", "1.0.0", Active),
142 ];
143 // (changing above list without updating src/doc/reference.md makes @cmr sad)
144
145 enum Status {
146     /// Represents an active feature that is currently being implemented or
147     /// currently being considered for addition/removal.
148     Active,
149
150     /// Represents a feature gate that is temporarily enabling deprecated behavior.
151     /// This gate will never be accepted.
152     Deprecated,
153
154     /// Represents a feature which has since been removed (it was once Active)
155     Removed,
156
157     /// This language feature has since been Accepted (it was once Active)
158     Accepted,
159 }
160
161 // Attributes that have a special meaning to rustc or rustdoc
162 pub static KNOWN_ATTRIBUTES: &'static [(&'static str, AttributeType)] = &[
163     // Normal attributes
164
165     ("warn", Normal),
166     ("allow", Normal),
167     ("forbid", Normal),
168     ("deny", Normal),
169
170     ("macro_reexport", Normal),
171     ("macro_use", Normal),
172     ("macro_export", Normal),
173     ("plugin_registrar", Normal),
174
175     ("cfg", Normal),
176     ("main", Normal),
177     ("start", Normal),
178     ("test", Normal),
179     ("bench", Normal),
180     ("simd", Normal),
181     ("repr", Normal),
182     ("path", Normal),
183     ("abi", Normal),
184     ("unsafe_destructor", Normal),
185     ("automatically_derived", Normal),
186     ("no_mangle", Normal),
187     ("no_link", Normal),
188     ("derive", Normal),
189     ("should_fail", Normal),
190     ("ignore", Normal),
191     ("no_implicit_prelude", Normal),
192     ("reexport_test_harness_main", Normal),
193     ("link_args", Normal),
194     ("macro_escape", Normal),
195
196
197     ("staged_api", Gated("staged_api",
198                          "staged_api is for use by rustc only")),
199     ("plugin", Gated("plugin",
200                      "compiler plugins are experimental \
201                       and possibly buggy")),
202     ("no_std", Gated("no_std",
203                      "no_std is experimental")),
204     ("lang", Gated("lang_items",
205                      "language items are subject to change")),
206     ("linkage", Gated("linkage",
207                       "the `linkage` attribute is experimental \
208                        and not portable across platforms")),
209     ("thread_local", Gated("thread_local",
210                             "`#[thread_local]` is an experimental feature, and does not \
211                              currently handle destructors. There is no corresponding \
212                              `#[task_local]` mapping to the task model")),
213
214     ("rustc_on_unimplemented", Gated("on_unimplemented",
215                                      "the `#[rustc_on_unimplemented]` attribute \
216                                       is an experimental feature")),
217     ("rustc_variance", Gated("rustc_attrs",
218                              "the `#[rustc_variance]` attribute \
219                               is an experimental feature")),
220     ("rustc_error", Gated("rustc_attrs",
221                           "the `#[rustc_error]` attribute \
222                            is an experimental feature")),
223     ("rustc_move_fragments", Gated("rustc_attrs",
224                                    "the `#[rustc_move_fragments]` attribute \
225                                     is an experimental feature")),
226
227     // FIXME: #14408 whitelist docs since rustdoc looks at them
228     ("doc", Whitelisted),
229
230     // FIXME: #14406 these are processed in trans, which happens after the
231     // lint pass
232     ("cold", Whitelisted),
233     ("export_name", Whitelisted),
234     ("inline", Whitelisted),
235     ("link", Whitelisted),
236     ("link_name", Whitelisted),
237     ("link_section", Whitelisted),
238     ("no_builtins", Whitelisted),
239     ("no_mangle", Whitelisted),
240     ("no_split_stack", Whitelisted),
241     ("no_stack_check", Whitelisted),
242     ("packed", Whitelisted),
243     ("static_assert", Whitelisted),
244     ("no_debug", Whitelisted),
245     ("omit_gdb_pretty_printer_section", Whitelisted),
246     ("unsafe_no_drop_flag", Whitelisted),
247
248     // used in resolve
249     ("prelude_import", Whitelisted),
250
251     // FIXME: #14407 these are only looked at on-demand so we can't
252     // guarantee they'll have already been checked
253     ("deprecated", Whitelisted),
254     ("must_use", Whitelisted),
255     ("stable", Whitelisted),
256     ("unstable", Whitelisted),
257
258     // FIXME: #19470 this shouldn't be needed forever
259     ("old_orphan_check", Whitelisted),
260     ("old_impl_check", Whitelisted),
261     ("rustc_paren_sugar", Whitelisted), // FIXME: #18101 temporary unboxed closure hack
262
263     // Crate level attributes
264     ("crate_name", CrateLevel),
265     ("crate_type", CrateLevel),
266     ("crate_id", CrateLevel),
267     ("feature", CrateLevel),
268     ("no_start", CrateLevel),
269     ("no_main", CrateLevel),
270     ("no_builtins", CrateLevel),
271     ("recursion_limit", CrateLevel),
272 ];
273
274 #[derive(PartialEq, Copy)]
275 pub enum AttributeType {
276     /// Normal, builtin attribute that is consumed
277     /// by the compiler before the unused_attribute check
278     Normal,
279
280     /// Builtin attribute that may not be consumed by the compiler
281     /// before the unused_attribute check. These attributes
282     /// will be ignored by the unused_attribute lint
283     Whitelisted,
284
285     /// Is gated by a given feature gate and reason
286     /// These get whitelisted too
287     Gated(&'static str, &'static str),
288
289     /// Builtin attribute that is only allowed at the crate level
290     CrateLevel,
291 }
292
293 /// A set of features to be used by later passes.
294 pub struct Features {
295     pub unboxed_closures: bool,
296     pub rustc_diagnostic_macros: bool,
297     pub visible_private_types: bool,
298     pub allow_quote: bool,
299     pub allow_asm: bool,
300     pub allow_log_syntax: bool,
301     pub allow_concat_idents: bool,
302     pub allow_trace_macros: bool,
303     pub old_orphan_check: bool,
304     pub simd_ffi: bool,
305     pub unmarked_api: bool,
306     /// spans of #![feature] attrs for stable language features. for error reporting
307     pub declared_stable_lang_features: Vec<Span>,
308     /// #![feature] attrs for non-language (library) features
309     pub declared_lib_features: Vec<(InternedString, Span)>
310 }
311
312 impl Features {
313     pub fn new() -> Features {
314         Features {
315             unboxed_closures: false,
316             rustc_diagnostic_macros: false,
317             visible_private_types: false,
318             allow_quote: false,
319             allow_asm: false,
320             allow_log_syntax: false,
321             allow_concat_idents: false,
322             allow_trace_macros: false,
323             old_orphan_check: false,
324             simd_ffi: false,
325             unmarked_api: false,
326             declared_stable_lang_features: Vec::new(),
327             declared_lib_features: Vec::new()
328         }
329     }
330 }
331
332 struct Context<'a> {
333     features: Vec<&'static str>,
334     span_handler: &'a SpanHandler,
335     cm: &'a CodeMap,
336 }
337
338 impl<'a> Context<'a> {
339     fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
340         if !self.has_feature(feature) {
341             emit_feature_err(self.span_handler, feature, span, explain);
342         }
343     }
344
345     fn warn_feature(&self, feature: &str, span: Span, explain: &str) {
346         if !self.has_feature(feature) {
347             emit_feature_warn(self.span_handler, feature, span, explain);
348         }
349     }
350     fn has_feature(&self, feature: &str) -> bool {
351         self.features.iter().any(|&n| n == feature)
352     }
353 }
354
355 pub fn emit_feature_err(diag: &SpanHandler, feature: &str, span: Span, explain: &str) {
356     diag.span_err(span, explain);
357     diag.span_help(span, &format!("add #![feature({})] to the \
358                                    crate attributes to enable",
359                                   feature));
360 }
361
362 pub fn emit_feature_warn(diag: &SpanHandler, feature: &str, span: Span, explain: &str) {
363     diag.span_warn(span, explain);
364     if diag.handler.can_emit_warnings {
365         diag.span_help(span, &format!("add #![feature({})] to the \
366                                        crate attributes to silence this warning",
367                                       feature));
368     }
369 }
370
371 pub const EXPLAIN_ASM: &'static str =
372     "inline assembly is not stable enough for use and is subject to change";
373
374 pub const EXPLAIN_LOG_SYNTAX: &'static str =
375     "`log_syntax!` is not stable enough for use and is subject to change";
376
377 pub const EXPLAIN_CONCAT_IDENTS: &'static str =
378     "`concat_idents` is not stable enough for use and is subject to change";
379
380 pub const EXPLAIN_TRACE_MACROS: &'static str =
381     "`trace_macros` is not stable enough for use and is subject to change";
382
383 struct MacroVisitor<'a> {
384     context: &'a Context<'a>
385 }
386
387 impl<'a, 'v> Visitor<'v> for MacroVisitor<'a> {
388     fn visit_mac(&mut self, mac: &ast::Mac) {
389         let ast::MacInvocTT(ref path, _, _) = mac.node;
390         let id = path.segments.last().unwrap().identifier;
391
392         // Issue 22234: If you add a new case here, make sure to also
393         // add code to catch the macro during or after expansion.
394         //
395         // We still keep this MacroVisitor (rather than *solely*
396         // relying on catching cases during or after expansion) to
397         // catch uses of these macros within conditionally-compiled
398         // code, e.g. `#[cfg]`-guarded functions.
399
400         if id == token::str_to_ident("asm") {
401             self.context.gate_feature("asm", path.span, EXPLAIN_ASM);
402         }
403
404         else if id == token::str_to_ident("log_syntax") {
405             self.context.gate_feature("log_syntax", path.span, EXPLAIN_LOG_SYNTAX);
406         }
407
408         else if id == token::str_to_ident("trace_macros") {
409             self.context.gate_feature("trace_macros", path.span, EXPLAIN_TRACE_MACROS);
410         }
411
412         else if id == token::str_to_ident("concat_idents") {
413             self.context.gate_feature("concat_idents", path.span, EXPLAIN_CONCAT_IDENTS);
414         }
415     }
416 }
417
418 struct PostExpansionVisitor<'a> {
419     context: &'a Context<'a>
420 }
421
422 impl<'a> PostExpansionVisitor<'a> {
423     fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
424         if !self.context.cm.span_is_internal(span) {
425             self.context.gate_feature(feature, span, explain)
426         }
427     }
428 }
429
430 impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
431     fn visit_name(&mut self, sp: Span, name: ast::Name) {
432         if !token::get_name(name).is_ascii() {
433             self.gate_feature("non_ascii_idents", sp,
434                               "non-ascii idents are not fully supported.");
435         }
436     }
437
438     fn visit_item(&mut self, i: &ast::Item) {
439         match i.node {
440             ast::ItemExternCrate(_) => {
441                 if attr::contains_name(&i.attrs[..], "macro_reexport") {
442                     self.gate_feature("macro_reexport", i.span,
443                                       "macros reexports are experimental \
444                                        and possibly buggy");
445                 }
446             }
447
448             ast::ItemForeignMod(ref foreign_module) => {
449                 if attr::contains_name(&i.attrs[..], "link_args") {
450                     self.gate_feature("link_args", i.span,
451                                       "the `link_args` attribute is not portable \
452                                        across platforms, it is recommended to \
453                                        use `#[link(name = \"foo\")]` instead")
454                 }
455                 if foreign_module.abi == RustIntrinsic {
456                     self.gate_feature("intrinsics",
457                                       i.span,
458                                       "intrinsics are subject to change")
459                 }
460             }
461
462             ast::ItemFn(..) => {
463                 if attr::contains_name(&i.attrs[..], "plugin_registrar") {
464                     self.gate_feature("plugin_registrar", i.span,
465                                       "compiler plugins are experimental and possibly buggy");
466                 }
467                 if attr::contains_name(&i.attrs[..], "start") {
468                     self.gate_feature("start", i.span,
469                                       "a #[start] function is an experimental \
470                                        feature whose signature may change \
471                                        over time");
472                 }
473                 if attr::contains_name(&i.attrs[..], "main") {
474                     self.gate_feature("main", i.span,
475                                       "declaration of a nonstandard #[main] \
476                                        function may change over time, for now \
477                                        a top-level `fn main()` is required");
478                 }
479             }
480
481             ast::ItemStruct(..) => {
482                 if attr::contains_name(&i.attrs[..], "simd") {
483                     self.gate_feature("simd", i.span,
484                                       "SIMD types are experimental and possibly buggy");
485                 }
486             }
487
488             ast::ItemImpl(_, polarity, _, _, _, _) => {
489                 match polarity {
490                     ast::ImplPolarity::Negative => {
491                         self.gate_feature("optin_builtin_traits",
492                                           i.span,
493                                           "negative trait bounds are not yet fully implemented; \
494                                           use marker types for now");
495                     },
496                     _ => {}
497                 }
498
499                 if attr::contains_name(&i.attrs,
500                                        "unsafe_destructor") {
501                     self.gate_feature("unsafe_destructor",
502                                       i.span,
503                                       "`#[unsafe_destructor]` allows too \
504                                        many unsafe patterns and may be \
505                                        removed in the future");
506                 }
507
508                 if attr::contains_name(&i.attrs[..],
509                                        "old_orphan_check") {
510                     self.gate_feature(
511                         "old_orphan_check",
512                         i.span,
513                         "the new orphan check rules will eventually be strictly enforced");
514                 }
515
516                 if attr::contains_name(&i.attrs[..],
517                                        "old_impl_check") {
518                     self.gate_feature("old_impl_check",
519                                       i.span,
520                                       "`#[old_impl_check]` will be removed in the future");
521                 }
522             }
523
524             _ => {}
525         }
526
527         visit::walk_item(self, i);
528     }
529
530     fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
531         if attr::contains_name(&i.attrs, "linkage") {
532             self.gate_feature("linkage", i.span,
533                               "the `linkage` attribute is experimental \
534                                and not portable across platforms")
535         }
536
537         let links_to_llvm = match attr::first_attr_value_str_by_name(&i.attrs,
538                                                                      "link_name") {
539             Some(val) => val.starts_with("llvm."),
540             _ => false
541         };
542         if links_to_llvm {
543             self.gate_feature("link_llvm_intrinsics", i.span,
544                               "linking to LLVM intrinsics is experimental");
545         }
546
547         visit::walk_foreign_item(self, i)
548     }
549
550     fn visit_ty(&mut self, t: &ast::Ty) {
551         match t.node {
552             ast::TyPath(ref p, _) => {
553                 match &*p.segments {
554
555                     [ast::PathSegment { identifier, .. }] => {
556                         let name = token::get_ident(identifier);
557                         let msg = if name == "int" {
558                             Some("the `int` type is deprecated; \
559                                   use `isize` or a fixed-sized integer")
560                         } else if name == "uint" {
561                             Some("the `uint` type is deprecated; \
562                                   use `usize` or a fixed-sized integer")
563                         } else {
564                             None
565                         };
566
567                         if let Some(msg) = msg {
568                             self.context.warn_feature("int_uint", t.span, msg)
569                         }
570                     }
571                     _ => {}
572                 }
573             }
574             _ => {}
575         }
576         visit::walk_ty(self, t);
577     }
578
579     fn visit_expr(&mut self, e: &ast::Expr) {
580         match e.node {
581             ast::ExprBox(..) | ast::ExprUnary(ast::UnOp::UnUniq, _) => {
582                 self.gate_feature("box_syntax",
583                                   e.span,
584                                   "box expression syntax is experimental; \
585                                    you can call `Box::new` instead.");
586             }
587             ast::ExprLit(ref lit) => {
588                 match lit.node {
589                     ast::LitInt(_, ty) => {
590                         let msg = if let ast::SignedIntLit(ast::TyIs(true), _) = ty {
591                             Some("the `i` and `is` suffixes on integers are deprecated; \
592                                   use `isize` or one of the fixed-sized suffixes")
593                         } else if let ast::UnsignedIntLit(ast::TyUs(true)) = ty {
594                             Some("the `u` and `us` suffixes on integers are deprecated; \
595                                   use `usize` or one of the fixed-sized suffixes")
596                         } else {
597                             None
598                         };
599                         if let Some(msg) = msg {
600                             self.context.warn_feature("int_uint", e.span, msg);
601                         }
602                     }
603                     _ => {}
604                 }
605             }
606             _ => {}
607         }
608         visit::walk_expr(self, e);
609     }
610
611     fn visit_attribute(&mut self, attr: &ast::Attribute) {
612         let name = &*attr.name();
613         for &(n, ty) in KNOWN_ATTRIBUTES {
614             if n == name {
615                 if let Gated(gate, desc) = ty {
616                     self.gate_feature(gate, attr.span, desc);
617                 }
618                 return;
619             }
620         }
621         if name.starts_with("rustc_") {
622             self.gate_feature("rustc_attrs", attr.span,
623                               "unless otherwise specified, attributes \
624                                with the prefix `rustc_` \
625                                are reserved for internal compiler diagnostics");
626         } else {
627             self.gate_feature("custom_attribute", attr.span,
628                        format!("The attribute `{}` is currently \
629                                 unknown to the the compiler and \
630                                 may have meaning \
631                                 added to it in the future",
632                                 name).as_slice());
633         }
634     }
635
636     fn visit_pat(&mut self, pattern: &ast::Pat) {
637         match pattern.node {
638             ast::PatVec(_, Some(_), ref last) if !last.is_empty() => {
639                 self.gate_feature("advanced_slice_patterns",
640                                   pattern.span,
641                                   "multiple-element slice matches anywhere \
642                                    but at the end of a slice (e.g. \
643                                    `[0, ..xs, 0]` are experimental")
644             }
645             ast::PatBox(..) => {
646                 self.gate_feature("box_patterns",
647                                   pattern.span,
648                                   "box pattern syntax is experimental");
649             }
650             _ => {}
651         }
652         visit::walk_pat(self, pattern)
653     }
654
655     fn visit_fn(&mut self,
656                 fn_kind: visit::FnKind<'v>,
657                 fn_decl: &'v ast::FnDecl,
658                 block: &'v ast::Block,
659                 span: Span,
660                 _node_id: NodeId) {
661         match fn_kind {
662             visit::FkItemFn(_, _, _, abi) if abi == RustIntrinsic => {
663                 self.gate_feature("intrinsics",
664                                   span,
665                                   "intrinsics are subject to change")
666             }
667             _ => {}
668         }
669         visit::walk_fn(self, fn_kind, fn_decl, block, span);
670     }
671 }
672
673 fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate,
674                         check: F)
675                        -> Features
676     where F: FnOnce(&mut Context, &ast::Crate)
677 {
678     let mut cx = Context {
679         features: Vec::new(),
680         span_handler: span_handler,
681         cm: cm,
682     };
683
684     let mut accepted_features = Vec::new();
685     let mut unknown_features = Vec::new();
686
687     for attr in &krate.attrs {
688         if !attr.check_name("feature") {
689             continue
690         }
691
692         match attr.meta_item_list() {
693             None => {
694                 span_handler.span_err(attr.span, "malformed feature attribute, \
695                                                   expected #![feature(...)]");
696             }
697             Some(list) => {
698                 for mi in list {
699                     let name = match mi.node {
700                         ast::MetaWord(ref word) => (*word).clone(),
701                         _ => {
702                             span_handler.span_err(mi.span,
703                                                   "malformed feature, expected just \
704                                                    one word");
705                             continue
706                         }
707                     };
708                     match KNOWN_FEATURES.iter()
709                                         .find(|& &(n, _, _)| name == n) {
710                         Some(&(name, _, Active)) => {
711                             cx.features.push(name);
712                         }
713                         Some(&(name, _, Deprecated)) => {
714                             cx.features.push(name);
715                             span_handler.span_warn(
716                                 mi.span,
717                                 "feature is deprecated and will only be available \
718                                  for a limited time, please rewrite code that relies on it");
719                         }
720                         Some(&(_, _, Removed)) => {
721                             span_handler.span_err(mi.span, "feature has been removed");
722                         }
723                         Some(&(_, _, Accepted)) => {
724                             accepted_features.push(mi.span);
725                         }
726                         None => {
727                             unknown_features.push((name, mi.span));
728                         }
729                     }
730                 }
731             }
732         }
733     }
734
735     check(&mut cx, krate);
736
737     // FIXME (pnkfelix): Before adding the 99th entry below, change it
738     // to a single-pass (instead of N calls to `.has_feature`).
739
740     Features {
741         unboxed_closures: cx.has_feature("unboxed_closures"),
742         rustc_diagnostic_macros: cx.has_feature("rustc_diagnostic_macros"),
743         visible_private_types: cx.has_feature("visible_private_types"),
744         allow_quote: cx.has_feature("quote"),
745         allow_asm: cx.has_feature("asm"),
746         allow_log_syntax: cx.has_feature("log_syntax"),
747         allow_concat_idents: cx.has_feature("concat_idents"),
748         allow_trace_macros: cx.has_feature("trace_macros"),
749         old_orphan_check: cx.has_feature("old_orphan_check"),
750         simd_ffi: cx.has_feature("simd_ffi"),
751         unmarked_api: cx.has_feature("unmarked_api"),
752         declared_stable_lang_features: accepted_features,
753         declared_lib_features: unknown_features
754     }
755 }
756
757 pub fn check_crate_macros(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
758 -> Features {
759     check_crate_inner(cm, span_handler, krate,
760                       |ctx, krate| visit::walk_crate(&mut MacroVisitor { context: ctx }, krate))
761 }
762
763 pub fn check_crate(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
764 -> Features {
765     check_crate_inner(cm, span_handler, krate,
766                       |ctx, krate| visit::walk_crate(&mut PostExpansionVisitor { context: ctx },
767                                                      krate))
768 }
769