1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // The compiler code necessary to support the env! extension. Eventually this
12 // should all get sucked into either the compiler syntax extension plugin
16 use syntax::ast::{self, Ident};
17 use syntax::ext::base::*;
18 use syntax::ext::base;
19 use syntax::ext::build::AstBuilder;
20 use syntax::symbol::Symbol;
22 use syntax::tokenstream;
26 pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt,
28 tts: &[tokenstream::TokenTree])
29 -> Box<base::MacResult + 'cx> {
30 let var = match get_single_str_from_tts(cx, sp, tts, "option_env!") {
31 None => return DummyResult::expr(sp),
35 let e = match env::var(&*var.as_str()) {
37 cx.expr_path(cx.path_all(sp,
39 cx.std_path(&["option", "Option", "None"]),
42 cx.ty_ident(sp, Ident::from_str("str")),
44 Ident::from_str("'static"))),
45 ast::Mutability::Immutable)],
49 cx.expr_call_global(sp,
50 cx.std_path(&["option", "Option", "Some"]),
51 vec![cx.expr_str(sp, Symbol::intern(&s))])
57 pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt,
59 tts: &[tokenstream::TokenTree])
60 -> Box<base::MacResult + 'cx> {
61 let mut exprs = match get_exprs_from_tts(cx, sp, tts) {
62 Some(ref exprs) if exprs.is_empty() => {
63 cx.span_err(sp, "env! takes 1 or 2 arguments");
64 return DummyResult::expr(sp);
66 None => return DummyResult::expr(sp),
67 Some(exprs) => exprs.into_iter(),
70 let var = match expr_to_string(cx, exprs.next().unwrap(), "expected string literal") {
71 None => return DummyResult::expr(sp),
72 Some((v, _style)) => v,
74 let msg = match exprs.next() {
75 None => Symbol::intern(&format!("environment variable `{}` not defined", var)),
77 match expr_to_string(cx, second, "expected string literal") {
78 None => return DummyResult::expr(sp),
79 Some((s, _style)) => s,
84 if let Some(_) = exprs.next() {
85 cx.span_err(sp, "env! takes 1 or 2 arguments");
86 return DummyResult::expr(sp);
89 let e = match env::var(&*var.as_str()) {
91 cx.span_err(sp, &msg.as_str());
94 Ok(s) => cx.expr_str(sp, Symbol::intern(&s)),