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