]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_builtin_macros/src/env.rs
New upstream version 1.48.0~beta.8+dfsg1
[rustc.git] / compiler / rustc_builtin_macros / src / env.rs
1 // The compiler code necessary to support the env! extension. Eventually this
2 // should all get sucked into either the compiler syntax extension plugin
3 // interface.
4 //
5
6 use rustc_ast::tokenstream::TokenStream;
7 use rustc_ast::{self as ast, GenericArg};
8 use rustc_expand::base::{self, *};
9 use rustc_span::symbol::{kw, sym, Ident, Symbol};
10 use rustc_span::Span;
11
12 use std::env;
13
14 pub fn expand_option_env<'cx>(
15 cx: &'cx mut ExtCtxt<'_>,
16 sp: Span,
17 tts: TokenStream,
18 ) -> Box<dyn base::MacResult + 'cx> {
19 let var = match get_single_str_from_tts(cx, sp, tts, "option_env!") {
20 None => return DummyResult::any(sp),
21 Some(v) => v,
22 };
23
24 let sp = cx.with_def_site_ctxt(sp);
25 let value = env::var(&var.as_str()).ok().as_deref().map(Symbol::intern);
26 cx.sess.parse_sess.env_depinfo.borrow_mut().insert((Symbol::intern(&var), value));
27 let e = match value {
28 None => {
29 let lt = cx.lifetime(sp, Ident::new(kw::StaticLifetime, sp));
30 cx.expr_path(cx.path_all(
31 sp,
32 true,
33 cx.std_path(&[sym::option, sym::Option, sym::None]),
34 vec![GenericArg::Type(cx.ty_rptr(
35 sp,
36 cx.ty_ident(sp, Ident::new(sym::str, sp)),
37 Some(lt),
38 ast::Mutability::Not,
39 ))],
40 ))
41 }
42 Some(value) => cx.expr_call_global(
43 sp,
44 cx.std_path(&[sym::option, sym::Option, sym::Some]),
45 vec![cx.expr_str(sp, value)],
46 ),
47 };
48 MacEager::expr(e)
49 }
50
51 pub fn expand_env<'cx>(
52 cx: &'cx mut ExtCtxt<'_>,
53 sp: Span,
54 tts: TokenStream,
55 ) -> Box<dyn base::MacResult + 'cx> {
56 let mut exprs = match get_exprs_from_tts(cx, sp, tts) {
57 Some(ref exprs) if exprs.is_empty() => {
58 cx.span_err(sp, "env! takes 1 or 2 arguments");
59 return DummyResult::any(sp);
60 }
61 None => return DummyResult::any(sp),
62 Some(exprs) => exprs.into_iter(),
63 };
64
65 let var = match expr_to_string(cx, exprs.next().unwrap(), "expected string literal") {
66 None => return DummyResult::any(sp),
67 Some((v, _style)) => v,
68 };
69 let msg = match exprs.next() {
70 None => Symbol::intern(&format!("environment variable `{}` not defined", var)),
71 Some(second) => match expr_to_string(cx, second, "expected string literal") {
72 None => return DummyResult::any(sp),
73 Some((s, _style)) => s,
74 },
75 };
76
77 if exprs.next().is_some() {
78 cx.span_err(sp, "env! takes 1 or 2 arguments");
79 return DummyResult::any(sp);
80 }
81
82 let sp = cx.with_def_site_ctxt(sp);
83 let value = env::var(&*var.as_str()).ok().as_deref().map(Symbol::intern);
84 cx.sess.parse_sess.env_depinfo.borrow_mut().insert((var, value));
85 let e = match value {
86 None => {
87 cx.span_err(sp, &msg.as_str());
88 return DummyResult::any(sp);
89 }
90 Some(value) => cx.expr_str(sp, value),
91 };
92 MacEager::expr(e)
93 }