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