Skip to content

Commit

Permalink
Auto merge of #107788 - matthiaskrgr:rollup-mw10sli, r=matthiaskrgr
Browse files Browse the repository at this point in the history
Rollup of 8 pull requests

Successful merges:

 - #107656 (Bump rust-installer)
 - #107757 (Allow automatically creating vscode `settings.json` with `x setup`)
 - #107769 (Rename `PointerSized` to `PointerLike`)
 - #107770 (rustdoc: use a newline instead of `<br>` to format code headers)
 - #107771 (Tweak ICE message)
 - #107773 (Clearly signal purpose of the yaml template)
 - #107776 (Docs: Fix format of headings in String::reserve)
 - #107779 (Remove astconv usage in diagnostic)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed Feb 8, 2023
2 parents 7ba4e95 + fe26182 commit 6eb9f2d
Show file tree
Hide file tree
Showing 53 changed files with 375 additions and 165 deletions.
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/ice.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Internal Compiler Error (Structured form)
name: Internal Compiler Error (for use by automated tooling)
description: For now, you'll want to use the other ICE template, as GitHub forms have strict limits on the size of fields so backtraces cannot be pasted directly.
labels: ["C-bug", "I-ICE", "T-compiler"]
title: "[ICE]: "
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_const_eval/src/interpret/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
let vtable = self.get_vtable_ptr(src.layout.ty, data.principal())?;
let vtable = Scalar::from_maybe_pointer(vtable, self);
let data = self.read_immediate(src)?.to_scalar();
let _assert_pointer_sized = data.to_pointer(self)?;
let _assert_pointer_like = data.to_pointer(self)?;
let val = Immediate::ScalarPair(data, vtable);
self.write_immediate(val, dest)?;
} else {
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_driver_impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1200,11 +1200,9 @@ pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
if !info.payload().is::<rustc_errors::ExplicitBug>()
&& !info.payload().is::<rustc_errors::DelayedBugPanic>()
{
let mut d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
handler.emit_diagnostic(&mut d);
handler.emit_err(session_diagnostics::Ice);
}

handler.emit_note(session_diagnostics::Ice);
handler.emit_note(session_diagnostics::IceBugReport { bug_report_url });
handler.emit_note(session_diagnostics::IceVersion {
version: util::version_str!().unwrap_or("unknown_version"),
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir/src/lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ language_item_table! {
TryTraitBranch, sym::branch, branch_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None;
TryTraitFromYeet, sym::from_yeet, from_yeet_fn, Target::Fn, GenericRequirement::None;

PointerSized, sym::pointer_sized, pointer_sized, Target::Trait, GenericRequirement::Exact(0);
PointerLike, sym::pointer_like, pointer_like, Target::Trait, GenericRequirement::Exact(0);

Poll, sym::Poll, poll, Target::Enum, GenericRequirement::None;
PollReady, sym::Ready, poll_ready_variant, Target::Variant, GenericRequirement::None;
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/coercion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -765,7 +765,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
self.cause.clone(),
self.param_env,
ty::Binder::dummy(
self.tcx.at(self.cause.span).mk_trait_ref(hir::LangItem::PointerSized, [a]),
self.tcx.at(self.cause.span).mk_trait_ref(hir::LangItem::PointerLike, [a]),
),
));

Expand Down
21 changes: 11 additions & 10 deletions compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1336,16 +1336,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
hir::Path { segments: [segment], .. },
))
| hir::ExprKind::Path(QPath::TypeRelative(ty, segment)) => {
let self_ty = self.astconv().ast_ty_to_ty(ty);
if let Ok(pick) = self.probe_for_name(
Mode::Path,
Ident::new(capitalized_name, segment.ident.span),
Some(expected_ty),
IsSuggestion(true),
self_ty,
expr.hir_id,
ProbeScope::TraitsInScope,
) {
if let Some(self_ty) = self.typeck_results.borrow().node_type_opt(ty.hir_id)
&& let Ok(pick) = self.probe_for_name(
Mode::Path,
Ident::new(capitalized_name, segment.ident.span),
Some(expected_ty),
IsSuggestion(true),
self_ty,
expr.hir_id,
ProbeScope::TraitsInScope,
)
{
(pick.item, segment)
} else {
return false;
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1084,7 +1084,7 @@ symbols! {
plugins,
pointee_trait,
pointer,
pointer_sized,
pointer_like,
poll,
position,
post_dash_lto: "post-lto",
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_trait_selection/src/solve/assembly.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,9 @@ pub(super) trait GoalKind<'tcx>: TypeFoldable<'tcx> + Copy + Eq {
goal: Goal<'tcx, Self>,
) -> QueryResult<'tcx>;

// A type is `PointerSized` if we can compute its layout, and that layout
// A type is `PointerLike` if we can compute its layout, and that layout
// matches the layout of `usize`.
fn consider_builtin_pointer_sized_candidate(
fn consider_builtin_pointer_like_candidate(
ecx: &mut EvalCtxt<'_, 'tcx>,
goal: Goal<'tcx, Self>,
) -> QueryResult<'tcx>;
Expand Down Expand Up @@ -312,8 +312,8 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
|| lang_items.clone_trait() == Some(trait_def_id)
{
G::consider_builtin_copy_clone_candidate(self, goal)
} else if lang_items.pointer_sized() == Some(trait_def_id) {
G::consider_builtin_pointer_sized_candidate(self, goal)
} else if lang_items.pointer_like() == Some(trait_def_id) {
G::consider_builtin_pointer_like_candidate(self, goal)
} else if let Some(kind) = self.tcx().fn_trait_kind_from_def_id(trait_def_id) {
G::consider_builtin_fn_trait_candidates(self, goal, kind)
} else if lang_items.tuple_trait() == Some(trait_def_id) {
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_trait_selection/src/solve/project_goals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,11 +370,11 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> {
bug!("`Copy`/`Clone` does not have an associated type: {:?}", goal);
}

fn consider_builtin_pointer_sized_candidate(
fn consider_builtin_pointer_like_candidate(
_ecx: &mut EvalCtxt<'_, 'tcx>,
goal: Goal<'tcx, Self>,
) -> QueryResult<'tcx> {
bug!("`PointerSized` does not have an associated type: {:?}", goal);
bug!("`PointerLike` does not have an associated type: {:?}", goal);
}

fn consider_builtin_fn_trait_candidates(
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_trait_selection/src/solve/trait_goals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> {
)
}

fn consider_builtin_pointer_sized_candidate(
fn consider_builtin_pointer_like_candidate(
ecx: &mut EvalCtxt<'_, 'tcx>,
goal: Goal<'tcx, Self>,
) -> QueryResult<'tcx> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
self.assemble_candidates_for_transmutability(obligation, &mut candidates);
} else if lang_items.tuple_trait() == Some(def_id) {
self.assemble_candidate_for_tuple(obligation, &mut candidates);
} else if lang_items.pointer_sized() == Some(def_id) {
} else if lang_items.pointer_like() == Some(def_id) {
self.assemble_candidate_for_ptr_sized(obligation, &mut candidates);
} else {
if lang_items.clone_trait() == Some(def_id) {
Expand Down
4 changes: 2 additions & 2 deletions library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -928,12 +928,12 @@ impl String {

/// Copies elements from `src` range to the end of the string.
///
/// ## Panics
/// # Panics
///
/// Panics if the starting point or end point do not lie on a [`char`]
/// boundary, or if they're out of bounds.
///
/// ## Examples
/// # Examples
///
/// ```
/// #![feature(string_extend_from_within)]
Expand Down
11 changes: 6 additions & 5 deletions library/core/src/marker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -872,13 +872,14 @@ pub trait Destruct {}
pub trait Tuple {}

/// A marker for things
#[unstable(feature = "pointer_sized_trait", issue = "none")]
#[lang = "pointer_sized"]
#[unstable(feature = "pointer_like_trait", issue = "none")]
#[cfg_attr(bootstrap, lang = "pointer_sized")]
#[cfg_attr(not(bootstrap), lang = "pointer_like")]
#[rustc_on_unimplemented(
message = "`{Self}` needs to be a pointer-sized type",
label = "`{Self}` needs to be a pointer-sized type"
message = "`{Self}` needs to have the same alignment and size as a pointer",
label = "`{Self}` needs to be a pointer-like type"
)]
pub trait PointerSized {}
pub trait PointerLike {}

/// Implementations of `Copy` for primitive types.
///
Expand Down
147 changes: 121 additions & 26 deletions src/bootstrap/setup.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::builder::{Builder, RunConfig, ShouldRun, Step};
use crate::Config;
use crate::{t, VERSION};
use sha2::Digest;
use std::env::consts::EXE_SUFFIX;
use std::fmt::Write as _;
use std::fs::File;
Expand All @@ -10,6 +11,9 @@ use std::process::Command;
use std::str::FromStr;
use std::{fmt, fs, io};

#[cfg(test)]
mod tests;

#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum Profile {
Compiler,
Expand All @@ -19,6 +23,13 @@ pub enum Profile {
User,
}

/// A list of historical hashes of `src/etc/vscode_settings.json`.
/// New entries should be appended whenever this is updated so we can detected
/// outdated vs. user-modified settings files.
static SETTINGS_HASHES: &[&str] =
&["ea67e259dedf60d4429b6c349a564ffcd1563cf41c920a856d1f5b16b4701ac8"];
static VSCODE_SETTINGS: &str = include_str!("../etc/vscode_settings.json");

impl Profile {
fn include_path(&self, src_path: &Path) -> PathBuf {
PathBuf::from(format!("{}/src/bootstrap/defaults/config.{}.toml", src_path.display(), self))
Expand Down Expand Up @@ -155,6 +166,7 @@ pub fn setup(config: &Config, profile: Profile) {

if !config.dry_run() {
t!(install_git_hook_maybe(&config));
t!(create_vscode_settings_maybe(&config));
}

println!();
Expand Down Expand Up @@ -351,6 +363,34 @@ pub fn interactive_path() -> io::Result<Profile> {
Ok(template)
}

#[derive(PartialEq)]
enum PromptResult {
Yes, // y/Y/yes
No, // n/N/no
Print, // p/P/print
}

/// Prompt a user for a answer, looping until they enter an accepted input or nothing
fn prompt_user(prompt: &str) -> io::Result<Option<PromptResult>> {
let mut input = String::new();
loop {
print!("{prompt} ");
io::stdout().flush()?;
input.clear();
io::stdin().read_line(&mut input)?;
match input.trim().to_lowercase().as_str() {
"y" | "yes" => return Ok(Some(PromptResult::Yes)),
"n" | "no" => return Ok(Some(PromptResult::No)),
"p" | "print" => return Ok(Some(PromptResult::Print)),
"" => return Ok(None),
_ => {
eprintln!("error: unrecognized option '{}'", input.trim());
eprintln!("note: press Ctrl+C to exit");
}
};
}
}

// install a git hook to automatically run tidy, if they want
fn install_git_hook_maybe(config: &Config) -> io::Result<()> {
let git = t!(config.git().args(&["rev-parse", "--git-common-dir"]).output().map(|output| {
Expand All @@ -363,43 +403,98 @@ fn install_git_hook_maybe(config: &Config) -> io::Result<()> {
return Ok(());
}

let mut input = String::new();
println!();
println!(
"Rust's CI will automatically fail if it doesn't pass `tidy`, the internal tool for ensuring code quality.
"\nRust'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 `test tidy` 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 {
print!("Would you like to install the git hook?: [y/N] ");
io::stdout().flush()?;
input.clear();
io::stdin().read_line(&mut input)?;
break match input.trim().to_lowercase().as_str() {
"y" | "yes" => true,
"n" | "no" | "" => false,
_ => {
eprintln!("error: unrecognized option '{}'", input.trim());
eprintln!("note: press Ctrl+C to exit");
continue;
}
};
};

if should_install {
let src = config.src.join("src").join("etc").join("pre-push.sh");
match fs::hard_link(src, &dst) {
Err(e) => eprintln!(
if prompt_user("Would you like to install the git hook?: [y/N]")? != Some(PromptResult::Yes) {
println!("Ok, skipping installation!");
return Ok(());
}
let src = config.src.join("src").join("etc").join("pre-push.sh");
match fs::hard_link(src, &dst) {
Err(e) => {
eprintln!(
"error: could not create hook {}: do you already have the git hook installed?\n{}",
dst.display(),
e
),
Ok(_) => println!("Linked `src/etc/pre-push.sh` to `.git/hooks/pre-push`"),
);
return Err(e);
}
Ok(_) => println!("Linked `src/etc/pre-push.sh` to `.git/hooks/pre-push`"),
};
Ok(())
}

/// Create a `.vscode/settings.json` file for rustc development, or just print it
fn create_vscode_settings_maybe(config: &Config) -> io::Result<()> {
let (current_hash, historical_hashes) = SETTINGS_HASHES.split_last().unwrap();
let vscode_settings = config.src.join(".vscode").join("settings.json");
// If None, no settings.json exists
// If Some(true), is a previous version of settings.json
// If Some(false), is not a previous version (i.e. user modified)
// If it's up to date we can just skip this
let mut mismatched_settings = None;
if let Ok(current) = fs::read_to_string(&vscode_settings) {
let mut hasher = sha2::Sha256::new();
hasher.update(&current);
let hash = hex::encode(hasher.finalize().as_slice());
if hash == *current_hash {
return Ok(());
} else if historical_hashes.contains(&hash.as_str()) {
mismatched_settings = Some(true);
} else {
mismatched_settings = Some(false);
}
}
println!(
"\nx.py can automatically install the recommended `.vscode/settings.json` file for rustc development"
);
match mismatched_settings {
Some(true) => eprintln!(
"warning: existing `.vscode/settings.json` is out of date, x.py will update it"
),
Some(false) => eprintln!(
"warning: existing `.vscode/settings.json` has been modified by user, x.py will back it up and replace it"
),
_ => (),
}
let should_create = match prompt_user(
"Would you like to create/update `settings.json`, or only print suggested settings?: [y/p/N]",
)? {
Some(PromptResult::Yes) => true,
Some(PromptResult::Print) => false,
_ => {
println!("Ok, skipping settings!");
return Ok(());
}
};
if should_create {
let path = config.src.join(".vscode");
if !path.exists() {
fs::create_dir(&path)?;
}
let verb = match mismatched_settings {
// exists but outdated, we can replace this
Some(true) => "Updated",
// exists but user modified, back it up
Some(false) => {
// exists and is not current version or outdated, so back it up
let mut backup = vscode_settings.clone();
backup.set_extension("bak");
eprintln!("warning: copying `settings.json` to `settings.json.bak`");
fs::copy(&vscode_settings, &backup)?;
"Updated"
}
_ => "Created",
};
fs::write(&vscode_settings, &VSCODE_SETTINGS)?;
println!("{verb} `.vscode/settings.json`");
} else {
println!("Ok, skipping installation!");
println!("\n{VSCODE_SETTINGS}");
}
Ok(())
}
14 changes: 14 additions & 0 deletions src/bootstrap/setup/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use super::{SETTINGS_HASHES, VSCODE_SETTINGS};
use sha2::Digest;

#[test]
fn check_matching_settings_hash() {
let mut hasher = sha2::Sha256::new();
hasher.update(&VSCODE_SETTINGS);
let hash = hex::encode(hasher.finalize().as_slice());
assert_eq!(
&hash,
SETTINGS_HASHES.last().unwrap(),
"Update `SETTINGS_HASHES` with the new hash of `src/etc/vscode_settings.json`"
);
}
Loading

0 comments on commit 6eb9f2d

Please sign in to comment.