Skip to content

Commit

Permalink
fix: don't panic in leanPosToLspPos (#3071)
Browse files Browse the repository at this point in the history
Testing a problem in the REPL.
  • Loading branch information
kim-em authored Dec 16, 2023
1 parent cddc808 commit 4497aba
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/Lean/Data/Lsp/Utf16.lean
Original file line number Diff line number Diff line change
Expand Up @@ -62,21 +62,24 @@ end String
namespace Lean
namespace FileMap

private def lineStartPos (text : FileMap) (line : Nat) : String.Pos :=
if h : line < text.positions.size then
text.positions.get ⟨line, h⟩
else if text.positions.isEmpty then
0
else
text.positions.back

/-- Computes an UTF-8 offset into `text.source`
from an LSP-style 0-indexed (ln, col) position. -/
def lspPosToUtf8Pos (text : FileMap) (pos : Lsp.Position) : String.Pos :=
let colPos :=
if h : pos.line < text.positions.size then
text.positions.get ⟨pos.line, h⟩
else if text.positions.isEmpty then
0
else
text.positions.back
let chr := text.source.utf16PosToCodepointPosFrom pos.character colPos
text.source.codepointPosToUtf8PosFrom colPos chr
let lineStartPos := lineStartPos text pos.line
let chr := text.source.utf16PosToCodepointPosFrom pos.character lineStartPos
text.source.codepointPosToUtf8PosFrom lineStartPos chr

def leanPosToLspPos (text : FileMap) : Lean.Position → Lsp.Position
| ⟨ln, col⟩ => ⟨ln-1, text.source.codepointPosToUtf16PosFrom col (text.positions.get! $ ln - 1)⟩
| ⟨line, col⟩ =>
⟨line - 1, text.source.codepointPosToUtf16PosFrom col (lineStartPos text (line - 1))⟩

def utf8PosToLspPos (text : FileMap) (pos : String.Pos) : Lsp.Position :=
text.leanPosToLspPos (text.toPosition pos)
Expand Down

0 comments on commit 4497aba

Please sign in to comment.