]> git.lizzy.rs Git - rust.git/blob - src/librustc/front/std_inject.rs
auto merge of #15411 : mitchmindtree/rust/master, r=alexcrichton
[rust.git] / src / librustc / front / std_inject.rs
1 // Copyright 2012 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 use driver::config;
12 use driver::session::Session;
13
14 use syntax::ast;
15 use syntax::attr;
16 use syntax::codemap::DUMMY_SP;
17 use syntax::codemap;
18 use syntax::fold::Folder;
19 use syntax::fold;
20 use syntax::owned_slice::OwnedSlice;
21 use syntax::parse::token::InternedString;
22 use syntax::parse::token;
23 use syntax::util::small_vector::SmallVector;
24
25 use std::mem;
26 use std::gc::{Gc, GC};
27
28 pub fn maybe_inject_crates_ref(sess: &Session, krate: ast::Crate)
29                                -> ast::Crate {
30     if use_std(&krate) {
31         inject_crates_ref(sess, krate)
32     } else {
33         krate
34     }
35 }
36
37 pub fn maybe_inject_prelude(sess: &Session, krate: ast::Crate) -> ast::Crate {
38     if use_std(&krate) {
39         inject_prelude(sess, krate)
40     } else {
41         krate
42     }
43 }
44
45 fn use_std(krate: &ast::Crate) -> bool {
46     !attr::contains_name(krate.attrs.as_slice(), "no_std")
47 }
48
49 fn use_start(krate: &ast::Crate) -> bool {
50     !attr::contains_name(krate.attrs.as_slice(), "no_start")
51 }
52
53 fn no_prelude(attrs: &[ast::Attribute]) -> bool {
54     attr::contains_name(attrs, "no_implicit_prelude")
55 }
56
57 struct StandardLibraryInjector<'a> {
58     sess: &'a Session,
59 }
60
61 impl<'a> fold::Folder for StandardLibraryInjector<'a> {
62     fn fold_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
63         let mut vis = vec!(ast::ViewItem {
64             node: ast::ViewItemExternCrate(token::str_to_ident("std"),
65                                            None,
66                                            ast::DUMMY_NODE_ID),
67             attrs: vec!(
68                 attr::mk_attr_outer(attr::mk_attr_id(), attr::mk_list_item(
69                         InternedString::new("phase"),
70                         vec!(
71                             attr::mk_word_item(InternedString::new("plugin")),
72                             attr::mk_word_item(InternedString::new("link")
73                         ))))),
74             vis: ast::Inherited,
75             span: DUMMY_SP
76         });
77
78         let any_exe = self.sess.crate_types.borrow().iter().any(|ty| {
79             *ty == config::CrateTypeExecutable
80         });
81         if use_start(&krate) && any_exe {
82             vis.push(ast::ViewItem {
83                 node: ast::ViewItemExternCrate(token::str_to_ident("native"),
84                                                None,
85                                                ast::DUMMY_NODE_ID),
86                 attrs: Vec::new(),
87                 vis: ast::Inherited,
88                 span: DUMMY_SP
89             });
90         }
91
92         // `extern crate` must be precede `use` items
93         mem::swap(&mut vis, &mut krate.module.view_items);
94         krate.module.view_items.push_all_move(vis);
95
96         // don't add #![no_std] here, that will block the prelude injection later.
97         // Add it during the prelude injection instead.
98
99         // Add #![feature(phase)] here, because we use #[phase] on extern crate std.
100         let feat_phase_attr = attr::mk_attr_inner(attr::mk_attr_id(),
101                                                   attr::mk_list_item(
102                                   InternedString::new("feature"),
103                                   vec![attr::mk_word_item(InternedString::new("phase"))],
104                               ));
105         // std_inject runs after feature checking so manually mark this attr
106         attr::mark_used(&feat_phase_attr);
107         krate.attrs.push(feat_phase_attr);
108
109         krate
110     }
111 }
112
113 fn inject_crates_ref(sess: &Session, krate: ast::Crate) -> ast::Crate {
114     let mut fold = StandardLibraryInjector {
115         sess: sess,
116     };
117     fold.fold_crate(krate)
118 }
119
120 struct PreludeInjector<'a>;
121
122
123 impl<'a> fold::Folder for PreludeInjector<'a> {
124     fn fold_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
125         // Add #![no_std] here, so we don't re-inject when compiling pretty-printed source.
126         // This must happen here and not in StandardLibraryInjector because this
127         // fold happens second.
128
129         let no_std_attr = attr::mk_attr_inner(attr::mk_attr_id(),
130                                               attr::mk_word_item(InternedString::new("no_std")));
131         // std_inject runs after feature checking so manually mark this attr
132         attr::mark_used(&no_std_attr);
133         krate.attrs.push(no_std_attr);
134
135         if !no_prelude(krate.attrs.as_slice()) {
136             // only add `use std::prelude::*;` if there wasn't a
137             // `#![no_implicit_prelude]` at the crate level.
138
139             // fold_mod() will insert glob path.
140             let globs_attr = attr::mk_attr_inner(attr::mk_attr_id(),
141                                                  attr::mk_list_item(
142                 InternedString::new("feature"),
143                 vec!(
144                     attr::mk_word_item(InternedString::new("globs")),
145                 )));
146             // std_inject runs after feature checking so manually mark this attr
147             attr::mark_used(&globs_attr);
148             krate.attrs.push(globs_attr);
149
150             krate.module = self.fold_mod(&krate.module);
151         }
152         krate
153     }
154
155     fn fold_item(&mut self, item: Gc<ast::Item>) -> SmallVector<Gc<ast::Item>> {
156         if !no_prelude(item.attrs.as_slice()) {
157             // only recur if there wasn't `#![no_implicit_prelude]`
158             // on this item, i.e. this means that the prelude is not
159             // implicitly imported though the whole subtree
160             fold::noop_fold_item(&*item, self)
161         } else {
162             SmallVector::one(item)
163         }
164     }
165
166     fn fold_mod(&mut self, module: &ast::Mod) -> ast::Mod {
167         let prelude_path = ast::Path {
168             span: DUMMY_SP,
169             global: false,
170             segments: vec!(
171                 ast::PathSegment {
172                     identifier: token::str_to_ident("std"),
173                     lifetimes: Vec::new(),
174                     types: OwnedSlice::empty(),
175                 },
176                 ast::PathSegment {
177                     identifier: token::str_to_ident("prelude"),
178                     lifetimes: Vec::new(),
179                     types: OwnedSlice::empty(),
180                 }),
181         };
182
183         let vp = box(GC) codemap::dummy_spanned(ast::ViewPathGlob(prelude_path,
184                                                                   ast::DUMMY_NODE_ID));
185         let vi2 = ast::ViewItem {
186             node: ast::ViewItemUse(vp),
187             attrs: Vec::new(),
188             vis: ast::Inherited,
189             span: DUMMY_SP,
190         };
191
192         let (crates, uses) = module.view_items.partitioned(|x| {
193             match x.node {
194                 ast::ViewItemExternCrate(..) => true,
195                 _ => false,
196             }
197         });
198
199         // add vi2 after any `extern crate` but before any `use`
200         let mut view_items = crates;
201         view_items.push(vi2);
202         view_items.push_all_move(uses);
203
204         let new_module = ast::Mod {
205             view_items: view_items,
206             ..(*module).clone()
207         };
208         fold::noop_fold_mod(&new_module, self)
209     }
210 }
211
212 fn inject_prelude(_: &Session, krate: ast::Crate) -> ast::Crate {
213     let mut fold = PreludeInjector;
214     fold.fold_crate(krate)
215 }