1 use syntax::{ast, attr};
2 use syntax::edition::Edition;
3 use syntax::ext::hygiene::{ExpnId, MacroKind};
5 use syntax::source_map::{ExpnInfo, ExpnKind, dummy_spanned, respan};
6 use syntax::symbol::{Ident, Symbol, kw, sym};
7 use syntax::tokenstream::TokenStream;
8 use syntax_pos::DUMMY_SP;
13 mut krate: ast::Crate, alt_std_name: Option<&str>, edition: Edition
14 ) -> (ast::Crate, Option<Symbol>) {
15 let rust_2018 = edition >= Edition::Edition2018;
17 // the first name in this list is the crate name of the crate with the prelude
18 let names: &[&str] = if attr::contains_name(&krate.attrs, sym::no_core) {
20 } else if attr::contains_name(&krate.attrs, sym::no_std) {
21 if attr::contains_name(&krate.attrs, sym::compiler_builtins) {
24 &["core", "compiler_builtins"]
30 // .rev() to preserve ordering above in combination with insert(0, ...)
31 let alt_std_name = alt_std_name.map(Symbol::intern);
32 for orig_name_str in names.iter().rev() {
33 // HACK(eddyb) gensym the injected crates on the Rust 2018 edition,
34 // so they don't accidentally interfere with the new import paths.
35 let orig_name_sym = Symbol::intern(orig_name_str);
36 let orig_name_ident = Ident::with_empty_ctxt(orig_name_sym);
37 let (rename, orig_name) = if rust_2018 {
38 (orig_name_ident.gensym(), Some(orig_name_sym))
40 (orig_name_ident, None)
42 krate.module.items.insert(0, P(ast::Item {
43 attrs: vec![attr::mk_attr_outer(
46 attr::mk_word_item(ast::Ident::with_empty_ctxt(sym::macro_use))
48 vis: dummy_spanned(ast::VisibilityKind::Inherited),
49 node: ast::ItemKind::ExternCrate(alt_std_name.or(orig_name)),
51 id: ast::DUMMY_NODE_ID,
57 // the crates have been injected, the assumption is that the first one is the one with
61 let span = DUMMY_SP.fresh_expansion(ExpnId::root(), ExpnInfo::allow_unstable(
62 ExpnKind::Macro(MacroKind::Attr, sym::std_inject), DUMMY_SP, edition,
63 [sym::prelude_import][..].into(),
66 krate.module.items.insert(0, P(ast::Item {
67 attrs: vec![ast::Attribute {
68 style: ast::AttrStyle::Outer,
69 path: ast::Path::from_ident(ast::Ident::new(sym::prelude_import, span)),
70 tokens: TokenStream::empty(),
71 id: attr::mk_attr_id(),
72 is_sugared_doc: false,
75 vis: respan(span.shrink_to_lo(), ast::VisibilityKind::Inherited),
76 node: ast::ItemKind::Use(P(ast::UseTree {
78 segments: iter::once(ast::Ident::with_empty_ctxt(kw::PathRoot))
80 [name, "prelude", "v1"].iter().cloned()
81 .map(ast::Ident::from_str)
82 ).map(ast::PathSegment::from_ident).collect(),
85 kind: ast::UseTreeKind::Glob,
88 id: ast::DUMMY_NODE_ID,
89 ident: ast::Ident::invalid(),
94 (krate, Some(Symbol::intern(name)))