Auto merge of #124448 - matthiaskrgr:rollup-iloy9vz, r=matthiaskrgr
Some checks failed
CI / Calculate job matrix (push) Failing after 15s
CI / master (push) Has been skipped
CI / bors build finished (push) Has been skipped
CI / ${{ matrix.name }} (push) Has been skipped

Rollup of 7 pull requests

Successful merges:

 - #124370 (Fix substitution parts having a shifted underline in some cases)
 - #124394 (Fix ICE on invalid const param types)
 - #124425 (Do not ICE on invalid consts when walking mono-reachable blocks)
 - #124434 (Remove lazycell and once_cell from compiletest dependencies)
 - #124437 (doc: Make the `mod.rs` in the comment point to the correct location)
 - #124443 (Elaborate in comment about `statx` probe)
 - #124445 (bootstrap: Change `global(true)` to `global = true` for flags for consistency)

r? `@ghost`
`@rustbot` modify labels: rollup
This commit is contained in:
bors 2024-04-27 20:49:06 +00:00
commit aed2187d53
19 changed files with 232 additions and 176 deletions

View File

@ -760,11 +760,9 @@ dependencies = [
"glob", "glob",
"home", "home",
"indexmap", "indexmap",
"lazycell",
"libc", "libc",
"miow", "miow",
"miropt-test-tools", "miropt-test-tools",
"once_cell",
"regex", "regex",
"rustfix 0.8.1", "rustfix 0.8.1",
"serde", "serde",
@ -2151,12 +2149,6 @@ version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "lazycell"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55"
[[package]] [[package]]
name = "leb128" name = "leb128"
version = "0.2.5" version = "0.2.5"

View File

@ -2019,7 +2019,7 @@ fn emit_suggestion_default(
let offset: isize = offsets let offset: isize = offsets
.iter() .iter()
.filter_map( .filter_map(
|(start, v)| if span_start_pos <= *start { None } else { Some(v) }, |(start, v)| if span_start_pos < *start { None } else { Some(v) },
) )
.sum(); .sum();
let underline_start = (span_start_pos + start) as isize + offset; let underline_start = (span_start_pos + start) as isize + offset;
@ -2028,7 +2028,7 @@ fn emit_suggestion_default(
let padding: usize = max_line_num_len + 3; let padding: usize = max_line_num_len + 3;
for p in underline_start..underline_end { for p in underline_start..underline_end {
if let DisplaySuggestion::Underline = show_code_change { if let DisplaySuggestion::Underline = show_code_change {
// If this is a replacement, underline with `^`, if this is an addition // If this is a replacement, underline with `~`, if this is an addition
// underline with `+`. // underline with `+`.
buffer.putc( buffer.putc(
row_num, row_num,

View File

@ -386,6 +386,8 @@ fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
fn ct_infer(&self, ty: Ty<'tcx>, _: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> { fn ct_infer(&self, ty: Ty<'tcx>, _: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> {
let ty = self.tcx.fold_regions(ty, |r, _| match *r { let ty = self.tcx.fold_regions(ty, |r, _| match *r {
rustc_type_ir::RegionKind::ReStatic => r,
// This is never reached in practice. If it ever is reached, // This is never reached in practice. If it ever is reached,
// `ReErased` should be changed to `ReStatic`, and any other region // `ReErased` should be changed to `ReStatic`, and any other region
// left alone. // left alone.

View File

@ -1,6 +1,6 @@
//! Type checking expressions. //! Type checking expressions.
//! //!
//! See `mod.rs` for more context on type checking in general. //! See [`rustc_hir_analysis::check`] for more context on type checking in general.
use crate::cast; use crate::cast;
use crate::coercion::CoerceMany; use crate::coercion::CoerceMany;

View File

@ -701,10 +701,7 @@ fn try_const_mono_switchint<'a>(
env, env,
crate::ty::EarlyBinder::bind(constant.const_), crate::ty::EarlyBinder::bind(constant.const_),
); );
let Some(bits) = mono_literal.try_eval_bits(tcx, env) else { mono_literal.try_eval_bits(tcx, env)
bug!("Couldn't evaluate constant {:?} in mono {:?}", constant, instance);
};
bits
}; };
let TerminatorKind::SwitchInt { discr, targets } = &block.terminator().kind else { let TerminatorKind::SwitchInt { discr, targets } = &block.terminator().kind else {
@ -714,7 +711,7 @@ fn try_const_mono_switchint<'a>(
// If this is a SwitchInt(const _), then we can just evaluate the constant and return. // If this is a SwitchInt(const _), then we can just evaluate the constant and return.
let discr = match discr { let discr = match discr {
Operand::Constant(constant) => { Operand::Constant(constant) => {
let bits = eval_mono_const(constant); let bits = eval_mono_const(constant)?;
return Some((bits, targets)); return Some((bits, targets));
} }
Operand::Move(place) | Operand::Copy(place) => place, Operand::Move(place) | Operand::Copy(place) => place,
@ -748,7 +745,7 @@ fn try_const_mono_switchint<'a>(
match rvalue { match rvalue {
Rvalue::NullaryOp(NullOp::UbChecks, _) => Some((tcx.sess.ub_checks() as u128, targets)), Rvalue::NullaryOp(NullOp::UbChecks, _) => Some((tcx.sess.ub_checks() as u128, targets)),
Rvalue::Use(Operand::Constant(constant)) => { Rvalue::Use(Operand::Constant(constant)) => {
let bits = eval_mono_const(constant); let bits = eval_mono_const(constant)?;
Some((bits, targets)) Some((bits, targets))
} }
_ => None, _ => None,

View File

@ -198,20 +198,16 @@ fn statx(
return Some(Err(err)); return Some(Err(err));
} }
// `ENOSYS` might come from a faulty FUSE driver. // We're not yet entirely sure whether `statx` is usable on this kernel
// // or not. Syscalls can return errors from things other than the kernel
// Other errors are not a good enough indicator either -- it is // per se, e.g. `EPERM` can be returned if seccomp is used to block the
// known that `EPERM` can be returned as a result of using seccomp to // syscall, or `ENOSYS` might be returned from a faulty FUSE driver.
// block the syscall.
// //
// Availability is checked by performing a call which expects `EFAULT` // Availability is checked by performing a call which expects `EFAULT`
// if the syscall is usable. // if the syscall is usable.
// //
// See: https://github.com/rust-lang/rust/issues/65662 // See: https://github.com/rust-lang/rust/issues/65662
// //
// FIXME this can probably just do the call if `EPERM` was received, but
// previous iteration of the code checked it for all errors and for now
// this is retained.
// FIXME what about transient conditions like `ENOMEM`? // FIXME what about transient conditions like `ENOMEM`?
let err2 = cvt(statx(0, ptr::null(), 0, libc::STATX_ALL, ptr::null_mut())) let err2 = cvt(statx(0, ptr::null(), 0, libc::STATX_ALL, ptr::null_mut()))
.err() .err()

View File

@ -41,72 +41,72 @@ pub struct Flags {
#[command(subcommand)] #[command(subcommand)]
pub cmd: Subcommand, pub cmd: Subcommand,
#[arg(global(true), short, long, action = clap::ArgAction::Count)] #[arg(global = true, short, long, action = clap::ArgAction::Count)]
/// use verbose output (-vv for very verbose) /// use verbose output (-vv for very verbose)
pub verbose: u8, // each extra -v after the first is passed to Cargo pub verbose: u8, // each extra -v after the first is passed to Cargo
#[arg(global(true), short, long)] #[arg(global = true, short, long)]
/// use incremental compilation /// use incremental compilation
pub incremental: bool, pub incremental: bool,
#[arg(global(true), long, value_hint = clap::ValueHint::FilePath, value_name = "FILE")] #[arg(global = true, long, value_hint = clap::ValueHint::FilePath, value_name = "FILE")]
/// TOML configuration file for build /// TOML configuration file for build
pub config: Option<PathBuf>, pub config: Option<PathBuf>,
#[arg(global(true), long, value_hint = clap::ValueHint::DirPath, value_name = "DIR")] #[arg(global = true, long, value_hint = clap::ValueHint::DirPath, value_name = "DIR")]
/// Build directory, overrides `build.build-dir` in `config.toml` /// Build directory, overrides `build.build-dir` in `config.toml`
pub build_dir: Option<PathBuf>, pub build_dir: Option<PathBuf>,
#[arg(global(true), long, value_hint = clap::ValueHint::Other, value_name = "BUILD")] #[arg(global = true, long, value_hint = clap::ValueHint::Other, value_name = "BUILD")]
/// build target of the stage0 compiler /// build target of the stage0 compiler
pub build: Option<String>, pub build: Option<String>,
#[arg(global(true), long, value_hint = clap::ValueHint::Other, value_name = "HOST", value_parser = target_selection_list)] #[arg(global = true, long, value_hint = clap::ValueHint::Other, value_name = "HOST", value_parser = target_selection_list)]
/// host targets to build /// host targets to build
pub host: Option<TargetSelectionList>, pub host: Option<TargetSelectionList>,
#[arg(global(true), long, value_hint = clap::ValueHint::Other, value_name = "TARGET", value_parser = target_selection_list)] #[arg(global = true, long, value_hint = clap::ValueHint::Other, value_name = "TARGET", value_parser = target_selection_list)]
/// target targets to build /// target targets to build
pub target: Option<TargetSelectionList>, pub target: Option<TargetSelectionList>,
#[arg(global(true), long, value_name = "PATH")] #[arg(global = true, long, value_name = "PATH")]
/// build paths to exclude /// build paths to exclude
pub exclude: Vec<PathBuf>, // keeping for client backward compatibility pub exclude: Vec<PathBuf>, // keeping for client backward compatibility
#[arg(global(true), long, value_name = "PATH")] #[arg(global = true, long, value_name = "PATH")]
/// build paths to skip /// build paths to skip
pub skip: Vec<PathBuf>, pub skip: Vec<PathBuf>,
#[arg(global(true), long)] #[arg(global = true, long)]
/// include default paths in addition to the provided ones /// include default paths in addition to the provided ones
pub include_default_paths: bool, pub include_default_paths: bool,
#[arg(global(true), value_hint = clap::ValueHint::Other, long)] #[arg(global = true, value_hint = clap::ValueHint::Other, long)]
pub rustc_error_format: Option<String>, pub rustc_error_format: Option<String>,
#[arg(global(true), long, value_hint = clap::ValueHint::CommandString, value_name = "CMD")] #[arg(global = true, long, value_hint = clap::ValueHint::CommandString, value_name = "CMD")]
/// command to run on failure /// command to run on failure
pub on_fail: Option<String>, pub on_fail: Option<String>,
#[arg(global(true), long)] #[arg(global = true, long)]
/// dry run; don't build anything /// dry run; don't build anything
pub dry_run: bool, pub dry_run: bool,
/// Indicates whether to dump the work done from bootstrap shims /// Indicates whether to dump the work done from bootstrap shims
#[arg(global(true), long)] #[arg(global = true, long)]
pub dump_bootstrap_shims: bool, pub dump_bootstrap_shims: bool,
#[arg(global(true), value_hint = clap::ValueHint::Other, long, value_name = "N")] #[arg(global = true, value_hint = clap::ValueHint::Other, long, value_name = "N")]
/// stage to build (indicates compiler to use/test, e.g., stage 0 uses the /// stage to build (indicates compiler to use/test, e.g., stage 0 uses the
/// bootstrap compiler, stage 1 the stage 0 rustc artifacts, etc.) /// bootstrap compiler, stage 1 the stage 0 rustc artifacts, etc.)
pub stage: Option<u32>, pub stage: Option<u32>,
#[arg(global(true), value_hint = clap::ValueHint::Other, long, value_name = "N")] #[arg(global = true, value_hint = clap::ValueHint::Other, long, value_name = "N")]
/// stage(s) to keep without recompiling /// stage(s) to keep without recompiling
/// (pass multiple times to keep e.g., both stages 0 and 1) /// (pass multiple times to keep e.g., both stages 0 and 1)
pub keep_stage: Vec<u32>, pub keep_stage: Vec<u32>,
#[arg(global(true), value_hint = clap::ValueHint::Other, long, value_name = "N")] #[arg(global = true, value_hint = clap::ValueHint::Other, long, value_name = "N")]
/// stage(s) of the standard library to keep without recompiling /// stage(s) of the standard library to keep without recompiling
/// (pass multiple times to keep e.g., both stages 0 and 1) /// (pass multiple times to keep e.g., both stages 0 and 1)
pub keep_stage_std: Vec<u32>, pub keep_stage_std: Vec<u32>,
#[arg(global(true), long, value_hint = clap::ValueHint::DirPath, value_name = "DIR")] #[arg(global = true, long, value_hint = clap::ValueHint::DirPath, value_name = "DIR")]
/// path to the root of the rust checkout /// path to the root of the rust checkout
pub src: Option<PathBuf>, pub src: Option<PathBuf>,
#[arg( #[arg(
global(true), global = true,
short, short,
long, long,
value_hint = clap::ValueHint::Other, value_hint = clap::ValueHint::Other,
@ -117,26 +117,26 @@ pub struct Flags {
pub jobs: usize, pub jobs: usize,
// This overrides the deny-warnings configuration option, // This overrides the deny-warnings configuration option,
// which passes -Dwarnings to the compiler invocations. // which passes -Dwarnings to the compiler invocations.
#[arg(global(true), long)] #[arg(global = true, long)]
#[arg(value_enum, default_value_t=Warnings::Default, value_name = "deny|warn")] #[arg(value_enum, default_value_t=Warnings::Default, value_name = "deny|warn")]
/// if value is deny, will deny warnings /// if value is deny, will deny warnings
/// if value is warn, will emit warnings /// if value is warn, will emit warnings
/// otherwise, use the default configured behaviour /// otherwise, use the default configured behaviour
pub warnings: Warnings, pub warnings: Warnings,
#[arg(global(true), value_hint = clap::ValueHint::Other, long, value_name = "FORMAT")] #[arg(global = true, value_hint = clap::ValueHint::Other, long, value_name = "FORMAT")]
/// rustc error format /// rustc error format
pub error_format: Option<String>, pub error_format: Option<String>,
#[arg(global(true), long)] #[arg(global = true, long)]
/// use message-format=json /// use message-format=json
pub json_output: bool, pub json_output: bool,
#[arg(global(true), long, value_name = "STYLE")] #[arg(global = true, long, value_name = "STYLE")]
#[arg(value_enum, default_value_t = Color::Auto)] #[arg(value_enum, default_value_t = Color::Auto)]
/// whether to use color in cargo and rustc output /// whether to use color in cargo and rustc output
pub color: Color, pub color: Color,
#[arg(global(true), long)] #[arg(global = true, long)]
/// Bootstrap uses this value to decide whether it should bypass locking the build process. /// Bootstrap uses this value to decide whether it should bypass locking the build process.
/// This is rarely needed (e.g., compiling the std library for different targets in parallel). /// This is rarely needed (e.g., compiling the std library for different targets in parallel).
/// ///
@ -144,41 +144,41 @@ pub struct Flags {
pub bypass_bootstrap_lock: bool, pub bypass_bootstrap_lock: bool,
/// whether rebuilding llvm should be skipped, overriding `skip-rebuld` in config.toml /// whether rebuilding llvm should be skipped, overriding `skip-rebuld` in config.toml
#[arg(global(true), long, value_name = "VALUE")] #[arg(global = true, long, value_name = "VALUE")]
pub llvm_skip_rebuild: Option<bool>, pub llvm_skip_rebuild: Option<bool>,
/// generate PGO profile with rustc build /// generate PGO profile with rustc build
#[arg(global(true), value_hint = clap::ValueHint::FilePath, long, value_name = "PROFILE")] #[arg(global = true, value_hint = clap::ValueHint::FilePath, long, value_name = "PROFILE")]
pub rust_profile_generate: Option<String>, pub rust_profile_generate: Option<String>,
/// use PGO profile for rustc build /// use PGO profile for rustc build
#[arg(global(true), value_hint = clap::ValueHint::FilePath, long, value_name = "PROFILE")] #[arg(global = true, value_hint = clap::ValueHint::FilePath, long, value_name = "PROFILE")]
pub rust_profile_use: Option<String>, pub rust_profile_use: Option<String>,
/// use PGO profile for LLVM build /// use PGO profile for LLVM build
#[arg(global(true), value_hint = clap::ValueHint::FilePath, long, value_name = "PROFILE")] #[arg(global = true, value_hint = clap::ValueHint::FilePath, long, value_name = "PROFILE")]
pub llvm_profile_use: Option<String>, pub llvm_profile_use: Option<String>,
// LLVM doesn't support a custom location for generating profile // LLVM doesn't support a custom location for generating profile
// information. // information.
// //
// llvm_out/build/profiles/ is the location this writes to. // llvm_out/build/profiles/ is the location this writes to.
/// generate PGO profile with llvm built for rustc /// generate PGO profile with llvm built for rustc
#[arg(global(true), long)] #[arg(global = true, long)]
pub llvm_profile_generate: bool, pub llvm_profile_generate: bool,
/// Enable BOLT link flags /// Enable BOLT link flags
#[arg(global(true), long)] #[arg(global = true, long)]
pub enable_bolt_settings: bool, pub enable_bolt_settings: bool,
/// Skip stage0 compiler validation /// Skip stage0 compiler validation
#[arg(global(true), long)] #[arg(global = true, long)]
pub skip_stage0_validation: bool, pub skip_stage0_validation: bool,
/// Additional reproducible artifacts that should be added to the reproducible artifacts archive. /// Additional reproducible artifacts that should be added to the reproducible artifacts archive.
#[arg(global(true), long)] #[arg(global = true, long)]
pub reproducible_artifact: Vec<String>, pub reproducible_artifact: Vec<String>,
#[arg(global(true))] #[arg(global = true)]
/// paths for the subcommand /// paths for the subcommand
pub paths: Vec<PathBuf>, pub paths: Vec<PathBuf>,
/// override options in config.toml /// override options in config.toml
#[arg(global(true), value_hint = clap::ValueHint::Other, long, value_name = "section.option=value")] #[arg(global = true, value_hint = clap::ValueHint::Other, long, value_name = "section.option=value")]
pub set: Vec<String>, pub set: Vec<String>,
/// arguments passed to subcommands /// arguments passed to subcommands
#[arg(global(true), last(true), value_name = "ARGS")] #[arg(global = true, last(true), value_name = "ARGS")]
pub free_args: Vec<String>, pub free_args: Vec<String>,
} }
@ -192,7 +192,7 @@ pub fn parse(args: &[String]) -> Self {
struct HelpVerboseOnly { struct HelpVerboseOnly {
#[arg(short, long)] #[arg(short, long)]
help: bool, help: bool,
#[arg(global(true), short, long, action = clap::ArgAction::Count)] #[arg(global = true, short, long, action = clap::ArgAction::Count)]
pub verbose: u8, pub verbose: u8,
#[arg(value_enum)] #[arg(value_enum)]
cmd: Kind, cmd: Kind,
@ -260,16 +260,16 @@ pub enum Subcommand {
#[arg(long, requires = "fix")] #[arg(long, requires = "fix")]
allow_staged: bool, allow_staged: bool,
/// clippy lints to allow /// clippy lints to allow
#[arg(global(true), short = 'A', action = clap::ArgAction::Append, value_name = "LINT")] #[arg(global = true, short = 'A', action = clap::ArgAction::Append, value_name = "LINT")]
allow: Vec<String>, allow: Vec<String>,
/// clippy lints to deny /// clippy lints to deny
#[arg(global(true), short = 'D', action = clap::ArgAction::Append, value_name = "LINT")] #[arg(global = true, short = 'D', action = clap::ArgAction::Append, value_name = "LINT")]
deny: Vec<String>, deny: Vec<String>,
/// clippy lints to warn on /// clippy lints to warn on
#[arg(global(true), short = 'W', action = clap::ArgAction::Append, value_name = "LINT")] #[arg(global = true, short = 'W', action = clap::ArgAction::Append, value_name = "LINT")]
warn: Vec<String>, warn: Vec<String>,
/// clippy lints to forbid /// clippy lints to forbid
#[arg(global(true), short = 'F', action = clap::ArgAction::Append, value_name = "LINT")] #[arg(global = true, short = 'F', action = clap::ArgAction::Append, value_name = "LINT")]
forbid: Vec<String>, forbid: Vec<String>,
}, },
/// Run cargo fix /// Run cargo fix

View File

@ -21,10 +21,8 @@ regex = "1.0"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
rustfix = "0.8.1" rustfix = "0.8.1"
once_cell = "1.16.0"
walkdir = "2" walkdir = "2"
glob = "0.3.0" glob = "0.3.0"
lazycell = "1.3.0"
anyhow = "1" anyhow = "1"
home = "0.5.5" home = "0.5.5"

View File

@ -6,10 +6,10 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::Command; use std::process::Command;
use std::str::FromStr; use std::str::FromStr;
use std::sync::OnceLock;
use crate::util::{add_dylib_path, PathBufExt}; use crate::util::{add_dylib_path, PathBufExt};
use build_helper::git::GitConfig; use build_helper::git::GitConfig;
use lazycell::AtomicLazyCell;
use serde::de::{Deserialize, Deserializer, Error as _}; use serde::de::{Deserialize, Deserializer, Error as _};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use test::{ColorConfig, OutputFormat}; use test::{ColorConfig, OutputFormat};
@ -384,7 +384,7 @@ pub struct Config {
/// Only rerun the tests that result has been modified accoring to Git status /// Only rerun the tests that result has been modified accoring to Git status
pub only_modified: bool, pub only_modified: bool,
pub target_cfgs: AtomicLazyCell<TargetCfgs>, pub target_cfgs: OnceLock<TargetCfgs>,
pub nocapture: bool, pub nocapture: bool,
@ -406,13 +406,7 @@ pub fn run_enabled(&self) -> bool {
} }
pub fn target_cfgs(&self) -> &TargetCfgs { pub fn target_cfgs(&self) -> &TargetCfgs {
match self.target_cfgs.borrow() { self.target_cfgs.get_or_init(|| TargetCfgs::new(self))
Some(cfgs) => cfgs,
None => {
let _ = self.target_cfgs.fill(TargetCfgs::new(self));
self.target_cfgs.borrow().unwrap()
}
}
} }
pub fn target_cfg(&self) -> &TargetCfg { pub fn target_cfg(&self) -> &TargetCfg {

View File

@ -6,8 +6,8 @@
use std::io::BufReader; use std::io::BufReader;
use std::path::Path; use std::path::Path;
use std::str::FromStr; use std::str::FromStr;
use std::sync::OnceLock;
use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use tracing::*; use tracing::*;
@ -117,10 +117,11 @@ fn parse_expected(
// //~^^^^^ // //~^^^^^
// //[rev1]~ // //[rev1]~
// //[rev1,rev2]~^^ // //[rev1,rev2]~^^
static RE: Lazy<Regex> = static RE: OnceLock<Regex> = OnceLock::new();
Lazy::new(|| Regex::new(r"//(?:\[(?P<revs>[\w\-,]+)])?~(?P<adjust>\||\^*)").unwrap());
let captures = RE.captures(line)?; let captures = RE
.get_or_init(|| Regex::new(r"//(?:\[(?P<revs>[\w\-,]+)])?~(?P<adjust>\||\^*)").unwrap())
.captures(line)?;
match (test_revision, captures.name("revs")) { match (test_revision, captures.name("revs")) {
// Only error messages that contain our revision between the square brackets apply to us. // Only error messages that contain our revision between the square brackets apply to us.

View File

@ -5,8 +5,8 @@
use std::io::BufReader; use std::io::BufReader;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::Command; use std::process::Command;
use std::sync::OnceLock;
use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use tracing::*; use tracing::*;
@ -1021,8 +1021,9 @@ fn iter_header(
let mut line_number = 0; let mut line_number = 0;
// Match on error annotations like `//~ERROR`. // Match on error annotations like `//~ERROR`.
static REVISION_MAGIC_COMMENT_RE: Lazy<Regex> = static REVISION_MAGIC_COMMENT_RE: OnceLock<Regex> = OnceLock::new();
Lazy::new(|| Regex::new("//(\\[.*\\])?~.*").unwrap()); let revision_magic_comment_re =
REVISION_MAGIC_COMMENT_RE.get_or_init(|| Regex::new("//(\\[.*\\])?~.*").unwrap());
loop { loop {
line_number += 1; line_number += 1;
@ -1087,7 +1088,7 @@ fn iter_header(
}); });
// Then we try to check for legacy-style candidates, which are not the magic ~ERROR family // Then we try to check for legacy-style candidates, which are not the magic ~ERROR family
// error annotations. // error annotations.
} else if !REVISION_MAGIC_COMMENT_RE.is_match(ln) { } else if !revision_magic_comment_re.is_match(ln) {
let Some((_, rest)) = line_directive("//", ln) else { let Some((_, rest)) = line_directive("//", ln) else {
continue; continue;
}; };

View File

@ -24,13 +24,13 @@
use build_helper::git::{get_git_modified_files, get_git_untracked_files}; use build_helper::git::{get_git_modified_files, get_git_untracked_files};
use core::panic; use core::panic;
use getopts::Options; use getopts::Options;
use lazycell::AtomicLazyCell;
use std::collections::HashSet; use std::collections::HashSet;
use std::ffi::OsString; use std::ffi::OsString;
use std::fs; use std::fs;
use std::io::{self, ErrorKind}; use std::io::{self, ErrorKind};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
use std::sync::{Arc, OnceLock};
use std::time::SystemTime; use std::time::SystemTime;
use std::{env, vec}; use std::{env, vec};
use test::ColorConfig; use test::ColorConfig;
@ -39,7 +39,6 @@
use self::header::{make_test_description, EarlyProps}; use self::header::{make_test_description, EarlyProps};
use crate::header::HeadersCache; use crate::header::HeadersCache;
use std::sync::Arc;
pub fn parse_config(args: Vec<String>) -> Config { pub fn parse_config(args: Vec<String>) -> Config {
let mut opts = Options::new(); let mut opts = Options::new();
@ -320,7 +319,7 @@ fn make_absolute(path: PathBuf) -> PathBuf {
force_rerun: matches.opt_present("force-rerun"), force_rerun: matches.opt_present("force-rerun"),
target_cfgs: AtomicLazyCell::new(), target_cfgs: OnceLock::new(),
nocapture: matches.opt_present("nocapture"), nocapture: matches.opt_present("nocapture"),

View File

@ -36,7 +36,6 @@
use anyhow::Context; use anyhow::Context;
use glob::glob; use glob::glob;
use once_cell::sync::Lazy;
use tracing::*; use tracing::*;
use crate::extract_gdb_version; use crate::extract_gdb_version;
@ -48,6 +47,13 @@
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
macro_rules! static_regex {
($re:literal) => {{
static RE: ::std::sync::OnceLock<::regex::Regex> = ::std::sync::OnceLock::new();
RE.get_or_init(|| ::regex::Regex::new($re).unwrap())
}};
}
const FAKE_SRC_BASE: &str = "fake-test-src-base"; const FAKE_SRC_BASE: &str = "fake-test-src-base";
#[cfg(windows)] #[cfg(windows)]
@ -765,28 +771,23 @@ fn anonymize_coverage_line_numbers(coverage: &str) -> String {
// ` 100|` => ` LL|` // ` 100|` => ` LL|`
// ` | 1000|` => ` | LL|` // ` | 1000|` => ` | LL|`
// ` | | 1000|` => ` | | LL|` // ` | | 1000|` => ` | | LL|`
static LINE_NUMBER_RE: Lazy<Regex> = let coverage = static_regex!(r"(?m:^)(?<prefix>(?: \|)*) *[0-9]+\|")
Lazy::new(|| Regex::new(r"(?m:^)(?<prefix>(?: \|)*) *[0-9]+\|").unwrap()); .replace_all(&coverage, "${prefix} LL|");
let coverage = LINE_NUMBER_RE.replace_all(&coverage, "${prefix} LL|");
// ` | Branch (1:` => ` | Branch (LL:` // ` | Branch (1:` => ` | Branch (LL:`
// ` | | Branch (10:` => ` | | Branch (LL:` // ` | | Branch (10:` => ` | | Branch (LL:`
static BRANCH_LINE_NUMBER_RE: Lazy<Regex> = let coverage = static_regex!(r"(?m:^)(?<prefix>(?: \|)+ Branch \()[0-9]+:")
Lazy::new(|| Regex::new(r"(?m:^)(?<prefix>(?: \|)+ Branch \()[0-9]+:").unwrap()); .replace_all(&coverage, "${prefix}LL:");
let coverage = BRANCH_LINE_NUMBER_RE.replace_all(&coverage, "${prefix}LL:");
// ` |---> MC/DC Decision Region (1:30) to (2:` => ` |---> MC/DC Decision Region (LL:30) to (LL:` // ` |---> MC/DC Decision Region (1:30) to (2:` => ` |---> MC/DC Decision Region (LL:30) to (LL:`
static MCDC_DECISION_LINE_NUMBER_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"(?m:^)(?<prefix>(?: \|)+---> MC/DC Decision Region \()[0-9]+:(?<middle>[0-9]+\) to \()[0-9]+:").unwrap()
});
let coverage = let coverage =
MCDC_DECISION_LINE_NUMBER_RE.replace_all(&coverage, "${prefix}LL:${middle}LL:"); static_regex!(r"(?m:^)(?<prefix>(?: \|)+---> MC/DC Decision Region \()[0-9]+:(?<middle>[0-9]+\) to \()[0-9]+:")
.replace_all(&coverage, "${prefix}LL:${middle}LL:");
// ` | Condition C1 --> (1:` => ` | Condition C1 --> (LL:` // ` | Condition C1 --> (1:` => ` | Condition C1 --> (LL:`
static MCDC_CONDITION_LINE_NUMBER_RE: Lazy<Regex> = Lazy::new(|| { let coverage =
Regex::new(r"(?m:^)(?<prefix>(?: \|)+ Condition C[0-9]+ --> \()[0-9]+:").unwrap() static_regex!(r"(?m:^)(?<prefix>(?: \|)+ Condition C[0-9]+ --> \()[0-9]+:")
}); .replace_all(&coverage, "${prefix}LL:");
let coverage = MCDC_CONDITION_LINE_NUMBER_RE.replace_all(&coverage, "${prefix}LL:");
coverage.into_owned() coverage.into_owned()
} }
@ -3471,13 +3472,12 @@ fn codegen_units_to_str(cgus: &HashSet<String>) -> String {
// the form <crate-name1>.<crate-disambiguator1>-in-<crate-name2>.<crate-disambiguator2>, // the form <crate-name1>.<crate-disambiguator1>-in-<crate-name2>.<crate-disambiguator2>,
// remove all crate-disambiguators. // remove all crate-disambiguators.
fn remove_crate_disambiguator_from_cgu(cgu: &str) -> String { fn remove_crate_disambiguator_from_cgu(cgu: &str) -> String {
static RE: Lazy<Regex> = Lazy::new(|| { let Some(captures) =
Regex::new(r"^[^\.]+(?P<d1>\.[[:alnum:]]+)(-in-[^\.]+(?P<d2>\.[[:alnum:]]+))?") static_regex!(r"^[^\.]+(?P<d1>\.[[:alnum:]]+)(-in-[^\.]+(?P<d2>\.[[:alnum:]]+))?")
.unwrap() .captures(cgu)
}); else {
panic!("invalid cgu name encountered: {cgu}");
let captures = };
RE.captures(cgu).unwrap_or_else(|| panic!("invalid cgu name encountered: {}", cgu));
let mut new_name = cgu.to_owned(); let mut new_name = cgu.to_owned();
@ -4073,18 +4073,16 @@ fn load_compare_outputs(
// 'uploaded "$TEST_BUILD_DIR/<test_executable>, waiting for result"' // 'uploaded "$TEST_BUILD_DIR/<test_executable>, waiting for result"'
// is printed to stdout by the client and then captured in the ProcRes, // is printed to stdout by the client and then captured in the ProcRes,
// so it needs to be removed when comparing the run-pass test execution output. // so it needs to be removed when comparing the run-pass test execution output.
static REMOTE_TEST_RE: Lazy<Regex> = Lazy::new(|| { normalized_stdout = static_regex!(
Regex::new( "^uploaded \"\\$TEST_BUILD_DIR(/[[:alnum:]_\\-.]+)+\", waiting for result\n"
"^uploaded \"\\$TEST_BUILD_DIR(/[[:alnum:]_\\-.]+)+\", waiting for result\n" )
) .replace(&normalized_stdout, "")
.unwrap() .to_string();
});
normalized_stdout = REMOTE_TEST_RE.replace(&normalized_stdout, "").to_string();
// When there is a panic, the remote-test-client also prints "died due to signal"; // When there is a panic, the remote-test-client also prints "died due to signal";
// that needs to be removed as well. // that needs to be removed as well.
static SIGNAL_DIED_RE: Lazy<Regex> = normalized_stdout = static_regex!("^died due to signal [0-9]+\n")
Lazy::new(|| Regex::new("^died due to signal [0-9]+\n").unwrap()); .replace(&normalized_stdout, "")
normalized_stdout = SIGNAL_DIED_RE.replace(&normalized_stdout, "").to_string(); .to_string();
// FIXME: it would be much nicer if we could just tell the remote-test-client to not // FIXME: it would be much nicer if we could just tell the remote-test-client to not
// print these things. // print these things.
} }
@ -4556,10 +4554,9 @@ fn normalize_output(&self, output: &str, custom_rules: &[(String, String)]) -> S
// with placeholders as we do not want tests needing updated when compiler source code // with placeholders as we do not want tests needing updated when compiler source code
// changes. // changes.
// eg. $SRC_DIR/libcore/mem.rs:323:14 becomes $SRC_DIR/libcore/mem.rs:LL:COL // eg. $SRC_DIR/libcore/mem.rs:323:14 becomes $SRC_DIR/libcore/mem.rs:LL:COL
static SRC_DIR_RE: Lazy<Regex> = normalized = static_regex!("SRC_DIR(.+):\\d+:\\d+(: \\d+:\\d+)?")
Lazy::new(|| Regex::new("SRC_DIR(.+):\\d+:\\d+(: \\d+:\\d+)?").unwrap()); .replace_all(&normalized, "SRC_DIR$1:LL:COL")
.into_owned();
normalized = SRC_DIR_RE.replace_all(&normalized, "SRC_DIR$1:LL:COL").into_owned();
normalized = Self::normalize_platform_differences(&normalized); normalized = Self::normalize_platform_differences(&normalized);
normalized = normalized.replace("\t", "\\t"); // makes tabs visible normalized = normalized.replace("\t", "\\t"); // makes tabs visible
@ -4568,34 +4565,29 @@ fn normalize_output(&self, output: &str, custom_rules: &[(String, String)]) -> S
// since they duplicate actual errors and make the output hard to read. // since they duplicate actual errors and make the output hard to read.
// This mirrors the regex in src/tools/tidy/src/style.rs, please update // This mirrors the regex in src/tools/tidy/src/style.rs, please update
// both if either are changed. // both if either are changed.
static ANNOTATION_RE: Lazy<Regex> = normalized =
Lazy::new(|| Regex::new("\\s*//(\\[.*\\])?~.*").unwrap()); static_regex!("\\s*//(\\[.*\\])?~.*").replace_all(&normalized, "").into_owned();
normalized = ANNOTATION_RE.replace_all(&normalized, "").into_owned();
// This code normalizes various hashes in v0 symbol mangling that is // This code normalizes various hashes in v0 symbol mangling that is
// emitted in the ui and mir-opt tests. // emitted in the ui and mir-opt tests.
static V0_CRATE_HASH_PREFIX_RE: Lazy<Regex> = let v0_crate_hash_prefix_re = static_regex!(r"_R.*?Cs[0-9a-zA-Z]+_");
Lazy::new(|| Regex::new(r"_R.*?Cs[0-9a-zA-Z]+_").unwrap()); let v0_crate_hash_re = static_regex!(r"Cs[0-9a-zA-Z]+_");
static V0_CRATE_HASH_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"Cs[0-9a-zA-Z]+_").unwrap());
const V0_CRATE_HASH_PLACEHOLDER: &str = r"CsCRATE_HASH_"; const V0_CRATE_HASH_PLACEHOLDER: &str = r"CsCRATE_HASH_";
if V0_CRATE_HASH_PREFIX_RE.is_match(&normalized) { if v0_crate_hash_prefix_re.is_match(&normalized) {
// Normalize crate hash // Normalize crate hash
normalized = normalized =
V0_CRATE_HASH_RE.replace_all(&normalized, V0_CRATE_HASH_PLACEHOLDER).into_owned(); v0_crate_hash_re.replace_all(&normalized, V0_CRATE_HASH_PLACEHOLDER).into_owned();
} }
static V0_BACK_REF_PREFIX_RE: Lazy<Regex> = let v0_back_ref_prefix_re = static_regex!(r"\(_R.*?B[0-9a-zA-Z]_");
Lazy::new(|| Regex::new(r"\(_R.*?B[0-9a-zA-Z]_").unwrap()); let v0_back_ref_re = static_regex!(r"B[0-9a-zA-Z]_");
static V0_BACK_REF_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"B[0-9a-zA-Z]_").unwrap());
const V0_BACK_REF_PLACEHOLDER: &str = r"B<REF>_"; const V0_BACK_REF_PLACEHOLDER: &str = r"B<REF>_";
if V0_BACK_REF_PREFIX_RE.is_match(&normalized) { if v0_back_ref_prefix_re.is_match(&normalized) {
// Normalize back references (see RFC 2603) // Normalize back references (see RFC 2603)
normalized = normalized =
V0_BACK_REF_RE.replace_all(&normalized, V0_BACK_REF_PLACEHOLDER).into_owned(); v0_back_ref_re.replace_all(&normalized, V0_BACK_REF_PLACEHOLDER).into_owned();
} }
// AllocId are numbered globally in a compilation session. This can lead to changes // AllocId are numbered globally in a compilation session. This can lead to changes
@ -4608,26 +4600,22 @@ fn normalize_output(&self, output: &str, custom_rules: &[(String, String)]) -> S
let mut seen_allocs = indexmap::IndexSet::new(); let mut seen_allocs = indexmap::IndexSet::new();
// The alloc-id appears in pretty-printed allocations. // The alloc-id appears in pretty-printed allocations.
static ALLOC_ID_PP_RE: Lazy<Regex> = Lazy::new(|| { normalized = static_regex!(
Regex::new(r"╾─*a(lloc)?([0-9]+)(\+0x[0-9]+)?(<imm>)?( \([0-9]+ ptr bytes\))?─*╼") r"╾─*a(lloc)?([0-9]+)(\+0x[0-9]+)?(<imm>)?( \([0-9]+ ptr bytes\))?─*╼"
.unwrap() )
}); .replace_all(&normalized, |caps: &Captures<'_>| {
normalized = ALLOC_ID_PP_RE // Renumber the captured index.
.replace_all(&normalized, |caps: &Captures<'_>| { let index = caps.get(2).unwrap().as_str().to_string();
// Renumber the captured index. let (index, _) = seen_allocs.insert_full(index);
let index = caps.get(2).unwrap().as_str().to_string(); let offset = caps.get(3).map_or("", |c| c.as_str());
let (index, _) = seen_allocs.insert_full(index); let imm = caps.get(4).map_or("", |c| c.as_str());
let offset = caps.get(3).map_or("", |c| c.as_str()); // Do not bother keeping it pretty, just make it deterministic.
let imm = caps.get(4).map_or("", |c| c.as_str()); format!("╾ALLOC{index}{offset}{imm}")
// Do not bother keeping it pretty, just make it deterministic. })
format!("╾ALLOC{index}{offset}{imm}") .into_owned();
})
.into_owned();
// The alloc-id appears in a sentence. // The alloc-id appears in a sentence.
static ALLOC_ID_RE: Lazy<Regex> = normalized = static_regex!(r"\balloc([0-9]+)\b")
Lazy::new(|| Regex::new(r"\balloc([0-9]+)\b").unwrap());
normalized = ALLOC_ID_RE
.replace_all(&normalized, |caps: &Captures<'_>| { .replace_all(&normalized, |caps: &Captures<'_>| {
let index = caps.get(1).unwrap().as_str().to_string(); let index = caps.get(1).unwrap().as_str().to_string();
let (index, _) = seen_allocs.insert_full(index); let (index, _) = seen_allocs.insert_full(index);
@ -4650,12 +4638,13 @@ fn normalize_output(&self, output: &str, custom_rules: &[(String, String)]) -> S
/// Replaces backslashes in paths with forward slashes, and replaces CRLF line endings /// Replaces backslashes in paths with forward slashes, and replaces CRLF line endings
/// with LF. /// with LF.
fn normalize_platform_differences(output: &str) -> String { fn normalize_platform_differences(output: &str) -> String {
/// Used to find Windows paths. let output = output.replace(r"\\", r"\");
///
/// It's not possible to detect paths in the error messages generally, but this is a // Used to find Windows paths.
/// decent enough heuristic. //
static PATH_BACKSLASH_RE: Lazy<Regex> = Lazy::new(|| { // It's not possible to detect paths in the error messages generally, but this is a
Regex::new( // decent enough heuristic.
static_regex!(
r#"(?x) r#"(?x)
(?: (?:
# Match paths that don't include spaces. # Match paths that don't include spaces.
@ -4663,14 +4652,8 @@ fn normalize_platform_differences(output: &str) -> String {
| |
# If the path starts with a well-known root, then allow spaces and no file extension. # If the path starts with a well-known root, then allow spaces and no file extension.
\$(?:DIR|SRC_DIR|TEST_BUILD_DIR|BUILD_DIR|LIB_DIR)(?:\\[\pL\pN\.\-_'\ ]+)+ \$(?:DIR|SRC_DIR|TEST_BUILD_DIR|BUILD_DIR|LIB_DIR)(?:\\[\pL\pN\.\-_'\ ]+)+
)"#, )"#
) )
.unwrap()
});
let output = output.replace(r"\\", r"\");
PATH_BACKSLASH_RE
.replace_all(&output, |caps: &Captures<'_>| { .replace_all(&output, |caps: &Captures<'_>| {
println!("{}", &caps[0]); println!("{}", &caps[0]);
caps[0].replace(r"\", "/") caps[0].replace(r"\", "/")

View File

@ -1,6 +0,0 @@
//@ known-bug: #123863
const fn concat_strs<const A: &'static str>() -> &'static str {
struct Inner<const A: &'static str>;
Inner::concat_strs::<"a">::A
}
pub fn main() {}

View File

@ -0,0 +1,23 @@
//@ build-fail
struct Bar<const BITS: usize>;
impl<const BITS: usize> Bar<BITS> {
const ASSERT: bool = {
let b = std::convert::identity(1);
["oops"][b]; //~ ERROR evaluation of `Bar::<0>::ASSERT` failed
true
};
fn assert() {
let val = Self::ASSERT;
if val {
std::convert::identity(val);
}
}
}
fn main() {
Bar::<0>::assert();
}

View File

@ -0,0 +1,29 @@
error[E0080]: evaluation of `Bar::<0>::ASSERT` failed
--> $DIR/mono-reachable-invalid-const.rs:8:9
|
LL | ["oops"][b];
| ^^^^^^^^^^^ index out of bounds: the length is 1 but the index is 1
note: erroneous constant encountered
--> $DIR/mono-reachable-invalid-const.rs:13:19
|
LL | let val = Self::ASSERT;
| ^^^^^^^^^^^^
note: erroneous constant encountered
--> $DIR/mono-reachable-invalid-const.rs:13:19
|
LL | let val = Self::ASSERT;
| ^^^^^^^^^^^^
|
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
note: the above error was encountered while instantiating `fn Bar::<0>::assert`
--> $DIR/mono-reachable-invalid-const.rs:22:5
|
LL | Bar::<0>::assert();
| ^^^^^^^^^^^^^^^^^^
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0080`.

View File

@ -9,7 +9,7 @@ LL | foo(|_|)
help: you might have meant to open the body of the closure help: you might have meant to open the body of the closure
| |
LL | foo(|_| {}) LL | foo(|_| {})
| ++ | ++
error[E0425]: cannot find function `foo` in this scope error[E0425]: cannot find function `foo` in this scope
--> $DIR/issue-32505.rs:2:5 --> $DIR/issue-32505.rs:2:5

View File

@ -0,0 +1,9 @@
const fn concat_strs<const A: &'static str>() -> &'static str {
//~^ ERROR &'static str` is forbidden as the type of a const generic parameter
struct Inner<const A: &'static str>;
//~^ ERROR &'static str` is forbidden as the type of a const generic parameter
Inner::concat_strs::<"a">::A
//~^ ERROR ambiguous associated type
}
pub fn main() {}

View File

@ -0,0 +1,38 @@
error: `&'static str` is forbidden as the type of a const generic parameter
--> $DIR/ice-unexpected-region-123863.rs:1:31
|
LL | const fn concat_strs<const A: &'static str>() -> &'static str {
| ^^^^^^^^^^^^
|
= note: the only supported types are integers, `bool` and `char`
help: add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types
|
LL + #![feature(adt_const_params)]
|
error: `&'static str` is forbidden as the type of a const generic parameter
--> $DIR/ice-unexpected-region-123863.rs:3:27
|
LL | struct Inner<const A: &'static str>;
| ^^^^^^^^^^^^
|
= note: the only supported types are integers, `bool` and `char`
help: add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types
|
LL + #![feature(adt_const_params)]
|
error[E0223]: ambiguous associated type
--> $DIR/ice-unexpected-region-123863.rs:5:5
|
LL | Inner::concat_strs::<"a">::A
| ^^^^^^^^^^^^^^^^^^^^^^^^^
|
help: if there were a trait named `Example` with associated type `concat_strs` implemented for `Inner<_>`, you could use the fully-qualified path
|
LL | <Inner<_> as Example>::concat_strs::A
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to 3 previous errors
For more information about this error, try `rustc --explain E0223`.