`impl Default for EarlyDiagCtxt`
for small rustc_driver programs, most of their imports will currently be related to diagnostics. this change simplifies their code so it's more clear what in the driver is modified from the default.
this is especially important for external drivers which are out of tree and not updated in response to breaking changes. for these drivers, each import is a liability for future code, since it can be broken when refactors happen.
here is an example driver which is simplified by these changes:
```diff
diff --git a/src/main.rs b/src/main.rs
index f81aa3e..11e5f18 100644
--- a/src/main.rs
+++ b/src/main.rs
`@@` -1,16 +1,8 `@@`
#![feature(rustc_private)]
extern crate rustc_driver;
extern crate rustc_interface;
-extern crate rustc_errors;
-extern crate rustc_session;
use rustc_driver::Callbacks;
-use rustc_errors::{emitter::HumanReadableErrorType, ColorConfig};
use rustc_interface::interface;
-use rustc_session::config::ErrorOutputType;
-use rustc_session::EarlyDiagCtxt;
struct DisableSafetyChecks;
`@@` -26,11 +18,7 `@@` fn main() {
"https://github.com/jyn514/jyn514.github.io/issues/new",
|_| (),
);
- let handler = EarlyDiagCtxt::new(ErrorOutputType::HumanReadable(
- HumanReadableErrorType::Default,
- ColorConfig::Auto,
- ));
- rustc_driver::init_rustc_env_logger(&handler);
+ rustc_driver::init_rustc_env_logger(&Default::default());
std::process::exit(rustc_driver::catch_with_exit_code(move || {
let args: Vec<String> = std::env::args().collect();
rustc_driver::RunCompiler::new(&args, &mut DisableSafetyChecks).run()
```
remove `Ty::is_copy_modulo_regions`
Using these functions is likely incorrect if an `InferCtxt` is available, I moved this function to `TyCtxt` (and added it to `LateContext`) and added a note to the documentation that one should prefer `Infer::type_is_copy_modulo_regions` instead.
I didn't yet move `is_sized` and `is_freeze`, though I think we should move these as well.
r? `@compiler-errors` cc #132279
Add `needs-target-has-atomic` directive
Before this PR, the test writer has to specify platforms and architectures by hand for targets that have differing atomic width support. `#[cfg(target_has_atomic="...")]` is not quite the same because (1) you may have to specify additional matchers manually which has to be maintained individually, and (2) the `#[cfg]` blocks does not communicate to compiletest that a test would be ignored for a given target.
This PR implements a `//@ needs-target-has-atomic` directive which admits a comma-separated list of required atomic widths that the target must satisfy in order for the test to run.
```
//@ needs-target-has-atomic: 8, 16, ptr
```
See <https://github.com/rust-lang/rust/issues/87377>.
This PR supersedes #133095 and is co-authored by `@kei519,` because it was somewhat subtle, and it turned out easier to implement than to review.
rustc-dev-guide docs PR: https://github.com/rust-lang/rustc-dev-guide/pull/2154
Add pretty-printer parenthesis insertion test
This test demonstrates numerous bugs in rustc_ast_pretty, including all five of:
- Failing to insert parentheses where necessary to preserve the meaning of a syntax tree, producing invalid syntax.
- Failing to insert parentheses, producing valid syntax with the wrong meaning.
- Inserting too many parentheses.
- Inserting parentheses in the wrong place, producing invalid syntax.
- Losing syntactically significant parts of the syntax tree.
These pretty-printer bugs have consequences for `-Zunpretty=expanded`. The `cargo expand` subcommand cannot work reliably unless rustc can consistently produce valid Rust output. Erroneous syntax cannot be passed through rustfmt, or queried with [syn-select](https://crates.io/crates/syn-select).
The test in this PR is a port of a test from Syn that tests the automatic parenthesis insertion performed by Syn's `ToTokens` impls. In Syn we actually run this test over every expression in every Rust source file in the whole rust-lang/rust repo, including rustc and the standard library and tools and test suites. For the test here, I have only used a small selection of interesting expressions. This will serve as an easy spot to accumulate regression tests as the various bugs get fixed. Once rustc's pretty-printer is in better shape, it's possible that the test can be expanded to cover a larger set of expressions collected automatically like in Syn.
Remove `//@ compare-output-lines-by-subset`
There was only ever one test which used this flag, and it was removed in https://github.com/rust-lang/rust/pull/132244. I think this is a bad flag that should never have been added; comparing by subset makes the test failures extremely hard to debug. Any test that needs complicated output filtering like this should just use run-make instead.
Note that this does not remove the underlying comparison code, because it's still used if `runner` is set. I don't quite understand what's going on there, but since we still test on other platforms and in CI that the full output is accurate, I think it will be easier to debug than a test that uses compare-by-subset unconditionally.
rustc-dev-guide update PR: https://github.com/rust-lang/rustc-dev-guide/pull/2151
rustdoc-json: Include safety of `static`s
`static`s in an `extern` block can have an associated safety annotation ["because there is nothing guaranteeing that the bit pattern at the static’s memory is valid for the type it is declared with"](https://doc.rust-lang.org/reference/items/external-blocks.html#statics). Rustdoc already knows this and displays in for HTML. This PR also includes it in JSON.
Inspired by https://github.com/obi1kenobi/cargo-semver-checks/issues/975 which needs this, but it's probably useful in other places.
r? `@GuillaumeGomez.` Possibly easier to review commit-by-commit.
Eliminate magic numbers from expression precedence
Context: see https://github.com/rust-lang/rust/pull/133140.
This PR continues on backporting Syn's expression precedence design into rustc. Rustc's design used mysterious integer quantities represented variously as `i8` or `usize` (e.g. `PREC_CLOSURE = -40i8`), a special significance around `0` that is never named, and an extra `PREC_FORCE_PAREN` precedence level that does not correspond to any expression. Syn's design uses a C-like enum with variants that clearly correspond to specific sets of expression kinds.
This PR is a refactoring that has no intended behavior change on its own, but it unblocks other precedence work that rustc's precedence design was poorly suited to accommodate.
- Asymmetrical precedence, so that a pretty-printer can tell `(return 1) + 1` needs parens but `1 + return 1` does not.
- Squashing the `Closure` and `Jump` cases into a single precedence level.
- Numerous remaining false positives and false negatives in rustc pretty-printer's parenthesization of macro metavariables, for example in `$e < rhs` where $e is `lhs as Thing<T>`.
FYI `@fmease` — you don't need to review if rustbot picks someone else, but you mentioned being interested in the followup PRs.
check local cache even if global is usable
we store overflow errors locally, even if we can otherwise use the global cache for this goal. should fix#133616, didn't test it locally yet as diesel tends to hit an unrelated debug assertion in rustdoc.
r? types
for small rustc_driver programs, most of their imports will currently be related to diagnostics. this change simplifiers their code so it's more clear what in the driver is modified from the default.
this is especially important for external drivers which are out of tree and not updated in response to breaking changes. for these drivers, each import is a liability for future code, since it can be broken when refactors happen.
here is an example driver which is simplified by these changes:
```
diff --git a/src/main.rs b/src/main.rs
index f81aa3e..11e5f18 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,16 +1,8 @@
#![feature(rustc_private)]
extern crate rustc_driver;
extern crate rustc_interface;
-extern crate rustc_errors;
-extern crate rustc_session;
use rustc_driver::Callbacks;
-use rustc_errors::{emitter::HumanReadableErrorType, ColorConfig};
use rustc_interface::interface;
-use rustc_session::config::ErrorOutputType;
-use rustc_session::EarlyDiagCtxt;
struct DisableSafetyChecks;
@@ -26,11 +18,7 @@ fn main() {
"https://github.com/jyn514/jyn514.github.io/issues/new",
|_| (),
);
- let handler = EarlyDiagCtxt::new(ErrorOutputType::HumanReadable(
- HumanReadableErrorType::Default,
- ColorConfig::Auto,
- ));
- rustc_driver::init_rustc_env_logger(&handler);
+ rustc_driver::init_rustc_env_logger(&Default::default());
std::process::exit(rustc_driver::catch_with_exit_code(move || {
let args: Vec<String> = std::env::args().collect();
rustc_driver::RunCompiler::new(&args, &mut DisableSafetyChecks).run()
```
Before this commit, the test writer has to specify platforms and
architectures by hand for targets that have differing atomic width
support. `#[cfg(target_has_atomic)]` is not quite the same because (1)
you may have to specify additional matchers manually which has to be
maintained individually, and (2) the `#[cfg]` blocks does not
communicate to compiletest that a test would be ignored for a given
target.
This commit implements a `//@ needs-target-has-atomic` directive which
admits a comma-separated list of required atomic widths that the target
must satisfy in order for the test to run.
```
//@ needs-target-has-atomic: 8, 16, ptr
```
See <https://github.com/rust-lang/rust/issues/87377>.
Co-authored-by: kei519 <masaki.keigo.q00@kyoto-u.jp>
Rollup of 5 pull requests
Successful merges:
- #131416 (Mark `slice::copy_from_slice` unstably const)
- #131784 (Stabilize unsigned and float variants of `num_midpoint` feature)
- #133446 (coverage: Use a query to identify which counter/expression IDs are used)
- #133711 (add isatty doc alias for `is_terminal`)
- #133712 (rust_analyzer_settings: force use of 'nightly' toolchain)
r? `@ghost`
`@rustbot` modify labels: rollup
Remove `hir::ArrayLen`
This refactoring removes `hir::ArrayLen`, replacing it with `hir::ConstArg`. To represent inferred array lengths (previously `hir::ArrayLen::Infer`), a new variant `ConstArgKind::Infer` is added.
r? `@BoxyUwU`
There was only ever one test which used this flag, and it was removed in https://github.com/rust-lang/rust/pull/132244. I think this is a bad flag that should never have been added; comparing by subset makes the test failures extremely hard to debug. Any test that needs complicated output filtering like this should just use run-make instead.
Note that this does not remove the underlying comparison code, because it's still used if `runner` is set. I don't quite understand what's going on there, but since we still test on other platforms and in CI that the full output is accurate, I think it will be easier to debug than a test that uses compare-by-subset unconditionally.
rust_analyzer_settings: force use of 'nightly' toolchain
The cranelift folder contains a rust-toolchain file. That means when RA opens `compiler/rustc_codegen_cranelift/Cargo.toml`, it will try to use that toolchain or fail. (Maybe that toolchain gets auto-installed for others? On my system, it just fails, but I also run vscodium in a sandbox.)
However, it shouldn't be necessary to use more than one toolchain for the rustc workspace. So we can set the `RUSTUP_TOOLCHAIN` variable on the server side to force the same toolchain to be used everywhere.
Suggested by `@ChayimFriedman2` in https://github.com/rust-lang/rust-analyzer/issues/18585.
add isatty doc alias for `is_terminal`
(first Rust contribution!)
This adds `isatty` as a doc alias for [`std::io::IsTerminal::is_terminal`](https://doc.rust-lang.org/stable/std/io/trait.IsTerminal.html#tymethod.is_terminal).
I think this change does meet the [doc alias policy](https://std-dev-guide.rust-lang.org/policy/doc-alias.html). This would be especially useful because searching "rust isatty" gets you the `isatty` crate which is deprecated in favor of `atty`. `atty` is unmaintained and you might get to `is-terminal`, which will finally tell you that the function you're looking for has been in `std` all along.
The Windows implementation of `is_terminal()` doesn't use `isatty`, but that hasn't been a problem for the analogous cases of `create_dir()`'s alias `mkdir` or `remove_dir()`/`rmdir`.
coverage: Use a query to identify which counter/expression IDs are used
Given that we already have a query to identify the highest-numbered counter ID in a MIR body, we can extend that query to also build bitsets of used counter/expression IDs. That lets us avoid some messy coverage bookkeeping during the main MIR traversal for codegen.
This does mean that we fail to treat some IDs as used in certain MIR-inlining scenarios, but I think that's fine, because it means that the results will be consistent across all instantiations of a function.
---
There's some more cleanup I want to do in the function coverage collector, since it isn't really collecting anything any more, but I'll leave that for future work.
Stabilize unsigned and float variants of `num_midpoint` feature
This PR proposes that we stabilize the unsigned variants of the [`num_midpoint`](https://github.com/rust-lang/rust/issues/110840#issue-1684506201) feature as well as the floats variants, since they are not subject to any unresolved questions, which is equivalent to doing `(a + b) / 2` (and `(a + b) >> 1`) in a sufficiently large number.
The stabilized API surface would be:
```rust
/// Calculates the middle point of `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a sufficiently-large unsigned integral type.
/// This implies that the result is always rounded towards negative infinity and that no overflow will ever occur.
impl u{8,16,32,64,128,size} {
pub const fn midpoint(self, rhs: Self) -> Self;
}
impl NonZeroU{8,16,32,64,size} {
pub const fn midpoint(self, rhs: Self) -> Self;
}
impl f{32,64} {
pub const fn midpoint(self, rhs: Self) -> Self;
}
```
The signed variants `u{8,16,32,64,128,size}` would remain gated, until a decision is made about the rounding mode, in other words that the [unresolved questions](https://github.com/rust-lang/rust/issues/110840#issue-1684506201) are resolved.
cc `@rust-lang/libs-api`
cc `@scottmcm`
r? libs-api
Mark `slice::copy_from_slice` unstably const
Tracking issue #131415
I used `const_eval_select` for runtime and const panic functions because const formatting isn't available yet.
Stop cloning `Context` so much
This is a first step for https://github.com/rust-lang/rust/issues/82381.
It's already big enough so I'll continue in a follow-up once this PR is merged. Next step will be to get rid of `SharedContext` by inlining it directly into `Context`.
cc `@camelid`
r? `@notriddle`