nac3standalone: add tests for option

This commit is contained in:
ychenfo 2022-03-24 02:21:41 +08:00
parent d18292dd28
commit 91d697c327
2 changed files with 75 additions and 0 deletions

View File

@ -8,6 +8,38 @@ import pathlib
from numpy import int32, int64, uint32, uint64
from typing import TypeVar, Generic
T = TypeVar('T')
class Option(Generic[T]):
_nac3_option: T
def __init__(self, v: T):
self._nac3_option = v
def is_none(self):
return self._nac3_option is None
def is_some(self):
return not self.is_none()
def unwrap(self):
return self._nac3_option
def __repr__(self) -> str:
if self.is_none():
return "none"
else:
return "Some({})".format(repr(self._nac3_option))
def __str__(self) -> str:
if self.is_none():
return "none"
else:
return "Some({})".format(str(self._nac3_option))
def Some(v: T) -> Option[T]:
return Option(v)
none = Option(None)
def patch(module):
def output_asciiart(x):
@ -39,6 +71,9 @@ def patch(module):
module.TypeVar = TypeVar
module.Generic = Generic
module.extern = extern
module.Option = Option
module.Some = Some
module.none = none
def file_import(filename, prefix="file_import_"):

View File

@ -0,0 +1,40 @@
@extern
def output_int32(x: int32):
...
class A:
d: Option[int32]
e: Option[Option[int32]]
def __init__(self, a: Option[int32], b: Option[Option[int32]]):
self.d = a
self.e = b
def run() -> int32:
a = Some(3)
if a.is_some():
d = a.unwrap()
output_int32(a.unwrap())
a = none
if a.is_none():
output_int32(d + 2)
else:
a = Some(5)
c = Some(6)
output_int32(a.unwrap() + c.unwrap())
f = Some(4.3)
output_int32(int32(f.unwrap()))
obj = A(Some(6), none)
output_int32(obj.d.unwrap())
obj2 = Some(A(Some(7), none))
output_int32(obj2.unwrap().d.unwrap())
obj3 = Some(A(Some(8), Some(none)))
if obj3.unwrap().e.unwrap().is_none():
obj3.unwrap().e = Some(Some(9))
output_int32(obj3.unwrap().d.unwrap())
output_int32(obj3.unwrap().e.unwrap().unwrap())
return 0