Skip to content

Commit d55fa2a

Browse files
committed
Add #env syntax extension for plucking strings out of the compilation environment.
1 parent a7db032 commit d55fa2a

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed

src/comp/front/extenv.rs

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
* The compiler code necessary to support the #env extension. Eventually this
3+
* should all get sucked into either the compiler syntax extension plugin
4+
* interface.
5+
*/
6+
7+
import util.common;
8+
9+
import std._str;
10+
import std._vec;
11+
import std.option;
12+
import std.GenericOS;
13+
14+
export expand_syntax_ext;
15+
16+
// FIXME: Need to thread parser through here to handle errors correctly
17+
fn expand_syntax_ext(parser.parser p,
18+
common.span sp,
19+
vec[@ast.expr] args,
20+
option.t[str] body) -> @ast.expr {
21+
22+
if (_vec.len[@ast.expr](args) != 1u) {
23+
p.err("malformed #env call");
24+
}
25+
26+
auto var = expr_to_str(p, args.(0));
27+
auto val = GenericOS.getenv(var);
28+
ret make_new_str(sp, val);
29+
}
30+
31+
// FIXME: duplicate code copied from extfmt.
32+
33+
fn expr_to_str(parser.parser p,
34+
@ast.expr expr) -> str {
35+
alt (expr.node) {
36+
case (ast.expr_lit(?l, _)) {
37+
alt (l.node) {
38+
case (ast.lit_str(?s)) {
39+
ret s;
40+
}
41+
}
42+
}
43+
}
44+
p.err("malformed #env call");
45+
fail;
46+
}
47+
48+
fn make_new_lit(common.span sp, ast.lit_ lit) -> @ast.expr {
49+
auto sp_lit = @rec(node=lit, span=sp);
50+
auto expr = ast.expr_lit(sp_lit, ast.ann_none);
51+
ret @rec(node=expr, span=sp);
52+
}
53+
54+
fn make_new_str(common.span sp, str s) -> @ast.expr {
55+
auto lit = ast.lit_str(s);
56+
ret make_new_lit(sp, lit);
57+
}
58+
59+
//
60+
// Local Variables:
61+
// mode: rust
62+
// fill-column: 78;
63+
// indent-tabs-mode: nil
64+
// c-basic-offset: 4
65+
// buffer-file-coding-system: utf-8-unix
66+
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
67+
// End:
68+
//

src/comp/front/parser.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -948,6 +948,13 @@ fn expand_syntax_ext(parser p, ast.span sp,
948948
expanded,
949949
ast.ann_none);
950950

951+
ret newexpr;
952+
} else if (_str.eq(extname, "env")) {
953+
auto expanded = extenv.expand_syntax_ext(p, sp, args, body);
954+
auto newexpr = ast.expr_ext(path, args, body,
955+
expanded,
956+
ast.ann_none);
957+
951958
ret newexpr;
952959
} else {
953960
p.err("unknown syntax extension");

src/comp/rustc.rc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ mod front {
2424
mod ast;
2525
mod creader;
2626
mod extfmt;
27+
mod extenv;
2728
mod codemap;
2829
mod lexer;
2930
mod parser;

0 commit comments

Comments
 (0)