PCI 16x50 UART Controller, O2 Enablement (#39)
[lunaix-os.git] / lunaix-os / scripts / build-tools / lcfg / types.py
1 from .api import TypeProviderBase
2 from .utils import is_primitive, is_basic
3
4 class PrimitiveType(TypeProviderBase):
5     def __init__(self, type) -> None:
6         super().__init__(type)
7
8     @staticmethod
9     def typedef_matched(typedef):
10         return is_primitive(typedef)
11     
12     def check(self, val):
13         return isinstance(val, self._type)
14     
15     def serialise(self, val):
16         return str(val)
17     
18     def deserialise(self, val):
19         if val.lower() == "true":
20             return True
21         elif val.lower() == "false":
22             return False
23         
24         return self._type(val)
25     
26     def parse_input(self, input_str):
27         return self.deserialise(input_str)
28     
29     def to_input(self, val):
30         return self.serialise(val)
31     
32     def __str__(self) -> str:
33         if isinstance(self._type, type):
34             return f"any with type of {self._type}"
35         return f"exact of value '{self._type}'"
36
37
38 class MultipleChoiceType(PrimitiveType):
39     def __init__(self, type) -> None:
40         super().__init__(type)
41
42     @staticmethod
43     def typedef_matched(typedef):
44         if not isinstance(typedef, list):
45             return False
46         return all([is_basic(x) for x in typedef])
47
48     def check(self, val):
49         if not is_basic(val):
50             return False
51         return val in self._type
52     
53     def parse_input(self, input_str):
54         return super().parse_input(input_str)
55
56     def deserialise(self, val):
57         if val.lower() == "true":
58             return True
59         elif val.lower() == "false":
60             return False
61         
62         for sv in self._type:
63             if val != str(sv):
64                 continue
65             return type(sv)(val)
66
67         return None
68     
69     def allow_none(self):
70         return None in self._type
71     
72     def __str__(self) -> str:
73         accepted = [f"  {t}" for t in self._type]
74         return "\n".join([
75             "choose one: \n",
76             *accepted
77         ])