Skip to content

misc cleanups #1

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

Draft
wants to merge 22 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
11 changes: 6 additions & 5 deletions compiler/rustc_ast/src/attr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -534,13 +534,14 @@ impl MetaItemInner {
pub fn singleton_lit_list(&self) -> Option<(Symbol, &MetaItemLit)> {
self.meta_item().and_then(|meta_item| {
meta_item.meta_item_list().and_then(|meta_item_list| {
if meta_item_list.len() == 1
&& let Some(ident) = meta_item.ident()
&& let Some(lit) = meta_item_list[0].lit()
if let Some(ident) = meta_item.ident()
&& let [item] = meta_item_list
&& let Some(lit) = item.lit()
{
return Some((ident.name, lit));
Some((ident.name, lit))
} else {
None
}
None
})
})
}
Expand Down
29 changes: 15 additions & 14 deletions compiler/rustc_ast_lowering/src/asm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,20 +269,21 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
}
let valid_modifiers = class.valid_modifiers(asm_arch.unwrap());
if !valid_modifiers.contains(&modifier) {
let sub = if !valid_modifiers.is_empty() {
let mut mods = format!("`{}`", valid_modifiers[0]);
for m in &valid_modifiers[1..] {
let _ = write!(mods, ", `{m}`");
}
InvalidAsmTemplateModifierRegClassSub::SupportModifier {
class_name: class.name(),
modifiers: mods,
}
} else {
InvalidAsmTemplateModifierRegClassSub::DoesNotSupportModifier {
class_name: class.name(),
}
};
let sub =
if let [first_modifier, valid_modifiers @ ..] = valid_modifiers {
let mut mods = format!("`{first_modifier}`");
for m in valid_modifiers {
let _ = write!(mods, ", `{m}`");
}
InvalidAsmTemplateModifierRegClassSub::SupportModifier {
class_name: class.name(),
modifiers: mods,
}
} else {
InvalidAsmTemplateModifierRegClassSub::DoesNotSupportModifier {
class_name: class.name(),
}
};
self.dcx().emit_err(InvalidAsmTemplateModifierRegClass {
placeholder_span,
op_span: op_sp,
Expand Down
12 changes: 7 additions & 5 deletions compiler/rustc_ast_lowering/src/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -562,11 +562,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
}

// Condition should match `build_reduced_graph_for_use_tree`.
let path = if trees.is_empty()
&& !(prefix.segments.is_empty()
|| prefix.segments.len() == 1
&& prefix.segments[0].ident.name == kw::PathRoot)
{
let empty_for_self = |prefix: &[PathSegment]| {
matches!(
prefix,
[] | [PathSegment { ident: Ident { name: kw::PathRoot, .. }, .. }]
)
};
let path = if trees.is_empty() && !empty_for_self(&prefix.segments) {
// For empty lists we need to lower the prefix so it is checked for things
// like stability later.
let res = self.lower_import_res(id, span);
Expand Down
25 changes: 16 additions & 9 deletions compiler/rustc_borrowck/src/borrowck_errors.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]

use std::fmt;

use rustc_errors::codes::*;
use rustc_errors::{Applicability, Diag, DiagCtxtHandle, struct_span_code_err};
use rustc_hir as hir;
Expand Down Expand Up @@ -48,6 +50,10 @@ impl<'infcx, 'tcx> crate::MirBorrowckCtxt<'_, 'infcx, 'tcx> {
.with_span_label(span, format!("use of borrowed {borrow_desc}"))
}

fn print_via(msg: &str) -> impl fmt::Display + '_ {
fmt::from_fn(move |f| if msg.is_empty() { Ok(()) } else { write!(f, " (via {msg})") })
}

pub(crate) fn cannot_mutably_borrow_multiply(
&self,
new_loan_span: Span,
Expand All @@ -57,14 +63,13 @@ impl<'infcx, 'tcx> crate::MirBorrowckCtxt<'_, 'infcx, 'tcx> {
old_opt_via: &str,
old_load_end_span: Option<Span>,
) -> Diag<'infcx> {
let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {msg})") };
let mut err = struct_span_code_err!(
self.dcx(),
new_loan_span,
E0499,
"cannot borrow {}{} as mutable more than once at a time",
desc,
via(opt_via),
Self::print_via(opt_via),
);
if old_loan_span == new_loan_span {
// Both borrows are happening in the same place
Expand All @@ -74,7 +79,7 @@ impl<'infcx, 'tcx> crate::MirBorrowckCtxt<'_, 'infcx, 'tcx> {
format!(
"{}{} was mutably borrowed here in the previous iteration of the loop{}",
desc,
via(opt_via),
Self::print_via(opt_via),
opt_via,
),
);
Expand All @@ -84,11 +89,11 @@ impl<'infcx, 'tcx> crate::MirBorrowckCtxt<'_, 'infcx, 'tcx> {
} else {
err.span_label(
old_loan_span,
format!("first mutable borrow occurs here{}", via(old_opt_via)),
format!("first mutable borrow occurs here{}", Self::print_via(old_opt_via)),
);
err.span_label(
new_loan_span,
format!("second mutable borrow occurs here{}", via(opt_via)),
format!("second mutable borrow occurs here{}", Self::print_via(opt_via)),
);
if let Some(old_load_end_span) = old_load_end_span {
err.span_label(old_load_end_span, "first borrow ends here");
Expand Down Expand Up @@ -201,18 +206,17 @@ impl<'infcx, 'tcx> crate::MirBorrowckCtxt<'_, 'infcx, 'tcx> {
msg_old: &str,
old_load_end_span: Option<Span>,
) -> Diag<'infcx> {
let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {msg})") };
let mut err = struct_span_code_err!(
self.dcx(),
span,
E0502,
"cannot borrow {}{} as {} because {} is also borrowed as {}{}",
desc_new,
via(msg_new),
Self::print_via(msg_new),
kind_new,
noun_old,
kind_old,
via(msg_old),
Self::print_via(msg_old),
);

if msg_new.is_empty() {
Expand All @@ -227,7 +231,10 @@ impl<'infcx, 'tcx> crate::MirBorrowckCtxt<'_, 'infcx, 'tcx> {
"{kind_new} borrow of {msg_new} -- which overlaps with {msg_old} -- occurs here",
),
);
err.span_label(old_span, format!("{} borrow occurs here{}", kind_old, via(msg_old)));
err.span_label(
old_span,
format!("{} borrow occurs here{}", kind_old, Self::print_via(msg_old)),
);
}

if let Some(old_load_end_span) = old_load_end_span {
Expand Down
15 changes: 8 additions & 7 deletions compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2656,13 +2656,14 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
&& let Res::Local(hir_id) = seg.res
&& Some(hir_id) == self.closure_local_id
{
let (span, arg_str) = if args.len() > 0 {
(args[0].span.shrink_to_lo(), "self, ".to_string())
} else {
let span = e.span.trim_start(seg.ident.span).unwrap_or(e.span);
(span, "(self)".to_string())
};
self.closure_call_changes.push((span, arg_str));
let change = args
.get(0)
.map(|arg| (arg.span.shrink_to_lo(), "self, ".to_string()))
.unwrap_or_else(|| {
let span = e.span.trim_start(seg.ident.span).unwrap_or(e.span);
(span, "(self)".to_string())
});
self.closure_call_changes.push(change);
}
hir::intravisit::walk_stmt(self, s);
}
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_borrowck/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#![doc(rust_logo)]
#![feature(assert_matches)]
#![feature(box_patterns)]
#![feature(debug_closure_helpers)]
#![feature(file_buffered)]
#![feature(if_let_guard)]
#![feature(let_chains)]
Expand Down
30 changes: 16 additions & 14 deletions compiler/rustc_borrowck/src/region_infer/opaque_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,20 +356,22 @@ fn check_opaque_type_parameter_valid<'tcx>(
}

for (_, indices) in seen_params {
if indices.len() > 1 {
let descr = opaque_generics.param_at(indices[0], tcx).kind.descr();
let spans: Vec<_> = indices
.into_iter()
.map(|i| tcx.def_span(opaque_generics.param_at(i, tcx).def_id))
.collect();
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)]
return Err(infcx
.dcx()
.struct_span_err(span, "non-defining opaque type use in defining scope")
.with_span_note(spans, format!("{descr} used multiple times"))
.emit());
}
let [first_index, _, ..] = indices[..] else {
continue;
};

let descr = opaque_generics.param_at(first_index, tcx).kind.descr();
let spans: Vec<_> = indices
.into_iter()
.map(|i| tcx.def_span(opaque_generics.param_at(i, tcx).def_id))
.collect();
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)]
return Err(infcx
.dcx()
.struct_span_err(span, "non-defining opaque type use in defining scope")
.with_span_note(spans, format!("{descr} used multiple times"))
.emit());
}

Ok(())
Expand Down
46 changes: 25 additions & 21 deletions compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,27 +78,31 @@ pub(crate) fn expand_deriving_coerce_pointee(
})
.collect();

let pointee_param_idx = if type_params.is_empty() {
// `#[derive(CoercePointee)]` requires at least one generic type on the target `struct`
cx.dcx().emit_err(RequireOneGeneric { span });
return;
} else if type_params.len() == 1 {
// Regardless of the only type param being designed as `#[pointee]` or not, we can just use it as such
type_params[0].0
} else {
let mut pointees = type_params
.iter()
.filter_map(|&(idx, span, is_pointee)| is_pointee.then_some((idx, span)))
.fuse();
match (pointees.next(), pointees.next()) {
(Some((idx, _span)), None) => idx,
(None, _) => {
cx.dcx().emit_err(RequireOnePointee { span });
return;
}
(Some((_, one)), Some((_, another))) => {
cx.dcx().emit_err(TooManyPointees { one, another });
return;
let pointee_param_idx = match type_params[..] {
[] => {
// `#[derive(CoercePointee)]` requires at least one generic type on the target `struct`
cx.dcx().emit_err(RequireOneGeneric { span });
return;
}
[(idx, ..)] => {
// Regardless of the only type param being designed as `#[pointee]` or not, we can just use it as such
idx
}
_ => {
let mut pointees = type_params
.iter()
.filter_map(|&(idx, span, is_pointee)| is_pointee.then_some((idx, span)))
.fuse();
match (pointees.next(), pointees.next()) {
(Some((idx, _span)), None) => idx,
(None, _) => {
cx.dcx().emit_err(RequireOnePointee { span });
return;
}
(Some((_, one)), Some((_, another))) => {
cx.dcx().emit_err(TooManyPointees { one, another });
return;
}
}
}
};
Expand Down
33 changes: 13 additions & 20 deletions compiler/rustc_codegen_ssa/src/back/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,7 @@ pub fn each_linked_rlib(
f: &mut dyn FnMut(CrateNum, &Path),
) -> Result<(), errors::LinkRlibError> {
let fmts = if let Some(crate_type) = crate_type {
let Some(fmts) = info.dependency_formats.get(&crate_type) else {
return Err(errors::LinkRlibError::MissingFormat);
};

fmts
info.dependency_formats.get(&crate_type).ok_or(errors::LinkRlibError::MissingFormat)?
} else {
for combination in info.dependency_formats.iter().combinations(2) {
let (ty1, list1) = &combination[0];
Expand All @@ -256,28 +252,25 @@ pub fn each_linked_rlib(
});
}
}
if info.dependency_formats.is_empty() {
return Err(errors::LinkRlibError::MissingFormat);
}
info.dependency_formats.first().unwrap().1
info.dependency_formats.first().ok_or(errors::LinkRlibError::MissingFormat)?.1
};

let used_dep_crates = info.used_crates.iter();
for &cnum in used_dep_crates {
match fmts.get(cnum) {
Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
Some(_) => {}
None => return Err(errors::LinkRlibError::MissingFormat),
let fmt = fmts.get(cnum).ok_or(errors::LinkRlibError::MissingFormat)?;
if matches!(fmt, Linkage::NotLinked | Linkage::Dynamic | Linkage::IncludedFromDylib) {
continue;
}
let crate_name = info.crate_name[&cnum];
let used_crate_source = &info.used_crate_source[&cnum];
if let Some((path, _)) = &used_crate_source.rlib {
f(cnum, path);
} else if used_crate_source.rmeta.is_some() {
return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
} else {
return Err(errors::LinkRlibError::NotFound { crate_name });
}
let Some((path, _)) = &used_crate_source.rlib else {
return Err(if used_crate_source.rmeta.is_some() {
errors::LinkRlibError::OnlyRmetaFound { crate_name }
} else {
errors::LinkRlibError::NotFound { crate_name }
});
};
f(cnum, path);
}
Ok(())
}
Expand Down
10 changes: 5 additions & 5 deletions compiler/rustc_codegen_ssa/src/back/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -572,10 +572,10 @@ fn produce_final_output_artifacts(
};

let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
if compiled_modules.modules.len() == 1 {
if let [module] = &compiled_modules.modules[..] {
// 1) Only one codegen unit. In this case it's no difficulty
// to copy `foo.0.x` to `foo.x`.
let module_name = Some(&compiled_modules.modules[0].name[..]);
let module_name = Some(&module.name[..]);
let path = crate_output.temp_path(output_type, module_name);
let output = crate_output.path(output_type);
if !output_type.is_text_output() && output.is_tty() {
Expand Down Expand Up @@ -707,8 +707,8 @@ fn produce_final_output_artifacts(
}

if sess.opts.json_artifact_notifications {
if compiled_modules.modules.len() == 1 {
compiled_modules.modules[0].for_each_output(|_path, ty| {
if let [module] = &compiled_modules.modules[..] {
module.for_each_output(|_path, ty| {
if sess.opts.output_types.contains_key(&ty) {
let descr = ty.shorthand();
// for single cgu file is renamed to drop cgu specific suffix
Expand Down Expand Up @@ -864,7 +864,7 @@ pub(crate) fn compute_per_cgu_lto_type(
// require LTO so the request for LTO is always unconditionally
// passed down to the backend, but we don't actually want to do
// anything about it yet until we've got a final product.
let is_rlib = sess_crate_types.len() == 1 && sess_crate_types[0] == CrateType::Rlib;
let is_rlib = matches!(sess_crate_types, [CrateType::Rlib]);

match sess_lto {
Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
Expand Down
Loading
Loading