Skip to content

Commit b97dc20

Browse files
committed
Auto merge of rust-lang#94734 - matthiaskrgr:rollup-28shqhy, r=matthiaskrgr
Rollup of 8 pull requests Successful merges: - rust-lang#91993 (Tweak output for non-exhaustive `match` expression) - rust-lang#92385 (Add Result::{ok, err, and, or, unwrap_or} as const) - rust-lang#94559 (Remove argument from closure in thread::Scope::spawn.) - rust-lang#94580 (Emit `unused_attributes` if a level attr only has a reason) - rust-lang#94586 (Generalize `get_nullable_type` to allow types where null is all-ones.) - rust-lang#94708 (diagnostics: only talk about `Cargo.toml` if running under Cargo) - rust-lang#94712 (promot debug_assert to assert) - rust-lang#94726 (:arrow_up: rust-analyzer) Failed merges: r? `@ghost` `@rustbot` modify labels: rollup
2 parents d2710db + b879216 commit b97dc20

File tree

97 files changed

+2785
-1093
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

97 files changed

+2785
-1093
lines changed

compiler/rustc_errors/src/diagnostic.rs

+13
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use crate::SuggestionStyle;
77
use crate::ToolMetadata;
88
use rustc_lint_defs::Applicability;
99
use rustc_serialize::json::Json;
10+
use rustc_span::edition::LATEST_STABLE_EDITION;
1011
use rustc_span::{MultiSpan, Span, DUMMY_SP};
1112
use std::fmt;
1213
use std::hash::{Hash, Hasher};
@@ -342,6 +343,18 @@ impl Diagnostic {
342343
self
343344
}
344345

346+
/// Help the user upgrade to the latest edition.
347+
/// This is factored out to make sure it does the right thing with `Cargo.toml`.
348+
pub fn help_use_latest_edition(&mut self) -> &mut Self {
349+
if std::env::var_os("CARGO").is_some() {
350+
self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
351+
} else {
352+
self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
353+
}
354+
self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
355+
self
356+
}
357+
345358
/// Disallow attaching suggestions this diagnostic.
346359
/// Any suggestions attached e.g. with the `span_suggestion_*` methods
347360
/// (before and after the call to `disable_suggestions`) will be ignored.

compiler/rustc_errors/src/diagnostic_builder.rs

+1
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
409409
sp: impl Into<MultiSpan>,
410410
msg: &str,
411411
) -> &mut Self);
412+
forward!(pub fn help_use_latest_edition(&mut self,) -> &mut Self);
412413
forward!(pub fn set_is_lint(&mut self,) -> &mut Self);
413414

414415
forward!(pub fn disable_suggestions(&mut self,) -> &mut Self);

compiler/rustc_feature/src/builtin_attrs.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -606,17 +606,17 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
606606
rustc_attr!(
607607
rustc_layout_scalar_valid_range_start, Normal, template!(List: "value"), ErrorFollowing,
608608
"the `#[rustc_layout_scalar_valid_range_start]` attribute is just used to enable \
609-
niche optimizations in libcore and will never be stable",
609+
niche optimizations in libcore and libstd and will never be stable",
610610
),
611611
rustc_attr!(
612612
rustc_layout_scalar_valid_range_end, Normal, template!(List: "value"), ErrorFollowing,
613613
"the `#[rustc_layout_scalar_valid_range_end]` attribute is just used to enable \
614-
niche optimizations in libcore and will never be stable",
614+
niche optimizations in libcore and libstd and will never be stable",
615615
),
616616
rustc_attr!(
617617
rustc_nonnull_optimization_guaranteed, Normal, template!(Word), WarnFollowing,
618618
"the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to enable \
619-
niche optimizations in libcore and will never be stable",
619+
niche optimizations in libcore and libstd and will never be stable",
620620
),
621621

622622
// ==========================================================================

compiler/rustc_lint/src/levels.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ impl<'s> LintLevelsBuilder<'s> {
258258
};
259259

260260
if metas.is_empty() {
261-
// FIXME (#55112): issue unused-attributes lint for `#[level()]`
261+
// This emits the unused_attributes lint for `#[level()]`
262262
continue;
263263
}
264264

@@ -271,8 +271,6 @@ impl<'s> LintLevelsBuilder<'s> {
271271
ast::MetaItemKind::Word => {} // actual lint names handled later
272272
ast::MetaItemKind::NameValue(ref name_value) => {
273273
if item.path == sym::reason {
274-
// FIXME (#55112): issue unused-attributes lint if we thereby
275-
// don't have any lint names (`#[level(reason = "foo")]`)
276274
if let ast::LitKind::Str(rationale, _) = name_value.kind {
277275
if !self.sess.features_untracked().lint_reasons {
278276
feature_err(

compiler/rustc_lint/src/types.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -795,7 +795,9 @@ crate fn repr_nullable_ptr<'tcx>(
795795
let field_ty_abi = &cx.layout_of(field_ty).unwrap().abi;
796796
if let Abi::Scalar(field_ty_scalar) = field_ty_abi {
797797
match (field_ty_scalar.valid_range.start, field_ty_scalar.valid_range.end) {
798-
(0, _) => unreachable!("Non-null optimisation extended to a non-zero value."),
798+
(0, x) if x == field_ty_scalar.value.size(&cx.tcx).unsigned_int_max() - 1 => {
799+
return Some(get_nullable_type(cx, field_ty).unwrap());
800+
}
799801
(1, _) => {
800802
return Some(get_nullable_type(cx, field_ty).unwrap());
801803
}

compiler/rustc_mir_build/src/thir/pattern/check_match.rs

+123-20
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use rustc_session::lint::builtin::{
2020
};
2121
use rustc_session::Session;
2222
use rustc_span::source_map::Spanned;
23-
use rustc_span::{DesugaringKind, ExpnKind, Span};
23+
use rustc_span::{DesugaringKind, ExpnKind, MultiSpan, Span};
2424

2525
crate fn check_match(tcx: TyCtxt<'_>, def_id: DefId) {
2626
let body_id = match def_id.as_local() {
@@ -64,7 +64,9 @@ impl<'tcx> Visitor<'tcx> for MatchVisitor<'_, '_, 'tcx> {
6464
fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
6565
intravisit::walk_expr(self, ex);
6666
match &ex.kind {
67-
hir::ExprKind::Match(scrut, arms, source) => self.check_match(scrut, arms, *source),
67+
hir::ExprKind::Match(scrut, arms, source) => {
68+
self.check_match(scrut, arms, *source, ex.span)
69+
}
6870
hir::ExprKind::Let(hir::Let { pat, init, span, .. }) => {
6971
self.check_let(pat, init, *span)
7072
}
@@ -163,6 +165,7 @@ impl<'p, 'tcx> MatchVisitor<'_, 'p, 'tcx> {
163165
scrut: &hir::Expr<'_>,
164166
hir_arms: &'tcx [hir::Arm<'tcx>],
165167
source: hir::MatchSource,
168+
expr_span: Span,
166169
) {
167170
let mut cx = self.new_cx(scrut.hir_id);
168171

@@ -208,15 +211,14 @@ impl<'p, 'tcx> MatchVisitor<'_, 'p, 'tcx> {
208211
}
209212

210213
// Check if the match is exhaustive.
211-
let is_empty_match = arms.is_empty();
212214
let witnesses = report.non_exhaustiveness_witnesses;
213215
if !witnesses.is_empty() {
214216
if source == hir::MatchSource::ForLoopDesugar && hir_arms.len() == 2 {
215217
// the for loop pattern is not irrefutable
216218
let pat = hir_arms[1].pat.for_loop_some().unwrap();
217219
self.check_irrefutable(pat, "`for` loop binding", None);
218220
} else {
219-
non_exhaustive_match(&cx, scrut_ty, scrut.span, witnesses, is_empty_match);
221+
non_exhaustive_match(&cx, scrut_ty, scrut.span, witnesses, hir_arms, expr_span);
220222
}
221223
}
222224
}
@@ -334,7 +336,7 @@ fn check_for_bindings_named_same_as_variants(
334336
let ty_path = cx.tcx.def_path_str(edef.did);
335337
let mut err = lint.build(&format!(
336338
"pattern binding `{}` is named the same as one \
337-
of the variants of the type `{}`",
339+
of the variants of the type `{}`",
338340
ident, ty_path
339341
));
340342
err.code(error_code!(E0170));
@@ -494,21 +496,26 @@ fn non_exhaustive_match<'p, 'tcx>(
494496
scrut_ty: Ty<'tcx>,
495497
sp: Span,
496498
witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
497-
is_empty_match: bool,
499+
arms: &[hir::Arm<'tcx>],
500+
expr_span: Span,
498501
) {
502+
let is_empty_match = arms.is_empty();
499503
let non_empty_enum = match scrut_ty.kind() {
500504
ty::Adt(def, _) => def.is_enum() && !def.variants.is_empty(),
501505
_ => false,
502506
};
503507
// In the case of an empty match, replace the '`_` not covered' diagnostic with something more
504508
// informative.
505509
let mut err;
510+
let pattern;
511+
let mut patterns_len = 0;
506512
if is_empty_match && !non_empty_enum {
507513
err = create_e0004(
508514
cx.tcx.sess,
509515
sp,
510516
format!("non-exhaustive patterns: type `{}` is non-empty", scrut_ty),
511517
);
518+
pattern = "_".to_string();
512519
} else {
513520
let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
514521
err = create_e0004(
@@ -517,6 +524,16 @@ fn non_exhaustive_match<'p, 'tcx>(
517524
format!("non-exhaustive patterns: {} not covered", joined_patterns),
518525
);
519526
err.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns));
527+
patterns_len = witnesses.len();
528+
pattern = if witnesses.len() < 4 {
529+
witnesses
530+
.iter()
531+
.map(|witness| witness.to_pat(cx).to_string())
532+
.collect::<Vec<String>>()
533+
.join(" | ")
534+
} else {
535+
"_".to_string()
536+
};
520537
};
521538

522539
let is_variant_list_non_exhaustive = match scrut_ty.kind() {
@@ -525,10 +542,6 @@ fn non_exhaustive_match<'p, 'tcx>(
525542
};
526543

527544
adt_defined_here(cx, &mut err, scrut_ty, &witnesses);
528-
err.help(
529-
"ensure that all possible cases are being handled, \
530-
possibly by adding wildcards or more match arms",
531-
);
532545
err.note(&format!(
533546
"the matched value is of type `{}`{}",
534547
scrut_ty,
@@ -540,14 +553,14 @@ fn non_exhaustive_match<'p, 'tcx>(
540553
&& matches!(witnesses[0].ctor(), Constructor::NonExhaustive)
541554
{
542555
err.note(&format!(
543-
"`{}` does not have a fixed maximum value, \
544-
so a wildcard `_` is necessary to match exhaustively",
556+
"`{}` does not have a fixed maximum value, so a wildcard `_` is necessary to match \
557+
exhaustively",
545558
scrut_ty,
546559
));
547560
if cx.tcx.sess.is_nightly_build() {
548561
err.help(&format!(
549-
"add `#![feature(precise_pointer_size_matching)]` \
550-
to the crate attributes to enable precise `{}` matching",
562+
"add `#![feature(precise_pointer_size_matching)]` to the crate attributes to \
563+
enable precise `{}` matching",
551564
scrut_ty,
552565
));
553566
}
@@ -557,6 +570,84 @@ fn non_exhaustive_match<'p, 'tcx>(
557570
err.note("references are always considered inhabited");
558571
}
559572
}
573+
574+
let mut suggestion = None;
575+
let sm = cx.tcx.sess.source_map();
576+
match arms {
577+
[] if sp.ctxt() == expr_span.ctxt() => {
578+
// Get the span for the empty match body `{}`.
579+
let (indentation, more) = if let Some(snippet) = sm.indentation_before(sp) {
580+
(format!("\n{}", snippet), " ")
581+
} else {
582+
(" ".to_string(), "")
583+
};
584+
suggestion = Some((
585+
sp.shrink_to_hi().with_hi(expr_span.hi()),
586+
format!(
587+
" {{{indentation}{more}{pattern} => todo!(),{indentation}}}",
588+
indentation = indentation,
589+
more = more,
590+
pattern = pattern,
591+
),
592+
));
593+
}
594+
[only] => {
595+
let pre_indentation = if let (Some(snippet), true) = (
596+
sm.indentation_before(only.span),
597+
sm.is_multiline(sp.shrink_to_hi().with_hi(only.span.lo())),
598+
) {
599+
format!("\n{}", snippet)
600+
} else {
601+
" ".to_string()
602+
};
603+
let comma = if matches!(only.body.kind, hir::ExprKind::Block(..)) { "" } else { "," };
604+
suggestion = Some((
605+
only.span.shrink_to_hi(),
606+
format!("{}{}{} => todo!()", comma, pre_indentation, pattern),
607+
));
608+
}
609+
[.., prev, last] if prev.span.ctxt() == last.span.ctxt() => {
610+
if let Ok(snippet) = sm.span_to_snippet(prev.span.between(last.span)) {
611+
let comma =
612+
if matches!(last.body.kind, hir::ExprKind::Block(..)) { "" } else { "," };
613+
suggestion = Some((
614+
last.span.shrink_to_hi(),
615+
format!(
616+
"{}{}{} => todo!()",
617+
comma,
618+
snippet.strip_prefix(",").unwrap_or(&snippet),
619+
pattern
620+
),
621+
));
622+
}
623+
}
624+
_ => {}
625+
}
626+
627+
let msg = format!(
628+
"ensure that all possible cases are being handled by adding a match arm with a wildcard \
629+
pattern{}{}",
630+
if patterns_len > 1 && patterns_len < 4 && suggestion.is_some() {
631+
", a match arm with multiple or-patterns"
632+
} else {
633+
// we are either not suggesting anything, or suggesting `_`
634+
""
635+
},
636+
match patterns_len {
637+
// non-exhaustive enum case
638+
0 if suggestion.is_some() => " as shown",
639+
0 => "",
640+
1 if suggestion.is_some() => " or an explicit pattern as shown",
641+
1 => " or an explicit pattern",
642+
_ if suggestion.is_some() => " as shown, or multiple match arms",
643+
_ => " or multiple match arms",
644+
},
645+
);
646+
if let Some((span, sugg)) = suggestion {
647+
err.span_suggestion_verbose(span, &msg, sugg, Applicability::HasPlaceholders);
648+
} else {
649+
err.help(&msg);
650+
}
560651
err.emit();
561652
}
562653

@@ -597,15 +688,27 @@ fn adt_defined_here<'p, 'tcx>(
597688
) {
598689
let ty = ty.peel_refs();
599690
if let ty::Adt(def, _) = ty.kind() {
600-
if let Some(sp) = cx.tcx.hir().span_if_local(def.did) {
601-
err.span_label(sp, format!("`{}` defined here", ty));
602-
}
603-
604-
if witnesses.len() < 4 {
691+
let mut spans = vec![];
692+
if witnesses.len() < 5 {
605693
for sp in maybe_point_at_variant(cx, def, witnesses.iter()) {
606-
err.span_label(sp, "not covered");
694+
spans.push(sp);
607695
}
608696
}
697+
let def_span = cx
698+
.tcx
699+
.hir()
700+
.get_if_local(def.did)
701+
.and_then(|node| node.ident())
702+
.map(|ident| ident.span)
703+
.unwrap_or_else(|| cx.tcx.def_span(def.did));
704+
let mut span: MultiSpan =
705+
if spans.is_empty() { def_span.into() } else { spans.clone().into() };
706+
707+
span.push_span_label(def_span, String::new());
708+
for pat in spans {
709+
span.push_span_label(pat, "not covered".to_string());
710+
}
711+
err.span_note(span, &format!("`{}` defined here", ty));
609712
}
610713
}
611714

compiler/rustc_parse/src/parser/expr.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ use rustc_ast_pretty::pprust;
2020
use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, PResult};
2121
use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP;
2222
use rustc_session::lint::BuiltinLintDiagnostics;
23-
use rustc_span::edition::LATEST_STABLE_EDITION;
2423
use rustc_span::source_map::{self, Span, Spanned};
2524
use rustc_span::symbol::{kw, sym, Ident, Symbol};
2625
use rustc_span::{BytePos, Pos};
@@ -2712,8 +2711,7 @@ impl<'a> Parser<'a> {
27122711
let mut async_block_err = |e: &mut Diagnostic, span: Span| {
27132712
recover_async = true;
27142713
e.span_label(span, "`async` blocks are only allowed in Rust 2018 or later");
2715-
e.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
2716-
e.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
2714+
e.help_use_latest_edition();
27172715
};
27182716

27192717
while self.token != token::CloseDelim(close_delim) {

compiler/rustc_parse/src/parser/item.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use rustc_ast::{FnHeader, ForeignItem, Path, PathSegment, Visibility, Visibility
1414
use rustc_ast::{MacArgs, MacCall, MacDelimiter};
1515
use rustc_ast_pretty::pprust;
1616
use rustc_errors::{struct_span_err, Applicability, PResult, StashKey};
17-
use rustc_span::edition::{Edition, LATEST_STABLE_EDITION};
17+
use rustc_span::edition::Edition;
1818
use rustc_span::lev_distance::lev_distance;
1919
use rustc_span::source_map::{self, Span};
2020
use rustc_span::symbol::{kw, sym, Ident, Symbol};
@@ -2102,8 +2102,7 @@ impl<'a> Parser<'a> {
21022102
let diag = self.diagnostic();
21032103
struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
21042104
.span_label(span, "to use `async fn`, switch to Rust 2018 or later")
2105-
.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION))
2106-
.note("for more on editions, read https://doc.rust-lang.org/edition-guide")
2105+
.help_use_latest_edition()
21072106
.emit();
21082107
}
21092108
}

0 commit comments

Comments
 (0)