2392: Fix panic during the expansion of `column!` r=edwin0cheng a=marcogroppo

Fixes #2379. Well, this isn't the "proper" fix but it doesn't hurt, IMHO.

The problem is that `to_col_number`, called by `column_expand`, receives a position number that isn't included in the text range of the file. My (very limited) understanding is that the text is the one of the original file, while `pos` is relative to something else, probably the text of the macro. Notice that in this case the `column!` expansion seems to be triggered by `assert_eq!`, so we're in the middle of another expansion. This PR simply avoids the panic by checking the length of the text.

r? @edwin0cheng 


Co-authored-by: Marco Groppo <marco.groppo@gmail.com>
This commit is contained in:
bors[bot] 2019-11-25 02:42:17 +00:00 committed by GitHub
commit a888441c47
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -57,16 +57,21 @@ fn to_line_number(db: &dyn AstDatabase, file: HirFileId, pos: TextUnit) -> usize
let text = db.file_text(file_id);
let mut line_num = 1;
let pos = pos.to_usize();
if pos > text.len() {
// FIXME: `pos` at the moment could be an offset inside the "wrong" file
// in this case, when we know it's wrong, we return a dummy value
return 0;
}
// Count line end
for (i, c) in text.chars().enumerate() {
if i == pos.to_usize() {
if i == pos {
break;
}
if c == '\n' {
line_num += 1;
}
}
line_num
}
@ -118,15 +123,21 @@ fn to_col_number(db: &dyn AstDatabase, file: HirFileId, pos: TextUnit) -> usize
// FIXME: Use expansion info
let file_id = file.original_file(db);
let text = db.file_text(file_id);
let mut col_num = 1;
for c in text[..pos.to_usize()].chars().rev() {
let pos = pos.to_usize();
if pos > text.len() {
// FIXME: `pos` at the moment could be an offset inside the "wrong" file
// in this case we return a dummy value so that we don't `panic!`
return 0;
}
let mut col_num = 1;
for c in text[..pos].chars().rev() {
if c == '\n' {
break;
}
col_num = col_num + 1;
}
col_num
}