2 use rustc_expand::base::{ExtCtxt, ResolverExpand};
3 use rustc_expand::expand::ExpansionConfig;
4 use rustc_session::Session;
5 use rustc_span::edition::Edition::*;
6 use rustc_span::hygiene::AstPass;
7 use rustc_span::symbol::{kw, sym, Ident, Symbol};
8 use rustc_span::DUMMY_SP;
9 use thin_vec::thin_vec;
12 mut krate: ast::Crate,
13 resolver: &mut dyn ResolverExpand,
16 let edition = sess.parse_sess.edition;
18 // the first name in this list is the crate name of the crate with the prelude
19 let names: &[Symbol] = if sess.contains_name(&krate.attrs, sym::no_core) {
21 } else if sess.contains_name(&krate.attrs, sym::no_std) {
22 if sess.contains_name(&krate.attrs, sym::compiler_builtins) {
25 &[sym::core, sym::compiler_builtins]
31 let expn_id = resolver.expansion_for_ast_pass(
34 &[sym::prelude_import],
37 let span = DUMMY_SP.with_def_site_ctxt(expn_id.to_expn_id());
38 let call_site = DUMMY_SP.with_call_site_ctxt(expn_id.to_expn_id());
40 let ecfg = ExpansionConfig::default("std_lib_injection".to_string());
41 let cx = ExtCtxt::new(sess, ecfg, resolver, None);
43 // .rev() to preserve ordering above in combination with insert(0, ...)
44 for &name in names.iter().rev() {
45 let ident = if edition >= Edition2018 {
46 Ident::new(name, span)
48 Ident::new(name, call_site)
55 thin_vec![cx.attribute(cx.meta_word(span, sym::macro_use))],
56 ast::ItemKind::ExternCrate(None),
61 // The crates have been injected, the assumption is that the first one is
62 // the one with the prelude.
65 let root = (edition == Edition2015).then(|| kw::PathRoot);
67 let import_path = root
69 .chain(&[name, sym::prelude])
70 .chain(&[match edition {
71 Edition2015 => sym::rust_2015,
72 Edition2018 => sym::rust_2018,
73 Edition2021 => sym::rust_2021,
74 Edition2024 => sym::rust_2024,
76 .map(|&symbol| Ident::new(symbol, span))
79 let use_item = cx.item(
82 thin_vec![cx.attribute(cx.meta_word(span, sym::prelude_import))],
83 ast::ItemKind::Use(ast::UseTree {
84 prefix: cx.path(span, import_path),
85 kind: ast::UseTreeKind::Glob,
90 krate.items.insert(0, use_item);