43 lines
1.0 KiB
Python
43 lines
1.0 KiB
Python
from dataclasses import dataclass
|
|
from functools import cached_property
|
|
from typing import overload
|
|
from lsprotocol.types import Position, Range
|
|
|
|
from parsimonious.nodes import Node
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Locator:
|
|
raw: list[str]
|
|
|
|
def _locate_pos(self, index: int) -> Position:
|
|
counter = 0
|
|
line = 0
|
|
for ix, raw_line in enumerate(self.raw):
|
|
if counter + len(raw_line) + 1 > index:
|
|
line = ix
|
|
break
|
|
else:
|
|
counter += len(raw_line) + 1
|
|
|
|
print(counter, line)
|
|
return Position(line + 1, index - counter + 1)
|
|
|
|
@overload
|
|
def locate(self, index: int) -> Position:
|
|
...
|
|
|
|
@overload
|
|
def locate(self, index: Node) -> Range:
|
|
...
|
|
|
|
def locate(self, index: int | Node) -> Position | Range:
|
|
if isinstance(index, int):
|
|
return self._locate_pos(index)
|
|
|
|
print(index.start, index.end)
|
|
start = self._locate_pos(index.start)
|
|
end = self._locate_pos(index.end)
|
|
|
|
return Range(start, end)
|