Skip to content

Commit 486e55e

Browse files
committedDec 10, 2023
Implement --env compiler flag
1 parent 8043f62 commit 486e55e

File tree

3 files changed

+55
-3
lines changed

3 files changed

+55
-3
lines changed
 

‎compiler/rustc_builtin_macros/src/env.rs

+12-2
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,16 @@ use thin_vec::thin_vec;
1313

1414
use crate::errors;
1515

16+
fn lookup_env<'cx>(cx: &'cx ExtCtxt<'_>, var: Symbol) -> Option<Symbol> {
17+
let var = var.as_str();
18+
if let Some(value) = cx.sess.opts.logical_env.get(var) {
19+
return Some(Symbol::intern(value));
20+
}
21+
// If the environment variable was not defined with the `--env` option, we try to retrieve it
22+
// from rustc's environment.
23+
env::var(var).ok().as_deref().map(Symbol::intern)
24+
}
25+
1626
pub fn expand_option_env<'cx>(
1727
cx: &'cx mut ExtCtxt<'_>,
1828
sp: Span,
@@ -23,7 +33,7 @@ pub fn expand_option_env<'cx>(
2333
};
2434

2535
let sp = cx.with_def_site_ctxt(sp);
26-
let value = env::var(var.as_str()).ok().as_deref().map(Symbol::intern);
36+
let value = lookup_env(cx, var);
2737
cx.sess.parse_sess.env_depinfo.borrow_mut().insert((var, value));
2838
let e = match value {
2939
None => {
@@ -77,7 +87,7 @@ pub fn expand_env<'cx>(
7787
};
7888

7989
let span = cx.with_def_site_ctxt(sp);
80-
let value = env::var(var.as_str()).ok().as_deref().map(Symbol::intern);
90+
let value = lookup_env(cx, var);
8191
cx.sess.parse_sess.env_depinfo.borrow_mut().insert((var, value));
8292
let e = match value {
8393
None => {

‎compiler/rustc_session/src/config.rs

+39-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use crate::search_paths::SearchPath;
88
use crate::utils::{CanonicalizedPath, NativeLib, NativeLibKind};
99
use crate::{lint, HashStableContext};
1010
use crate::{EarlyErrorHandler, Session};
11-
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
11+
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
1212
use rustc_data_structures::stable_hasher::{StableOrd, ToStableHashKey};
1313
use rustc_errors::emitter::HumanReadableErrorType;
1414
use rustc_errors::{ColorConfig, DiagnosticArgValue, HandlerFlags, IntoDiagnosticArg};
@@ -1114,6 +1114,7 @@ impl Default for Options {
11141114
pretty: None,
11151115
working_dir: RealFileName::LocalPath(std::env::current_dir().unwrap()),
11161116
color: ColorConfig::Auto,
1117+
logical_env: FxIndexMap::default(),
11171118
}
11181119
}
11191120
}
@@ -1810,6 +1811,7 @@ pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
18101811
"Remap source names in all output (compiler messages and output files)",
18111812
"FROM=TO",
18121813
),
1814+
opt::multi("", "env", "Inject an environment variable", "VAR=VALUE"),
18131815
]);
18141816
opts
18151817
}
@@ -2589,6 +2591,23 @@ fn parse_remap_path_prefix(
25892591
mapping
25902592
}
25912593

2594+
fn parse_logical_env(
2595+
handler: &mut EarlyErrorHandler,
2596+
matches: &getopts::Matches,
2597+
) -> FxIndexMap<String, String> {
2598+
let mut vars = FxIndexMap::default();
2599+
2600+
for arg in matches.opt_strs("env") {
2601+
if let Some((name, val)) = arg.split_once('=') {
2602+
vars.insert(name.to_string(), val.to_string());
2603+
} else {
2604+
handler.early_error(format!("`--env`: specify value for variable `{arg}`"));
2605+
}
2606+
}
2607+
2608+
vars
2609+
}
2610+
25922611
// JUSTIFICATION: before wrapper fn is available
25932612
#[allow(rustc::bad_opt_access)]
25942613
pub fn build_session_options(
@@ -2827,6 +2846,8 @@ pub fn build_session_options(
28272846
handler.early_error("can't dump dependency graph without `-Z query-dep-graph`");
28282847
}
28292848

2849+
let logical_env = parse_logical_env(handler, matches);
2850+
28302851
// Try to find a directory containing the Rust `src`, for more details see
28312852
// the doc comment on the `real_rust_source_base_dir` field.
28322853
let tmp_buf;
@@ -2907,6 +2928,7 @@ pub fn build_session_options(
29072928
pretty,
29082929
working_dir,
29092930
color,
2931+
logical_env,
29102932
}
29112933
}
29122934

@@ -3181,6 +3203,7 @@ pub(crate) mod dep_tracking {
31813203
};
31823204
use crate::lint;
31833205
use crate::utils::NativeLib;
3206+
use rustc_data_structures::fx::FxIndexMap;
31843207
use rustc_data_structures::stable_hasher::Hash64;
31853208
use rustc_errors::LanguageIdentifier;
31863209
use rustc_feature::UnstableFeatures;
@@ -3339,6 +3362,21 @@ pub(crate) mod dep_tracking {
33393362
}
33403363
}
33413364

3365+
impl<T: DepTrackingHash, V: DepTrackingHash> DepTrackingHash for FxIndexMap<T, V> {
3366+
fn hash(
3367+
&self,
3368+
hasher: &mut DefaultHasher,
3369+
error_format: ErrorOutputType,
3370+
for_crate_hash: bool,
3371+
) {
3372+
Hash::hash(&self.len(), hasher);
3373+
for (key, value) in self.iter() {
3374+
DepTrackingHash::hash(key, hasher, error_format, for_crate_hash);
3375+
DepTrackingHash::hash(value, hasher, error_format, for_crate_hash);
3376+
}
3377+
}
3378+
}
3379+
33423380
impl DepTrackingHash for OutputTypes {
33433381
fn hash(
33443382
&self,

‎compiler/rustc_session/src/options.rs

+4
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use crate::config::*;
33
use crate::search_paths::SearchPath;
44
use crate::utils::NativeLib;
55
use crate::{lint, EarlyErrorHandler};
6+
use rustc_data_structures::fx::FxIndexMap;
67
use rustc_data_structures::profiling::TimePassesFormat;
78
use rustc_data_structures::stable_hasher::Hash64;
89
use rustc_errors::ColorConfig;
@@ -150,6 +151,9 @@ top_level_options!(
150151

151152
target_triple: TargetTriple [TRACKED],
152153

154+
/// Effective logical environment used by `env!`/`option_env!` macros
155+
logical_env: FxIndexMap<String, String> [TRACKED],
156+
153157
test: bool [TRACKED],
154158
error_format: ErrorOutputType [UNTRACKED],
155159
diagnostic_width: Option<usize> [UNTRACKED],

0 commit comments

Comments
 (0)
Please sign in to comment.