]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/std_inject.rs
6784a2abe551c1340c64bf48b0eb40e52196ef9c
[rust.git] / src / libsyntax / std_inject.rs
1 use crate::ast;
2 use crate::attr;
3 use crate::edition::Edition;
4 use crate::ext::hygiene::{Mark, SyntaxContext};
5 use crate::symbol::{Symbol, keywords, sym};
6 use crate::source_map::{ExpnInfo, MacroAttribute, dummy_spanned, hygiene, respan};
7 use crate::ptr::P;
8 use crate::tokenstream::TokenStream;
9
10 use std::cell::Cell;
11 use std::iter;
12 use syntax_pos::{DUMMY_SP, Span};
13
14 /// Craft a span that will be ignored by the stability lint's
15 /// call to source_map's `is_internal` check.
16 /// The expanded code uses the unstable `#[prelude_import]` attribute.
17 fn ignored_span(sp: Span) -> Span {
18     let mark = Mark::fresh(Mark::root());
19     mark.set_expn_info(ExpnInfo {
20         call_site: DUMMY_SP,
21         def_site: None,
22         format: MacroAttribute(Symbol::intern("std_inject")),
23         allow_internal_unstable: Some(vec![
24             Symbol::intern("prelude_import"),
25         ].into()),
26         allow_internal_unsafe: false,
27         local_inner_macros: false,
28         edition: hygiene::default_edition(),
29     });
30     sp.with_ctxt(SyntaxContext::empty().apply_mark(mark))
31 }
32
33 pub fn injected_crate_name() -> Option<&'static str> {
34     INJECTED_CRATE_NAME.with(|name| name.get())
35 }
36
37 thread_local! {
38     // A `Symbol` might make more sense here, but it doesn't work, probably for
39     // reasons relating to the use of thread-local storage for the Symbol
40     // interner.
41     static INJECTED_CRATE_NAME: Cell<Option<&'static str>> = Cell::new(None);
42 }
43
44 pub fn maybe_inject_crates_ref(
45     mut krate: ast::Crate,
46     alt_std_name: Option<&str>,
47     edition: Edition,
48 ) -> ast::Crate {
49     let rust_2018 = edition >= Edition::Edition2018;
50
51     // the first name in this list is the crate name of the crate with the prelude
52     let names: &[&str] = if attr::contains_name(&krate.attrs, sym::no_core) {
53         return krate;
54     } else if attr::contains_name(&krate.attrs, sym::no_std) {
55         if attr::contains_name(&krate.attrs, sym::compiler_builtins) {
56             &["core"]
57         } else {
58             &["core", "compiler_builtins"]
59         }
60     } else {
61         &["std"]
62     };
63
64     // .rev() to preserve ordering above in combination with insert(0, ...)
65     let alt_std_name = alt_std_name.map(Symbol::intern);
66     for orig_name in names.iter().rev() {
67         let orig_name = Symbol::intern(orig_name);
68         let mut rename = orig_name;
69         // HACK(eddyb) gensym the injected crates on the Rust 2018 edition,
70         // so they don't accidentally interfere with the new import paths.
71         if rust_2018 {
72             rename = orig_name.gensymed();
73         }
74         let orig_name = if rename != orig_name {
75             Some(orig_name)
76         } else {
77             None
78         };
79         krate.module.items.insert(0, P(ast::Item {
80             attrs: vec![attr::mk_attr_outer(
81                 DUMMY_SP,
82                 attr::mk_attr_id(),
83                 attr::mk_word_item(ast::Ident::with_empty_ctxt(sym::macro_use))
84             )],
85             vis: dummy_spanned(ast::VisibilityKind::Inherited),
86             node: ast::ItemKind::ExternCrate(alt_std_name.or(orig_name)),
87             ident: ast::Ident::with_empty_ctxt(rename),
88             id: ast::DUMMY_NODE_ID,
89             span: DUMMY_SP,
90             tokens: None,
91         }));
92     }
93
94     // the crates have been injected, the assumption is that the first one is the one with
95     // the prelude.
96     let name = names[0];
97
98     INJECTED_CRATE_NAME.with(|opt_name| opt_name.set(Some(name)));
99
100     let span = ignored_span(DUMMY_SP);
101     krate.module.items.insert(0, P(ast::Item {
102         attrs: vec![ast::Attribute {
103             style: ast::AttrStyle::Outer,
104             path: ast::Path::from_ident(ast::Ident::new(Symbol::intern("prelude_import"), span)),
105             tokens: TokenStream::empty(),
106             id: attr::mk_attr_id(),
107             is_sugared_doc: false,
108             span,
109         }],
110         vis: respan(span.shrink_to_lo(), ast::VisibilityKind::Inherited),
111         node: ast::ItemKind::Use(P(ast::UseTree {
112             prefix: ast::Path {
113                 segments: iter::once(keywords::PathRoot.ident())
114                     .chain(
115                         [name, "prelude", "v1"].iter().cloned()
116                             .map(ast::Ident::from_str)
117                     ).map(ast::PathSegment::from_ident).collect(),
118                 span,
119             },
120             kind: ast::UseTreeKind::Glob,
121             span,
122         })),
123         id: ast::DUMMY_NODE_ID,
124         ident: keywords::Invalid.ident(),
125         span,
126         tokens: None,
127     }));
128
129     krate
130 }