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

Format the world (considering let-chains and let-else) #95262

Closed
Closed
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
4 changes: 1 addition & 3 deletions compiler/rustc_ast/src/attr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -595,9 +595,7 @@ impl NestedMetaItem {
I: Iterator<Item = TokenTree>,
{
match tokens.peek() {
Some(TokenTree::Token(token))
if let Ok(lit) = Lit::from_token(token) =>
{
Some(TokenTree::Token(token)) if let Ok(lit) = Lit::from_token(token) => {
tokens.next();
return Some(NestedMetaItem::Literal(lit));
}
Expand Down
23 changes: 14 additions & 9 deletions compiler/rustc_ast_passes/src/ast_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1003,8 +1003,10 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
}

fn visit_expr(&mut self, expr: &'a Expr) {
self.with_let_management(Some(ForbiddenLetReason::GenericForbidden), |this, forbidden_let_reason| {
match &expr.kind {
self.with_let_management(
Some(ForbiddenLetReason::GenericForbidden),
|this, forbidden_let_reason| {
match &expr.kind {
ExprKind::Binary(Spanned { node: BinOpKind::Or, span }, lhs, rhs) => {
let forbidden_let_reason = Some(ForbiddenLetReason::ForbiddenWithOr(*span));
this.with_let_management(forbidden_let_reason, |this, _| this.visit_expr(lhs));
Expand All @@ -1018,23 +1020,25 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
}
ExprKind::Let(..) if let Some(elem) = forbidden_let_reason => {
this.ban_let_expr(expr, elem);
},
}
ExprKind::Match(scrutinee, arms) => {
this.visit_expr(scrutinee);
for arm in arms {
this.visit_expr(&arm.body);
this.visit_pat(&arm.pat);
walk_list!(this, visit_attribute, &arm.attrs);
if let Some(guard) = &arm.guard && let ExprKind::Let(_, guard_expr, _) = &guard.kind {
this.with_let_management(None, |this, _| {
this.visit_expr(guard_expr)
});
if let Some(guard) = &arm.guard
&& let ExprKind::Let(_, guard_expr, _) = &guard.kind
{
this.with_let_management(None, |this, _| this.visit_expr(guard_expr));
return;
}
}
}
ExprKind::Paren(_) | ExprKind::Binary(Spanned { node: BinOpKind::And, .. }, ..) => {
this.with_let_management(forbidden_let_reason, |this, _| visit::walk_expr(this, expr));
this.with_let_management(forbidden_let_reason, |this, _| {
visit::walk_expr(this, expr)
});
return;
}
ExprKind::While(cond, then, opt_label) => {
Expand All @@ -1045,7 +1049,8 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
}
_ => visit::walk_expr(this, expr),
}
});
},
);
}

fn visit_ty(&mut self, ty: &'a Ty) {
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1840,9 +1840,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
err.span_label(assigned_span, format!("first assignment to {}", place_description));
}
}
if let Some(decl) = local_decl
&& let Some(name) = local_name
&& decl.can_be_made_mutable()
if let Some(decl) = local_decl && let Some(name) = local_name && decl.can_be_made_mutable()
{
err.span_suggestion(
decl.source_info.span,
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
if self.local_names[local].is_some()
&& let Some((WriteKind::StorageDeadOrDrop, place)) = kind_place
&& let Some(borrowed_local) = place.as_local()
&& self.local_names[borrowed_local].is_some() && local != borrowed_local
&& self.local_names[borrowed_local].is_some()
&& local != borrowed_local
{
should_note_order = true;
}
Expand Down
13 changes: 7 additions & 6 deletions compiler/rustc_expand/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,8 @@ impl<'a> StripUnconfigured<'a> {
let trees: Vec<_> = stream
.0
.iter()
.flat_map(|(tree, spacing)| match tree.clone() {
.flat_map(|(tree, spacing)| {
match tree.clone() {
AttrAnnotatedTokenTree::Attributes(mut data) => {
let mut attrs: Vec<_> = std::mem::take(&mut data.attrs).into();
attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
Expand All @@ -310,15 +311,15 @@ impl<'a> StripUnconfigured<'a> {
Some((AttrAnnotatedTokenTree::Delimited(sp, delim, inner), *spacing))
.into_iter()
}
AttrAnnotatedTokenTree::Token(ref token) if let TokenKind::Interpolated(ref nt) = token.kind => {
panic!(
"Nonterminal should have been flattened at {:?}: {:?}",
token.span, nt
);
AttrAnnotatedTokenTree::Token(ref token)
if let TokenKind::Interpolated(ref nt) = token.kind =>
{
panic!("Nonterminal should have been flattened at {:?}: {:?}", token.span, nt);
}
AttrAnnotatedTokenTree::Token(token) => {
Some((AttrAnnotatedTokenTree::Token(token), *spacing)).into_iter()
}
}
})
.collect();
AttrAnnotatedTokenStream::new(trees)
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_expand/src/mbe/metavar_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,7 @@ fn parse_depth<'sess>(
&& let Ok(n_usize) = usize::try_from(n_u128)
{
Ok(n_usize)
}
else {
} else {
let msg = "only unsuffixes integer literals are supported in meta-variable expressions";
Err(sess.span_diagnostic.struct_span_err(span, msg))
}
Expand Down
4 changes: 3 additions & 1 deletion compiler/rustc_expand/src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,9 @@ crate fn mod_dir_path(
inline: Inline,
) -> (PathBuf, DirOwnership) {
match inline {
Inline::Yes if let Some(file_path) = mod_file_path_from_attr(sess, attrs, &module.dir_path) => {
Inline::Yes
if let Some(file_path) = mod_file_path_from_attr(sess, attrs, &module.dir_path) =>
{
// For inline modules file path from `#[path]` is actually the directory path
// for historical reasons, so we don't pop the last segment here.
(file_path, DirOwnership::Owned { relative: None })
Expand Down
6 changes: 4 additions & 2 deletions compiler/rustc_infer/src/infer/error_reporting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,8 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
err.span_label(span, format!("this expression has type `{}`", ty));
}
if let Some(ty::error::ExpectedFound { found, .. }) = exp_found
&& ty.is_box() && ty.boxed_ty() == found
&& ty.is_box()
&& ty.boxed_ty() == found
&& let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
{
err.span_suggestion(
Expand Down Expand Up @@ -2047,7 +2048,8 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
// specify a character literal (issue #92479)
(ty::Char, ty::Ref(_, r, _)) if r.is_str() => {
if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
&& let Some(code) = code.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
&& let Some(code) =
code.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
&& code.chars().count() == 1
{
err.span_suggestion(
Expand Down
21 changes: 10 additions & 11 deletions compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,12 +124,13 @@ impl<'a, 'tcx> Visitor<'tcx> for FindHirNodeVisitor<'a, 'tcx> {
}
if let ExprKind::MethodCall(segment, exprs, _) = expr.kind
&& segment.ident.span == self.target_span
&& Some(self.target) == self.infcx.in_progress_typeck_results.and_then(|typeck_results| {
typeck_results
.borrow()
.node_type_opt(exprs.first().unwrap().hir_id)
.map(Into::into)
})
&& Some(self.target)
== self.infcx.in_progress_typeck_results.and_then(|typeck_results| {
typeck_results
.borrow()
.node_type_opt(exprs.first().unwrap().hir_id)
.map(Into::into)
})
{
self.found_exact_method_call = Some(&expr);
return;
Expand Down Expand Up @@ -731,17 +732,15 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
// | help: specify type like: `<Impl as Into<u32>>::into(foo_impl)`
// |
// = note: cannot satisfy `Impl: Into<_>`
if !impl_candidates.is_empty() && e.span.contains(span)
if !impl_candidates.is_empty()
&& e.span.contains(span)
&& let Some(expr) = exprs.first()
&& let ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind
&& let [path_segment] = path.segments
{
let candidate_len = impl_candidates.len();
let suggestions = impl_candidates.iter().map(|candidate| {
format!(
"{}::{}({})",
candidate, segment.ident, path_segment.ident
)
format!("{}::{}({})", candidate, segment.ident, path_segment.ident)
});
err.span_suggestions(
e.span,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,8 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
ObligationCauseCode::MatchImpl(parent, ..) => parent.code(),
_ => cause.code(),
}
&& let (ObligationCauseCode::ItemObligation(item_def_id), None) = (code, override_error_code)
&& let (ObligationCauseCode::ItemObligation(item_def_id), None) =
(code, override_error_code)
{
// Same case of `impl Foo for dyn Bar { fn qux(&self) {} }` introducing a `'static`
// lifetime as above, but called using a fully-qualified path to the method:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,14 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
let error = self.error.as_ref()?;
debug!("try_report_impl_not_conforming_to_trait {:?}", error);
if let RegionResolutionError::SubSupConflict(
_, var_origin, sub_origin, _sub, sup_origin, _sup, _,
) = error.clone()
_,
var_origin,
sub_origin,
_sub,
sup_origin,
_sup,
_,
) = error.clone()
&& let (&Subtype(ref sup_trace), &Subtype(ref sub_trace)) = (&sup_origin, &sub_origin)
&& let (
sub_expected_found @ Some((sub_expected, sub_found)),
Expand All @@ -33,16 +39,12 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
) = (sub_trace.values.ty(), sup_trace.values.ty(), sub_trace.cause.code())
&& sup_expected_found == sub_expected_found
{
let guar = self.emit_err(
var_origin.span(),
sub_expected,
sub_found,
*trait_item_def_id,
);
let guar =
self.emit_err(var_origin.span(), sub_expected, sub_found, *trait_item_def_id);
return Some(guar);
}
if let RegionResolutionError::ConcreteFailure(origin, _, _)
| RegionResolutionError::GenericBoundFailure(origin, _, _) = error.clone()
| RegionResolutionError::GenericBoundFailure(origin, _, _) = error.clone()
&& let SubregionOrigin::CompareImplTypeObligation {
span,
impl_item_def_id,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_lint/src/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ impl LateLintPass<'_> for QueryStability {
if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) =>
{
(segment.ident.span, def_id, cx.typeck_results().node_substs(expr.hir_id))
},
}
_ => {
let &ty::FnDef(def_id, substs) =
cx.typeck_results()
Expand Down
61 changes: 32 additions & 29 deletions compiler/rustc_lint/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1500,7 +1500,8 @@ impl InvalidAtomicOrdering {
fn check_atomic_load_store(cx: &LateContext<'_>, expr: &Expr<'_>) {
use rustc_hir::def::{DefKind, Res};
use rustc_hir::QPath;
if let Some((method, args)) = Self::inherent_atomic_method_call(cx, expr, &[sym::load, sym::store])
if let Some((method, args)) =
Self::inherent_atomic_method_call(cx, expr, &[sym::load, sym::store])
&& let Some((ordering_arg, invalid_ordering)) = match method {
sym::load => Some((&args[1], sym::Release)),
sym::store => Some((&args[2], sym::Acquire)),
Expand Down Expand Up @@ -1536,56 +1537,58 @@ impl InvalidAtomicOrdering {
{
cx.struct_span_lint(INVALID_ATOMIC_ORDERING, args[0].span, |diag| {
diag.build("memory fences cannot have `Relaxed` ordering")
.help("consider using ordering modes `Acquire`, `Release`, `AcqRel` or `SeqCst`")
.help(
"consider using ordering modes `Acquire`, `Release`, `AcqRel` or `SeqCst`",
)
.emit();
});
}
}

fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) {
if let Some((method, args)) = Self::inherent_atomic_method_call(cx, expr, &[sym::fetch_update, sym::compare_exchange, sym::compare_exchange_weak])
&& let Some((success_order_arg, failure_order_arg)) = match method {
sym::fetch_update => Some((&args[1], &args[2])),
sym::compare_exchange | sym::compare_exchange_weak => Some((&args[3], &args[4])),
_ => None,
}
&& let Some(fail_ordering_def_id) = Self::opt_ordering_defid(cx, failure_order_arg)
if let Some((method, args)) = Self::inherent_atomic_method_call(
cx,
expr,
&[sym::fetch_update, sym::compare_exchange, sym::compare_exchange_weak],
) && let Some((success_order_arg, failure_order_arg)) = match method {
sym::fetch_update => Some((&args[1], &args[2])),
sym::compare_exchange | sym::compare_exchange_weak => Some((&args[3], &args[4])),
_ => None,
} && let Some(fail_ordering_def_id) = Self::opt_ordering_defid(cx, failure_order_arg)
{
// Helper type holding on to some checking and error reporting data. Has
// - (success ordering,
// - list of failure orderings forbidden by the success order,
// - suggestion message)
type OrdLintInfo = (Symbol, &'static [Symbol], &'static str);
const RELAXED: OrdLintInfo = (sym::Relaxed, &[sym::SeqCst, sym::Acquire], "ordering mode `Relaxed`");
const ACQUIRE: OrdLintInfo = (sym::Acquire, &[sym::SeqCst], "ordering modes `Acquire` or `Relaxed`");
const SEQ_CST: OrdLintInfo = (sym::SeqCst, &[], "ordering modes `Acquire`, `SeqCst` or `Relaxed`");
const RELAXED: OrdLintInfo =
(sym::Relaxed, &[sym::SeqCst, sym::Acquire], "ordering mode `Relaxed`");
const ACQUIRE: OrdLintInfo =
(sym::Acquire, &[sym::SeqCst], "ordering modes `Acquire` or `Relaxed`");
const SEQ_CST: OrdLintInfo =
(sym::SeqCst, &[], "ordering modes `Acquire`, `SeqCst` or `Relaxed`");
const RELEASE: OrdLintInfo = (sym::Release, RELAXED.1, RELAXED.2);
const ACQREL: OrdLintInfo = (sym::AcqRel, ACQUIRE.1, ACQUIRE.2);
const SEARCH: [OrdLintInfo; 5] = [RELAXED, ACQUIRE, SEQ_CST, RELEASE, ACQREL];

let success_lint_info = Self::opt_ordering_defid(cx, success_order_arg)
.and_then(|success_ord_def_id| -> Option<OrdLintInfo> {
SEARCH
.iter()
.copied()
.find(|(ordering, ..)| {
Self::matches_ordering(cx, success_ord_def_id, &[*ordering])
})
});
let success_lint_info = Self::opt_ordering_defid(cx, success_order_arg).and_then(
|success_ord_def_id| -> Option<OrdLintInfo> {
SEARCH.iter().copied().find(|(ordering, ..)| {
Self::matches_ordering(cx, success_ord_def_id, &[*ordering])
})
},
);
if Self::matches_ordering(cx, fail_ordering_def_id, &[sym::Release, sym::AcqRel]) {
// If we don't know the success order is, use what we'd suggest
// if it were maximally permissive.
let suggested = success_lint_info.unwrap_or(SEQ_CST).2;
cx.struct_span_lint(INVALID_ATOMIC_ORDERING, failure_order_arg.span, |diag| {
let msg = format!(
"{}'s failure ordering may not be `Release` or `AcqRel`",
method,
);
diag.build(&msg)
.help(&format!("consider using {} instead", suggested))
.emit();
let msg =
format!("{}'s failure ordering may not be `Release` or `AcqRel`", method,);
diag.build(&msg).help(&format!("consider using {} instead", suggested)).emit();
});
} else if let Some((success_ord, bad_ords_given_success, suggested)) = success_lint_info {
} else if let Some((success_ord, bad_ords_given_success, suggested)) = success_lint_info
{
if Self::matches_ordering(cx, fail_ordering_def_id, bad_ords_given_success) {
cx.struct_span_lint(INVALID_ATOMIC_ORDERING, failure_order_arg.span, |diag| {
let msg = format!(
Expand Down
19 changes: 9 additions & 10 deletions compiler/rustc_middle/src/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -910,9 +910,10 @@ pub trait PrettyPrinter<'tcx>:

for (assoc_item_def_id, term) in assoc_items {
// Skip printing `<[generator@] as Generator<_>>::Return` from async blocks
if let Some(ty) = term.skip_binder().ty() &&
let ty::Projection(ty::ProjectionTy { item_def_id, .. }) = ty.kind() &&
Some(*item_def_id) == self.tcx().lang_items().generator_return() {
if let Some(ty) = term.skip_binder().ty()
&& let ty::Projection(ty::ProjectionTy { item_def_id, .. }) = ty.kind()
&& Some(*item_def_id) == self.tcx().lang_items().generator_return()
{
continue;
}

Expand Down Expand Up @@ -1202,14 +1203,12 @@ pub trait PrettyPrinter<'tcx>:
}
}
}
ty::ConstKind::Infer(infer_ct) => {
match infer_ct {
ty::InferConst::Var(ct_vid)
if let Some(name) = self.const_infer_name(ct_vid) =>
p!(write("{}", name)),
_ => print_underscore!(),
ty::ConstKind::Infer(infer_ct) => match infer_ct {
ty::InferConst::Var(ct_vid) if let Some(name) = self.const_infer_name(ct_vid) => {
p!(write("{}", name))
}
}
_ => print_underscore!(),
},
ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
ty::ConstKind::Value(value) => {
return self.pretty_print_const_value(value, ct.ty(), print_ty);
Expand Down
Loading