Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rollup of 9 pull requests #93734

Closed
wants to merge 24 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
9d664b2
Make the pre-commit script pre-push instead
jyn514 Aug 25, 2021
4738ce4
Suggest 1-tuple parentheses, without existing parens
bobrippling Dec 4, 2021
c734c32
Replace span suggestion with multipart
bobrippling Dec 4, 2021
18cea90
Handle existing parentheses when suggesting trailing-tuple-comma
bobrippling Jan 28, 2022
91a43f0
Only suggest 1-tuple if expected and found types match
bobrippling Jan 28, 2022
72d3b45
Test 1-tuple parentheses wrapping
bobrippling Jan 28, 2022
0fb2b7a
Drop json::from_reader
Mark-Simulacrum Feb 5, 2022
a4112dc
fix linking stage1 toolchain in setup
yerke Feb 6, 2022
57b102f
Fix tracking issue for `const_fn_trait_bound`
PatchMixolydic Feb 5, 2022
afb7a50
rewrite from_bytes_with_nul to match code style in from_vec_with_nul
inteon Feb 6, 2022
cf4ac6b
Add From<u8> for ExitCode
yaahc Jan 28, 2022
344ea6e
Factor out emit_tuple_wrap_err, improve Applicability
bobrippling Feb 2, 2022
82a0122
Merge duplicate suggestion string
bobrippling Feb 2, 2022
1870db6
Use shallow clones for submodules managed by rustbuild, not just boot…
jyn514 Feb 7, 2022
b5b2150
Rerun bootstrap's build script when RUSTC changes
jyn514 Feb 7, 2022
05a2c77
Rollup merge of #88313 - jyn514:pre-push, r=Mark-Simulacrum
matthiaskrgr Feb 7, 2022
cbde03e
Rollup merge of #91530 - bobrippling:suggest-1-tuple-parens, r=camelid
matthiaskrgr Feb 7, 2022
63dc52d
Rollup merge of #92724 - inteon:cleanup, r=Mark-Simulacrum
matthiaskrgr Feb 7, 2022
d736a96
Rollup merge of #93445 - yaahc:exitcode-constructor, r=dtolnay
matthiaskrgr Feb 7, 2022
b26068c
Rollup merge of #93487 - yerke:yerke/fix-link-toolchain-in-setup, r=M…
matthiaskrgr Feb 7, 2022
ea3b7ed
Rollup merge of #93680 - Mark-Simulacrum:drop-json-reader, r=bjorn3
matthiaskrgr Feb 7, 2022
ee1740b
Rollup merge of #93682 - PatchMixolydic:where-in-the-world-is-const_f…
matthiaskrgr Feb 7, 2022
530eba4
Rollup merge of #93722 - jyn514:less-submodule-cloning, r=Mark-Simula…
matthiaskrgr Feb 7, 2022
ae6a34c
Rollup merge of #93723 - jyn514:rerun-if-changed, r=Mark-Simulacrum
matthiaskrgr Feb 7, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion compiler/rustc_feature/src/active.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ declare_features! (
/// Allows using and casting function pointers in a `const fn`.
(active, const_fn_fn_ptr_basics, "1.48.0", Some(57563), None),
/// Allows trait bounds in `const fn`.
(active, const_fn_trait_bound, "1.53.0", Some(57563), None),
(active, const_fn_trait_bound, "1.53.0", Some(93706), None),
/// Allows `for _ in _` loops in const contexts.
(active, const_for, "1.56.0", Some(87575), None),
/// Allows argument and return position `impl Trait` in a `const fn`.
Expand Down
50 changes: 37 additions & 13 deletions compiler/rustc_infer/src/infer/error_reporting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2044,19 +2044,8 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
// If a tuple of length one was expected and the found expression has
// parentheses around it, perhaps the user meant to write `(expr,)` to
// build a tuple (issue #86100)
(ty::Tuple(_), _) if expected.tuple_fields().count() == 1 => {
if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) {
if let Some(code) =
code.strip_prefix('(').and_then(|s| s.strip_suffix(')'))
{
err.span_suggestion(
span,
"use a trailing comma to create a tuple with one element",
format!("({},)", code),
Applicability::MaybeIncorrect,
);
}
}
(ty::Tuple(_), _) => {
self.emit_tuple_wrap_err(&mut err, span, found, expected)
}
// If a character was expected and the found expression is a string literal
// containing a single character, perhaps the user meant to write `'c'` to
Expand Down Expand Up @@ -2119,6 +2108,41 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
diag
}

fn emit_tuple_wrap_err(
&self,
err: &mut DiagnosticBuilder<'tcx>,
span: Span,
found: Ty<'tcx>,
expected: Ty<'tcx>,
) {
let [expected_tup_elem] = &expected.tuple_fields().collect::<Vec<_>>()[..]
else { return };

if !same_type_modulo_infer(expected_tup_elem, found) {
return;
}

let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
else { return };

let msg = "use a trailing comma to create a tuple with one element";
if code.starts_with('(') && code.ends_with(')') {
let before_close = span.hi() - BytePos::from_u32(1);
err.span_suggestion(
span.with_hi(before_close).shrink_to_hi(),
msg,
",".into(),
Applicability::MachineApplicable,
);
} else {
err.multipart_suggestion(
msg,
vec![(span.shrink_to_lo(), "(".into()), (span.shrink_to_hi(), ",)".into())],
Applicability::MachineApplicable,
);
}
}

fn values_str(
&self,
values: ValuePairs<'tcx>,
Expand Down
22 changes: 0 additions & 22 deletions compiler/rustc_serialize/src/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,6 @@ use self::ParserState::*;

use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::io;
use std::io::prelude::*;
use std::mem::swap;
use std::num::FpCategory as Fp;
use std::ops::Index;
Expand Down Expand Up @@ -250,7 +248,6 @@ pub enum ErrorCode {
pub enum ParserError {
/// msg, line, col
SyntaxError(ErrorCode, usize, usize),
IoError(io::ErrorKind, String),
}

// Builder and Parser have the same errors.
Expand Down Expand Up @@ -329,10 +326,6 @@ impl fmt::Display for ErrorCode {
}
}

fn io_error_to_error(io: io::Error) -> ParserError {
IoError(io.kind(), io.to_string())
}

impl fmt::Display for ParserError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// FIXME this should be a nicer error
Expand Down Expand Up @@ -2163,21 +2156,6 @@ impl<T: Iterator<Item = char>> Builder<T> {
}
}

/// Decodes a json value from an `&mut io::Read`
pub fn from_reader(rdr: &mut dyn Read) -> Result<Json, BuilderError> {
let mut contents = Vec::new();
match rdr.read_to_end(&mut contents) {
Ok(c) => c,
Err(e) => return Err(io_error_to_error(e)),
};
let s = match str::from_utf8(&contents).ok() {
Some(s) => s,
_ => return Err(SyntaxError(NotUtf8, 0, 0)),
};
let mut builder = Builder::new(s.chars());
builder.build()
}

/// Decodes a json value from a string
pub fn from_str(s: &str) -> Result<Json, BuilderError> {
let mut builder = Builder::new(s.chars());
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_target/src/spec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2148,8 +2148,8 @@ impl Target {
use std::fs;

fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
let contents = fs::read(path).map_err(|e| e.to_string())?;
let obj = json::from_reader(&mut &contents[..]).map_err(|e| e.to_string())?;
let contents = fs::read_to_string(path).map_err(|e| e.to_string())?;
let obj = json::from_str(&contents).map_err(|e| e.to_string())?;
Target::from_json(obj)
}

Expand Down
15 changes: 8 additions & 7 deletions library/std/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1252,15 +1252,16 @@ impl CStr {
/// assert!(cstr.is_err());
/// ```
#[stable(feature = "cstr_from_bytes", since = "1.10.0")]
pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> {
pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, FromBytesWithNulError> {
let nul_pos = memchr::memchr(0, bytes);
if let Some(nul_pos) = nul_pos {
if nul_pos + 1 != bytes.len() {
return Err(FromBytesWithNulError::interior_nul(nul_pos));
match nul_pos {
Some(nul_pos) if nul_pos + 1 == bytes.len() => {
// SAFETY: We know there is only one nul byte, at the end
// of the byte slice.
Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
}
Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
} else {
Err(FromBytesWithNulError::not_nul_terminated())
Some(nul_pos) => Err(FromBytesWithNulError::interior_nul(nul_pos)),
None => Err(FromBytesWithNulError::not_nul_terminated()),
}
}

Expand Down
8 changes: 8 additions & 0 deletions library/std/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1691,6 +1691,14 @@ impl ExitCode {
}
}

#[unstable(feature = "process_exitcode_placeholder", issue = "48711")]
impl From<u8> for ExitCode {
/// Construct an exit code from an arbitrary u8 value.
fn from(code: u8) -> Self {
ExitCode(imp::ExitCode::from(code))
}
}

impl Child {
/// Forces the child process to exit. If the child has already exited, an [`InvalidInput`]
/// error is returned.
Expand Down
6 changes: 6 additions & 0 deletions library/std/src/sys/unix/process/process_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,12 @@ impl ExitCode {
}
}

impl From<u8> for ExitCode {
fn from(code: u8) -> Self {
Self(code)
}
}

pub struct CommandArgs<'a> {
iter: crate::slice::Iter<'a, CString>,
}
Expand Down
9 changes: 9 additions & 0 deletions library/std/src/sys/unsupported/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,15 @@ impl ExitCode {
}
}

impl From<u8> for ExitCode {
fn from(code: u8) -> Self {
match code {
0 => Self::SUCCESS,
1..255 => Self::FAILURE,
}
}
}

pub struct Process(!);

impl Process {
Expand Down
6 changes: 6 additions & 0 deletions library/std/src/sys/windows/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,12 @@ impl ExitCode {
}
}

impl From<u8> for ExitCode {
fn from(code: u8) -> Self {
ExitCode(c::DWORD::from(code))
}
}

fn zeroed_startupinfo() -> c::STARTUPINFO {
c::STARTUPINFO {
cb: 0,
Expand Down
14 changes: 14 additions & 0 deletions src/bootstrap/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ fn main() {
println!("{}", suggestion);
}

let pre_commit = config.src.join(".git").join("hooks").join("pre-commit");
Build::new(config).build();

if suggest_setup {
Expand All @@ -42,6 +43,19 @@ fn main() {
println!("{}", suggestion);
}

// Give a warning if the pre-commit script is in pre-commit and not pre-push.
// HACK: Since the commit script uses hard links, we can't actually tell if it was installed by x.py setup or not.
// We could see if it's identical to src/etc/pre-push.sh, but pre-push may have been modified in the meantime.
// Instead, look for this comment, which is almost certainly not in any custom hook.
if std::fs::read_to_string(pre_commit).map_or(false, |contents| {
contents.contains("https://github.com/rust-lang/rust/issues/77620#issuecomment-705144570")
}) {
println!(
"warning: You have the pre-push script installed to .git/hooks/pre-commit. \
Consider moving it to .git/hooks/pre-push instead, which runs less often."
);
}

if suggest_setup || changelog_suggestion.is_some() {
println!("note: this message was printed twice to make it more likely to be seen");
}
Expand Down
2 changes: 2 additions & 0 deletions src/bootstrap/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use std::path::PathBuf;

fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=RUSTC");
println!("cargo:rerun-if-env-changed=PATH");
println!("cargo:rustc-env=BUILD_TRIPLE={}", env::var("HOST").unwrap());

// This may not be a canonicalized path.
Expand Down
2 changes: 1 addition & 1 deletion src/bootstrap/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,7 @@ impl Build {
// Try passing `--progress` to start, then run git again without if that fails.
let update = |progress: bool| {
let mut git = Command::new("git");
git.args(&["submodule", "update", "--init", "--recursive"]);
git.args(&["submodule", "update", "--init", "--recursive", "--depth=1"]);
if progress {
git.arg("--progress");
}
Expand Down
53 changes: 45 additions & 8 deletions src/bootstrap/setup.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use crate::TargetSelection;
use crate::{t, VERSION};
use std::env::consts::EXE_SUFFIX;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::fs::File;
use std::path::{Path, PathBuf, MAIN_SEPARATOR};
use std::process::Command;
use std::str::FromStr;
use std::{
Expand Down Expand Up @@ -109,7 +111,8 @@ pub fn setup(src_path: &Path, profile: Profile) {
println!("`x.py` will now use the configuration at {}", include_path.display());

let build = TargetSelection::from_user(&env!("BUILD_TRIPLE"));
let stage_path = ["build", build.rustc_target_arg(), "stage1"].join("/");
let stage_path =
["build", build.rustc_target_arg(), "stage1"].join(&MAIN_SEPARATOR.to_string());

println!();

Expand Down Expand Up @@ -171,6 +174,13 @@ fn attempt_toolchain_link(stage_path: &str) {
return;
}

if !ensure_stage1_toolchain_placeholder_exists(stage_path) {
println!(
"Failed to create a template for stage 1 toolchain or confirm that it already exists"
);
return;
}

if try_link_toolchain(&stage_path[..]) {
println!(
"Added `stage1` rustup toolchain; try `cargo +stage1 build` on a separate rust project to run a newly-built toolchain"
Expand Down Expand Up @@ -219,6 +229,33 @@ fn try_link_toolchain(stage_path: &str) -> bool {
.map_or(false, |output| output.status.success())
}

fn ensure_stage1_toolchain_placeholder_exists(stage_path: &str) -> bool {
let pathbuf = PathBuf::from(stage_path);

if fs::create_dir_all(pathbuf.join("lib")).is_err() {
return false;
};

let pathbuf = pathbuf.join("bin");
if fs::create_dir_all(&pathbuf).is_err() {
return false;
};

let pathbuf = pathbuf.join(format!("rustc{}", EXE_SUFFIX));

if pathbuf.exists() {
return true;
}

// Take care not to overwrite the file
let result = File::options().append(true).create(true).open(&pathbuf);
if result.is_err() {
return false;
}

return true;
}

// Used to get the path for `Subcommand::Setup`
pub fn interactive_path() -> io::Result<Profile> {
fn abbrev_all() -> impl Iterator<Item = ((String, String), Profile)> {
Expand Down Expand Up @@ -271,9 +308,9 @@ fn install_git_hook_maybe(src_path: &Path) -> io::Result<()> {
let mut input = String::new();
println!(
"Rust's CI will automatically fail if it doesn't pass `tidy`, the internal tool for ensuring code quality.
If you'd like, x.py can install a git hook for you that will automatically run `tidy --bless` on each commit
to ensure your code is up to par. If you decide later that this behavior is undesirable,
simply delete the `pre-commit` file from .git/hooks."
If you'd like, x.py can install a git hook for you that will automatically run `tidy --bless` before
pushing your code to ensure your code is up to par. If you decide later that this behavior is
undesirable, simply delete the `pre-push` file from .git/hooks."
);

let should_install = loop {
Expand All @@ -293,21 +330,21 @@ simply delete the `pre-commit` file from .git/hooks."
};

if should_install {
let src = src_path.join("src").join("etc").join("pre-commit.sh");
let src = src_path.join("src").join("etc").join("pre-push.sh");
let git = t!(Command::new("git").args(&["rev-parse", "--git-common-dir"]).output().map(
|output| {
assert!(output.status.success(), "failed to run `git`");
PathBuf::from(t!(String::from_utf8(output.stdout)).trim())
}
));
let dst = git.join("hooks").join("pre-commit");
let dst = git.join("hooks").join("pre-push");
match fs::hard_link(src, &dst) {
Err(e) => println!(
"error: could not create hook {}: do you already have the git hook installed?\n{}",
dst.display(),
e
),
Ok(_) => println!("Linked `src/etc/pre-commit.sh` to `.git/hooks/pre-commit`"),
Ok(_) => println!("Linked `src/etc/pre-commit.sh` to `.git/hooks/pre-push`"),
};
} else {
println!("Ok, skipping installation!");
Expand Down
2 changes: 1 addition & 1 deletion src/etc/pre-commit.sh → src/etc/pre-push.sh
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "win32" ]]; then
COMMAND="python $COMMAND"
fi

echo "Running pre-commit script '$COMMAND'"
echo "Running pre-push script '$COMMAND'"

cd "$ROOT_DIR"

Expand Down
4 changes: 4 additions & 0 deletions src/test/ui/consts/const-tup-index-span.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ LL | const TUP: (usize,) = 5usize << 64;
|
= note: expected tuple `(usize,)`
found type `usize`
help: use a trailing comma to create a tuple with one element
|
LL | const TUP: (usize,) = (5usize << 64,);
| + ++

error: aborting due to previous error

Expand Down
Loading