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