From ddc7687ac6260562b1bf0454f48baf680debaa05 Mon Sep 17 00:00:00 2001 From: ychenfo Date: Thu, 24 Mar 2022 02:21:41 +0800 Subject: [PATCH] nac3standalone: add tests for option --- nac3standalone/demo/interpret_demo.py | 35 +++++++++++++++++++++++ nac3standalone/demo/src/option.py | 40 +++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 nac3standalone/demo/src/option.py diff --git a/nac3standalone/demo/interpret_demo.py b/nac3standalone/demo/interpret_demo.py index d892833c..71bb4264 100755 --- a/nac3standalone/demo/interpret_demo.py +++ b/nac3standalone/demo/interpret_demo.py @@ -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_"): diff --git a/nac3standalone/demo/src/option.py b/nac3standalone/demo/src/option.py new file mode 100644 index 00000000..8cc0d5aa --- /dev/null +++ b/nac3standalone/demo/src/option.py @@ -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