| 1 |
from typing import Any, NamedTuple, TYPE_CHECKING |
| 2 |
|
| 3 |
try: |
| 4 |
from typing import TypedDict |
| 5 |
except ImportError: # Python < 3.8 |
| 6 |
from typing_extensions import TypedDict |
| 7 |
|
| 8 |
if TYPE_CHECKING: |
| 9 |
from .source import Source # noqa: F401 |
| 10 |
|
| 11 |
__all__ = ["get_location", "SourceLocation", "FormattedSourceLocation"] |
| 12 |
|
| 13 |
|
| 14 |
class FormattedSourceLocation(TypedDict): |
| 15 |
"""Formatted source location""" |
| 16 |
|
| 17 |
line: int |
| 18 |
column: int |
| 19 |
|
| 20 |
|
| 21 |
class SourceLocation(NamedTuple): |
| 22 |
"""Represents a location in a Source.""" |
| 23 |
|
| 24 |
line: int |
| 25 |
column: int |
| 26 |
|
| 27 |
@property |
| 28 |
def formatted(self) -> FormattedSourceLocation: |
| 29 |
return dict(line=self.line, column=self.column) |
| 30 |
|
| 31 |
def __eq__(self, other: Any) -> bool: |
| 32 |
if isinstance(other, dict): |
| 33 |
return self.formatted == other |
| 34 |
return tuple(self) == other |
| 35 |
|
| 36 |
def __ne__(self, other: Any) -> bool: |
| 37 |
return not self == other |
| 38 |
|
| 39 |
|
| 40 |
def get_location(source: "Source", position: int) -> SourceLocation: |
| 41 |
"""Get the line and column for a character position in the source. |
| 42 |
|
| 43 |
Takes a Source and a UTF-8 character offset, and returns the corresponding line and |
| 44 |
column as a SourceLocation. |
| 45 |
""" |
| 46 |
return source.get_location(position) |