]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/std_inject.rs
rollup merge of #21396: japaric/no-parens-in-range
[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_word_item(
69                         InternedString::new("macro_use")))),
70             vis: ast::Inherited,
71             span: DUMMY_SP
72         });
73
74         // `extern crate` must be precede `use` items
75         mem::swap(&mut vis, &mut krate.module.view_items);
76         krate.module.view_items.extend(vis.into_iter());
77
78         // don't add #![no_std] here, that will block the prelude injection later.
79         // Add it during the prelude injection instead.
80
81         krate
82     }
83 }
84
85 fn inject_crates_ref(krate: ast::Crate, alt_std_name: Option<String>) -> ast::Crate {
86     let mut fold = StandardLibraryInjector {
87         alt_std_name: alt_std_name
88     };
89     fold.fold_crate(krate)
90 }
91
92 struct PreludeInjector<'a>;
93
94 impl<'a> fold::Folder for PreludeInjector<'a> {
95     fn fold_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
96         // Add #![no_std] here, so we don't re-inject when compiling pretty-printed source.
97         // This must happen here and not in StandardLibraryInjector because this
98         // fold happens second.
99
100         let no_std_attr = attr::mk_attr_inner(attr::mk_attr_id(),
101                                               attr::mk_word_item(InternedString::new("no_std")));
102         // std_inject runs after feature checking so manually mark this attr
103         attr::mark_used(&no_std_attr);
104         krate.attrs.push(no_std_attr);
105
106         // only add `use std::prelude::*;` if there wasn't a
107         // `#![no_implicit_prelude]` at the crate level.
108         // fold_mod() will insert glob path.
109         if !no_prelude(&krate.attrs[]) {
110             krate.module = self.fold_mod(krate.module);
111         }
112         krate
113     }
114
115     fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
116         if !no_prelude(&item.attrs[]) {
117             // only recur if there wasn't `#![no_implicit_prelude]`
118             // on this item, i.e. this means that the prelude is not
119             // implicitly imported though the whole subtree
120             fold::noop_fold_item(item, self)
121         } else {
122             SmallVector::one(item)
123         }
124     }
125
126     fn fold_mod(&mut self, ast::Mod {inner, view_items, items}: ast::Mod) -> ast::Mod {
127         let prelude_path = ast::Path {
128             span: DUMMY_SP,
129             global: false,
130             segments: vec![
131                 ast::PathSegment {
132                     identifier: token::str_to_ident("std"),
133                     parameters: ast::PathParameters::none(),
134                 },
135                 ast::PathSegment {
136                     identifier: token::str_to_ident("prelude"),
137                     parameters: ast::PathParameters::none(),
138                 },
139                 ast::PathSegment {
140                     identifier: token::str_to_ident("v1"),
141                     parameters: ast::PathParameters::none(),
142                 },
143             ],
144         };
145
146         let (crates, uses): (Vec<_>, _) = view_items.iter().cloned().partition(|x| {
147             match x.node {
148                 ast::ViewItemExternCrate(..) => true,
149                 _ => false,
150             }
151         });
152
153         // add prelude after any `extern crate` but before any `use`
154         let mut view_items = crates;
155         let vp = P(codemap::dummy_spanned(ast::ViewPathGlob(prelude_path, ast::DUMMY_NODE_ID)));
156         view_items.push(ast::ViewItem {
157             node: ast::ViewItemUse(vp),
158             attrs: vec![ast::Attribute {
159                 span: DUMMY_SP,
160                 node: ast::Attribute_ {
161                     id: attr::mk_attr_id(),
162                     style: ast::AttrOuter,
163                     value: P(ast::MetaItem {
164                         span: DUMMY_SP,
165                         node: ast::MetaWord(token::get_name(
166                                 special_idents::prelude_import.name)),
167                     }),
168                     is_sugared_doc: false,
169                 },
170             }],
171             vis: ast::Inherited,
172             span: DUMMY_SP,
173         });
174         view_items.extend(uses.into_iter());
175
176         fold::noop_fold_mod(ast::Mod {
177             inner: inner,
178             view_items: view_items,
179             items: items
180         }, self)
181     }
182 }
183
184 fn inject_prelude(krate: ast::Crate) -> ast::Crate {
185     let mut fold = PreludeInjector;
186     fold.fold_crate(krate)
187 }