use format-args-capture and remove unnecessary nested if blocks in some parts of rustc_passes

break before the `&&`

Update compiler/rustc_passes/src/check_const.rs

Co-authored-by: bjorn3 <bjorn3@users.noreply.github.com>
This commit is contained in:
Takayuki Maeda 2022-03-18 22:48:21 +09:00
parent d6f3a4ecb4
commit 726206696e
5 changed files with 61 additions and 78 deletions

View File

@ -196,8 +196,7 @@ impl CheckAttrVisitor<'_> {
fn inline_attr_str_error_with_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) { fn inline_attr_str_error_with_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
lint.build(&format!( lint.build(&format!(
"`#[{}]` is ignored on struct fields, match arms and macro defs", "`#[{sym}]` is ignored on struct fields, match arms and macro defs",
sym,
)) ))
.warn( .warn(
"this was previously accepted by the compiler but is \ "this was previously accepted by the compiler but is \
@ -214,7 +213,7 @@ impl CheckAttrVisitor<'_> {
fn inline_attr_str_error_without_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) { fn inline_attr_str_error_without_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
lint.build(&format!("`#[{}]` is ignored on struct fields and match arms", sym)) lint.build(&format!("`#[{sym}]` is ignored on struct fields and match arms"))
.warn( .warn(
"this was previously accepted by the compiler but is \ "this was previously accepted by the compiler but is \
being phased out; it will become a hard error in \ being phased out; it will become a hard error in \
@ -721,7 +720,7 @@ impl CheckAttrVisitor<'_> {
.sess .sess
.struct_span_err( .struct_span_err(
meta.name_value_literal_span().unwrap_or_else(|| meta.span()), meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
&format!("`{}` is not a valid identifier", doc_keyword), &format!("`{doc_keyword}` is not a valid identifier"),
) )
.emit(); .emit();
return false; return false;
@ -805,8 +804,7 @@ impl CheckAttrVisitor<'_> {
.struct_span_err( .struct_span_err(
meta.span(), meta.span(),
&format!( &format!(
"`#![doc({} = \"...\")]` isn't allowed as a crate-level attribute", "`#![doc({attr_name} = \"...\")]` isn't allowed as a crate-level attribute",
attr_name,
), ),
) )
.emit(); .emit();
@ -1035,8 +1033,7 @@ impl CheckAttrVisitor<'_> {
attr.meta().unwrap().span, attr.meta().unwrap().span,
"use `doc = include_str!` instead", "use `doc = include_str!` instead",
format!( format!(
"#{}[doc = include_str!(\"{}\")]", "#{inner}[doc = include_str!(\"{value}\")]",
inner, value
), ),
applicability, applicability,
); );
@ -1230,7 +1227,7 @@ impl CheckAttrVisitor<'_> {
if let Some(value) = attr.value_str() { if let Some(value) = attr.value_str() {
diag.span_help( diag.span_help(
attr.span, attr.span,
&format!(r#"try `#[link(name = "{}")]` instead"#, value), &format!(r#"try `#[link(name = "{value}")]` instead"#),
); );
} else { } else {
diag.span_help(attr.span, r#"try `#[link(name = "...")]` instead"#); diag.span_help(attr.span, r#"try `#[link(name = "...")]` instead"#);
@ -1518,15 +1515,14 @@ impl CheckAttrVisitor<'_> {
}; };
self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
lint.build(&format!( lint.build(&format!(
"`#[no_mangle]` has no effect on a foreign {}", "`#[no_mangle]` has no effect on a foreign {foreign_item_kind}"
foreign_item_kind
)) ))
.warn( .warn(
"this was previously accepted by the compiler but is \ "this was previously accepted by the compiler but is \
being phased out; it will become a hard error in \ being phased out; it will become a hard error in \
a future release!", a future release!",
) )
.span_label(span, format!("foreign {}", foreign_item_kind)) .span_label(span, format!("foreign {foreign_item_kind}"))
.note("symbol names in extern blocks are not mangled") .note("symbol names in extern blocks are not mangled")
.span_suggestion( .span_suggestion(
attr.span, attr.span,
@ -1692,9 +1688,9 @@ impl CheckAttrVisitor<'_> {
hint.span(), hint.span(),
E0517, E0517,
"{}", "{}",
&format!("attribute should be applied to {} {}", article, allowed_targets) &format!("attribute should be applied to {article} {allowed_targets}")
) )
.span_label(span, &format!("not {} {}", article, allowed_targets)) .span_label(span, &format!("not {article} {allowed_targets}"))
.emit(); .emit();
} }

View File

@ -80,8 +80,7 @@ impl<'tcx> hir::itemlikevisit::ItemLikeVisitor<'tcx> for CheckConstTraitVisitor<
/// of the trait being implemented; as those provided functions can be non-const. /// of the trait being implemented; as those provided functions can be non-const.
fn visit_item<'hir>(&mut self, item: &'hir hir::Item<'hir>) { fn visit_item<'hir>(&mut self, item: &'hir hir::Item<'hir>) {
let _: Option<_> = try { let _: Option<_> = try {
if let hir::ItemKind::Impl(ref imp) = item.kind { if let hir::ItemKind::Impl(ref imp) = item.kind && let hir::Constness::Const = imp.constness {
if let hir::Constness::Const = imp.constness {
let trait_def_id = imp.of_trait.as_ref()?.trait_def_id()?; let trait_def_id = imp.of_trait.as_ref()?.trait_def_id()?;
let ancestors = self let ancestors = self
.tcx .tcx
@ -132,7 +131,6 @@ impl<'tcx> hir::itemlikevisit::ItemLikeVisitor<'tcx> for CheckConstTraitVisitor<
.note(&format!("`{}` not implemented", to_implement.join("`, `"))) .note(&format!("`{}` not implemented", to_implement.join("`, `")))
.emit(); .emit();
} }
}
} }
}; };
} }

View File

@ -61,10 +61,9 @@ fn collect_item(tcx: TyCtxt<'_>, items: &mut DiagnosticItems, name: Symbol, item
if let Some(original_def_id) = items.name_to_id.insert(name, item_def_id) { if let Some(original_def_id) = items.name_to_id.insert(name, item_def_id) {
if original_def_id != item_def_id { if original_def_id != item_def_id {
let mut err = match tcx.hir().span_if_local(item_def_id) { let mut err = match tcx.hir().span_if_local(item_def_id) {
Some(span) => tcx.sess.struct_span_err( Some(span) => tcx
span, .sess
&format!("duplicate diagnostic item found: `{}`.", name), .struct_span_err(span, &format!("duplicate diagnostic item found: `{name}`.")),
),
None => tcx.sess.struct_err(&format!( None => tcx.sess.struct_err(&format!(
"duplicate diagnostic item in crate `{}`: `{}`.", "duplicate diagnostic item in crate `{}`: `{}`.",
tcx.crate_name(item_def_id.krate), tcx.crate_name(item_def_id.krate),

View File

@ -148,33 +148,29 @@ fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) -> Option<(De
} else if let Some((def_id, _)) = visitor.attr_main_fn { } else if let Some((def_id, _)) = visitor.attr_main_fn {
Some((def_id.to_def_id(), EntryFnType::Main)) Some((def_id.to_def_id(), EntryFnType::Main))
} else { } else {
if let Some(main_def) = tcx.resolutions(()).main_def { if let Some(main_def) = tcx.resolutions(()).main_def && let Some(def_id) = main_def.opt_fn_def_id() {
if let Some(def_id) = main_def.opt_fn_def_id() { // non-local main imports are handled below
// non-local main imports are handled below if let Some(def_id) = def_id.as_local() && matches!(tcx.hir().find_by_def_id(def_id), Some(Node::ForeignItem(_))) {
if let Some(def_id) = def_id.as_local() { tcx.sess
if matches!(tcx.hir().find_by_def_id(def_id), Some(Node::ForeignItem(_))) { .struct_span_err(
tcx.sess tcx.def_span(def_id),
.struct_span_err( "the `main` function cannot be declared in an `extern` block",
tcx.def_span(def_id),
"the `main` function cannot be declared in an `extern` block",
)
.emit();
return None;
}
}
if main_def.is_import && !tcx.features().imported_main {
let span = main_def.span;
feature_err(
&tcx.sess.parse_sess,
sym::imported_main,
span,
"using an imported function as entry point `main` is experimental",
) )
.emit(); .emit();
} return None;
return Some((def_id, EntryFnType::Main));
} }
if main_def.is_import && !tcx.features().imported_main {
let span = main_def.span;
feature_err(
&tcx.sess.parse_sess,
sym::imported_main,
span,
"using an imported function as entry point `main` is experimental",
)
.emit();
}
return Some((def_id, EntryFnType::Main));
} }
no_main_err(tcx, visitor); no_main_err(tcx, visitor);
None None
@ -225,11 +221,9 @@ fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) {
err.note(&note); err.note(&note);
} }
if let Some(main_def) = tcx.resolutions(()).main_def { if let Some(main_def) = tcx.resolutions(()).main_def && main_def.opt_fn_def_id().is_none(){
if main_def.opt_fn_def_id().is_none() { // There is something at `crate::main`, but it is not a function definition.
// There is something at `crate::main`, but it is not a function definition. err.span_label(main_def.span, "non-function item at `crate::main` is found");
err.span_label(main_def.span, "non-function item at `crate::main` is found");
}
} }
if tcx.sess.teach(&err.get_code().unwrap()) { if tcx.sess.teach(&err.get_code().unwrap()) {

View File

@ -79,27 +79,25 @@ impl<'tcx> ExprVisitor<'tcx> {
// Special-case transmuting from `typeof(function)` and // Special-case transmuting from `typeof(function)` and
// `Option<typeof(function)>` to present a clearer error. // `Option<typeof(function)>` to present a clearer error.
let from = unpack_option_like(self.tcx, from); let from = unpack_option_like(self.tcx, from);
if let (&ty::FnDef(..), SizeSkeleton::Known(size_to)) = (from.kind(), sk_to) { if let (&ty::FnDef(..), SizeSkeleton::Known(size_to)) = (from.kind(), sk_to) && size_to == Pointer.size(&self.tcx) {
if size_to == Pointer.size(&self.tcx) { struct_span_err!(self.tcx.sess, span, E0591, "can't transmute zero-sized type")
struct_span_err!(self.tcx.sess, span, E0591, "can't transmute zero-sized type") .note(&format!("source type: {from}"))
.note(&format!("source type: {}", from)) .note(&format!("target type: {to}"))
.note(&format!("target type: {}", to)) .help("cast with `as` to a pointer instead")
.help("cast with `as` to a pointer instead") .emit();
.emit(); return;
return;
}
} }
} }
// Try to display a sensible error with as much information as possible. // Try to display a sensible error with as much information as possible.
let skeleton_string = |ty: Ty<'tcx>, sk| match sk { let skeleton_string = |ty: Ty<'tcx>, sk| match sk {
Ok(SizeSkeleton::Known(size)) => format!("{} bits", size.bits()), Ok(SizeSkeleton::Known(size)) => format!("{} bits", size.bits()),
Ok(SizeSkeleton::Pointer { tail, .. }) => format!("pointer to `{}`", tail), Ok(SizeSkeleton::Pointer { tail, .. }) => format!("pointer to `{tail}`"),
Err(LayoutError::Unknown(bad)) => { Err(LayoutError::Unknown(bad)) => {
if bad == ty { if bad == ty {
"this type does not have a fixed size".to_owned() "this type does not have a fixed size".to_owned()
} else { } else {
format!("size can vary because of {}", bad) format!("size can vary because of {bad}")
} }
} }
Err(err) => err.to_string(), Err(err) => err.to_string(),
@ -113,7 +111,7 @@ impl<'tcx> ExprVisitor<'tcx> {
or dependently-sized types" or dependently-sized types"
); );
if from == to { if from == to {
err.note(&format!("`{}` does not have a fixed size", from)); err.note(&format!("`{from}` does not have a fixed size"));
} else { } else {
err.note(&format!("source type: `{}` ({})", from, skeleton_string(from, sk_from))) err.note(&format!("source type: `{}` ({})", from, skeleton_string(from, sk_from)))
.note(&format!("target type: `{}` ({})", to, skeleton_string(to, sk_to))); .note(&format!("target type: `{}` ({})", to, skeleton_string(to, sk_to)));
@ -201,7 +199,7 @@ impl<'tcx> ExprVisitor<'tcx> {
_ => None, _ => None,
}; };
let Some(asm_ty) = asm_ty else { let Some(asm_ty) = asm_ty else {
let msg = &format!("cannot use value of type `{}` for inline assembly", ty); let msg = &format!("cannot use value of type `{ty}` for inline assembly");
let mut err = self.tcx.sess.struct_span_err(expr.span, msg); let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
err.note( err.note(
"only integers, floats, SIMD vectors, pointers and function pointers \ "only integers, floats, SIMD vectors, pointers and function pointers \
@ -216,7 +214,7 @@ impl<'tcx> ExprVisitor<'tcx> {
if !ty.is_copy_modulo_regions(self.tcx.at(DUMMY_SP), self.param_env) { if !ty.is_copy_modulo_regions(self.tcx.at(DUMMY_SP), self.param_env) {
let msg = "arguments for inline assembly must be copyable"; let msg = "arguments for inline assembly must be copyable";
let mut err = self.tcx.sess.struct_span_err(expr.span, msg); let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
err.note(&format!("`{}` does not implement the Copy trait", ty)); err.note(&format!("`{ty}` does not implement the Copy trait"));
err.emit(); err.emit();
} }
@ -237,7 +235,7 @@ impl<'tcx> ExprVisitor<'tcx> {
in_expr.span, in_expr.span,
&format!("type `{}`", self.typeck_results.expr_ty_adjusted(in_expr)), &format!("type `{}`", self.typeck_results.expr_ty_adjusted(in_expr)),
); );
err.span_label(expr.span, &format!("type `{}`", ty)); err.span_label(expr.span, &format!("type `{ty}`"));
err.note( err.note(
"asm inout arguments must have the same type, \ "asm inout arguments must have the same type, \
unless they are both pointers or integers of the same size", unless they are both pointers or integers of the same size",
@ -256,7 +254,7 @@ impl<'tcx> ExprVisitor<'tcx> {
let reg_class = reg.reg_class(); let reg_class = reg.reg_class();
let supported_tys = reg_class.supported_types(asm_arch); let supported_tys = reg_class.supported_types(asm_arch);
let Some((_, feature)) = supported_tys.iter().find(|&&(t, _)| t == asm_ty) else { let Some((_, feature)) = supported_tys.iter().find(|&&(t, _)| t == asm_ty) else {
let msg = &format!("type `{}` cannot be used with this register class", ty); let msg = &format!("type `{ty}` cannot be used with this register class");
let mut err = self.tcx.sess.struct_span_err(expr.span, msg); let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
let supported_tys: Vec<_> = let supported_tys: Vec<_> =
supported_tys.iter().map(|(t, _)| t.to_string()).collect(); supported_tys.iter().map(|(t, _)| t.to_string()).collect();
@ -326,12 +324,10 @@ impl<'tcx> ExprVisitor<'tcx> {
let mut err = lint.build(msg); let mut err = lint.build(msg);
err.span_label(expr.span, "for this argument"); err.span_label(expr.span, "for this argument");
err.help(&format!( err.help(&format!(
"use the `{}` modifier to have the register formatted as `{}`", "use the `{suggested_modifier}` modifier to have the register formatted as `{suggested_result}`",
suggested_modifier, suggested_result,
)); ));
err.help(&format!( err.help(&format!(
"or use the `{}` modifier to keep the default formatting of `{}`", "or use the `{default_modifier}` modifier to keep the default formatting of `{default_result}`",
default_modifier, default_result,
)); ));
err.emit(); err.emit();
}, },
@ -509,14 +505,14 @@ impl<'tcx> Visitor<'tcx> for ExprVisitor<'tcx> {
match expr.kind { match expr.kind {
hir::ExprKind::Path(ref qpath) => { hir::ExprKind::Path(ref qpath) => {
let res = self.typeck_results.qpath_res(qpath, expr.hir_id); let res = self.typeck_results.qpath_res(qpath, expr.hir_id);
if let Res::Def(DefKind::Fn, did) = res { if let Res::Def(DefKind::Fn, did) = res
if self.def_id_is_transmute(did) { && self.def_id_is_transmute(did)
let typ = self.typeck_results.node_type(expr.hir_id); {
let sig = typ.fn_sig(self.tcx); let typ = self.typeck_results.node_type(expr.hir_id);
let from = sig.inputs().skip_binder()[0]; let sig = typ.fn_sig(self.tcx);
let to = sig.output().skip_binder(); let from = sig.inputs().skip_binder()[0];
self.check_transmute(expr.span, from, to); let to = sig.output().skip_binder();
} self.check_transmute(expr.span, from, to);
} }
} }