This repository was archived by the owner on Apr 4, 2024. It is now read-only.
forked from diffplug/selfie
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLiterals.py
89 lines (70 loc) · 2.74 KB
/
Literals.py
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
from enum import Enum, auto
from typing import Protocol, TypeVar
from abc import abstractmethod
from .EscapeLeadingWhitespace import EscapeLeadingWhitespace
import io
T = TypeVar("T")
class Language(Enum):
PYTHON = auto()
@classmethod
def from_filename(cls, filename: str) -> "Language":
extension = filename.rsplit(".", 1)[-1]
if extension == "py":
return cls.PYTHON
else:
raise ValueError(f"Unknown language for file {filename}")
class LiteralValue:
def __init__(self, expected: T | None, actual: T, format: "LiteralFormat") -> None:
self.expected = expected
self.actual = actual
self.format = format
class LiteralFormat(Protocol[T]):
@abstractmethod
def encode(
self, value: T, language: Language, encoding_policy: "EscapeLeadingWhitespace"
) -> str:
raise NotImplementedError("Subclasses must implement the encode method")
@abstractmethod
def parse(self, string: str, language: Language) -> T:
raise NotImplementedError("Subclasses must implement the parse method")
MAX_RAW_NUMBER = 1000
PADDING_SIZE = len(str(MAX_RAW_NUMBER)) - 1
class LiteralInt(LiteralFormat[int]):
def _encode_underscores(
self, buffer: io.StringIO, value: int, language: Language
) -> io.StringIO:
if value >= MAX_RAW_NUMBER:
mod = value % MAX_RAW_NUMBER
left_padding = PADDING_SIZE - len(str(mod))
self._encode_underscores(buffer, value // MAX_RAW_NUMBER, language)
buffer.write("_")
buffer.write("0" * left_padding)
buffer.write(str(mod))
return buffer
elif value < 0:
buffer.write("-")
self._encode_underscores(buffer, abs(value), language)
return buffer
else:
buffer.write(str(value))
return buffer
def encode(
self, value: int, language: Language, encoding_policy: EscapeLeadingWhitespace
) -> str:
return self._encode_underscores(io.StringIO(), value, language).getvalue()
def parse(self, string: str, language: Language) -> int:
return int(string.replace("_", ""))
class LiteralBoolean(LiteralFormat[bool]):
def encode(
self, value: bool, language: Language, encoding_policy: EscapeLeadingWhitespace
) -> str:
return str(value)
def __to_boolean_strict(self, string: str) -> bool:
if string.lower() == "true":
return True
elif string.lower() == "false":
return False
else:
raise ValueError("String is not a valid boolean representation: " + string)
def parse(self, string: str, language: Language) -> bool:
return self.__to_boolean_strict(string)