Skip to content

Commit 5af97e8

Browse files
committed
Auto merge of #100304 - matthiaskrgr:rollup-gs56vlw, r=matthiaskrgr
Rollup of 6 pull requests Successful merges: - #100163 (Refactor: remove an unnecessary string search) - #100212 (Remove more Clean trait implementations) - #100238 (Further improve error message for E0081) - #100268 (Add regression test for #79148) - #100294 (Update Duration::as_secs doc to point to as_secs_f64/32 for including fractional part) - #100303 (:arrow_up: rust-analyzer) Failed merges: - #100281 (Remove more Clean trait implementations) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 8d1fa71 + cacd37a commit 5af97e8

File tree

84 files changed

+1950
-550
lines changed

Some content is hidden

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

84 files changed

+1950
-550
lines changed

Diff for: compiler/rustc_typeck/src/check/check.rs

+95-63
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
3232
use rustc_trait_selection::traits::{self, ObligationCtxt};
3333
use rustc_ty_utils::representability::{self, Representability};
3434

35-
use std::iter;
3635
use std::ops::ControlFlow;
3736

3837
pub(super) fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: Abi) {
@@ -1494,76 +1493,109 @@ fn check_enum<'tcx>(tcx: TyCtxt<'tcx>, vs: &'tcx [hir::Variant<'tcx>], def_id: L
14941493
}
14951494
}
14961495

1497-
let mut disr_vals: Vec<Discr<'tcx>> = Vec::with_capacity(vs.len());
1498-
// This tracks the previous variant span (in the loop) incase we need it for diagnostics
1499-
let mut prev_variant_span: Span = DUMMY_SP;
1500-
for ((_, discr), v) in iter::zip(def.discriminants(tcx), vs) {
1501-
// Check for duplicate discriminant values
1502-
if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) {
1503-
let variant_did = def.variant(VariantIdx::new(i)).def_id;
1504-
let variant_i_hir_id = tcx.hir().local_def_id_to_hir_id(variant_did.expect_local());
1505-
let variant_i = tcx.hir().expect_variant(variant_i_hir_id);
1506-
let i_span = match variant_i.disr_expr {
1507-
Some(ref expr) => tcx.hir().span(expr.hir_id),
1508-
None => tcx.def_span(variant_did),
1509-
};
1510-
let span = match v.disr_expr {
1511-
Some(ref expr) => tcx.hir().span(expr.hir_id),
1512-
None => v.span,
1513-
};
1514-
let display_discr = format_discriminant_overflow(tcx, v, discr);
1515-
let display_discr_i = format_discriminant_overflow(tcx, variant_i, disr_vals[i]);
1516-
let no_disr = v.disr_expr.is_none();
1517-
let mut err = struct_span_err!(
1518-
tcx.sess,
1519-
sp,
1520-
E0081,
1521-
"discriminant value `{}` assigned more than once",
1522-
discr,
1523-
);
1524-
1525-
err.span_label(i_span, format!("first assignment of {display_discr_i}"));
1526-
err.span_label(span, format!("second assignment of {display_discr}"));
1527-
1528-
if no_disr {
1529-
err.span_label(
1530-
prev_variant_span,
1531-
format!(
1532-
"assigned discriminant for `{}` was incremented from this discriminant",
1533-
v.ident
1534-
),
1535-
);
1536-
}
1537-
err.emit();
1538-
}
1539-
1540-
disr_vals.push(discr);
1541-
prev_variant_span = v.span;
1542-
}
1496+
detect_discriminant_duplicate(tcx, def.discriminants(tcx).collect(), vs, sp);
15431497

15441498
check_representable(tcx, sp, def_id);
15451499
check_transparent(tcx, sp, def);
15461500
}
15471501

1548-
/// In the case that a discriminant is both a duplicate and an overflowing literal,
1549-
/// we insert both the assigned discriminant and the literal it overflowed from into the formatted
1550-
/// output. Otherwise we format the discriminant normally.
1551-
fn format_discriminant_overflow<'tcx>(
1502+
/// Part of enum check. Given the discriminants of an enum, errors if two or more discriminants are equal
1503+
fn detect_discriminant_duplicate<'tcx>(
15521504
tcx: TyCtxt<'tcx>,
1553-
variant: &hir::Variant<'_>,
1554-
dis: Discr<'tcx>,
1555-
) -> String {
1556-
if let Some(expr) = &variant.disr_expr {
1557-
let body = &tcx.hir().body(expr.body).value;
1558-
if let hir::ExprKind::Lit(lit) = &body.kind
1559-
&& let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1560-
&& dis.val != *lit_value
1561-
{
1562-
return format!("`{dis}` (overflowed from `{lit_value}`)");
1505+
mut discrs: Vec<(VariantIdx, Discr<'tcx>)>,
1506+
vs: &'tcx [hir::Variant<'tcx>],
1507+
self_span: Span,
1508+
) {
1509+
// Helper closure to reduce duplicate code. This gets called everytime we detect a duplicate.
1510+
// Here `idx` refers to the order of which the discriminant appears, and its index in `vs`
1511+
let report = |dis: Discr<'tcx>,
1512+
idx: usize,
1513+
err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>| {
1514+
let var = &vs[idx]; // HIR for the duplicate discriminant
1515+
let (span, display_discr) = match var.disr_expr {
1516+
Some(ref expr) => {
1517+
// In the case the discriminant is both a duplicate and overflowed, let the user know
1518+
if let hir::ExprKind::Lit(lit) = &tcx.hir().body(expr.body).value.kind
1519+
&& let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1520+
&& *lit_value != dis.val
1521+
{
1522+
(tcx.hir().span(expr.hir_id), format!("`{dis}` (overflowed from `{lit_value}`)"))
1523+
// Otherwise, format the value as-is
1524+
} else {
1525+
(tcx.hir().span(expr.hir_id), format!("`{dis}`"))
1526+
}
1527+
}
1528+
None => {
1529+
// At this point we know this discriminant is a duplicate, and was not explicitly
1530+
// assigned by the user. Here we iterate backwards to fetch the HIR for the last
1531+
// explictly assigned discriminant, and letting the user know that this was the
1532+
// increment startpoint, and how many steps from there leading to the duplicate
1533+
if let Some((n, hir::Variant { span, ident, .. })) =
1534+
vs[..idx].iter().rev().enumerate().find(|v| v.1.disr_expr.is_some())
1535+
{
1536+
let ve_ident = var.ident;
1537+
let n = n + 1;
1538+
let sp = if n > 1 { "variants" } else { "variant" };
1539+
1540+
err.span_label(
1541+
*span,
1542+
format!("discriminant for `{ve_ident}` incremented from this startpoint (`{ident}` + {n} {sp} later => `{ve_ident}` = {dis})"),
1543+
);
1544+
}
1545+
1546+
(vs[idx].span, format!("`{dis}`"))
1547+
}
1548+
};
1549+
1550+
err.span_label(span, format!("{display_discr} assigned here"));
1551+
};
1552+
1553+
// Here we loop through the discriminants, comparing each discriminant to another.
1554+
// When a duplicate is detected, we instatiate an error and point to both
1555+
// initial and duplicate value. The duplicate discriminant is then discarded by swapping
1556+
// it with the last element and decrementing the `vec.len` (which is why we have to evaluate
1557+
// `discrs.len()` anew every iteration, and why this could be tricky to do in a functional
1558+
// style as we are mutating `discrs` on the fly).
1559+
let mut i = 0;
1560+
while i < discrs.len() {
1561+
let hir_var_i_idx = discrs[i].0.index();
1562+
let mut error: Option<DiagnosticBuilder<'_, _>> = None;
1563+
1564+
let mut o = i + 1;
1565+
while o < discrs.len() {
1566+
let hir_var_o_idx = discrs[o].0.index();
1567+
1568+
if discrs[i].1.val == discrs[o].1.val {
1569+
let err = error.get_or_insert_with(|| {
1570+
let mut ret = struct_span_err!(
1571+
tcx.sess,
1572+
self_span,
1573+
E0081,
1574+
"discriminant value `{}` assigned more than once",
1575+
discrs[i].1,
1576+
);
1577+
1578+
report(discrs[i].1, hir_var_i_idx, &mut ret);
1579+
1580+
ret
1581+
});
1582+
1583+
report(discrs[o].1, hir_var_o_idx, err);
1584+
1585+
// Safe to unwrap here, as we wouldn't reach this point if `discrs` was empty
1586+
discrs[o] = *discrs.last().unwrap();
1587+
discrs.pop();
1588+
} else {
1589+
o += 1;
1590+
}
15631591
}
1564-
}
15651592

1566-
format!("`{dis}`")
1593+
if let Some(mut e) = error {
1594+
e.emit();
1595+
}
1596+
1597+
i += 1;
1598+
}
15671599
}
15681600

15691601
pub(super) fn check_type_params_are_used<'tcx>(

Diff for: compiler/rustc_typeck/src/check/expr.rs

+22-31
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@ use rustc_span::hygiene::DesugaringKind;
5050
use rustc_span::lev_distance::find_best_match_for_name;
5151
use rustc_span::source_map::{Span, Spanned};
5252
use rustc_span::symbol::{kw, sym, Ident, Symbol};
53-
use rustc_span::{BytePos, Pos};
5453
use rustc_target::spec::abi::Abi::RustIntrinsic;
5554
use rustc_trait_selection::infer::InferCtxtExt;
5655
use rustc_trait_selection::traits::{self, ObligationCauseCode};
@@ -2398,37 +2397,29 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
23982397
expr,
23992398
Some(span),
24002399
);
2400+
} else if let ty::RawPtr(ty_and_mut) = expr_t.kind()
2401+
&& let ty::Adt(adt_def, _) = ty_and_mut.ty.kind()
2402+
&& let ExprKind::Field(base_expr, _) = expr.kind
2403+
&& adt_def.variants().len() == 1
2404+
&& adt_def
2405+
.variants()
2406+
.iter()
2407+
.next()
2408+
.unwrap()
2409+
.fields
2410+
.iter()
2411+
.any(|f| f.ident(self.tcx) == field)
2412+
{
2413+
err.multipart_suggestion(
2414+
"to access the field, dereference first",
2415+
vec![
2416+
(base_expr.span.shrink_to_lo(), "(*".to_string()),
2417+
(base_expr.span.shrink_to_hi(), ")".to_string()),
2418+
],
2419+
Applicability::MaybeIncorrect,
2420+
);
24012421
} else {
2402-
let mut found = false;
2403-
2404-
if let ty::RawPtr(ty_and_mut) = expr_t.kind()
2405-
&& let ty::Adt(adt_def, _) = ty_and_mut.ty.kind()
2406-
{
2407-
if adt_def.variants().len() == 1
2408-
&& adt_def
2409-
.variants()
2410-
.iter()
2411-
.next()
2412-
.unwrap()
2413-
.fields
2414-
.iter()
2415-
.any(|f| f.ident(self.tcx) == field)
2416-
{
2417-
if let Some(dot_loc) = expr_snippet.rfind('.') {
2418-
found = true;
2419-
err.span_suggestion(
2420-
expr.span.with_hi(expr.span.lo() + BytePos::from_usize(dot_loc)),
2421-
"to access the field, dereference first",
2422-
format!("(*{})", &expr_snippet[0..dot_loc]),
2423-
Applicability::MaybeIncorrect,
2424-
);
2425-
}
2426-
}
2427-
}
2428-
2429-
if !found {
2430-
err.help("methods are immutable and cannot be assigned to");
2431-
}
2422+
err.help("methods are immutable and cannot be assigned to");
24322423
}
24332424

24342425
err.emit();

Diff for: compiler/rustc_typeck/src/check/mod.rs

-1
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,6 @@ use rustc_hir::def_id::{DefId, LocalDefId};
112112
use rustc_hir::intravisit::Visitor;
113113
use rustc_hir::{HirIdMap, ImplicitSelfKind, Node};
114114
use rustc_index::bit_set::BitSet;
115-
use rustc_index::vec::Idx;
116115
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
117116
use rustc_middle::ty::query::Providers;
118117
use rustc_middle::ty::subst::{InternalSubsts, Subst, SubstsRef};

Diff for: library/core/src/time.rs

+4-12
Original file line numberDiff line numberDiff line change
@@ -318,19 +318,11 @@ impl Duration {
318318
/// assert_eq!(duration.as_secs(), 5);
319319
/// ```
320320
///
321-
/// To determine the total number of seconds represented by the `Duration`,
322-
/// use `as_secs` in combination with [`subsec_nanos`]:
323-
///
324-
/// ```
325-
/// use std::time::Duration;
326-
///
327-
/// let duration = Duration::new(5, 730023852);
328-
///
329-
/// assert_eq!(5.730023852,
330-
/// duration.as_secs() as f64
331-
/// + duration.subsec_nanos() as f64 * 1e-9);
332-
/// ```
321+
/// To determine the total number of seconds represented by the `Duration`
322+
/// including the fractional part, use [`as_secs_f64`] or [`as_secs_f32`]
333323
///
324+
/// [`as_secs_f32`]: Duration::as_secs_f64
325+
/// [`as_secs_f64`]: Duration::as_secs_f32
334326
/// [`subsec_nanos`]: Duration::subsec_nanos
335327
#[stable(feature = "duration", since = "1.3.0")]
336328
#[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]

Diff for: src/librustdoc/clean/auto_trait.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,7 @@ where
476476
let mut ty_to_fn: FxHashMap<Type, (PolyTrait, Option<Type>)> = Default::default();
477477

478478
for p in clean_where_predicates {
479-
let (orig_p, p) = (p, p.clean(self.cx));
479+
let (orig_p, p) = (p, clean_predicate(p, self.cx));
480480
if p.is_none() {
481481
continue;
482482
}

0 commit comments

Comments
 (0)