1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
//! Utilities for translating from codespan types into Language Server Protocol (LSP) types

use codespan::{
    ByteIndex, ByteOffset, ColumnIndex, FileId, Files, LineIndex, LineIndexOutOfBoundsError,
    LocationError, RawIndex, RawOffset, Span, SpanOutOfBoundsError,
};
// WARNING: Be extremely careful when adding new imports here, as it could break
// the compatible version range that we claim in our `Cargo.toml`. This could
// potentially break down-stream builds on a `cargo update`. This is an
// absolute no-no, breaking much of what we enjoy about Cargo!
use lsp_types::{Position as LspPosition, Range as LspRange};
use std::ffi::OsString;
use std::path::PathBuf;
use std::{error, fmt};

#[derive(Debug, PartialEq)]
pub enum Error {
    UnableToCorrelateFilename(OsString),
    ColumnOutOfBounds {
        given: ColumnIndex,
        max: ColumnIndex,
    },
    Location(LocationError),
    LineIndexOutOfBounds(LineIndexOutOfBoundsError),
    SpanOutOfBounds(SpanOutOfBoundsError),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::UnableToCorrelateFilename(s) => {
                let p = PathBuf::from(s);
                write!(f, "Unable to correlate filename `{}` to url", p.display())
            }
            Error::ColumnOutOfBounds { given, max } => {
                write!(f, "Column out of bounds - given: {}, max: {}", given, max)
            }
            Error::Location(e) => e.fmt(f),
            Error::LineIndexOutOfBounds(e) => e.fmt(f),
            Error::SpanOutOfBounds(e) => e.fmt(f),
        }
    }
}

impl From<LocationError> for Error {
    fn from(e: LocationError) -> Error {
        Error::Location(e)
    }
}

impl From<LineIndexOutOfBoundsError> for Error {
    fn from(e: LineIndexOutOfBoundsError) -> Error {
        Error::LineIndexOutOfBounds(e)
    }
}

impl From<SpanOutOfBoundsError> for Error {
    fn from(e: SpanOutOfBoundsError) -> Error {
        Error::SpanOutOfBounds(e)
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Error::UnableToCorrelateFilename(_) | Error::ColumnOutOfBounds { .. } => None,
            Error::Location(error) => Some(error),
            Error::LineIndexOutOfBounds(error) => Some(error),
            Error::SpanOutOfBounds(error) => Some(error),
        }
    }
}

fn location_to_position(
    line_str: &str,
    line: LineIndex,
    column: ColumnIndex,
    byte_index: ByteIndex,
) -> Result<LspPosition, Error> {
    if column.to_usize() > line_str.len() {
        let max = ColumnIndex(line_str.len() as RawIndex);
        let given = column;

        Err(Error::ColumnOutOfBounds { given, max })
    } else if !line_str.is_char_boundary(column.to_usize()) {
        let given = byte_index;

        Err(LocationError::InvalidCharBoundary { given }.into())
    } else {
        let line_utf16 = line_str[..column.to_usize()].encode_utf16();
        let character = line_utf16.count() as u64;
        let line = line.to_usize() as u64;

        Ok(LspPosition { line, character })
    }
}

pub fn byte_index_to_position<Source: AsRef<str>>(
    files: &Files<Source>,
    file_id: FileId,
    byte_index: ByteIndex,
) -> Result<LspPosition, Error> {
    let location = files.location(file_id, byte_index)?;
    let line_span = files.line_span(file_id, location.line)?;
    let line_str = files.source_slice(file_id, line_span)?;
    let column = ColumnIndex::from((byte_index - line_span.start()).0 as RawIndex);

    location_to_position(line_str, location.line, column, byte_index)
}

pub fn byte_span_to_range<Source: AsRef<str>>(
    files: &Files<Source>,
    file_id: FileId,
    span: Span,
) -> Result<LspRange, Error> {
    Ok(LspRange {
        start: byte_index_to_position(files, file_id, span.start())?,
        end: byte_index_to_position(files, file_id, span.end())?,
    })
}

pub fn character_to_line_offset(line: &str, character: u64) -> Result<ByteOffset, Error> {
    let line_len = ByteOffset::from(line.len() as RawOffset);
    let mut character_offset = 0;

    let mut chars = line.chars();
    while let Some(ch) = chars.next() {
        if character_offset == character {
            let chars_off = ByteOffset::from_str_len(chars.as_str());
            let ch_off = ByteOffset::from_char_len(ch);

            return Ok(line_len - chars_off - ch_off);
        }

        character_offset += ch.len_utf16() as u64;
    }

    // Handle positions after the last character on the line
    if character_offset == character {
        Ok(line_len)
    } else {
        Err(Error::ColumnOutOfBounds {
            given: ColumnIndex(character_offset as RawIndex),
            max: ColumnIndex(line.len() as RawIndex),
        })
    }
}

pub fn position_to_byte_index<Source: AsRef<str>>(
    files: &Files<Source>,
    file_id: FileId,
    position: &LspPosition,
) -> Result<ByteIndex, Error> {
    let line_span = files.line_span(file_id, position.line as RawIndex)?;
    let source = files.source_slice(file_id, line_span)?;
    let byte_offset = character_to_line_offset(source, position.character)?;

    Ok(line_span.start() + byte_offset)
}

pub fn range_to_byte_span<Source: AsRef<str>>(
    files: &Files<Source>,
    file_id: FileId,
    range: &LspRange,
) -> Result<Span, Error> {
    Ok(Span::new(
        position_to_byte_index(files, file_id, &range.start)?,
        position_to_byte_index(files, file_id, &range.end)?,
    ))
}

#[cfg(test)]
mod tests {
    use codespan::Location;

    use super::*;

    #[test]
    fn position() {
        let text = r#"
let test = 2
let test1 = ""
test
"#;
        let mut files = Files::new();
        let file_id = files.add("test", text);
        let pos = position_to_byte_index(
            &files,
            file_id,
            &LspPosition {
                line: 3,
                character: 2,
            },
        )
        .unwrap();
        assert_eq!(Location::new(3, 2), files.location(file_id, pos).unwrap());
    }

    // The protocol specifies that each `character` in position is a UTF-16 character.
    // This means that `å` and `ä` here counts as 1 while `𐐀` counts as 2.
    const UNICODE: &str = "åä t𐐀b";

    #[test]
    fn unicode_get_byte_index() {
        let mut files = Files::new();
        let file_id = files.add("unicode", UNICODE);

        let result = position_to_byte_index(
            &files,
            file_id,
            &LspPosition {
                line: 0,
                character: 3,
            },
        );
        assert_eq!(result, Ok(ByteIndex::from(5)));

        let result = position_to_byte_index(
            &files,
            file_id,
            &LspPosition {
                line: 0,
                character: 6,
            },
        );
        assert_eq!(result, Ok(ByteIndex::from(10)));
    }

    #[test]
    fn unicode_get_position() {
        let mut files = Files::new();
        let file_id = files.add("unicode", UNICODE);

        let result = byte_index_to_position(&files, file_id, ByteIndex::from(5));
        assert_eq!(
            result,
            Ok(LspPosition {
                line: 0,
                character: 3,
            })
        );

        let result = byte_index_to_position(&files, file_id, ByteIndex::from(10));
        assert_eq!(
            result,
            Ok(LspPosition {
                line: 0,
                character: 6,
            })
        );
    }
}