Skip to content

Commit 2337bbb

Browse files
committed
only relevant parts of type paths highlighted in E0308 type mismatch error message
1 parent fedefec commit 2337bbb

File tree

1 file changed

+42
-7
lines changed
  • src/librustc/infer/error_reporting

1 file changed

+42
-7
lines changed

src/librustc/infer/error_reporting/mod.rs

+42-7
Original file line numberDiff line numberDiff line change
@@ -867,7 +867,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
867867
/// Compares two given types, eliding parts that are the same between them and highlighting
868868
/// relevant differences, and return two representation of those types for highlighted printing.
869869
fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
870-
debug!("cmp(t1={}, t2={})", t1, t2);
870+
debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind, t2, t2.kind);
871871

872872
// helper functions
873873
fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
@@ -1056,12 +1056,47 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
10561056
return values;
10571057
}
10581058

1059-
// We couldn't find anything in common, highlight everything.
1060-
// let x: Bar<Qux> = y::<Foo<Zar>>();
1061-
(
1062-
DiagnosticStyledString::highlighted(t1.to_string()),
1063-
DiagnosticStyledString::highlighted(t2.to_string()),
1064-
)
1059+
// We can't find anything in common, highlight relevant part of type path.
1060+
// let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1061+
// foo::bar::Baz<Qux>
1062+
// foo::bar::Bar<Zar>
1063+
// -------- this part of the path is different
1064+
1065+
let t1_str = t1.to_string();
1066+
let t2_str = t2.to_string();
1067+
let min_len = t1_str.len().min(t2_str.len());
1068+
1069+
const SEPARATOR: &str = "::";
1070+
let separator_len = SEPARATOR.len();
1071+
let split_idx: usize =
1072+
t1_str.split(SEPARATOR)
1073+
.zip(t2_str.split(SEPARATOR))
1074+
.take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1075+
.map(|(mod_str, _)| mod_str.len() + separator_len)
1076+
.sum();
1077+
1078+
debug!("cmp: separator_len={}, split_idx={}, min_len={}",
1079+
separator_len, split_idx, min_len
1080+
);
1081+
1082+
if split_idx >= min_len {
1083+
// paths are identical, highlight everything
1084+
(
1085+
DiagnosticStyledString::highlighted(t1_str),
1086+
DiagnosticStyledString::highlighted(t2_str)
1087+
)
1088+
} else {
1089+
let (common, uniq1) = t1_str.split_at(split_idx);
1090+
let (_, uniq2) = t2_str.split_at(split_idx);
1091+
debug!("cmp: common={}, uniq1={}, uniq2={}", common, uniq1, uniq2);
1092+
1093+
values.0.push_normal(common);
1094+
values.0.push_highlighted(uniq1);
1095+
values.1.push_normal(common);
1096+
values.1.push_highlighted(uniq2);
1097+
1098+
values
1099+
}
10651100
}
10661101
}
10671102

0 commit comments

Comments
 (0)