Skip to content

Commit c45986a

Browse files
authored
Rollup merge of rust-lang#130883 - madsmtm:env-var-query, r=petrochenkov
Add environment variable query Generally, `rustc` prefers command-line arguments, but in some cases, an environment variable really is the most sensible option. We should make sure that this works properly with the compiler's change-tracking mechanisms, such that changing the relevant environment variable causes a rebuild. This PR is a first step forwards in doing that. Part of the work needed to do rust-lang#118204, see rust-lang#129342 for some discussion. r? ``@petrochenkov``
2 parents 2216f26 + 632ce38 commit c45986a

File tree

10 files changed

+118
-7
lines changed

10 files changed

+118
-7
lines changed

compiler/rustc_borrowck/src/nll.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
//! The entry point of the NLL borrow checker.
22
3+
use std::io;
34
use std::path::PathBuf;
45
use std::rc::Rc;
56
use std::str::FromStr;
6-
use std::{env, io};
77

88
use polonius_engine::{Algorithm, Output};
99
use rustc_index::IndexSlice;
@@ -162,9 +162,8 @@ pub(crate) fn compute_regions<'a, 'tcx>(
162162
}
163163

164164
if polonius_output {
165-
let algorithm =
166-
env::var("POLONIUS_ALGORITHM").unwrap_or_else(|_| String::from("Hybrid"));
167-
let algorithm = Algorithm::from_str(&algorithm).unwrap();
165+
let algorithm = infcx.tcx.env_var("POLONIUS_ALGORITHM").unwrap_or("Hybrid");
166+
let algorithm = Algorithm::from_str(algorithm).unwrap();
168167
debug!("compute_regions: using polonius algorithm {:?}", algorithm);
169168
let _prof_timer = infcx.tcx.prof.generic_activity("polonius_analysis");
170169
Some(Box::new(Output::compute(polonius_facts, algorithm, false)))

compiler/rustc_data_structures/src/stable_hasher.rs

+2
Original file line numberDiff line numberDiff line change
@@ -564,6 +564,8 @@ where
564564
}
565565
}
566566

567+
impl_stable_traits_for_trivial_type!(::std::ffi::OsStr);
568+
567569
impl_stable_traits_for_trivial_type!(::std::path::Path);
568570
impl_stable_traits_for_trivial_type!(::std::path::PathBuf);
569571

compiler/rustc_interface/src/passes.rs

+27-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use std::any::Any;
2-
use std::ffi::OsString;
2+
use std::ffi::{OsStr, OsString};
33
use std::io::{self, BufWriter, Write};
44
use std::path::{Path, PathBuf};
55
use std::sync::{Arc, LazyLock, OnceLock};
@@ -361,6 +361,31 @@ fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) {
361361
)
362362
}
363363

364+
fn env_var_os<'tcx>(tcx: TyCtxt<'tcx>, key: &'tcx OsStr) -> Option<&'tcx OsStr> {
365+
let value = env::var_os(key);
366+
367+
let value_tcx = value.as_ref().map(|value| {
368+
let encoded_bytes = tcx.arena.alloc_slice(value.as_encoded_bytes());
369+
debug_assert_eq!(value.as_encoded_bytes(), encoded_bytes);
370+
// SAFETY: The bytes came from `as_encoded_bytes`, and we assume that
371+
// `alloc_slice` is implemented correctly, and passes the same bytes
372+
// back (debug asserted above).
373+
unsafe { OsStr::from_encoded_bytes_unchecked(encoded_bytes) }
374+
});
375+
376+
// Also add the variable to Cargo's dependency tracking
377+
//
378+
// NOTE: This only works for passes run before `write_dep_info`. See that
379+
// for extension points for configuring environment variables to be
380+
// properly change-tracked.
381+
tcx.sess.psess.env_depinfo.borrow_mut().insert((
382+
Symbol::intern(&key.to_string_lossy()),
383+
value.as_ref().and_then(|value| value.to_str()).map(|value| Symbol::intern(&value)),
384+
));
385+
386+
value_tcx
387+
}
388+
364389
// Returns all the paths that correspond to generated files.
365390
fn generated_output_paths(
366391
tcx: TyCtxt<'_>,
@@ -725,6 +750,7 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
725750
|tcx, _| tcx.arena.alloc_from_iter(tcx.resolutions(()).stripped_cfg_items.steal());
726751
providers.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
727752
providers.early_lint_checks = early_lint_checks;
753+
providers.env_var_os = env_var_os;
728754
limits::provide(providers);
729755
proc_macro_decls::provide(providers);
730756
rustc_const_eval::provide(providers);

compiler/rustc_lint/src/non_local_def.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,10 @@ impl<'tcx> LateLintPass<'tcx> for NonLocalDefinitions {
104104
// determining if we are in a doctest context can't currently be determined
105105
// by the code itself (there are no specific attributes), but fortunately rustdoc
106106
// sets a perma-unstable env var for libtest so we just reuse that for now
107-
let is_at_toplevel_doctest =
108-
|| self.body_depth == 2 && std::env::var("UNSTABLE_RUSTDOC_TEST_PATH").is_ok();
107+
let is_at_toplevel_doctest = || {
108+
self.body_depth == 2
109+
&& cx.tcx.env_var_os("UNSTABLE_RUSTDOC_TEST_PATH".as_ref()).is_some()
110+
};
109111

110112
match item.kind {
111113
ItemKind::Impl(impl_) => {

compiler/rustc_middle/src/query/erase.rs

+9
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::ffi::OsStr;
12
use std::intrinsics::transmute_unchecked;
23
use std::mem::MaybeUninit;
34

@@ -67,6 +68,10 @@ impl<T> EraseType for &'_ [T] {
6768
type Result = [u8; size_of::<&'static [()]>()];
6869
}
6970

71+
impl EraseType for &'_ OsStr {
72+
type Result = [u8; size_of::<&'static OsStr>()];
73+
}
74+
7075
impl<T> EraseType for &'_ ty::List<T> {
7176
type Result = [u8; size_of::<&'static ty::List<()>>()];
7277
}
@@ -174,6 +179,10 @@ impl<T> EraseType for Option<&'_ [T]> {
174179
type Result = [u8; size_of::<Option<&'static [()]>>()];
175180
}
176181

182+
impl EraseType for Option<&'_ OsStr> {
183+
type Result = [u8; size_of::<Option<&'static OsStr>>()];
184+
}
185+
177186
impl EraseType for Option<mir::DestructuredConstant<'_>> {
178187
type Result = [u8; size_of::<Option<mir::DestructuredConstant<'static>>>()];
179188
}

compiler/rustc_middle/src/query/keys.rs

+10
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
//! Defines the set of legal keys that can be used in queries.
22
3+
use std::ffi::OsStr;
4+
35
use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalModDefId, ModDefId};
46
use rustc_hir::hir_id::{HirId, OwnerId};
57
use rustc_query_system::dep_graph::DepNodeIndex;
@@ -498,6 +500,14 @@ impl Key for Option<Symbol> {
498500
}
499501
}
500502

503+
impl<'tcx> Key for &'tcx OsStr {
504+
type Cache<V> = DefaultCache<Self, V>;
505+
506+
fn default_span(&self, _tcx: TyCtxt<'_>) -> Span {
507+
DUMMY_SP
508+
}
509+
}
510+
501511
/// Canonical query goals correspond to abstract trait operations that
502512
/// are not tied to any crate in particular.
503513
impl<'tcx, T: Clone> Key for CanonicalQueryInput<'tcx, T> {

compiler/rustc_middle/src/query/mod.rs

+16
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
77
#![allow(unused_parens)]
88

9+
use std::ffi::OsStr;
910
use std::mem;
1011
use std::path::PathBuf;
1112
use std::sync::Arc;
@@ -119,6 +120,21 @@ rustc_queries! {
119120
desc { "perform lints prior to AST lowering" }
120121
}
121122

123+
/// Tracked access to environment variables.
124+
///
125+
/// Useful for the implementation of `std::env!`, `proc-macro`s change
126+
/// detection and other changes in the compiler's behaviour that is easier
127+
/// to control with an environment variable than a flag.
128+
///
129+
/// NOTE: This currently does not work with dependency info in the
130+
/// analysis, codegen and linking passes, place extra code at the top of
131+
/// `rustc_interface::passes::write_dep_info` to make that work.
132+
query env_var_os(key: &'tcx OsStr) -> Option<&'tcx OsStr> {
133+
// Environment variables are global state
134+
eval_always
135+
desc { "get the value of an environment variable" }
136+
}
137+
122138
query resolutions(_: ()) -> &'tcx ty::ResolverGlobalCtxt {
123139
no_hash
124140
desc { "getting the resolver outputs" }

compiler/rustc_middle/src/ty/context.rs

+11
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ pub mod tls;
77
use std::assert_matches::{assert_matches, debug_assert_matches};
88
use std::borrow::Borrow;
99
use std::cmp::Ordering;
10+
use std::env::VarError;
11+
use std::ffi::OsStr;
1012
use std::hash::{Hash, Hasher};
1113
use std::marker::PhantomData;
1214
use std::ops::{Bound, Deref};
@@ -1883,6 +1885,15 @@ impl<'tcx> TyCtxt<'tcx> {
18831885
}
18841886
None
18851887
}
1888+
1889+
/// Helper to get a tracked environment variable via. [`TyCtxt::env_var_os`] and converting to
1890+
/// UTF-8 like [`std::env::var`].
1891+
pub fn env_var<K: ?Sized + AsRef<OsStr>>(self, key: &'tcx K) -> Result<&'tcx str, VarError> {
1892+
match self.env_var_os(key.as_ref()) {
1893+
Some(value) => value.to_str().ok_or_else(|| VarError::NotUnicode(value.to_os_string())),
1894+
None => Err(VarError::NotPresent),
1895+
}
1896+
}
18861897
}
18871898

18881899
impl<'tcx> TyCtxtAt<'tcx> {

tests/incremental/env/env_macro.rs

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Check that changes to environment variables are propagated to `env!`.
2+
//
3+
// This test is intentionally written to not use any `#[cfg(rpass*)]`, to
4+
// _really_ test that we re-compile if the environment variable changes.
5+
6+
//@ revisions: cfail1 rpass2 rpass3 cfail4
7+
//@ [cfail1]unset-rustc-env:EXAMPLE_ENV
8+
//@ [rpass2]rustc-env:EXAMPLE_ENV=one
9+
//@ [rpass2]exec-env:EXAMPLE_ENV=one
10+
//@ [rpass3]rustc-env:EXAMPLE_ENV=two
11+
//@ [rpass3]exec-env:EXAMPLE_ENV=two
12+
//@ [cfail4]unset-rustc-env:EXAMPLE_ENV
13+
14+
fn main() {
15+
assert_eq!(env!("EXAMPLE_ENV"), std::env::var("EXAMPLE_ENV").unwrap());
16+
//[cfail1]~^ ERROR environment variable `EXAMPLE_ENV` not defined at compile time
17+
//[cfail4]~^^ ERROR environment variable `EXAMPLE_ENV` not defined at compile time
18+
}
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Check that changes to environment variables are propagated to `option_env!`.
2+
//
3+
// This test is intentionally written to not use any `#[cfg(rpass*)]`, to
4+
// _really_ test that we re-compile if the environment variable changes.
5+
6+
//@ revisions: rpass1 rpass2 rpass3 rpass4
7+
//@ [rpass1]unset-rustc-env:EXAMPLE_ENV
8+
//@ [rpass1]unset-exec-env:EXAMPLE_ENV
9+
//@ [rpass2]rustc-env:EXAMPLE_ENV=one
10+
//@ [rpass2]exec-env:EXAMPLE_ENV=one
11+
//@ [rpass3]rustc-env:EXAMPLE_ENV=two
12+
//@ [rpass3]exec-env:EXAMPLE_ENV=two
13+
//@ [rpass4]unset-rustc-env:EXAMPLE_ENV
14+
//@ [rpass4]unset-exec-env:EXAMPLE_ENV
15+
16+
fn main() {
17+
assert_eq!(option_env!("EXAMPLE_ENV"), std::env::var("EXAMPLE_ENV").ok().as_deref());
18+
}

0 commit comments

Comments
 (0)