1 // The compiler code necessary to support the env! extension. Eventually this
2 // should all get sucked into either the compiler syntax extension plugin
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}
;
14 pub fn expand_option_env
<'cx
>(
15 cx
: &'cx
mut ExtCtxt
<'_
>,
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
),
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
));
29 let lt
= cx
.lifetime(sp
, Ident
::new(kw
::StaticLifetime
, sp
));
30 cx
.expr_path(cx
.path_all(
33 cx
.std_path(&[sym
::option
, sym
::Option
, sym
::None
]),
34 vec
![GenericArg
::Type(cx
.ty_rptr(
36 cx
.ty_ident(sp
, Ident
::new(sym
::str, sp
)),
42 Some(value
) => cx
.expr_call_global(
44 cx
.std_path(&[sym
::option
, sym
::Option
, sym
::Some
]),
45 vec
![cx
.expr_str(sp
, value
)],
51 pub fn expand_env
<'cx
>(
52 cx
: &'cx
mut ExtCtxt
<'_
>,
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
);
61 None
=> return DummyResult
::any(sp
),
62 Some(exprs
) => exprs
.into_iter(),
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
,
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
,
77 if exprs
.next().is_some() {
78 cx
.span_err(sp
, "env! takes 1 or 2 arguments");
79 return DummyResult
::any(sp
);
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
));
87 cx
.span_err(sp
, &msg
.as_str());
88 return DummyResult
::any(sp
);
90 Some(value
) => cx
.expr_str(sp
, value
),