Deprecate `std::env::{vars, args}` #4021
Renaming is not actionable. Edition is not a free card for breaking APIs. There is a reason why we still keep stuff like before_exec or trim_left around.
There are other options for std::env::vars, such as:
1. We could add a helper method to Vars to skip over invalid UTF-8 without erroring. If you're just searching for specific keys this is fine.
2. We could automatically skip over vars with invalid UTF-8 by default.
3. Have a Vars::lossy function that makes the iterator return lossy strings.
Changing std::env::args would be more risky though since skipping arguments can change the parsing of following args (unlike with vars).
Before going forward with deprecation a clippy lint and documentation update would be helpful for most developers. I recommend _strongly_ suggesting the _os versions to allow the ecosystem to migrate to it, avoiding widespread deprecation warnings.
I feel considering args and vars together does not make a lot of sense. As you note, vars is a lot more of a problem than args. I would add that's especially true as most "serious" applications will use an argument parsing library.
Changingstd::env::argswould be more risky though since skipping arguments can change the parsing of following args (unlike withvars).
For Unix-like system the argv is an array of C strings, so there is no parsing.
On Windows we already perform the splitting ourselves, and locale is not an issue as GetCommandLineW() always give us UCS-2.
In every other supported platform the system-dependent Args is effectively vec::IntoIter<OsString>, meaning each item can be mapped independently after being constructed.
By parsing I mean clap et al. For example, --option fo�o bar being interpreted as --option bar would be very wrong (where � is a placeholder for invalid unicode). Ignoring environment variables you don't care about or that contain invalid data is more reasonable than ignoring arguments.
I'm not sure what you mean by "edition is not a free card for breaking APIs". Doing this over an edition change would not break anything, because the old editions would still have the old APIs. It appears I've misremembered and there is no precedent for hiding obsolete standard library APIs over edition changes. I will update the RFC to reflect this shortly.
The RFC did not consider those options because they are changes to behavior that contradict the currently documented behavior of the iterators. I did not conceive of those options as necessary to consider because deprecation is a much simpler change that does not affect program behavior and has the much relevant effect of informing people so they could actually fix their error handling.
Considering the prior art, I am somewhat in favor of replacing x.into_string().unwrap() with String::from_utf8_lossy_owned(x.into_encoded_bytes()) for items of args and values of vars, skipping non-UTF-8 keys in vars entirely. That sounds like something worth doing in addition to deprecation, not instead of it, though.
Why would replacing a deprecation warning with a Clippy warning be a better option, considering that a lot of Rust users don't use Clippy, and those who do would have a user experience that is no different from a deprecation warning? For that matter, why would we want to avoid widespread deprecation warnings to start with? The code change from vars and args to vars_os and args_os is trivial, and the RFC provides examples of common substitutions that take no effort at all to perform.
The reason I discuss the two together for the majority of the RFC text is that they suffer from the same fundamental deficiency: the mere existence of non-UTF-8 information in the execution environment can cause panics even if the program doesn't care about it. In the case of vars, those are keys that are not of interest to the program; in the case of args, that is argument 0, ignoring which is well-established behavior. I don't think the disparity in the severity of the problem is a reason to consider the two iterators separately.
I would add that's especially true as most "serious" applications will use an argument parsing library.
rustc was affected by the panicking behavior of args. If that is not an example of a serious application, I don't know what is.
Renaming has been relegated to future possibilities.
Panicking on non-UTF-8 is a documented behavior, changing the existing behavior of args()/vars() to a silent lossy conversion or skipping would be a breaking change. You should need new methods like vars_lossy()/args_lossy() or vars_os().lossy()/args_os().lossy() for the new behavior.
Procedural note: I think that at this point we'd probably only need an ACP for this kind of change since it's just an API change, although I guess RFCs kind of double as an extra FCP to make the change. Although we've personally preferred still doing FCPs on stabilization PRs going forward for libs.
Either way, since both are just writing documents either way, keeping this as an RFC is fine, I think, just kind of want to point out this question for libs more broadly.
Will nominate to discuss at today's meeting.
@rustbot label I-libs-nominated
rustc only used it in a hack. And in the time since the hack was added, nobody reported a problem. It was only discovered when someone was intentionally trying to break another feature.
I don't think we should make this change.
Yes, these methods will break if they encounter non-UTF-8. Programs should mostly not use them today. We should not deprecate them, though. Deprecation implies "this is old and you shouldn't use it". The problem with these methods is the opposite: "this is from the future and you shouldn't use it". ;)
One day, we will be able to finally say "anything other than UTF-8 is incorrect". Today is not that day. But we also shouldn't say that day will never come.
One day, we will be able to finally say "anything other than UTF-8 is incorrect". Today is not that day. But we also shouldn't say that day will never come.
that future already exists in the land of wasi where arguments and env vars are guaranteed to be unicode (so can be encoded as valid utf-8, utf-16, etc.).
One day, we will be able to finally say "anything other than UTF-8 is incorrect".
This is predicated on the idea of platforms where environment variables are not guaranteed to be UTF-8 moving towards providing that guarantee. That is simply not the case. On every Unix-like system, the values of argument vector and environment block entries are C strings, i.e. sequences of non-zero bytes terminated by a zero byte. One cannot move something that has no concept of text encoding to begin with towards UTF-8. For as long as computers running Unix exist in this world, assuming that command-line arguments and the environment block are Unicode strings will be wishful thinking.
Additionally, there is (admittedly not very substantial) value in having non-UTF-8 environment variable values even on systems where UTF-8 is the encoding of all text in paths, command-line arguments and environment variables. A while ago, I wanted to add scripting to an LD_PRELOAD tool by way of bytecode in an environment variable (where interior nuls in the bytecode are prevented by construction), but ultimately decided to base-64-encode the bytecode out of fear that some Rust program on my system might use std::env::vars, crashing in the mere presence of that script. Do we really want the standard library to demand this sort of eggshell-walking of not just direct Rust users, but of all people who happen to run Rust programs?
There are a fair amount of programs that assume all paths are UTF-8 anyway. For those any case rejected by std::env::args() would almost certainly have been rejected later when using the arguments anyway. And if a program doesn't accept path arguments at all, there is a fair chance all arguments will be used as String anyway. args_os() would only be much less convenient for those programs and likely result in people writing .unwrap() instead.
I concur that args and vars are _very_ different:
That is, when invoking an application, the user decides exactly which arguments to pass. Most applications will simply NEVER be invoked with non-UTF-8 arguments, and in fact, if they _are_ accidentally invoked with non-UTF-8 arguments an early panic is perhaps preferable to choking on it later on.
On the other hand, environment variables are global, and therefore one single non-UTF-8 environment variables in the environment could poison pill any applications enumerating them, without the caller even realizing it.
So while _in theory_ both would choke on non-UTF-8 content, practically speaking there's a vast difference.
I'm sure there would be way fewer programs assuming all paths are UTF-8 if they didn't get all their paths from an iterator that blatantly lies to them in acting as if all command-line arguments and all paths by extension are always UTF-8.
args_os() would only be much less convenient for those programs
I've heard the ergonomics argument outside of this RFC discussion as well and I just truly do not empathize with it. Using .unwrap() to convert unfulfilled programmer expectations into panics is utterly basic Rust and any real program is going to have leagues more error handling (be it .unwrap() or proper) than the literal one-line change it takes to do the equivalent of what args does in terms of args_os. If this is too much to ask of an (as of yet hypothetical) language user, we certainly shouldn't prioritize the convenience whims of that language user above the robustness and correctness posture of the ecosystem.
This isn't to say that I think that me not feeling the same way about ergonomics as a lot of other language users is in itself an argument in favor of accepting this RFC, but to say that the usual complaint about ergonomics is not a valid argument against it. It has gotten rather exhausting for me to deal with the same low-effort dismissal of this proposal that does not even attempt to elaborate on the premise of there being meaningful harm to language users caused by making them add one mere string conversion to their program in the worst case (the best case being that type inference allows them to switch out args for args_os and have everything just work the same way it did previously).
If anyone would like to raise a usability concern, it would be most welcome if they provided an articulation that is sufficiently contextualized and which contains a meaningful analysis of the degradation to the language user experience caused by forcing them to use vars_os and args_os instead of vars and args, so that this articulation could be incorporated into the RFC text and be constructively discussed by all participants.
The RFC text purposely focuses on the problem of argument 0 and does not mention the conversion of the subsequent arguments, because that is the one aspect of args in which it resembles vars in its brokenness. The panics in arguments 1 and onward are of course not a good thing whatsoever, but that is largely outside the scope of the argument I'm making, which is that panicking on validation of inputs that are never even inspected (argument 0 in the case of args, environment variables of non-interest in the case of vars) is an unacceptable way of doing things.
Cargo also has some instances of these functions being used. I don't think they're user-facing though. https://github.com/search?q=repo%3Arust-lang%2Fcargo+%2F%5Cbargs%5C%28%5C%29%2F&type=code
Turns out that rustfmt also panics when faced with non-valid-UTF-8 paths lol https://github.com/rust-lang/rustfmt/issues/7210
With env::args() we could change the standard library to provide a proper error message, while env::args_os().map(|arg| arg.into_string().unwrap()) would always result in a panic message (+ not that helpful backtrace if RUST_BACKTRACE is set, like I have) and requires a non-trivial amount of code to get a proper error message that has to be duplicated across every program.
By the way I agree we should deprecate env::vars(). Just because the user happened to have a non-UTF-8 env var should not crash a program. In that case you also shouldn't unwrap on a .into_string() error, but ignore the env var. For env::args() however passing non-UTF-8 args to a program that needs UTF-8 args is not something that happens by accident just because you had some environment issue as you have to explicitly pass args, while env vars are implicit and as such non-UTF-8 args would also be rather obvious while non-UTF-8 env vars are not.
Passing of non-UTF-8 in argument 0 can easily happen by accident if the path to the program contains non-UTF-8 components.
Regarding the error message quality, while it would in theory be a downgrade in the way of error messages to emulate args compared to if the standard library improved its panic message, language users are still much better off propagating the error using the argument parsing error type that they already have.
Just adding a few (threaded) thoughts from a libs perspective after seeing the discussion on Discord:
Last libs meeting was time constrained so we did not have much time to discuss this. We will discuss more next meeting.
Lots of folks have expressed that deprecation is quite a high bar, but I don't think it's insurmountable in many cases.
I can state for a fact that we are expecting library edition redirects (making paths refer to different items in std with an edition bump) to be stabilised soon-ish in some form. The soon-ish is mostly just signifying that I think it's soon enough to consider fixing these APIs in a breaking way as an alternative to deprecation.
For a more personal take based upon some of that discussion: people have a tendency to treat Vars and VarsOs both as something to merely collect and access as a map which we'd like to avoid. I think that ultimately we could probably make things work without deprecating but overhauling the API to make them act more like maps, even though we offer standalone functions like var and var_os as the "get" operation.
I think that regardless of whether we think Unicode-only APIs should exist in std, we have them, and thus I do strictly think we should prefer offering alternatives to a flat-out deprecation. Simply map(OsString::into_string) isn't what we want, IMHO, and there should be better options with less surprising behaviour.
In particular, I think that while args is fine (a reasonable program will expect its arguments to all be Unicode under many circumstances), vars is less fine because I think it's a particularly high bar to expect every environment variable to be Unicode in both key and value, and generally most users only want to inspect a handful of them anyway.
So, I think maybe better APIs are needed and we should explore those. That is, I think deprecating args is not likely but at least major changes for vars makes a lot of sense.
Also another very reasonable take on vars might be to filter on an environment variable prefix, e.g. while you can't expect every variable to be Unicode you might expect every CARGO_ variable to be Unicode, for example.
[RFC] Hopefully, it is clear that programs for which use of args is actually appropriate are highly exotic.
[Comment] that is largely outside the scope of the argument I'm making, which is that panicking on validation of inputs that are never even inspected ([...]) is an unacceptable way of doing things.
You appear to have a very _principled_ stance. I know that "technically correct" is the best kind of correct... but.
The difference between theory and practice, is that in theory there's no difference. In this particular case, your _claims_ (not facts) that correct use of args are highly exotic and (therefore?) that args panicking on non-UTF-8 argv[0] is unacceptable seem to me exaggerated.
I understand your claims when distributing programs (& libraries) to a wide audience: CLIs, GUIs, and the libraries they are built upon. Those should NOT make any assumption on the environment they run in, including the filesystem they run from.
On the other hand, Rust applications are also developed be run on proprietary servers where the environment is under complete control, and where all environment variables and all paths are UTF-8. And this is far from an exotic usecase.
It appears that those applications are a complete blind spot for this RFC (and you, personally), and results in this high-handed way of issuing categorical statements which are... dubious. In the absence of statistics as to the proportions of applications/lines of code which should absolutely handle non-UTF-8 environment variables & paths, vs those which can be asserted never to have such a requirement, I would advocate for toning this down, and be less categorical.
There's a big wide world out there. Let's avoid alienating half (or more) of it just because you're unfamiliar with it.
This is predicated on the idea of platforms where environment variables are not guaranteed to be UTF-8 moving towards providing that guarantee. That is simply not the case. On every Unix-like system, the values of argument vector and environment block entries are C strings, i.e. sequences of non-zero bytes terminated by a zero byte. One cannot move something that has no concept of text encoding to begin with towards UTF-8. For as long as computers running Unix exist in this world, assuming that command-line arguments and the environment block are Unicode strings will be wishful thinking.
Exactly the same thing is true of filenames, and yet it is increasingly reasonable for some programs to assume UTF-8 filenames. I don't see it as particularly unlikely that environment variables will eventually go the same direction as filenames.
Filenames differ in that some filesystems inspect filenames to perform user-experience-improving operations like casefolding, collation, and Unicode normalization due to them being exposed to all end users, including those with limited technical knowledge. Filesystems that can do any of those things at all are in the vast minority, however, and the only one that is encoding-aware by default is APFS; ZFS can validate UTF-8 and perform Unicode normalization and casefolding, but doesn't do so by default; and other filesystems cannot be configured to disallow non-Unicode paths. Considering that [a patch to enforce UTF-8 filenames for ext4][e4-utf8] has been proposed and ignored in the past, there are very good reasons to be skeptical of the prospects of Linux adopting anything of the sort in the mainline kernel, and the BSDs are even more conservative.
[e4-utf8]: https://www.spinics.net/lists/linux-ext4/msg30588.html
No Unix system so far has introduced casefolding and collation for the environment variable block, and there have not been any proposals to do so.
Well, windows is moving, slowly. The GetCommandLineA function now returns utf8 if the application manifest is configured so.
And yet that use is _declining_ according to wikipedia, at least as far as websites go, I don't know anything about the japanese unix landscape.
I think this, together with the
The platforms are not in fact moving towards anything
statement further below, may be understating trends.
To me, at least as far as args goes it does look like a niche usecase, something that tools may choose not to support. It's not like we're excluding entire cultures here as we would if we only supported ASCII or latin-1.
Perhaps some tool developers chose unwisely given their audience, but that can be solved with a smaller hammer, by filing a bug with those affected tools.
Though the args[0] case mentioned in other discussions does seem like something that might be less of an intentional choice.
The process codepage being UTF-8 doesn't affect the string data model of Windows being WTF-16, it simply inserts a conversion at program startup (which, since Vista, fails on unpaired surrogates much like how OsString::into_string will fail on WTF-8-encoded unpaired surrogates). I'm not sure what happens if you run a program that asks for the UTF-8 codepage in its manifest with a command line that contains unpaired surrogates, but it doesn't seem possible for the behavior to be different from std::env::args. Regardless, Windows isn't the troublemaker in this situation anyway, it's mainly the Unix systems that get up to non-Unicode business because their string coding atom is 8-bit, not 16-bit.
Windows does lossy conversions rather than fail. That is true for all code pages (of which UTF-8 is just one).
The userspace usage is besides the point, as the part that is not moving anywhere is the kernel data model for strings, which cannot change, and for as long as it exists, it will be possible to make use of the ability to pass non-text data in arguments and the environment.
I agree that the argument for the deprecation of args is much weaker, but special-casing argument 0 is not a cut and dry solution, since it goes against the presently documented behavior.
Here are all the places we currently call vars() or args() in the rust-lang org: https://github.com/search?q=org%3Arust-lang+language%3Arust+%2F%5B%5E.%5D%5Cb%28vars%7Cargs%29%5C%28%5C%29%2F&type=code
There are many uses of them in our codebase.
Given the number of these uses, I believe that:
Non-utf-8 stuff isn't a big deal. Otherwise, we'd have seen bug reports on all these uses in our codebase by now.
Deprecating these functions now would result in too much immediate churn, since these would probably be called with too high of a frequency, even in high-quality codebases.
I propose that we add a pendantic clippy lint or two that warns on these two functions instead.
So, discussion from the libs meeting: we think that in general, it's probably not best to deprecate these methods and instead the most likely path is either removing some of the issues with panicking (e.g. don't panic on skipped arg0) or offering better APIs we can point people toward first.
In general, we are open to submitting ACPs to the libs-team repo to cover these various concerns also.
So, with that in mind:
@rfcbot close libs
@clarfonthey has proposed to close this. The next step is review by the rest of the tagged team members:
[x] @ChrisDenton
[x] @Mark-Simulacrum
[x] @cuviper
[x] @dtolnay
[ ] @joshtriplett
[x] @nia-e
[ ] @the8472
[x] @thomcc
No concerns currently listed.
Once a majority of reviewers approve (and at most 2 approvals are outstanding), this will enter its final comment period. If you spot a major issue that hasn't been raised at any point in this process, please speak up!
cc @rust-lang/libs-ping: FCP proposed for libs, please feel free to register concerns.
See this document for info about what commands tagged team members can give me.
:bell: This is now entering its final comment period, as per the review above. :bell:
The final comment period, with a disposition to close, as per the review above, is now complete.
As the automated representative of the governance process, I would like to thank the author for their work and everyone else who contributed.
This is now closed.
kennytm
kotauskas
View all comments
std::env::argsand especiallystd::env::varsare footguns whose existence in the standard library contradicts modern best practices of standard library API design. They do the language user a disservice by obfuscating the handling of errors and elevating an ignorant and buggy approach above one that is correct and only marginally more verbose. Accordingly, deprecateargsin favor ofargs_osandvarsin favor ofvars_os.Rendered