about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMichael Howell <michael@notriddle.com>2024-03-29 17:13:46 -0700
committerMichael Howell <michael@notriddle.com>2024-03-29 18:22:44 -0700
commit1c41dd6320f1729e799171d98f5ff384246ddcd5 (patch)
treea341e3c865d80d62641670b65476f16b856773fa
parent1b73c7d1e505152e96454364f1eb9d1c25b84772 (diff)
downloadrust-1c41dd6320f1729e799171d98f5ff384246ddcd5.tar.gz
rust-1c41dd6320f1729e799171d98f5ff384246ddcd5.zip
diagnostics: fix crash on completely empty included file
-rw-r--r--compiler/rustc_errors/src/emitter.rs9
-rw-r--r--tests/ui/include-macros/mismatched-types.stderr7
2 files changed, 12 insertions, 4 deletions
diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs
index bd8e78bda26..6ce3fa3535d 100644
--- a/compiler/rustc_errors/src/emitter.rs
+++ b/compiler/rustc_errors/src/emitter.rs
@@ -1513,7 +1513,9 @@ impl HumanEmitter {
                 for line_idx in 0..annotated_file.lines.len() {
                     let file = annotated_file.file.clone();
                     let line = &annotated_file.lines[line_idx];
-                    if let Some(source_string) = file.get_line(line.line_index - 1) {
+                    if let Some(source_string) =
+                        line.line_index.checked_sub(1).and_then(|l| file.get_line(l))
+                    {
                         let leading_whitespace = source_string
                             .chars()
                             .take_while(|c| c.is_whitespace())
@@ -1553,7 +1555,10 @@ impl HumanEmitter {
                 for line in &annotated_file.lines {
                     max_line_len = max(
                         max_line_len,
-                        annotated_file.file.get_line(line.line_index - 1).map_or(0, |s| s.len()),
+                        line.line_index
+                            .checked_sub(1)
+                            .and_then(|l| annotated_file.file.get_line(l))
+                            .map_or(0, |s| s.len()),
                     );
                     for ann in &line.annotations {
                         span_right_margin = max(span_right_margin, ann.start_col.display);
diff --git a/tests/ui/include-macros/mismatched-types.stderr b/tests/ui/include-macros/mismatched-types.stderr
index 4f2880e2f5d..9bc0e64464e 100644
--- a/tests/ui/include-macros/mismatched-types.stderr
+++ b/tests/ui/include-macros/mismatched-types.stderr
@@ -1,8 +1,11 @@
 error[E0308]: mismatched types
-  --> $DIR/mismatched-types.rs:2:20
+  --> $DIR/file.txt:0:1
+   |
+   |
+  ::: $DIR/mismatched-types.rs:2:12
    |
 LL |     let b: &[u8] = include_str!("file.txt");
-   |            -----   ^^^^^^^^^^^^^^^^^^^^^^^^ expected `&[u8]`, found `&str`
+   |            -----   ------------------------ in this macro invocation
    |            |
    |            expected due to this
    |