Skip to content

Commit 15b9e20

Browse files
authored
Rollup merge of rust-lang#105500 - oli-obk:unhide_unknown_spans, r=estebank
Make some diagnostics not depend on the source of what they reference being available r? `@estebank` follow up to rust-lang#104449
2 parents dcdbbd0 + 82ce70a commit 15b9e20

File tree

246 files changed

+381
-1666
lines changed

Some content is hidden

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

246 files changed

+381
-1666
lines changed

compiler/rustc_borrowck/src/diagnostics/mod.rs

+16-8
Original file line numberDiff line numberDiff line change
@@ -1059,17 +1059,12 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
10591059
);
10601060
if self.fn_self_span_reported.insert(fn_span) {
10611061
err.span_note(
1062-
// Check whether the source is accessible
1063-
if self.infcx.tcx.sess.source_map().is_span_accessible(self_arg.span) {
1064-
self_arg.span
1065-
} else {
1066-
fn_call_span
1067-
},
1062+
self_arg.span,
10681063
"calling this operator moves the left-hand side",
10691064
);
10701065
}
10711066
}
1072-
CallKind::Normal { self_arg, desugaring, is_option_or_result } => {
1067+
CallKind::Normal { self_arg, desugaring, method_did } => {
10731068
let self_arg = self_arg.unwrap();
10741069
if let Some((CallDesugaringKind::ForLoopIntoIter, _)) = desugaring {
10751070
let ty = moved_place.ty(self.body, self.infcx.tcx).ty;
@@ -1139,14 +1134,27 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
11391134
),
11401135
);
11411136
}
1137+
let tcx = self.infcx.tcx;
11421138
// Avoid pointing to the same function in multiple different
11431139
// error messages.
11441140
if span != DUMMY_SP && self.fn_self_span_reported.insert(self_arg.span) {
1141+
let func = tcx.def_path_str(method_did);
11451142
err.span_note(
11461143
self_arg.span,
1147-
&format!("this function takes ownership of the receiver `self`, which moves {}", place_name)
1144+
&format!("`{func}` takes ownership of the receiver `self`, which moves {place_name}")
11481145
);
11491146
}
1147+
let parent_did = tcx.parent(method_did);
1148+
let parent_self_ty = (tcx.def_kind(parent_did)
1149+
== rustc_hir::def::DefKind::Impl)
1150+
.then_some(parent_did)
1151+
.and_then(|did| match tcx.type_of(did).kind() {
1152+
ty::Adt(def, ..) => Some(def.did()),
1153+
_ => None,
1154+
});
1155+
let is_option_or_result = parent_self_ty.map_or(false, |def_id| {
1156+
matches!(tcx.get_diagnostic_name(def_id), Some(sym::Option | sym::Result))
1157+
});
11501158
if is_option_or_result && maybe_reinitialized_locations_is_empty {
11511159
err.span_label(
11521160
var_span,

compiler/rustc_const_eval/src/util/call_kind.rs

+3-15
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
use rustc_hir::def_id::DefId;
66
use rustc_hir::{lang_items, LangItem};
77
use rustc_middle::ty::subst::SubstsRef;
8-
use rustc_middle::ty::{self, AssocItemContainer, DefIdTree, Instance, ParamEnv, Ty, TyCtxt};
8+
use rustc_middle::ty::{AssocItemContainer, Instance, ParamEnv, Ty, TyCtxt};
99
use rustc_span::symbol::Ident;
1010
use rustc_span::{sym, DesugaringKind, Span};
1111

@@ -39,9 +39,7 @@ pub enum CallKind<'tcx> {
3939
Normal {
4040
self_arg: Option<Ident>,
4141
desugaring: Option<(CallDesugaringKind, Ty<'tcx>)>,
42-
/// Whether the self type of the method call has an `.as_ref()` method.
43-
/// Used for better diagnostics.
44-
is_option_or_result: bool,
42+
method_did: DefId,
4543
},
4644
/// A call to `Fn(..)::call(..)`, desugared from `my_closure(a, b, c)`
4745
FnCall { fn_trait_id: DefId, self_ty: Ty<'tcx> },
@@ -133,16 +131,6 @@ pub fn call_kind<'tcx>(
133131
} else {
134132
None
135133
};
136-
let parent_did = tcx.parent(method_did);
137-
let parent_self_ty = (tcx.def_kind(parent_did) == rustc_hir::def::DefKind::Impl)
138-
.then_some(parent_did)
139-
.and_then(|did| match tcx.type_of(did).kind() {
140-
ty::Adt(def, ..) => Some(def.did()),
141-
_ => None,
142-
});
143-
let is_option_or_result = parent_self_ty.map_or(false, |def_id| {
144-
matches!(tcx.get_diagnostic_name(def_id), Some(sym::Option | sym::Result))
145-
});
146-
CallKind::Normal { self_arg, desugaring, is_option_or_result }
134+
CallKind::Normal { self_arg, desugaring, method_did }
147135
})
148136
}

compiler/rustc_errors/src/emitter.rs

+44-35
Original file line numberDiff line numberDiff line change
@@ -1408,49 +1408,58 @@ impl EmitterWriter {
14081408
if !sm.ensure_source_file_source_present(annotated_file.file.clone()) {
14091409
if !self.short_message {
14101410
// We'll just print an unannotated message.
1411-
for (annotation_id, line) in annotated_file.lines.into_iter().enumerate() {
1411+
for (annotation_id, line) in annotated_file.lines.iter().enumerate() {
14121412
let mut annotations = line.annotations.clone();
14131413
annotations.sort_by_key(|a| Reverse(a.start_col));
14141414
let mut line_idx = buffer.num_lines();
1415-
buffer.append(
1416-
line_idx,
1417-
&format!(
1418-
"{}:{}:{}",
1419-
sm.filename_for_diagnostics(&annotated_file.file.name),
1420-
sm.doctest_offset_line(&annotated_file.file.name, line.line_index),
1421-
annotations[0].start_col + 1,
1422-
),
1423-
Style::LineAndColumn,
1424-
);
1425-
if annotation_id == 0 {
1426-
buffer.prepend(line_idx, "--> ", Style::LineNumber);
1415+
1416+
let labels: Vec<_> = annotations
1417+
.iter()
1418+
.filter_map(|a| Some((a.label.as_ref()?, a.is_primary)))
1419+
.filter(|(l, _)| !l.is_empty())
1420+
.collect();
1421+
1422+
if annotation_id == 0 || !labels.is_empty() {
1423+
buffer.append(
1424+
line_idx,
1425+
&format!(
1426+
"{}:{}:{}",
1427+
sm.filename_for_diagnostics(&annotated_file.file.name),
1428+
sm.doctest_offset_line(
1429+
&annotated_file.file.name,
1430+
line.line_index
1431+
),
1432+
annotations[0].start_col + 1,
1433+
),
1434+
Style::LineAndColumn,
1435+
);
1436+
if annotation_id == 0 {
1437+
buffer.prepend(line_idx, "--> ", Style::LineNumber);
1438+
} else {
1439+
buffer.prepend(line_idx, "::: ", Style::LineNumber);
1440+
}
14271441
for _ in 0..max_line_num_len {
14281442
buffer.prepend(line_idx, " ", Style::NoStyle);
14291443
}
14301444
line_idx += 1;
1431-
};
1432-
for (i, annotation) in annotations.into_iter().enumerate() {
1433-
if let Some(label) = &annotation.label {
1434-
let style = if annotation.is_primary {
1435-
Style::LabelPrimary
1436-
} else {
1437-
Style::LabelSecondary
1438-
};
1439-
if annotation_id == 0 {
1440-
buffer.prepend(line_idx, " |", Style::LineNumber);
1441-
for _ in 0..max_line_num_len {
1442-
buffer.prepend(line_idx, " ", Style::NoStyle);
1443-
}
1444-
line_idx += 1;
1445-
buffer.append(line_idx + i, " = note: ", style);
1446-
for _ in 0..max_line_num_len {
1447-
buffer.prepend(line_idx, " ", Style::NoStyle);
1448-
}
1449-
} else {
1450-
buffer.append(line_idx + i, ": ", style);
1451-
}
1452-
buffer.append(line_idx + i, label, style);
1445+
}
1446+
for (label, is_primary) in labels.into_iter() {
1447+
let style = if is_primary {
1448+
Style::LabelPrimary
1449+
} else {
1450+
Style::LabelSecondary
1451+
};
1452+
buffer.prepend(line_idx, " |", Style::LineNumber);
1453+
for _ in 0..max_line_num_len {
1454+
buffer.prepend(line_idx, " ", Style::NoStyle);
1455+
}
1456+
line_idx += 1;
1457+
buffer.append(line_idx, " = note: ", style);
1458+
for _ in 0..max_line_num_len {
1459+
buffer.prepend(line_idx, " ", Style::NoStyle);
14531460
}
1461+
buffer.append(line_idx, label, style);
1462+
line_idx += 1;
14541463
}
14551464
}
14561465
}

compiler/rustc_hir_typeck/src/method/suggest.rs

+18-5
Original file line numberDiff line numberDiff line change
@@ -1853,7 +1853,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
18531853
)],
18541854
) {
18551855
let mut derives = Vec::<(String, Span, Symbol)>::new();
1856-
let mut traits = Vec::<Span>::new();
1856+
let mut traits = Vec::new();
18571857
for (pred, _, _) in unsatisfied_predicates {
18581858
let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder() else { continue };
18591859
let adt = match trait_pred.self_ty().ty_adt_def() {
@@ -1892,10 +1892,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
18921892
}
18931893
derives.push((self_name, self_span, diagnostic_name));
18941894
} else {
1895-
traits.push(self.tcx.def_span(trait_pred.def_id()));
1895+
traits.push(trait_pred.def_id());
18961896
}
18971897
} else {
1898-
traits.push(self.tcx.def_span(trait_pred.def_id()));
1898+
traits.push(trait_pred.def_id());
18991899
}
19001900
}
19011901
traits.sort();
@@ -1918,10 +1918,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
19181918

19191919
let len = traits.len();
19201920
if len > 0 {
1921-
let span: MultiSpan = traits.into();
1921+
let span =
1922+
MultiSpan::from_spans(traits.iter().map(|&did| self.tcx.def_span(did)).collect());
1923+
let mut names = format!("`{}`", self.tcx.def_path_str(traits[0]));
1924+
for (i, &did) in traits.iter().enumerate().skip(1) {
1925+
if len > 2 {
1926+
names.push_str(", ");
1927+
}
1928+
if i == len - 1 {
1929+
names.push_str(" and ");
1930+
}
1931+
names.push('`');
1932+
names.push_str(&self.tcx.def_path_str(did));
1933+
names.push('`');
1934+
}
19221935
err.span_note(
19231936
span,
1924-
&format!("the following trait{} must be implemented", pluralize!(len),),
1937+
&format!("the trait{} {} must be implemented", pluralize!(len), names),
19251938
);
19261939
}
19271940

compiler/rustc_metadata/src/rmeta/decoder.rs

+9-7
Original file line numberDiff line numberDiff line change
@@ -1527,13 +1527,15 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
15271527
if let Some(virtual_dir) = &sess.opts.unstable_opts.simulate_remapped_rust_src_base
15281528
{
15291529
if let Some(real_dir) = &sess.opts.real_rust_source_base_dir {
1530-
if let rustc_span::FileName::Real(ref mut old_name) = name {
1531-
if let rustc_span::RealFileName::LocalPath(local) = old_name {
1532-
if let Ok(rest) = local.strip_prefix(real_dir) {
1533-
*old_name = rustc_span::RealFileName::Remapped {
1534-
local_path: None,
1535-
virtual_name: virtual_dir.join(rest),
1536-
};
1530+
for subdir in ["library", "compiler"] {
1531+
if let rustc_span::FileName::Real(ref mut old_name) = name {
1532+
if let rustc_span::RealFileName::LocalPath(local) = old_name {
1533+
if let Ok(rest) = local.strip_prefix(real_dir.join(subdir)) {
1534+
*old_name = rustc_span::RealFileName::Remapped {
1535+
local_path: None,
1536+
virtual_name: virtual_dir.join(subdir).join(rest),
1537+
};
1538+
}
15371539
}
15381540
}
15391541
}

compiler/rustc_privacy/src/lib.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -1308,15 +1308,15 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> {
13081308
let is_local_static =
13091309
if let DefKind::Static(_) = kind { def_id.is_local() } else { false };
13101310
if !self.item_is_accessible(def_id) && !is_local_static {
1311-
let sess = self.tcx.sess;
1312-
let sm = sess.source_map();
1313-
let name = match qpath {
1314-
hir::QPath::Resolved(..) | hir::QPath::LangItem(..) => {
1315-
sm.span_to_snippet(qpath.span()).ok()
1311+
let name = match *qpath {
1312+
hir::QPath::LangItem(it, ..) => {
1313+
self.tcx.lang_items().get(it).map(|did| self.tcx.def_path_str(did))
13161314
}
1315+
hir::QPath::Resolved(_, path) => Some(self.tcx.def_path_str(path.res.def_id())),
13171316
hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()),
13181317
};
13191318
let kind = kind.descr(def_id);
1319+
let sess = self.tcx.sess;
13201320
let _ = match name {
13211321
Some(name) => {
13221322
sess.emit_err(ItemIsPrivate { span, kind, descr: (&name).into() })

compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs

+11-21
Original file line numberDiff line numberDiff line change
@@ -2179,15 +2179,15 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
21792179
format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
21802180
};
21812181

2182-
let mut explain_yield = |interior_span: Span,
2183-
yield_span: Span,
2184-
scope_span: Option<Span>| {
2185-
let mut span = MultiSpan::from_span(yield_span);
2186-
if let Ok(snippet) = source_map.span_to_snippet(interior_span) {
2187-
// #70935: If snippet contains newlines, display "the value" instead
2188-
// so that we do not emit complex diagnostics.
2189-
let snippet = &format!("`{}`", snippet);
2190-
let snippet = if snippet.contains('\n') { "the value" } else { snippet };
2182+
let mut explain_yield =
2183+
|interior_span: Span, yield_span: Span, scope_span: Option<Span>| {
2184+
let mut span = MultiSpan::from_span(yield_span);
2185+
let snippet = match source_map.span_to_snippet(interior_span) {
2186+
// #70935: If snippet contains newlines, display "the value" instead
2187+
// so that we do not emit complex diagnostics.
2188+
Ok(snippet) if !snippet.contains('\n') => format!("`{}`", snippet),
2189+
_ => "the value".to_string(),
2190+
};
21912191
// note: future is not `Send` as this value is used across an await
21922192
// --> $DIR/issue-70935-complex-spans.rs:13:9
21932193
// |
@@ -2212,17 +2212,11 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
22122212
interior_span,
22132213
format!("has type `{}` which {}", target_ty, trait_explanation),
22142214
);
2215-
// If available, use the scope span to annotate the drop location.
2216-
let mut scope_note = None;
22172215
if let Some(scope_span) = scope_span {
22182216
let scope_span = source_map.end_point(scope_span);
22192217

22202218
let msg = format!("{} is later dropped here", snippet);
2221-
if source_map.is_multiline(yield_span.between(scope_span)) {
2222-
span.push_span_label(scope_span, msg);
2223-
} else {
2224-
scope_note = Some((scope_span, msg));
2225-
}
2219+
span.push_span_label(scope_span, msg);
22262220
}
22272221
err.span_note(
22282222
span,
@@ -2231,11 +2225,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
22312225
future_or_generator, trait_explanation, an_await_or_yield
22322226
),
22332227
);
2234-
if let Some((span, msg)) = scope_note {
2235-
err.span_note(span, &msg);
2236-
}
2237-
}
2238-
};
2228+
};
22392229
match interior_or_upvar_span {
22402230
GeneratorInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
22412231
if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {

src/test/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr

+1-4
Original file line numberDiff line numberDiff line change
@@ -660,10 +660,7 @@ LL | #[derive(Diagnostic)]
660660
= help: normalized in stderr
661661
note: required by a bound in `DiagnosticBuilder::<'a, G>::set_arg`
662662
--> $COMPILER_DIR/rustc_errors/src/diagnostic_builder.rs:LL:CC
663-
|
664-
LL | arg: impl IntoDiagnosticArg,
665-
| ^^^^^^^^^^^^^^^^^ required by this bound in `DiagnosticBuilder::<'a, G>::set_arg`
666-
= note: this error originates in the derive macro `Diagnostic` (in Nightly builds, run with -Z macro-backtrace for more info)
663+
= note: this error originates in the derive macro `Diagnostic` which comes from the expansion of the macro `forward` (in Nightly builds, run with -Z macro-backtrace for more info)
667664

668665
error: aborting due to 83 previous errors
669666

src/test/ui/alloc-error/alloc-error-handler-bad-signature-2.stderr

-3
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,6 @@ LL | | }
1717
= note: struct `core::alloc::Layout` and struct `Layout` have similar names, but are actually distinct types
1818
note: struct `core::alloc::Layout` is defined in crate `core`
1919
--> $SRC_DIR/core/src/alloc/layout.rs:LL:COL
20-
|
21-
LL | pub struct Layout {
22-
| ^^^^^^^^^^^^^^^^^
2320
note: struct `Layout` is defined in the current crate
2421
--> $DIR/alloc-error-handler-bad-signature-2.rs:7:1
2522
|

src/test/ui/associated-type-bounds/issue-99828.stderr

-3
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,6 @@ LL | fn get_iter(vec: &[i32]) -> impl Iterator<Item = {}> + '_ {
1515
|
1616
note: associated type defined here
1717
--> $SRC_DIR/core/src/iter/traits/iterator.rs:LL:COL
18-
|
19-
LL | type Item;
20-
| ^^^^^^^^^
2118

2219
error: aborting due to 2 previous errors
2320

src/test/ui/associated-types/defaults-wf.stderr

-3
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,6 @@ LL | type Ty = Vec<[u8]>;
77
= help: the trait `Sized` is not implemented for `[u8]`
88
note: required by a bound in `Vec`
99
--> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL
10-
|
11-
LL | pub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> {
12-
| ^ required by this bound in `Vec`
1310

1411
error: aborting due to previous error
1512

src/test/ui/associated-types/trait-with-supertraits-needing-sized-self.stderr

-3
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,6 @@ LL | trait ArithmeticOps: Add<Output=Self> + Sub<Output=Self> + Mul<Output=Self>
66
|
77
note: required by a bound in `Add`
88
--> $SRC_DIR/core/src/ops/arith.rs:LL:COL
9-
|
10-
LL | pub trait Add<Rhs = Self> {
11-
| ^^^^^^^^^^ required by this bound in `Add`
129
help: consider further restricting `Self`
1310
|
1411
LL | trait ArithmeticOps: Add<Output=Self> + Sub<Output=Self> + Mul<Output=Self> + Div<Output=Self> + Sized {}

0 commit comments

Comments
 (0)