]> git.proxmox.com Git - rustc.git/blob - src/librustc_builtin_macros/standard_library_imports.rs
New upstream version 1.46.0~beta.2+dfsg1
[rustc.git] / src / librustc_builtin_macros / standard_library_imports.rs
1 use rustc_ast::ptr::P;
2 use rustc_ast::{ast, attr};
3 use rustc_expand::base::{ExtCtxt, ResolverExpand};
4 use rustc_expand::expand::ExpansionConfig;
5 use rustc_session::parse::ParseSess;
6 use rustc_span::edition::Edition;
7 use rustc_span::hygiene::AstPass;
8 use rustc_span::symbol::{kw, sym, Ident, Symbol};
9 use rustc_span::DUMMY_SP;
10
11 pub fn inject(
12 mut krate: ast::Crate,
13 resolver: &mut dyn ResolverExpand,
14 sess: &ParseSess,
15 alt_std_name: Option<Symbol>,
16 ) -> (ast::Crate, Option<Symbol>) {
17 let rust_2018 = sess.edition >= Edition::Edition2018;
18
19 // the first name in this list is the crate name of the crate with the prelude
20 let names: &[Symbol] = if attr::contains_name(&krate.attrs, sym::no_core) {
21 return (krate, None);
22 } else if attr::contains_name(&krate.attrs, sym::no_std) {
23 if attr::contains_name(&krate.attrs, sym::compiler_builtins) {
24 &[sym::core]
25 } else {
26 &[sym::core, sym::compiler_builtins]
27 }
28 } else {
29 &[sym::std]
30 };
31
32 let expn_id = resolver.expansion_for_ast_pass(
33 DUMMY_SP,
34 AstPass::StdImports,
35 &[sym::prelude_import],
36 None,
37 );
38 let span = DUMMY_SP.with_def_site_ctxt(expn_id);
39 let call_site = DUMMY_SP.with_call_site_ctxt(expn_id);
40
41 let ecfg = ExpansionConfig::default("std_lib_injection".to_string());
42 let cx = ExtCtxt::new(sess, ecfg, resolver, None);
43
44 // .rev() to preserve ordering above in combination with insert(0, ...)
45 for &name in names.iter().rev() {
46 let ident = if rust_2018 { Ident::new(name, span) } else { Ident::new(name, call_site) };
47 krate.module.items.insert(
48 0,
49 cx.item(
50 span,
51 ident,
52 vec![cx.attribute(cx.meta_word(span, sym::macro_use))],
53 ast::ItemKind::ExternCrate(alt_std_name),
54 ),
55 );
56 }
57
58 // The crates have been injected, the assumption is that the first one is
59 // the one with the prelude.
60 let name = names[0];
61
62 let import_path = if rust_2018 {
63 [name, sym::prelude, sym::v1].iter().map(|symbol| Ident::new(*symbol, span)).collect()
64 } else {
65 [kw::PathRoot, name, sym::prelude, sym::v1]
66 .iter()
67 .map(|symbol| Ident::new(*symbol, span))
68 .collect()
69 };
70
71 let use_item = cx.item(
72 span,
73 Ident::invalid(),
74 vec![cx.attribute(cx.meta_word(span, sym::prelude_import))],
75 ast::ItemKind::Use(P(ast::UseTree {
76 prefix: cx.path(span, import_path),
77 kind: ast::UseTreeKind::Glob,
78 span,
79 })),
80 );
81
82 krate.module.items.insert(0, use_item);
83
84 (krate, Some(name))
85 }