]> git.lizzy.rs Git - rust.git/blob - src/librustc/front/std_inject.rs
auto merge of #16482 : pcwalton/rust/resolve-shadowing, r=brson
[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::util::small_vector::SmallVector;
25
26 use std::mem;
27 use std::gc::{Gc, GC};
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 std = "name";`
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
153             // fold_mod() will insert glob path.
154             let globs_attr = attr::mk_attr_inner(attr::mk_attr_id(),
155                                                  attr::mk_list_item(
156                 InternedString::new("feature"),
157                 vec!(
158                     attr::mk_word_item(InternedString::new("globs")),
159                 )));
160             // std_inject runs after feature checking so manually mark this attr
161             attr::mark_used(&globs_attr);
162             krate.attrs.push(globs_attr);
163
164             krate.module = self.fold_mod(&krate.module);
165         }
166         krate
167     }
168
169     fn fold_item(&mut self, item: Gc<ast::Item>) -> SmallVector<Gc<ast::Item>> {
170         if !no_prelude(item.attrs.as_slice()) {
171             // only recur if there wasn't `#![no_implicit_prelude]`
172             // on this item, i.e. this means that the prelude is not
173             // implicitly imported though the whole subtree
174             fold::noop_fold_item(&*item, self)
175         } else {
176             SmallVector::one(item)
177         }
178     }
179
180     fn fold_mod(&mut self, module: &ast::Mod) -> ast::Mod {
181         let prelude_path = ast::Path {
182             span: DUMMY_SP,
183             global: false,
184             segments: vec!(
185                 ast::PathSegment {
186                     identifier: token::str_to_ident("std"),
187                     lifetimes: Vec::new(),
188                     types: OwnedSlice::empty(),
189                 },
190                 ast::PathSegment {
191                     identifier: token::str_to_ident("prelude"),
192                     lifetimes: Vec::new(),
193                     types: OwnedSlice::empty(),
194                 }),
195         };
196
197         let vp = box(GC) codemap::dummy_spanned(ast::ViewPathGlob(prelude_path,
198                                                                   ast::DUMMY_NODE_ID));
199         let vi2 = ast::ViewItem {
200             node: ast::ViewItemUse(vp),
201             attrs: vec!(ast::Attribute {
202                 span: DUMMY_SP,
203                 node: ast::Attribute_ {
204                     id: attr::mk_attr_id(),
205                     style: ast::AttrOuter,
206                     value: box(GC) ast::MetaItem {
207                         span: DUMMY_SP,
208                         node: ast::MetaWord(token::get_name(
209                                 special_idents::prelude_import.name)),
210                     },
211                     is_sugared_doc: false,
212                 },
213             }),
214             vis: ast::Inherited,
215             span: DUMMY_SP,
216         };
217
218         let (crates, uses) = module.view_items.partitioned(|x| {
219             match x.node {
220                 ast::ViewItemExternCrate(..) => true,
221                 _ => false,
222             }
223         });
224
225         // add vi2 after any `extern crate` but before any `use`
226         let mut view_items = crates;
227         view_items.push(vi2);
228         view_items.push_all_move(uses);
229
230         let new_module = ast::Mod {
231             view_items: view_items,
232             ..(*module).clone()
233         };
234         fold::noop_fold_mod(&new_module, self)
235     }
236 }
237
238 fn inject_prelude(_: &Session, krate: ast::Crate) -> ast::Crate {
239     let mut fold = PreludeInjector;
240     fold.fold_crate(krate)
241 }