]> git.lizzy.rs Git - rust.git/blob - src/librustc/front/std_inject.rs
auto merge of #15425 : jbclements/rust/hygiene-for-3-kinds-of-args, r=cmr
[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";
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         _ => {
67             Some((token::intern_and_get_ident(format!("{}#{}",
68                                                       krate,
69                                                       VERSION).as_slice()),
70                   ast::CookedStr))
71         }
72     }
73 }
74
75 impl<'a> fold::Folder for StandardLibraryInjector<'a> {
76     fn fold_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
77         let mut vis = vec!(ast::ViewItem {
78             node: ast::ViewItemExternCrate(token::str_to_ident("std"),
79                                          with_version("std"),
80                                          ast::DUMMY_NODE_ID),
81             attrs: vec!(
82                 attr::mk_attr_outer(attr::mk_attr_id(), attr::mk_list_item(
83                         InternedString::new("phase"),
84                         vec!(
85                             attr::mk_word_item(InternedString::new("plugin")),
86                             attr::mk_word_item(InternedString::new("link")
87                         ))))),
88             vis: ast::Inherited,
89             span: DUMMY_SP
90         });
91
92         let any_exe = self.sess.crate_types.borrow().iter().any(|ty| {
93             *ty == config::CrateTypeExecutable
94         });
95         if use_start(&krate) && any_exe {
96             vis.push(ast::ViewItem {
97                 node: ast::ViewItemExternCrate(token::str_to_ident("native"),
98                                              with_version("native"),
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::new(),
202             vis: ast::Inherited,
203             span: DUMMY_SP,
204         };
205
206         let (crates, uses) = module.view_items.partitioned(|x| {
207             match x.node {
208                 ast::ViewItemExternCrate(..) => true,
209                 _ => false,
210             }
211         });
212
213         // add vi2 after any `extern crate` but before any `use`
214         let mut view_items = crates;
215         view_items.push(vi2);
216         view_items.push_all_move(uses);
217
218         let new_module = ast::Mod {
219             view_items: view_items,
220             ..(*module).clone()
221         };
222         fold::noop_fold_mod(&new_module, self)
223     }
224 }
225
226 fn inject_prelude(_: &Session, krate: ast::Crate) -> ast::Crate {
227     let mut fold = PreludeInjector;
228     fold.fold_crate(krate)
229 }