]> git.lizzy.rs Git - rust.git/blob - src/librustc/front/std_inject.rs
auto merge of #15991 : pcwalton/rust/resolve-regions-in-trait-matching, 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
64         // The name to use in `extern crate std = "name";`
65         let actual_crate_name = match self.sess.opts.alt_std_name {
66             Some(ref s) => token::intern_and_get_ident(s.as_slice()),
67             None => token::intern_and_get_ident("std"),
68         };
69
70         let mut vis = vec!(ast::ViewItem {
71             node: ast::ViewItemExternCrate(token::str_to_ident("std"),
72                                            Some((actual_crate_name, ast::CookedStr)),
73                                            ast::DUMMY_NODE_ID),
74             attrs: vec!(
75                 attr::mk_attr_outer(attr::mk_attr_id(), attr::mk_list_item(
76                         InternedString::new("phase"),
77                         vec!(
78                             attr::mk_word_item(InternedString::new("plugin")),
79                             attr::mk_word_item(InternedString::new("link")
80                         ))))),
81             vis: ast::Inherited,
82             span: DUMMY_SP
83         });
84
85         let any_exe = self.sess.crate_types.borrow().iter().any(|ty| {
86             *ty == config::CrateTypeExecutable
87         });
88         if use_start(&krate) && any_exe {
89             let visible_rt_name = "rt";
90             let actual_rt_name = "native";
91             // Gensym the ident so it can't be named
92             let visible_rt_name = token::gensym_ident(visible_rt_name);
93             let actual_rt_name = token::intern_and_get_ident(actual_rt_name);
94
95             vis.push(ast::ViewItem {
96                 node: ast::ViewItemExternCrate(visible_rt_name,
97                                                Some((actual_rt_name, ast::CookedStr)),
98                                                ast::DUMMY_NODE_ID),
99                 attrs: Vec::new(),
100                 vis: ast::Inherited,
101                 span: DUMMY_SP
102             });
103         }
104
105         // `extern crate` must be precede `use` items
106         mem::swap(&mut vis, &mut krate.module.view_items);
107         krate.module.view_items.push_all_move(vis);
108
109         // don't add #![no_std] here, that will block the prelude injection later.
110         // Add it during the prelude injection instead.
111
112         // Add #![feature(phase)] here, because we use #[phase] on extern crate std.
113         let feat_phase_attr = attr::mk_attr_inner(attr::mk_attr_id(),
114                                                   attr::mk_list_item(
115                                   InternedString::new("feature"),
116                                   vec![attr::mk_word_item(InternedString::new("phase"))],
117                               ));
118         // std_inject runs after feature checking so manually mark this attr
119         attr::mark_used(&feat_phase_attr);
120         krate.attrs.push(feat_phase_attr);
121
122         krate
123     }
124 }
125
126 fn inject_crates_ref(sess: &Session, krate: ast::Crate) -> ast::Crate {
127     let mut fold = StandardLibraryInjector {
128         sess: sess,
129     };
130     fold.fold_crate(krate)
131 }
132
133 struct PreludeInjector<'a>;
134
135
136 impl<'a> fold::Folder for PreludeInjector<'a> {
137     fn fold_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
138         // Add #![no_std] here, so we don't re-inject when compiling pretty-printed source.
139         // This must happen here and not in StandardLibraryInjector because this
140         // fold happens second.
141
142         let no_std_attr = attr::mk_attr_inner(attr::mk_attr_id(),
143                                               attr::mk_word_item(InternedString::new("no_std")));
144         // std_inject runs after feature checking so manually mark this attr
145         attr::mark_used(&no_std_attr);
146         krate.attrs.push(no_std_attr);
147
148         if !no_prelude(krate.attrs.as_slice()) {
149             // only add `use std::prelude::*;` if there wasn't a
150             // `#![no_implicit_prelude]` at the crate level.
151
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: Gc<ast::Item>) -> SmallVector<Gc<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, module: &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 vp = box(GC) codemap::dummy_spanned(ast::ViewPathGlob(prelude_path,
197                                                                   ast::DUMMY_NODE_ID));
198         let vi2 = ast::ViewItem {
199             node: ast::ViewItemUse(vp),
200             attrs: Vec::new(),
201             vis: ast::Inherited,
202             span: DUMMY_SP,
203         };
204
205         let (crates, uses) = module.view_items.partitioned(|x| {
206             match x.node {
207                 ast::ViewItemExternCrate(..) => true,
208                 _ => false,
209             }
210         });
211
212         // add vi2 after any `extern crate` but before any `use`
213         let mut view_items = crates;
214         view_items.push(vi2);
215         view_items.push_all_move(uses);
216
217         let new_module = ast::Mod {
218             view_items: view_items,
219             ..(*module).clone()
220         };
221         fold::noop_fold_mod(&new_module, self)
222     }
223 }
224
225 fn inject_prelude(_: &Session, krate: ast::Crate) -> ast::Crate {
226     let mut fold = PreludeInjector;
227     fold.fold_crate(krate)
228 }