Skip to content

Commit

Permalink
prisma-fmt: Correctly skip clrf line endings when computing field pos…
Browse files Browse the repository at this point in the history
…ition (#4870)

* prisma-fmt: Correctly skip clrf line endings when computing field position

Fixes the failure on Windows in prisma/language-tools#1731

* Fix clippy
  • Loading branch information
SevInf authored May 16, 2024
1 parent 97f638f commit 89e2d89
Showing 1 changed file with 38 additions and 2 deletions.
40 changes: 38 additions & 2 deletions prisma-fmt/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,9 +271,15 @@ pub(crate) fn range_to_span(range: Range, document: &str, file_id: FileId) -> as
ast::Span::new(start, end, file_id)
}

/// Gives the LSP position right after the given span.
/// Gives the LSP position right after the given span, skipping any trailing newlines
pub(crate) fn position_after_span(span: ast::Span, document: &str) -> Position {
offset_to_position(span.end - 1, document)
let end = match (document.chars().nth(span.end - 2), document.chars().nth(span.end - 1)) {
(Some('\r'), Some('\n')) => span.end - 2,
(_, Some('\n')) => span.end - 1,
_ => span.end,
};

offset_to_position(end, document)
}

/// Converts a byte offset to an LSP position, if the given offset
Expand Down Expand Up @@ -302,6 +308,9 @@ pub fn offset_to_position(offset: usize, document: &str) -> Position {
#[cfg(test)]
mod tests {
use lsp_types::Position;
use psl::diagnostics::{FileId, Span};

use crate::position_after_span;

// On Windows, a newline is actually two characters.
#[test]
Expand All @@ -313,4 +322,31 @@ mod tests {

assert_eq!(found_offset, expected_offset);
}

#[test]
fn position_after_span_no_newline() {
let str = "some string";
let span = Span::new(0, str.len(), FileId::ZERO);
let pos = position_after_span(span, str);
assert_eq!(pos.line, 0);
assert_eq!(pos.character, 11);
}

#[test]
fn position_after_span_lf() {
let str = "some string\n";
let span = Span::new(0, str.len(), FileId::ZERO);
let pos = position_after_span(span, str);
assert_eq!(pos.line, 0);
assert_eq!(pos.character, 11);
}

#[test]
fn position_after_span_crlf() {
let str = "some string\r\n";
let span = Span::new(0, str.len(), FileId::ZERO);
let pos = position_after_span(span, str);
assert_eq!(pos.line, 0);
assert_eq!(pos.character, 11);
}
}

0 comments on commit 89e2d89

Please sign in to comment.