chore(test): 迁移测试夹具到新语法
机械规则 R2/R3/R4/R6/R7/R8/R13 + R16 保守子集,共 86 文件 2127 行。R1(T | t.CPtr)与 R12(while 下标循环)未做,仍列为待办。全量 77/77 顺序回归通过。
This commit is contained in:
1 parent
c9d741c202
commit
f5da836fbb
86 files changed
+2121
-2121
No files matched your search
+14
-14
@@ -33,43 +33,43 @@ def main() -> int:
|
||||
# argv[0] = "myprog"
|
||||
s0: bytes = _mbuddy.alloc(16)
|
||||
string.strcpy(s0, "myprog")
|
||||
argv0: str | t.CPtr = (str | t.CPtr)(t.CUInt64T(argv))
|
||||
argv0: str | t.CPtr = (str | t.CPtr)(uint64(argv))
|
||||
argv0[0] = s0
|
||||
|
||||
# argv[1] = "--input"
|
||||
s1: bytes = _mbuddy.alloc(16)
|
||||
string.strcpy(s1, "--input")
|
||||
argv1: str | t.CPtr = (str | t.CPtr)(t.CUInt64T(argv) + 8)
|
||||
argv1: str | t.CPtr = (str | t.CPtr)(uint64(argv) + 8)
|
||||
argv1[0] = s1
|
||||
|
||||
# argv[2] = "test.txt"
|
||||
s2: bytes = _mbuddy.alloc(16)
|
||||
string.strcpy(s2, "test.txt")
|
||||
argv2: str | t.CPtr = (str | t.CPtr)(t.CUInt64T(argv) + 16)
|
||||
argv2: str | t.CPtr = (str | t.CPtr)(uint64(argv) + 16)
|
||||
argv2[0] = s2
|
||||
|
||||
# argv[3] = "-c"
|
||||
s3: bytes = _mbuddy.alloc(8)
|
||||
string.strcpy(s3, "-c")
|
||||
argv3: str | t.CPtr = (str | t.CPtr)(t.CUInt64T(argv) + 24)
|
||||
argv3: str | t.CPtr = (str | t.CPtr)(uint64(argv) + 24)
|
||||
argv3[0] = s3
|
||||
|
||||
# argv[4] = "42"
|
||||
s4: bytes = _mbuddy.alloc(8)
|
||||
string.strcpy(s4, "42")
|
||||
argv4: str | t.CPtr = (str | t.CPtr)(t.CUInt64T(argv) + 32)
|
||||
argv4: str | t.CPtr = (str | t.CPtr)(uint64(argv) + 32)
|
||||
argv4[0] = s4
|
||||
|
||||
# argv[5] = "--verbose"
|
||||
s5: bytes = _mbuddy.alloc(16)
|
||||
string.strcpy(s5, "--verbose")
|
||||
argv5: str | t.CPtr = (str | t.CPtr)(t.CUInt64T(argv) + 40)
|
||||
argv5: str | t.CPtr = (str | t.CPtr)(uint64(argv) + 40)
|
||||
argv5[0] = s5
|
||||
|
||||
# argv[6] = "output.dat"
|
||||
s6: bytes = _mbuddy.alloc(16)
|
||||
string.strcpy(s6, "output.dat")
|
||||
argv6: str | t.CPtr = (str | t.CPtr)(t.CUInt64T(argv) + 48)
|
||||
argv6: str | t.CPtr = (str | t.CPtr)(uint64(argv) + 48)
|
||||
argv6[0] = s6
|
||||
|
||||
argc: INT = 7
|
||||
@@ -109,17 +109,17 @@ def main() -> int:
|
||||
|
||||
a0: bytes = _mbuddy.alloc(16)
|
||||
string.strcpy(a0, "myprog")
|
||||
a0_ptr: str | t.CPtr = (str | t.CPtr)(t.CUInt64T(argv2))
|
||||
a0_ptr: str | t.CPtr = (str | t.CPtr)(uint64(argv2))
|
||||
a0_ptr[0] = a0
|
||||
|
||||
a1: bytes = _mbuddy.alloc(32)
|
||||
string.strcpy(a1, "--input=hello.txt")
|
||||
a1_ptr: str | t.CPtr = (str | t.CPtr)(t.CUInt64T(argv2) + 8)
|
||||
a1_ptr: str | t.CPtr = (str | t.CPtr)(uint64(argv2) + 8)
|
||||
a1_ptr[0] = a1
|
||||
|
||||
a2: bytes = _mbuddy.alloc(16)
|
||||
string.strcpy(a2, "output2.dat")
|
||||
a2_ptr: str | t.CPtr = (str | t.CPtr)(t.CUInt64T(argv2) + 16)
|
||||
a2_ptr: str | t.CPtr = (str | t.CPtr)(uint64(argv2) + 16)
|
||||
a2_ptr[0] = a2
|
||||
args2 = parser.parse_args(3, argv2)
|
||||
if args2 is not None:
|
||||
@@ -144,22 +144,22 @@ def main() -> int:
|
||||
|
||||
b0: bytes = _mbuddy.alloc(8)
|
||||
string.strcpy(b0, "myprog")
|
||||
b0_ptr: str | t.CPtr = (str | t.CPtr)(t.CUInt64T(argv3_arr))
|
||||
b0_ptr: str | t.CPtr = (str | t.CPtr)(uint64(argv3_arr))
|
||||
b0_ptr[0] = b0
|
||||
|
||||
b1: bytes = _mbuddy.alloc(8)
|
||||
string.strcpy(b1, "-v")
|
||||
b1_ptr: str | t.CPtr = (str | t.CPtr)(t.CUInt64T(argv3_arr) + 8)
|
||||
b1_ptr: str | t.CPtr = (str | t.CPtr)(uint64(argv3_arr) + 8)
|
||||
b1_ptr[0] = b1
|
||||
|
||||
b2: bytes = _mbuddy.alloc(8)
|
||||
string.strcpy(b2, "-v")
|
||||
b2_ptr: str | t.CPtr = (str | t.CPtr)(t.CUInt64T(argv3_arr) + 16)
|
||||
b2_ptr: str | t.CPtr = (str | t.CPtr)(uint64(argv3_arr) + 16)
|
||||
b2_ptr[0] = b2
|
||||
|
||||
b3: bytes = _mbuddy.alloc(16)
|
||||
string.strcpy(b3, "output3.dat")
|
||||
b3_ptr: str | t.CPtr = (str | t.CPtr)(t.CUInt64T(argv3_arr) + 24)
|
||||
b3_ptr: str | t.CPtr = (str | t.CPtr)(uint64(argv3_arr) + 24)
|
||||
b3_ptr[0] = b3
|
||||
|
||||
parser2 = argparse.ArgumentParser("myprog", "Count test", pool=_mbuddy)
|
||||
|
||||
+15
-15
@@ -11,25 +11,25 @@ import w32.win32console
|
||||
|
||||
|
||||
# MBuddy arena 大小:1MB
|
||||
ARENA_SIZE: t.CDefine = 1048576
|
||||
define ARENA_SIZE = 1048576
|
||||
# mpool 内存大小:512KB
|
||||
POOL_SIZE: t.CDefine = 524288
|
||||
define POOL_SIZE = 524288
|
||||
# dump 缓冲区大小:256KB
|
||||
DUMP_SIZE: t.CDefine = 262144
|
||||
define DUMP_SIZE = 262144
|
||||
|
||||
|
||||
def classify_list(lst: list[ast.AST | t.CPtr] | t.CPtr, depth: t.CInt):
|
||||
def classify_list(lst: list[ast.AST | t.CPtr] | t.CPtr, depth: int):
|
||||
"""递归遍历 list[AST | t.CPtr] 容器,逐元素分类(orelse/args/comparators 等)"""
|
||||
if lst is None:
|
||||
return
|
||||
n: t.CSizeT = lst.__len__()
|
||||
i: t.CSizeT = 0
|
||||
n: sizet = lst.__len__()
|
||||
i: sizet = 0
|
||||
while i < n:
|
||||
classify_print(lst.get(i), depth + 1)
|
||||
i += 1
|
||||
|
||||
|
||||
def classify_print(node: ast.AST | t.CPtr, depth: t.CInt):
|
||||
def classify_print(node: ast.AST | t.CPtr, depth: int):
|
||||
"""递归遍历 parse 树,用 isinstance 运行时判定每个节点的类别并打印。
|
||||
|
||||
依赖 TPV isinstance 的 vtable 子类集合比较:
|
||||
@@ -40,7 +40,7 @@ def classify_print(node: ast.AST | t.CPtr, depth: t.CInt):
|
||||
"""
|
||||
if node is None:
|
||||
return
|
||||
sp: t.CInt = 0
|
||||
sp: int = 0
|
||||
while sp < depth:
|
||||
printf(" ")
|
||||
sp += 1
|
||||
@@ -53,7 +53,7 @@ def classify_print(node: ast.AST | t.CPtr, depth: t.CInt):
|
||||
# 按 kind 遍历语句持有的表达式字段(语句 body 块均在 children)。
|
||||
# 属性访问前先 cast 成具体节点类:node 静态类型是 ast.AST,
|
||||
# 直接访问 node.value 会在 AST 基类字段表 fast-fail(按需过滤原则)。
|
||||
k: t.CInt = node.kind()
|
||||
k: int = node.kind()
|
||||
if k == ast.ASTKind.Assign:
|
||||
asg: ast.Assign | t.CPtr = (ast.Assign | t.CPtr)(node)
|
||||
classify_print(asg.value, depth + 1)
|
||||
@@ -98,8 +98,8 @@ def classify_print(node: ast.AST | t.CPtr, depth: t.CInt):
|
||||
pass
|
||||
# children(语句 body 块)
|
||||
if node.children is not None:
|
||||
n: t.CSizeT = node.children.__len__()
|
||||
i: t.CSizeT = 0
|
||||
n: sizet = node.children.__len__()
|
||||
i: sizet = 0
|
||||
while i < n:
|
||||
classify_print(node.children.get(i), depth + 1)
|
||||
i += 1
|
||||
@@ -139,7 +139,7 @@ def main() -> CInt | CExport:
|
||||
if dump_mem == None:
|
||||
printf("FAIL: malloc for dump failed\n")
|
||||
return 1
|
||||
dump_buf: t.CChar | t.CPtr = t.CChar(dump_mem, t.CPtr)
|
||||
dump_buf: char | t.CPtr = char(dump_mem, t.CPtr)
|
||||
|
||||
# 综合测试源码:覆盖 CPython 主要语法
|
||||
src: str = """x = 1
|
||||
@@ -214,9 +214,9 @@ class Point:
|
||||
printf("PASS: Module is neither Stmt nor ExprNode\n")
|
||||
|
||||
# 断言 2: 顶层 body 每条语句均为 Stmt
|
||||
top_ok: t.CInt = 1
|
||||
top_n: t.CSizeT = tree.children.__len__()
|
||||
i2: t.CSizeT = 0
|
||||
top_ok: int = 1
|
||||
top_n: sizet = tree.children.__len__()
|
||||
i2: sizet = 0
|
||||
while i2 < top_n:
|
||||
top_node: ast.AST | t.CPtr = tree.children.get(i2)
|
||||
if isinstance(top_node, ast.Stmt) == 0:
|
||||
|
||||
@@ -12,7 +12,7 @@ import w32.win32base
|
||||
|
||||
|
||||
# 线程函数: 在共享 MBuddy 上执行 alloc/free (测试 spinlock 线程安全)
|
||||
def _thread_alloc_free(param: t.CPtr) -> t.CUInt32T:
|
||||
def _thread_alloc_free(param: t.CPtr) -> uint32:
|
||||
bd: memhub.MemBuddy | t.CPtr = (memhub.MemBuddy | t.CPtr)(param)
|
||||
i: CInt
|
||||
for i in range(100):
|
||||
@@ -191,7 +191,7 @@ def mbuddy_main() -> CInt:
|
||||
testcheck.check(valid != None, "alloc for illegal test OK", "alloc FAILED")
|
||||
|
||||
# 1. free 随机地址 (地址 1)
|
||||
bd5.free(t.CPtr(t.CUInt64T(1)))
|
||||
bd5.free(t.CPtr(uint64(1)))
|
||||
testcheck.ok("free(addr=1) ignored")
|
||||
|
||||
# 2. free NULL
|
||||
@@ -199,15 +199,15 @@ def mbuddy_main() -> CInt:
|
||||
testcheck.ok("free(NULL) ignored")
|
||||
|
||||
# 3. free 越界指针 (arena 之前)
|
||||
bd5.free(t.CPtr(t.CUInt64T(arena5)))
|
||||
bd5.free(t.CPtr(uint64(arena5)))
|
||||
testcheck.ok("free(before arena) ignored")
|
||||
|
||||
# 4. free 越界指针 (arena 之后)
|
||||
bd5.free(t.CPtr(t.CUInt64T(arena5) + 99999))
|
||||
bd5.free(t.CPtr(uint64(arena5) + 99999))
|
||||
testcheck.ok("free(after arena) ignored")
|
||||
|
||||
# 5. free 未对齐指针 (arena + 1, 在 mem 区域内但不对齐)
|
||||
bd5.free(t.CPtr(t.CUInt64T(bd5.base) + 1))
|
||||
bd5.free(t.CPtr(uint64(bd5.base) + 1))
|
||||
testcheck.ok("free(misaligned) ignored")
|
||||
|
||||
# 6. 验证合法 free 仍正常工作 (释放后应能再次分配)
|
||||
@@ -237,7 +237,7 @@ def mbuddy_main() -> CInt:
|
||||
p: bytes = bd6.alloc(32)
|
||||
if p == None:
|
||||
break
|
||||
ptrs[alloc_count] = t.CUInt64T(p)
|
||||
ptrs[alloc_count] = uint64(p)
|
||||
alloc_count += 1
|
||||
|
||||
viperlib.snprintf(buf, 256, "allocated %d blocks before OOM", alloc_count)
|
||||
@@ -388,7 +388,7 @@ def mbuddy_main() -> CInt:
|
||||
# 创建 4 个线程并发 alloc/free
|
||||
t_idx: CInt
|
||||
for t_idx in range(NUM_THREADS):
|
||||
h: bytes = w32.win32process.CreateThread(None, 0, _thread_alloc_free, t.CPtr(bd_mt), 0, c.Addr(tid))
|
||||
h: bytes = w32.win32process.CreateThread(None, 0, _thread_alloc_free, t.CPtr(bd_mt), 0, &tid)
|
||||
handles[t_idx] = CUInt64T(h)
|
||||
|
||||
# 等待所有线程完成
|
||||
@@ -521,7 +521,7 @@ def mbuddy_main() -> CInt:
|
||||
fp: bytes = bd_fill.alloc(24)
|
||||
if fp == None:
|
||||
break
|
||||
fill_ptrs[fill_count] = t.CUInt64T(fp)
|
||||
fill_ptrs[fill_count] = uint64(fp)
|
||||
fill_count += 1
|
||||
|
||||
viperlib.snprintf(buf, 256, "fill: %d min blocks allocated", fill_count)
|
||||
|
||||
@@ -9,18 +9,18 @@ import testcheck
|
||||
# 测试 1:@property getter
|
||||
# ============================================================
|
||||
class Rect:
|
||||
width: t.CInt
|
||||
height: t.CInt
|
||||
width: int
|
||||
height: int
|
||||
|
||||
def __new__(self, w: t.CInt, h: t.CInt) -> 'Rect' | t.CPtr:
|
||||
def __new__(self, w: int, h: int) -> 'Rect' | t.CPtr:
|
||||
return t.CPtr(malloc(Rect.__sizeof__()))
|
||||
|
||||
def __init__(self, w: t.CInt, h: t.CInt):
|
||||
def __init__(self, w: int, h: int):
|
||||
self.width = w
|
||||
self.height = h
|
||||
|
||||
@property
|
||||
def area(self) -> t.CInt:
|
||||
def area(self) -> int:
|
||||
return self.width * self.height
|
||||
|
||||
@property
|
||||
@@ -42,24 +42,24 @@ def test_property_getter():
|
||||
# 测试 2:@property.setter
|
||||
# ============================================================
|
||||
class Temperature:
|
||||
_celsius: t.CDouble
|
||||
_celsius: double
|
||||
|
||||
def __new__(self, celsius_val: t.CDouble) -> 'Temperature' | t.CPtr:
|
||||
def __new__(self, celsius_val: double) -> 'Temperature' | t.CPtr:
|
||||
return t.CPtr(malloc(Temperature.__sizeof__()))
|
||||
|
||||
def __init__(self, celsius_val: t.CDouble):
|
||||
def __init__(self, celsius_val: double):
|
||||
self._celsius = celsius_val
|
||||
|
||||
@property
|
||||
def celsius(self) -> t.CDouble:
|
||||
def celsius(self) -> double:
|
||||
return self._celsius
|
||||
|
||||
@celsius.setter
|
||||
def celsius(self, val: t.CDouble):
|
||||
def celsius(self, val: double):
|
||||
self._celsius = val
|
||||
|
||||
@property
|
||||
def fahrenheit(self) -> t.CDouble:
|
||||
def fahrenheit(self) -> double:
|
||||
return self._celsius * 1.8 + 32.0
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ def test_property_setter():
|
||||
# 测试 3:@property.getter(重新定义 getter)
|
||||
# ============================================================
|
||||
class Counter:
|
||||
_count: t.CInt
|
||||
_count: int
|
||||
|
||||
def __new__(self) -> 'Counter' | t.CPtr:
|
||||
return t.CPtr(malloc(Counter.__sizeof__()))
|
||||
@@ -85,11 +85,11 @@ class Counter:
|
||||
self._count = 0
|
||||
|
||||
@property
|
||||
def value(self) -> t.CInt:
|
||||
def value(self) -> int:
|
||||
return self._count
|
||||
|
||||
@value.setter
|
||||
def value(self, v: t.CInt):
|
||||
def value(self, v: int):
|
||||
self._count = v
|
||||
|
||||
|
||||
@@ -105,22 +105,22 @@ def test_property_getter_redef():
|
||||
# 测试 4:@property.deleter
|
||||
# ============================================================
|
||||
class Config:
|
||||
_value: t.CInt
|
||||
_deleted: t.CInt
|
||||
_value: int
|
||||
_deleted: int
|
||||
|
||||
def __new__(self, v: t.CInt) -> 'Config' | t.CPtr:
|
||||
def __new__(self, v: int) -> 'Config' | t.CPtr:
|
||||
return t.CPtr(malloc(Config.__sizeof__()))
|
||||
|
||||
def __init__(self, v: t.CInt):
|
||||
def __init__(self, v: int):
|
||||
self._value = v
|
||||
self._deleted = 0
|
||||
|
||||
@property
|
||||
def value(self) -> t.CInt:
|
||||
def value(self) -> int:
|
||||
return self._value
|
||||
|
||||
@value.setter
|
||||
def value(self, v: t.CInt):
|
||||
def value(self, v: int):
|
||||
self._value = v
|
||||
|
||||
@value.deleter
|
||||
@@ -147,11 +147,11 @@ def test_property_deleter():
|
||||
# ============================================================
|
||||
class MathUtils:
|
||||
@staticmethod
|
||||
def add(a: t.CInt, b: t.CInt) -> t.CInt:
|
||||
def add(a: int, b: int) -> int:
|
||||
return a + b
|
||||
|
||||
@staticmethod
|
||||
def max_val(a: t.CInt, b: t.CInt) -> t.CInt:
|
||||
def max_val(a: int, b: int) -> int:
|
||||
return a if a > b else b
|
||||
|
||||
|
||||
@@ -166,13 +166,13 @@ def test_staticmethod():
|
||||
# 测试 6:@classmethod
|
||||
# ============================================================
|
||||
class Point:
|
||||
x: t.CDouble
|
||||
y: t.CDouble
|
||||
x: double
|
||||
y: double
|
||||
|
||||
def __new__(self, x: t.CDouble, y: t.CDouble) -> 'Point' | t.CPtr:
|
||||
def __new__(self, x: double, y: double) -> 'Point' | t.CPtr:
|
||||
return t.CPtr(malloc(Point.__sizeof__()))
|
||||
|
||||
def __init__(self, x: t.CDouble, y: t.CDouble):
|
||||
def __init__(self, x: double, y: double):
|
||||
self.x = x
|
||||
self.y = y
|
||||
|
||||
@@ -181,10 +181,10 @@ class Point:
|
||||
return Point(0.0, 0.0)
|
||||
|
||||
@classmethod
|
||||
def from_int(cls: Point, x: t.CInt, y: t.CInt) -> Point:
|
||||
def from_int(cls: Point, x: int, y: int) -> Point:
|
||||
return Point(x * 1.0, y * 1.0)
|
||||
|
||||
def dist_sq(self) -> t.CDouble:
|
||||
def dist_sq(self) -> double:
|
||||
return self.x * self.x + self.y * self.y
|
||||
|
||||
|
||||
@@ -206,28 +206,28 @@ def test_classmethod():
|
||||
# 测试 7:综合测试 — @property + @staticmethod + @classmethod
|
||||
# ============================================================
|
||||
class Circle:
|
||||
_radius: t.CDouble
|
||||
_radius: double
|
||||
|
||||
def __new__(self, r: t.CDouble) -> 'Circle' | t.CPtr:
|
||||
def __new__(self, r: double) -> 'Circle' | t.CPtr:
|
||||
return t.CPtr(malloc(Circle.__sizeof__()))
|
||||
|
||||
def __init__(self, r: t.CDouble):
|
||||
def __init__(self, r: double):
|
||||
self._radius = r
|
||||
|
||||
@property
|
||||
def radius(self) -> t.CDouble:
|
||||
def radius(self) -> double:
|
||||
return self._radius
|
||||
|
||||
@radius.setter
|
||||
def radius(self, val: t.CDouble):
|
||||
def radius(self, val: double):
|
||||
self._radius = val
|
||||
|
||||
@property
|
||||
def area(self) -> t.CDouble:
|
||||
def area(self) -> double:
|
||||
return 3.14159265 * self._radius * self._radius
|
||||
|
||||
@staticmethod
|
||||
def is_unit(r: t.CDouble) -> bool:
|
||||
def is_unit(r: double) -> bool:
|
||||
return r > 0.99 and r < 1.01
|
||||
|
||||
@classmethod
|
||||
@@ -254,7 +254,7 @@ def test_combined():
|
||||
# ============================================================
|
||||
# 主函数
|
||||
# ============================================================
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
testcheck.begin("Builtin Decorator Test")
|
||||
|
||||
test_property_getter()
|
||||
|
||||
+242
-242
@@ -24,141 +24,141 @@ extern def Py_DecRef(op: PyObject | t.CPtr)
|
||||
# ============================================================
|
||||
extern def Py_Initialize()
|
||||
extern def Py_Finalize()
|
||||
extern def Py_InitializeEx(initsigs: t.CInt)
|
||||
extern def Py_FinalizeEx() -> t.CInt
|
||||
extern def Py_IsInitialized() -> t.CInt
|
||||
extern def Py_InitializeEx(initsigs: int)
|
||||
extern def Py_FinalizeEx() -> int
|
||||
extern def Py_IsInitialized() -> int
|
||||
|
||||
|
||||
# ============================================================
|
||||
# PyConfig
|
||||
# ============================================================
|
||||
class PySTATUS:
|
||||
func: t.CConst | str
|
||||
err_msg: t.CConst | str
|
||||
exitcode: t.CInt
|
||||
func: const str
|
||||
err_msg: const str
|
||||
exitcode: int
|
||||
|
||||
class PyPreConfig:
|
||||
_config_version: t.CInt
|
||||
_config_init: t.CInt
|
||||
parse_argv: t.CInt
|
||||
isolated: t.CInt
|
||||
use_environment: t.CInt
|
||||
utf8_mode: t.CInt
|
||||
coerce_c_locale: t.CInt
|
||||
C_locale_warnings: t.CInt
|
||||
allocator: t.CInt
|
||||
dev_mode: t.CInt
|
||||
_config_version: int
|
||||
_config_init: int
|
||||
parse_argv: int
|
||||
isolated: int
|
||||
use_environment: int
|
||||
utf8_mode: int
|
||||
coerce_c_locale: int
|
||||
C_locale_warnings: int
|
||||
allocator: int
|
||||
dev_mode: int
|
||||
|
||||
class PyWideStringList:
|
||||
length: t.CSizeT
|
||||
length: sizet
|
||||
items: t.CPtr
|
||||
|
||||
class PyConfig:
|
||||
_config_version: t.CInt
|
||||
_config_init: t.CInt
|
||||
isolated: t.CInt
|
||||
use_environment: t.CInt
|
||||
dev_mode: t.CInt
|
||||
install_signal_handlers: t.CInt
|
||||
use_hash_seed: t.CInt
|
||||
_config_version: int
|
||||
_config_init: int
|
||||
isolated: int
|
||||
use_environment: int
|
||||
dev_mode: int
|
||||
install_signal_handlers: int
|
||||
use_hash_seed: int
|
||||
hash_seed: t.CUnsignedLong
|
||||
faulthandler: t.CInt
|
||||
tracemalloc: t.CInt
|
||||
import_time: t.CInt
|
||||
show_ref_count: t.CInt
|
||||
dump_refs: t.CInt
|
||||
dump_refs_file: t.CConst | str
|
||||
malloc_stats: t.CInt
|
||||
filesystem_errors: t.CInt
|
||||
pycache_prefix: t.CConst | str
|
||||
parse_argv: t.CInt
|
||||
faulthandler: int
|
||||
tracemalloc: int
|
||||
import_time: int
|
||||
show_ref_count: int
|
||||
dump_refs: int
|
||||
dump_refs_file: const str
|
||||
malloc_stats: int
|
||||
filesystem_errors: int
|
||||
pycache_prefix: const str
|
||||
parse_argv: int
|
||||
argv: PyWideStringList
|
||||
program_name: t.CConst | str
|
||||
program_name: const str
|
||||
xoptions: PyWideStringList
|
||||
warnoptions: PyWideStringList
|
||||
site_import: t.CInt
|
||||
bytes_warning: t.CInt
|
||||
warn_default_encoding: t.CInt
|
||||
inspect: t.CInt
|
||||
interactive: t.CInt
|
||||
optimization_level: t.CInt
|
||||
parser_debug: t.CInt
|
||||
verbose: t.CInt
|
||||
quiet: t.CInt
|
||||
home: t.CConst | str
|
||||
pythonpath_env: t.CConst | str
|
||||
site_import: int
|
||||
bytes_warning: int
|
||||
warn_default_encoding: int
|
||||
inspect: int
|
||||
interactive: int
|
||||
optimization_level: int
|
||||
parser_debug: int
|
||||
verbose: int
|
||||
quiet: int
|
||||
home: const str
|
||||
pythonpath_env: const str
|
||||
module_search_paths: PyWideStringList
|
||||
module_search_paths_set: t.CInt
|
||||
executable: t.CConst | str
|
||||
base_executable: t.CConst | str
|
||||
prefix: t.CConst | str
|
||||
base_prefix: t.CConst | str
|
||||
exec_prefix: t.CConst | str
|
||||
base_exec_prefix: t.CConst | str
|
||||
platlibdir: t.CConst | str
|
||||
stdio_filename: t.CConst | str
|
||||
module_search_paths_set: int
|
||||
executable: const str
|
||||
base_executable: const str
|
||||
prefix: const str
|
||||
base_prefix: const str
|
||||
exec_prefix: const str
|
||||
base_exec_prefix: const str
|
||||
platlibdir: const str
|
||||
stdio_filename: const str
|
||||
|
||||
extern def PyConfig_InitPythonConfig(config: PyConfig | t.CPtr)
|
||||
extern def PyConfig_InitIsolatedConfig(config: PyConfig | t.CPtr)
|
||||
extern def PyConfig_Clear(config: PyConfig | t.CPtr)
|
||||
extern def PyConfig_Read(config: PyConfig | t.CPtr) -> PySTATUS
|
||||
extern def Py_InitializeFromConfig(config: PyConfig | t.CPtr) -> PySTATUS
|
||||
extern def Py_DecodeLocale(s: t.CConst | str) -> str
|
||||
extern def PyStatus_Exception(status: PySTATUS) -> t.CInt
|
||||
extern def Py_DecodeLocale(s: const str) -> str
|
||||
extern def PyStatus_Exception(status: PySTATUS) -> int
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 整数操作 (PyLong)
|
||||
# ============================================================
|
||||
extern def PyLong_FromLong(v: t.CInt) -> PyObject | t.CPtr
|
||||
extern def PyLong_FromLong(v: int) -> PyObject | t.CPtr
|
||||
extern def PyLong_FromUnsignedLong(v: t.CUnsignedLong) -> PyObject | t.CPtr
|
||||
extern def PyLong_FromLongLong(v: t.CLong) -> PyObject | t.CPtr
|
||||
extern def PyLong_FromUnsignedLongLong(v: t.CUnsignedLong) -> PyObject | t.CPtr
|
||||
extern def PyLong_FromSsize_t(v: t.CPtrDiffT) -> PyObject | t.CPtr
|
||||
extern def PyLong_FromSize_t(v: t.CSizeT) -> PyObject | t.CPtr
|
||||
extern def PyLong_FromDouble(v: t.CDouble) -> PyObject | t.CPtr
|
||||
extern def PyLong_AsLong(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyLong_FromSize_t(v: sizet) -> PyObject | t.CPtr
|
||||
extern def PyLong_FromDouble(v: double) -> PyObject | t.CPtr
|
||||
extern def PyLong_AsLong(obj: PyObject | t.CPtr) -> int
|
||||
extern def PyLong_AsUnsignedLong(obj: PyObject | t.CPtr) -> t.CUnsignedLong
|
||||
extern def PyLong_AsLongLong(obj: PyObject | t.CPtr) -> t.CLong
|
||||
extern def PyLong_AsUnsignedLongLong(obj: PyObject | t.CPtr) -> t.CUnsignedLong
|
||||
extern def PyLong_AsDouble(obj: PyObject | t.CPtr) -> t.CDouble
|
||||
extern def PyLong_AsDouble(obj: PyObject | t.CPtr) -> double
|
||||
extern def PyLong_AsSsize_t(obj: PyObject | t.CPtr) -> t.CPtrDiffT
|
||||
extern def PyLong_AsSize_t(obj: PyObject | t.CPtr) -> t.CSizeT
|
||||
extern def PyLong_AsSize_t(obj: PyObject | t.CPtr) -> sizet
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 浮点数操作 (PyFloat)
|
||||
# ============================================================
|
||||
extern def PyFloat_FromDouble(v: t.CDouble) -> PyObject | t.CPtr
|
||||
extern def PyFloat_AsDouble(obj: PyObject | t.CPtr) -> t.CDouble
|
||||
extern def PyFloat_FromDouble(v: double) -> PyObject | t.CPtr
|
||||
extern def PyFloat_AsDouble(obj: PyObject | t.CPtr) -> double
|
||||
extern def PyFloat_FromString(s: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 字符串操作 (PyUnicode / PyBytes)
|
||||
# ============================================================
|
||||
extern def PyUnicode_FromString(u: t.CConst | str) -> PyObject | t.CPtr
|
||||
extern def PyUnicode_FromStringAndSize(u: t.CConst | str, size: t.CSizeT) -> PyObject | t.CPtr
|
||||
extern def PyUnicode_FromFormat(fmt: t.CConst | str) -> PyObject | t.CPtr
|
||||
extern def PyUnicode_FromString(u: const str) -> PyObject | t.CPtr
|
||||
extern def PyUnicode_FromStringAndSize(u: const str, size: sizet) -> PyObject | t.CPtr
|
||||
extern def PyUnicode_FromFormat(fmt: const str) -> PyObject | t.CPtr
|
||||
extern def PyUnicode_AsUTF8(obj: PyObject | t.CPtr) -> str
|
||||
extern def PyUnicode_AsUTF8AndSize(obj: PyObject | t.CPtr, size: t.CPtrDiffT | t.CPtr) -> str
|
||||
extern def PyUnicode_AsWideChar(obj: PyObject | t.CPtr, wbuf: t.CPtr, bufsize: t.CSizeT) -> t.CSizeT
|
||||
extern def PyUnicode_AsWideChar(obj: PyObject | t.CPtr, wbuf: t.CPtr, bufsize: sizet) -> sizet
|
||||
extern def PyUnicode_GetLength(obj: PyObject | t.CPtr) -> t.CPtrDiffT
|
||||
extern def PyUnicode_ReadChar(obj: PyObject | t.CPtr, idx: t.CSizeT) -> t.CUInt32T
|
||||
extern def PyUnicode_WriteChar(obj: PyObject | t.CPtr, idx: t.CSizeT, ch: t.CUInt32T) -> t.CInt
|
||||
extern def PyUnicode_Compare(l: PyObject | t.CPtr, r: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyUnicode_ReadChar(obj: PyObject | t.CPtr, idx: sizet) -> uint32
|
||||
extern def PyUnicode_WriteChar(obj: PyObject | t.CPtr, idx: sizet, ch: uint32) -> int
|
||||
extern def PyUnicode_Compare(l: PyObject | t.CPtr, r: PyObject | t.CPtr) -> int
|
||||
extern def PyUnicode_Concat(l: PyObject | t.CPtr, r: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyUnicode_Contains(container: PyObject | t.CPtr, element: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyUnicode_Contains(container: PyObject | t.CPtr, element: PyObject | t.CPtr) -> int
|
||||
extern def PyUnicode_Format(fmt: PyObject | t.CPtr, args: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyUnicode_InternInPlace(s: PyObject | t.CPtr | t.CPtr): pass
|
||||
extern def PyUnicode_InternFromString(u: t.CConst | str) -> PyObject | t.CPtr
|
||||
extern def PyUnicode_InternFromString(u: const str) -> PyObject | t.CPtr
|
||||
|
||||
extern def PyBytes_FromString(v: t.CConst | str) -> PyObject | t.CPtr
|
||||
extern def PyBytes_FromStringAndSize(v: t.CConst | str, size: t.CSizeT) -> PyObject | t.CPtr
|
||||
extern def PyBytes_FromString(v: const str) -> PyObject | t.CPtr
|
||||
extern def PyBytes_FromStringAndSize(v: const str, size: sizet) -> PyObject | t.CPtr
|
||||
extern def PyBytes_AsString(obj: PyObject | t.CPtr) -> str
|
||||
extern def PyBytes_Size(obj: PyObject | t.CPtr) -> t.CSizeT
|
||||
extern def PyBytes_Size(obj: PyObject | t.CPtr) -> sizet
|
||||
extern def PyBytes_FromObject(o: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyBytes_FromFormat(fmt: t.CConst | str) -> PyObject | t.CPtr
|
||||
extern def PyBytes_FromFormat(fmt: const str) -> PyObject | t.CPtr
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -174,28 +174,28 @@ Py_None: PyObject | t.CPtr | t.State
|
||||
# ============================================================
|
||||
# 列表操作 (PyList)
|
||||
# ============================================================
|
||||
extern def PyList_New(len: t.CSizeT) -> PyObject | t.CPtr
|
||||
extern def PyList_Size(lst: PyObject | t.CPtr) -> t.CSizeT
|
||||
extern def PyList_GetItem(lst: PyObject | t.CPtr, idx: t.CSizeT) -> PyObject | t.CPtr
|
||||
extern def PyList_SetItem(lst: PyObject | t.CPtr, idx: t.CSizeT, item: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyList_Insert(lst: PyObject | t.CPtr, idx: t.CSizeT, item: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyList_Append(lst: PyObject | t.CPtr, item: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyList_GetSlice(lst: PyObject | t.CPtr, lo: t.CSizeT, hi: t.CSizeT) -> PyObject | t.CPtr
|
||||
extern def PyList_SetSlice(lst: PyObject | t.CPtr, lo: t.CSizeT, hi: t.CSizeT, items: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyList_Sort(lst: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyList_Reverse(lst: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyList_New(len: sizet) -> PyObject | t.CPtr
|
||||
extern def PyList_Size(lst: PyObject | t.CPtr) -> sizet
|
||||
extern def PyList_GetItem(lst: PyObject | t.CPtr, idx: sizet) -> PyObject | t.CPtr
|
||||
extern def PyList_SetItem(lst: PyObject | t.CPtr, idx: sizet, item: PyObject | t.CPtr) -> int
|
||||
extern def PyList_Insert(lst: PyObject | t.CPtr, idx: sizet, item: PyObject | t.CPtr) -> int
|
||||
extern def PyList_Append(lst: PyObject | t.CPtr, item: PyObject | t.CPtr) -> int
|
||||
extern def PyList_GetSlice(lst: PyObject | t.CPtr, lo: sizet, hi: sizet) -> PyObject | t.CPtr
|
||||
extern def PyList_SetSlice(lst: PyObject | t.CPtr, lo: sizet, hi: sizet, items: PyObject | t.CPtr) -> int
|
||||
extern def PyList_Sort(lst: PyObject | t.CPtr) -> int
|
||||
extern def PyList_Reverse(lst: PyObject | t.CPtr) -> int
|
||||
extern def PyList_AsTuple(lst: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 元组操作 (PyTuple)
|
||||
# ============================================================
|
||||
extern def PyTuple_New(len: t.CSizeT) -> PyObject | t.CPtr
|
||||
extern def PyTuple_Size(tup: PyObject | t.CPtr) -> t.CSizeT
|
||||
extern def PyTuple_GetItem(tup: PyObject | t.CPtr, idx: t.CSizeT) -> PyObject | t.CPtr
|
||||
extern def PyTuple_SetItem(tup: PyObject | t.CPtr, idx: t.CSizeT, item: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyTuple_GetSlice(tup: PyObject | t.CPtr, lo: t.CSizeT, hi: t.CSizeT) -> PyObject | t.CPtr
|
||||
extern def PyTuple_Pack(n: t.CSizeT) -> PyObject | t.CPtr
|
||||
extern def PyTuple_New(len: sizet) -> PyObject | t.CPtr
|
||||
extern def PyTuple_Size(tup: PyObject | t.CPtr) -> sizet
|
||||
extern def PyTuple_GetItem(tup: PyObject | t.CPtr, idx: sizet) -> PyObject | t.CPtr
|
||||
extern def PyTuple_SetItem(tup: PyObject | t.CPtr, idx: sizet, item: PyObject | t.CPtr) -> int
|
||||
extern def PyTuple_GetSlice(tup: PyObject | t.CPtr, lo: sizet, hi: sizet) -> PyObject | t.CPtr
|
||||
extern def PyTuple_Pack(n: sizet) -> PyObject | t.CPtr
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -203,21 +203,21 @@ extern def PyTuple_Pack(n: t.CSizeT) -> PyObject | t.CPtr
|
||||
# ============================================================
|
||||
extern def PyDict_New() -> PyObject | t.CPtr
|
||||
extern def PyDict_GetItem(d: PyObject | t.CPtr, key: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyDict_GetItemString(d: PyObject | t.CPtr, key: t.CConst | str) -> PyObject | t.CPtr
|
||||
extern def PyDict_SetItem(d: PyObject | t.CPtr, key: PyObject | t.CPtr, val: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyDict_SetItemString(d: PyObject | t.CPtr, key: t.CConst | str, val: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyDict_DelItem(d: PyObject | t.CPtr, key: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyDict_DelItemString(d: PyObject | t.CPtr, key: t.CConst | str) -> t.CInt
|
||||
extern def PyDict_Size(d: PyObject | t.CPtr) -> t.CSizeT
|
||||
extern def PyDict_GetItemString(d: PyObject | t.CPtr, key: const str) -> PyObject | t.CPtr
|
||||
extern def PyDict_SetItem(d: PyObject | t.CPtr, key: PyObject | t.CPtr, val: PyObject | t.CPtr) -> int
|
||||
extern def PyDict_SetItemString(d: PyObject | t.CPtr, key: const str, val: PyObject | t.CPtr) -> int
|
||||
extern def PyDict_DelItem(d: PyObject | t.CPtr, key: PyObject | t.CPtr) -> int
|
||||
extern def PyDict_DelItemString(d: PyObject | t.CPtr, key: const str) -> int
|
||||
extern def PyDict_Size(d: PyObject | t.CPtr) -> sizet
|
||||
extern def PyDict_Keys(d: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyDict_Values(d: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyDict_Items(d: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyDict_Copy(d: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyDict_Clear(d: PyObject | t.CPtr): pass
|
||||
extern def PyDict_Contains(d: PyObject | t.CPtr, key: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyDict_Next(d: PyObject | t.CPtr, pos: t.CPtrDiffT | t.CPtr, key: PyObject | t.CPtr | t.CPtr, val: PyObject | t.CPtr | t.CPtr) -> t.CInt
|
||||
extern def PyDict_Merge(d: PyObject | t.CPtr, other: PyObject | t.CPtr, override: t.CInt) -> t.CInt
|
||||
extern def PyDict_Update(d: PyObject | t.CPtr, other: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyDict_Contains(d: PyObject | t.CPtr, key: PyObject | t.CPtr) -> int
|
||||
extern def PyDict_Next(d: PyObject | t.CPtr, pos: t.CPtrDiffT | t.CPtr, key: PyObject | t.CPtr | t.CPtr, val: PyObject | t.CPtr | t.CPtr) -> int
|
||||
extern def PyDict_Merge(d: PyObject | t.CPtr, other: PyObject | t.CPtr, override: int) -> int
|
||||
extern def PyDict_Update(d: PyObject | t.CPtr, other: PyObject | t.CPtr) -> int
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -226,29 +226,29 @@ extern def PyDict_Update(d: PyObject | t.CPtr, other: PyObject | t.CPtr) -> t.CI
|
||||
extern def PyObject_Str(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyObject_Repr(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyObject_Type(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyObject_IsInstance(obj: PyObject | t.CPtr, cls: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyObject_IsSubclass(obj: PyObject | t.CPtr, cls: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyObject_HasAttr(obj: PyObject | t.CPtr, name: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyObject_HasAttrString(obj: PyObject | t.CPtr, name: t.CConst | str) -> t.CInt
|
||||
extern def PyObject_IsInstance(obj: PyObject | t.CPtr, cls: PyObject | t.CPtr) -> int
|
||||
extern def PyObject_IsSubclass(obj: PyObject | t.CPtr, cls: PyObject | t.CPtr) -> int
|
||||
extern def PyObject_HasAttr(obj: PyObject | t.CPtr, name: PyObject | t.CPtr) -> int
|
||||
extern def PyObject_HasAttrString(obj: PyObject | t.CPtr, name: const str) -> int
|
||||
extern def PyObject_GetAttr(obj: PyObject | t.CPtr, name: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyObject_GetAttrString(obj: PyObject | t.CPtr, name: t.CConst | str) -> PyObject | t.CPtr
|
||||
extern def PyObject_SetAttr(obj: PyObject | t.CPtr, name: PyObject | t.CPtr, val: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyObject_SetAttrString(obj: PyObject | t.CPtr, name: t.CConst | str, val: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyObject_DelAttr(obj: PyObject | t.CPtr, name: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyObject_DelAttrString(obj: PyObject | t.CPtr, name: t.CConst | str) -> t.CInt
|
||||
extern def PyObject_GetAttrString(obj: PyObject | t.CPtr, name: const str) -> PyObject | t.CPtr
|
||||
extern def PyObject_SetAttr(obj: PyObject | t.CPtr, name: PyObject | t.CPtr, val: PyObject | t.CPtr) -> int
|
||||
extern def PyObject_SetAttrString(obj: PyObject | t.CPtr, name: const str, val: PyObject | t.CPtr) -> int
|
||||
extern def PyObject_DelAttr(obj: PyObject | t.CPtr, name: PyObject | t.CPtr) -> int
|
||||
extern def PyObject_DelAttrString(obj: PyObject | t.CPtr, name: const str) -> int
|
||||
extern def PyObject_Call(callable: PyObject | t.CPtr, args: PyObject | t.CPtr, kwargs: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyObject_CallObject(callable: PyObject | t.CPtr, args: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyObject_CallNoArgs(callable: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyObject_CallOneArg(callable: PyObject | t.CPtr, arg: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyObject_IsTrue(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyObject_Not(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyObject_RichCompare(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr, opid: t.CInt) -> PyObject | t.CPtr
|
||||
extern def PyObject_RichCompareBool(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr, opid: t.CInt) -> t.CInt
|
||||
extern def PyObject_IsTrue(obj: PyObject | t.CPtr) -> int
|
||||
extern def PyObject_Not(obj: PyObject | t.CPtr) -> int
|
||||
extern def PyObject_RichCompare(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr, opid: int) -> PyObject | t.CPtr
|
||||
extern def PyObject_RichCompareBool(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr, opid: int) -> int
|
||||
extern def PyObject_Hash(obj: PyObject | t.CPtr) -> t.CLong
|
||||
extern def PyObject_Length(obj: PyObject | t.CPtr) -> t.CSizeT
|
||||
extern def PyObject_Length(obj: PyObject | t.CPtr) -> sizet
|
||||
extern def PyObject_GetItem(obj: PyObject | t.CPtr, key: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyObject_SetItem(obj: PyObject | t.CPtr, key: PyObject | t.CPtr, val: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyObject_DelItem(obj: PyObject | t.CPtr, key: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyObject_SetItem(obj: PyObject | t.CPtr, key: PyObject | t.CPtr, val: PyObject | t.CPtr) -> int
|
||||
extern def PyObject_DelItem(obj: PyObject | t.CPtr, key: PyObject | t.CPtr) -> int
|
||||
extern def PyObject_Dir(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyObject_GetIter(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyIter_Next(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
@@ -257,45 +257,45 @@ extern def PyIter_Next(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
# ============================================================
|
||||
# 比较常量
|
||||
# ============================================================
|
||||
Py_LT: t.CInt | t.State
|
||||
Py_LE: t.CInt | t.State
|
||||
Py_EQ: t.CInt | t.State
|
||||
Py_NE: t.CInt | t.State
|
||||
Py_GT: t.CInt | t.State
|
||||
Py_GE: t.CInt | t.State
|
||||
Py_LT: int | t.State
|
||||
Py_LE: int | t.State
|
||||
Py_EQ: int | t.State
|
||||
Py_NE: int | t.State
|
||||
Py_GT: int | t.State
|
||||
Py_GE: int | t.State
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 模块操作
|
||||
# ============================================================
|
||||
extern def PyImport_ImportModule(name: t.CConst | str) -> PyObject | t.CPtr
|
||||
extern def PyImport_ImportModule(name: const str) -> PyObject | t.CPtr
|
||||
extern def PyImport_Import(name: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyImport_ImportModuleLevelObject(name: PyObject | t.CPtr, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr, fromlist: PyObject | t.CPtr, level: t.CInt) -> PyObject | t.CPtr
|
||||
extern def PyImport_ImportModuleLevelObject(name: PyObject | t.CPtr, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr, fromlist: PyObject | t.CPtr, level: int) -> PyObject | t.CPtr
|
||||
extern def PyImport_ReloadModule(mod: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyImport_AddModule(name: t.CConst | str) -> PyObject | t.CPtr
|
||||
extern def PyImport_AddModule(name: const str) -> PyObject | t.CPtr
|
||||
extern def PyImport_GetModuleDict() -> PyObject | t.CPtr
|
||||
extern def PyImport_ImportModuleEx(name: t.CConst | str, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr, fromlist: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyImport_ImportModuleEx(name: const str, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr, fromlist: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 模块创建
|
||||
# ============================================================
|
||||
class PyMethodDef:
|
||||
ml_name: t.CConst | str
|
||||
ml_name: const str
|
||||
ml_meth: t.CPtr
|
||||
ml_flags: t.CInt
|
||||
ml_doc: t.CConst | str
|
||||
ml_flags: int
|
||||
ml_doc: const str
|
||||
|
||||
class PyModuleDef_Base:
|
||||
ob_base: PyObject
|
||||
m_init: t.CPtr
|
||||
m_index: t.CSizeT
|
||||
m_index: sizet
|
||||
m_copy: PyObject | t.CPtr
|
||||
|
||||
class PyModuleDef:
|
||||
m_base: PyModuleDef_Base
|
||||
m_name: t.CConst | str
|
||||
m_doc: t.CConst | str
|
||||
m_name: const str
|
||||
m_doc: const str
|
||||
m_size: t.CPtrDiffT
|
||||
m_methods: PyMethodDef | t.CPtr
|
||||
m_slots: t.CPtr
|
||||
@@ -304,28 +304,28 @@ class PyModuleDef:
|
||||
m_free: t.CPtr
|
||||
|
||||
extern def PyModule_Create(mod: PyModuleDef | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyModule_Create2(mod: PyModuleDef | t.CPtr, ver: t.CInt) -> PyObject | t.CPtr
|
||||
extern def PyModule_Create2(mod: PyModuleDef | t.CPtr, ver: int) -> PyObject | t.CPtr
|
||||
extern def PyModule_GetName(mod: PyObject | t.CPtr) -> str
|
||||
extern def PyModule_GetDict(mod: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyModule_GetFilenameObject(mod: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyModule_AddObject(mod: PyObject | t.CPtr, name: t.CConst | str, val: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyModule_AddObjectRef(mod: PyObject | t.CPtr, name: t.CConst | str, val: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyModule_AddIntConstant(mod: PyObject | t.CPtr, name: t.CConst | str, val: t.CLong) -> t.CInt
|
||||
extern def PyModule_AddStringConstant(mod: PyObject | t.CPtr, name: t.CConst | str, val: t.CConst | str) -> t.CInt
|
||||
extern def PyModule_AddObject(mod: PyObject | t.CPtr, name: const str, val: PyObject | t.CPtr) -> int
|
||||
extern def PyModule_AddObjectRef(mod: PyObject | t.CPtr, name: const str, val: PyObject | t.CPtr) -> int
|
||||
extern def PyModule_AddIntConstant(mod: PyObject | t.CPtr, name: const str, val: t.CLong) -> int
|
||||
extern def PyModule_AddStringConstant(mod: PyObject | t.CPtr, name: const str, val: const str) -> int
|
||||
|
||||
|
||||
# ============================================================
|
||||
# GIL 管理
|
||||
# ============================================================
|
||||
extern def PyGILState_Ensure() -> t.CInt
|
||||
extern def PyGILState_Release(state: t.CInt): pass
|
||||
extern def PyGILState_Ensure() -> int
|
||||
extern def PyGILState_Release(state: int): pass
|
||||
extern def PyEval_SaveThread() -> t.CPtr
|
||||
extern def PyEval_RestoreThread(tstate: t.CPtr): pass
|
||||
extern def PyEval_AcquireThread(tstate: t.CPtr): pass
|
||||
extern def PyEval_ReleaseThread(tstate: t.CPtr): pass
|
||||
extern def PyEval_AcquireLock(): pass
|
||||
extern def PyEval_ReleaseLock(): pass
|
||||
extern def PyEval_ThreadsInitialized() -> t.CInt
|
||||
extern def PyEval_ThreadsInitialized() -> int
|
||||
extern def PyEval_InitThreads(): pass
|
||||
|
||||
|
||||
@@ -337,13 +337,13 @@ extern def PyErr_Clear(): pass
|
||||
extern def PyErr_Fetch(tp: PyObject | t.CPtr | t.CPtr, val: PyObject | t.CPtr | t.CPtr, tb: PyObject | t.CPtr | t.CPtr): pass
|
||||
extern def PyErr_Restore(tp: PyObject | t.CPtr, val: PyObject | t.CPtr, tb: PyObject | t.CPtr): pass
|
||||
extern def PyErr_NormalizeException(tp: PyObject | t.CPtr | t.CPtr, val: PyObject | t.CPtr | t.CPtr, tb: PyObject | t.CPtr | t.CPtr): pass
|
||||
extern def PyErr_SetString(tp: PyObject | t.CPtr, msg: t.CConst | str): pass
|
||||
extern def PyErr_SetString(tp: PyObject | t.CPtr, msg: const str): pass
|
||||
extern def PyErr_SetObject(tp: PyObject | t.CPtr, val: PyObject | t.CPtr): pass
|
||||
extern def PyErr_BadArgument() -> t.CPtr | t.State: pass
|
||||
extern def PyErr_NoMemory() -> t.CPtr | t.State: pass
|
||||
extern def PyErr_Print(): pass
|
||||
extern def PyErr_ExceptionMatches(exc: PyObject | t.CPtr) -> t.CInt | t.State: pass
|
||||
extern def PyErr_GivenExceptionMatches(given: PyObject | t.CPtr, exc: PyObject | t.CPtr) -> t.CInt | t.State: pass
|
||||
extern def PyErr_ExceptionMatches(exc: PyObject | t.CPtr) -> int | t.State: pass
|
||||
extern def PyErr_GivenExceptionMatches(given: PyObject | t.CPtr, exc: PyObject | t.CPtr) -> int | t.State: pass
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -376,103 +376,103 @@ PyExc_NotADirectoryError: PyObject | t.CPtr | t.State
|
||||
# ============================================================
|
||||
# 内置函数
|
||||
# ============================================================
|
||||
extern def Py_BuildValue(fmt: t.CConst | str) -> PyObject | t.CPtr
|
||||
extern def Py_VaBuildValue(fmt: t.CConst | str, va: t.CPtr) -> PyObject | t.CPtr
|
||||
extern def Py_BuildValue(fmt: const str) -> PyObject | t.CPtr
|
||||
extern def Py_VaBuildValue(fmt: const str, va: t.CPtr) -> PyObject | t.CPtr
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 类型检查
|
||||
# ============================================================
|
||||
extern def PyLong_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyFloat_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyUnicode_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyBytes_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyList_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyTuple_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyDict_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyBool_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyNone_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyLong_Check(obj: PyObject | t.CPtr) -> int
|
||||
extern def PyFloat_Check(obj: PyObject | t.CPtr) -> int
|
||||
extern def PyUnicode_Check(obj: PyObject | t.CPtr) -> int
|
||||
extern def PyBytes_Check(obj: PyObject | t.CPtr) -> int
|
||||
extern def PyList_Check(obj: PyObject | t.CPtr) -> int
|
||||
extern def PyTuple_Check(obj: PyObject | t.CPtr) -> int
|
||||
extern def PyDict_Check(obj: PyObject | t.CPtr) -> int
|
||||
extern def PyBool_Check(obj: PyObject | t.CPtr) -> int
|
||||
extern def PyNone_Check(obj: PyObject | t.CPtr) -> int
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 内存管理
|
||||
# ============================================================
|
||||
extern def PyMem_Malloc(size: t.CSizeT) -> t.CPtr
|
||||
extern def PyMem_Realloc(ptr: t.CPtr, size: t.CSizeT) -> t.CPtr
|
||||
extern def PyMem_Malloc(size: sizet) -> t.CPtr
|
||||
extern def PyMem_Realloc(ptr: t.CPtr, size: sizet) -> t.CPtr
|
||||
extern def PyMem_Free(ptr: t.CPtr)
|
||||
extern def PyMem_Calloc(nelem: t.CSizeT, elsize: t.CSizeT) -> t.CPtr
|
||||
extern def PyObject_Malloc(size: t.CSizeT) -> t.CPtr
|
||||
extern def PyObject_Realloc(ptr: t.CPtr, size: t.CSizeT) -> t.CPtr
|
||||
extern def PyMem_Calloc(nelem: sizet, elsize: sizet) -> t.CPtr
|
||||
extern def PyObject_Malloc(size: sizet) -> t.CPtr
|
||||
extern def PyObject_Realloc(ptr: t.CPtr, size: sizet) -> t.CPtr
|
||||
extern def PyObject_Free(ptr: t.CPtr)
|
||||
extern def PyObject_Calloc(nelem: t.CSizeT, elsize: t.CSizeT) -> t.CPtr
|
||||
extern def PyObject_Calloc(nelem: sizet, elsize: sizet) -> t.CPtr
|
||||
extern def PyObject_Init(obj: PyObject | t.CPtr, tp: t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyObject_InitVar(obj: PyObject | t.CPtr, tp: t.CPtr, size: t.CSizeT) -> PyObject | t.CPtr
|
||||
extern def PyObject_InitVar(obj: PyObject | t.CPtr, tp: t.CPtr, size: sizet) -> PyObject | t.CPtr
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 文件操作
|
||||
# ============================================================
|
||||
extern def PyFile_FromString(filename: t.CConst | str, mode: t.CConst | str) -> PyObject | t.CPtr
|
||||
extern def PyFile_FromString(filename: const str, mode: const str) -> PyObject | t.CPtr
|
||||
extern def PyFile_AsFile(file: PyObject | t.CPtr) -> t.CPtr
|
||||
extern def PyFile_WriteObject(obj: PyObject | t.CPtr, file: PyObject | t.CPtr, flags: t.CInt) -> t.CInt
|
||||
extern def PyFile_WriteString(s: t.CConst | str, file: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyFile_WriteObject(obj: PyObject | t.CPtr, file: PyObject | t.CPtr, flags: int) -> int
|
||||
extern def PyFile_WriteString(s: const str, file: PyObject | t.CPtr) -> int
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 编译/执行
|
||||
# ============================================================
|
||||
extern def Py_CompileString(s: t.CConst | str, filename: t.CConst | str, start: t.CInt) -> PyObject | t.CPtr
|
||||
extern def Py_CompileString(s: const str, filename: const str, start: int) -> PyObject | t.CPtr
|
||||
extern def PyEval_EvalCode(code: PyObject | t.CPtr, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyEval_EvalCodeEx(code: PyObject | t.CPtr, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr, args: PyObject | t.CPtr | t.CPtr, argc: t.CInt, kws: PyObject | t.CPtr | t.CPtr, kwc: t.CInt, defs: PyObject | t.CPtr | t.CPtr, defc: t.CInt, kwdefs: PyObject | t.CPtr, closure: PyObject | t.CPtr) -> PyObject | t.CPtr: pass
|
||||
extern def PyEval_EvalCodeEx(code: PyObject | t.CPtr, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr, args: PyObject | t.CPtr | t.CPtr, argc: int, kws: PyObject | t.CPtr | t.CPtr, kwc: int, defs: PyObject | t.CPtr | t.CPtr, defc: int, kwdefs: PyObject | t.CPtr, closure: PyObject | t.CPtr) -> PyObject | t.CPtr: pass
|
||||
extern def PyEval_EvalFrame(frame: t.CPtr) -> PyObject | t.CPtr: pass
|
||||
extern def PyEval_CallObject(callable: PyObject | t.CPtr, args: PyObject | t.CPtr) -> PyObject | t.CPtr: pass
|
||||
extern def PyEval_CallFunction(callable: PyObject | t.CPtr, fmt: t.CConst | str) -> PyObject | t.CPtr: pass
|
||||
extern def PyEval_CallMethod(obj: PyObject | t.CPtr, method: t.CConst | str, fmt: t.CConst | str) -> PyObject | t.CPtr: pass
|
||||
extern def PyEval_CallFunction(callable: PyObject | t.CPtr, fmt: const str) -> PyObject | t.CPtr: pass
|
||||
extern def PyEval_CallMethod(obj: PyObject | t.CPtr, method: const str, fmt: const str) -> PyObject | t.CPtr: pass
|
||||
|
||||
|
||||
# ============================================================
|
||||
# PyRun
|
||||
# ============================================================
|
||||
extern def PyRun_SimpleString(cmd: t.CConst | str) -> t.CInt
|
||||
extern def PyRun_SimpleFile(fp: t.CPtr, filename: t.CConst | str) -> t.CInt
|
||||
extern def PyRun_AnyFile(fp: t.CPtr, filename: t.CConst | str) -> t.CInt
|
||||
extern def PyRun_String(s: t.CConst | str, start: t.CInt, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyRun_File(fp: t.CPtr, filename: t.CConst | str, start: t.CInt, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyRun_SimpleString(cmd: const str) -> int
|
||||
extern def PyRun_SimpleFile(fp: t.CPtr, filename: const str) -> int
|
||||
extern def PyRun_AnyFile(fp: t.CPtr, filename: const str) -> int
|
||||
extern def PyRun_String(s: const str, start: int, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyRun_File(fp: t.CPtr, filename: const str, start: int, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
|
||||
Py_single_input: t.CInt | t.State
|
||||
Py_file_input: t.CInt | t.State
|
||||
Py_eval_input: t.CInt | t.State
|
||||
Py_single_input: int | t.State
|
||||
Py_file_input: int | t.State
|
||||
Py_eval_input: int | t.State
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Capsule
|
||||
# ============================================================
|
||||
extern def PyCapsule_New(ptr: t.CPtr, name: t.CConst | str, dtor: t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyCapsule_GetPointer(cap: PyObject | t.CPtr, name: t.CConst | str) -> t.CPtr
|
||||
extern def PyCapsule_New(ptr: t.CPtr, name: const str, dtor: t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyCapsule_GetPointer(cap: PyObject | t.CPtr, name: const str) -> t.CPtr
|
||||
extern def PyCapsule_GetName(cap: PyObject | t.CPtr) -> str
|
||||
extern def PyCapsule_IsValid(cap: PyObject | t.CPtr, name: t.CConst | str) -> t.CInt
|
||||
extern def PyCapsule_SetPointer(cap: PyObject | t.CPtr, ptr: t.CPtr) -> t.CInt
|
||||
extern def PyCapsule_SetName(cap: PyObject | t.CPtr, name: t.CConst | str) -> t.CInt
|
||||
extern def PyCapsule_SetDestructor(cap: PyObject | t.CPtr, dtor: t.CPtr) -> t.CInt
|
||||
extern def PyCapsule_IsValid(cap: PyObject | t.CPtr, name: const str) -> int
|
||||
extern def PyCapsule_SetPointer(cap: PyObject | t.CPtr, ptr: t.CPtr) -> int
|
||||
extern def PyCapsule_SetName(cap: PyObject | t.CPtr, name: const str) -> int
|
||||
extern def PyCapsule_SetDestructor(cap: PyObject | t.CPtr, dtor: t.CPtr) -> int
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 序列操作
|
||||
# ============================================================
|
||||
extern def PySequence_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PySequence_Size(obj: PyObject | t.CPtr) -> t.CSizeT
|
||||
extern def PySequence_Length(obj: PyObject | t.CPtr) -> t.CSizeT
|
||||
extern def PySequence_Check(obj: PyObject | t.CPtr) -> int
|
||||
extern def PySequence_Size(obj: PyObject | t.CPtr) -> sizet
|
||||
extern def PySequence_Length(obj: PyObject | t.CPtr) -> sizet
|
||||
extern def PySequence_Concat(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PySequence_Repeat(obj: PyObject | t.CPtr, count: t.CSizeT) -> PyObject | t.CPtr
|
||||
extern def PySequence_GetItem(obj: PyObject | t.CPtr, idx: t.CSizeT) -> PyObject | t.CPtr
|
||||
extern def PySequence_SetItem(obj: PyObject | t.CPtr, idx: t.CSizeT, val: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PySequence_DelItem(obj: PyObject | t.CPtr, idx: t.CSizeT) -> t.CInt
|
||||
extern def PySequence_GetSlice(obj: PyObject | t.CPtr, start: t.CSizeT, end: t.CSizeT) -> PyObject | t.CPtr
|
||||
extern def PySequence_SetSlice(obj: PyObject | t.CPtr, start: t.CSizeT, end: t.CSizeT, val: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PySequence_DelSlice(obj: PyObject | t.CPtr, start: t.CSizeT, end: t.CSizeT) -> t.CInt
|
||||
extern def PySequence_Contains(obj: PyObject | t.CPtr, val: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PySequence_Index(obj: PyObject | t.CPtr, val: PyObject | t.CPtr) -> t.CSizeT
|
||||
extern def PySequence_Count(obj: PyObject | t.CPtr, val: PyObject | t.CPtr) -> t.CSizeT
|
||||
extern def PySequence_Repeat(obj: PyObject | t.CPtr, count: sizet) -> PyObject | t.CPtr
|
||||
extern def PySequence_GetItem(obj: PyObject | t.CPtr, idx: sizet) -> PyObject | t.CPtr
|
||||
extern def PySequence_SetItem(obj: PyObject | t.CPtr, idx: sizet, val: PyObject | t.CPtr) -> int
|
||||
extern def PySequence_DelItem(obj: PyObject | t.CPtr, idx: sizet) -> int
|
||||
extern def PySequence_GetSlice(obj: PyObject | t.CPtr, start: sizet, end: sizet) -> PyObject | t.CPtr
|
||||
extern def PySequence_SetSlice(obj: PyObject | t.CPtr, start: sizet, end: sizet, val: PyObject | t.CPtr) -> int
|
||||
extern def PySequence_DelSlice(obj: PyObject | t.CPtr, start: sizet, end: sizet) -> int
|
||||
extern def PySequence_Contains(obj: PyObject | t.CPtr, val: PyObject | t.CPtr) -> int
|
||||
extern def PySequence_Index(obj: PyObject | t.CPtr, val: PyObject | t.CPtr) -> sizet
|
||||
extern def PySequence_Count(obj: PyObject | t.CPtr, val: PyObject | t.CPtr) -> sizet
|
||||
extern def PySequence_List(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PySequence_Tuple(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
|
||||
@@ -480,13 +480,13 @@ extern def PySequence_Tuple(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
# ============================================================
|
||||
# 映射操作
|
||||
# ============================================================
|
||||
extern def PyMapping_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyMapping_Size(obj: PyObject | t.CPtr) -> t.CSizeT
|
||||
extern def PyMapping_Length(obj: PyObject | t.CPtr) -> t.CSizeT
|
||||
extern def PyMapping_HasKey(obj: PyObject | t.CPtr, key: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyMapping_HasKeyString(obj: PyObject | t.CPtr, key: t.CConst | str) -> t.CInt
|
||||
extern def PyMapping_GetItemString(obj: PyObject | t.CPtr, key: t.CConst | str) -> PyObject | t.CPtr
|
||||
extern def PyMapping_SetItemString(obj: PyObject | t.CPtr, key: t.CConst | str, val: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyMapping_Check(obj: PyObject | t.CPtr) -> int
|
||||
extern def PyMapping_Size(obj: PyObject | t.CPtr) -> sizet
|
||||
extern def PyMapping_Length(obj: PyObject | t.CPtr) -> sizet
|
||||
extern def PyMapping_HasKey(obj: PyObject | t.CPtr, key: PyObject | t.CPtr) -> int
|
||||
extern def PyMapping_HasKeyString(obj: PyObject | t.CPtr, key: const str) -> int
|
||||
extern def PyMapping_GetItemString(obj: PyObject | t.CPtr, key: const str) -> PyObject | t.CPtr
|
||||
extern def PyMapping_SetItemString(obj: PyObject | t.CPtr, key: const str, val: PyObject | t.CPtr) -> int
|
||||
extern def PyMapping_Keys(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyMapping_Values(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyMapping_Items(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
@@ -515,7 +515,7 @@ extern def PyNumber_Or(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr) -> PyObject
|
||||
extern def PyNumber_Index(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyNumber_Long(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyNumber_Float(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyNumber_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyNumber_Check(obj: PyObject | t.CPtr) -> int
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -523,71 +523,71 @@ extern def PyNumber_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
# ============================================================
|
||||
extern def PyWeakref_NewRef(obj: PyObject | t.CPtr, cb: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyWeakref_GetObject(ref: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyWeakref_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyWeakref_Check(obj: PyObject | t.CPtr) -> int
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 属性描述符
|
||||
# ============================================================
|
||||
class PyGetSetDef:
|
||||
name: t.CConst | str
|
||||
name: const str
|
||||
get: t.CPtr
|
||||
set: t.CPtr
|
||||
doc: t.CConst | str
|
||||
doc: const str
|
||||
closure: t.CPtr
|
||||
|
||||
class PyMemberDef:
|
||||
name: t.CConst | str
|
||||
type: t.CInt
|
||||
name: const str
|
||||
type: int
|
||||
offset: t.CPtrDiffT
|
||||
flags: t.CInt
|
||||
doc: t.CConst | str
|
||||
flags: int
|
||||
doc: const str
|
||||
|
||||
|
||||
# ============================================================
|
||||
# sys 模块
|
||||
# ============================================================
|
||||
extern def PySys_GetObject(name: t.CConst | str) -> PyObject | t.CPtr
|
||||
extern def PySys_SetObject(name: t.CConst | str, val: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PySys_GetObject(name: const str) -> PyObject | t.CPtr
|
||||
extern def PySys_SetObject(name: const str, val: PyObject | t.CPtr) -> int
|
||||
extern def PySys_ResetWarnOptions(): pass
|
||||
extern def PySys_AddWarnOption(s: PyObject | t.CPtr): pass
|
||||
extern def PySYS_AddXOption(s: PyObject | t.CPtr): pass
|
||||
extern def PySys_WriteStdout(fmt: t.CConst | str): pass
|
||||
extern def PySys_WriteStderr(fmt: t.CConst | str): pass
|
||||
extern def PySys_FormatStdout(fmt: t.CConst | str): pass
|
||||
extern def PySys_FormatStderr(fmt: t.CConst | str): pass
|
||||
extern def PySys_WriteStdout(fmt: const str): pass
|
||||
extern def PySys_WriteStderr(fmt: const str): pass
|
||||
extern def PySys_FormatStdout(fmt: const str): pass
|
||||
extern def PySys_FormatStderr(fmt: const str): pass
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 内存视图
|
||||
# ============================================================
|
||||
extern def PyMemoryView_FromObject(obj: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyMemoryView_GetContiguous(obj: PyObject | t.CPtr, btype: t.CInt, order: t.CChar) -> PyObject | t.CPtr
|
||||
extern def PyMemoryView_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyMemoryView_GetContiguous(obj: PyObject | t.CPtr, btype: int, order: char) -> PyObject | t.CPtr
|
||||
extern def PyMemoryView_Check(obj: PyObject | t.CPtr) -> int
|
||||
|
||||
|
||||
# ============================================================
|
||||
# set / frozenset
|
||||
# ============================================================
|
||||
extern def PySet_New(iterable: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PySet_Add(s: PyObject | t.CPtr, key: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PySet_Discard(s: PyObject | t.CPtr, key: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PySet_Contains(s: PyObject | t.CPtr, key: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PySet_Size(s: PyObject | t.CPtr) -> t.CSizeT
|
||||
extern def PySet_Add(s: PyObject | t.CPtr, key: PyObject | t.CPtr) -> int
|
||||
extern def PySet_Discard(s: PyObject | t.CPtr, key: PyObject | t.CPtr) -> int
|
||||
extern def PySet_Contains(s: PyObject | t.CPtr, key: PyObject | t.CPtr) -> int
|
||||
extern def PySet_Size(s: PyObject | t.CPtr) -> sizet
|
||||
extern def PySet_Clear(s: PyObject | t.CPtr): pass
|
||||
extern def PySet_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PySet_Check(obj: PyObject | t.CPtr) -> int
|
||||
extern def PyFrozenSet_New(iterable: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PyFrozenSet_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PyFrozenSet_Check(obj: PyObject | t.CPtr) -> int
|
||||
|
||||
|
||||
# ============================================================
|
||||
# slice
|
||||
# ============================================================
|
||||
extern def PySlice_New(start: PyObject | t.CPtr, stop: PyObject | t.CPtr, step: PyObject | t.CPtr) -> PyObject | t.CPtr
|
||||
extern def PySlice_GetIndicesEx(sl: PyObject | t.CPtr, length: t.CSizeT, start: t.CSizeT | t.CPtr, stop: t.CSizeT | t.CPtr, step: t.CSizeT | t.CPtr, slicelen: t.CSizeT | t.CPtr) -> t.CInt
|
||||
extern def PySlice_GetIndicesEx(sl: PyObject | t.CPtr, length: sizet, start: sizet | t.CPtr, stop: sizet | t.CPtr, step: sizet | t.CPtr, slicelen: sizet | t.CPtr) -> int
|
||||
extern def PySlice_Unpack(sl: PyObject | t.CPtr, start: t.CPtrDiffT | t.CPtr, stop: t.CPtrDiffT | t.CPtr, step: t.CPtrDiffT | t.CPtr): pass
|
||||
extern def PySlice_AdjustIndices(length: t.CSizeT, start: t.CPtrDiffT | t.CPtr, stop: t.CPtrDiffT | t.CPtr, step: t.CPtrDiffT) -> t.CSizeT
|
||||
extern def PySlice_Check(obj: PyObject | t.CPtr) -> t.CInt
|
||||
extern def PySlice_AdjustIndices(length: sizet, start: t.CPtrDiffT | t.CPtr, stop: t.CPtrDiffT | t.CPtr, step: t.CPtrDiffT) -> sizet
|
||||
extern def PySlice_Check(obj: PyObject | t.CPtr) -> int
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -645,7 +645,7 @@ class PyFloatObj:
|
||||
return t.CPtr(malloc(PyFloatObj.__sizeof__()))
|
||||
|
||||
@staticmethod
|
||||
def from_double(val: t.CDouble) -> 'PyFloatObj' | t.CPtr:
|
||||
def from_double(val: double) -> 'PyFloatObj' | t.CPtr:
|
||||
obj: PyFloatObj | t.CPtr = PyFloatObj()
|
||||
obj.ptr = PyFloat_FromDouble(val)
|
||||
return obj
|
||||
@@ -675,7 +675,7 @@ class PyFloatObj:
|
||||
res.ptr = PyNumber_Negative(self.ptr)
|
||||
return res
|
||||
|
||||
def to_double(self) -> t.CDouble:
|
||||
def to_double(self) -> double:
|
||||
return PyFloat_AsDouble(self.ptr)
|
||||
|
||||
def __str__(self) -> PyObject | t.CPtr:
|
||||
@@ -693,7 +693,7 @@ class PyUnicodeObj:
|
||||
return t.CPtr(malloc(PyUnicodeObj.__sizeof__()))
|
||||
|
||||
@staticmethod
|
||||
def from_string(s: t.CChar | t.CPtr) -> 'PyUnicodeObj' | t.CPtr:
|
||||
def from_string(s: char | t.CPtr) -> 'PyUnicodeObj' | t.CPtr:
|
||||
obj: PyUnicodeObj | t.CPtr = PyUnicodeObj()
|
||||
obj.ptr = PyUnicode_FromString(s)
|
||||
return obj
|
||||
@@ -706,7 +706,7 @@ class PyUnicodeObj:
|
||||
def __len__(self) -> t.CPtrDiffT:
|
||||
return PyUnicode_GetLength(self.ptr)
|
||||
|
||||
def as_utf8(self) -> t.CChar | t.CPtr:
|
||||
def as_utf8(self) -> char | t.CPtr:
|
||||
return PyUnicode_AsUTF8(self.ptr)
|
||||
|
||||
def __str__(self) -> PyObject | t.CPtr:
|
||||
@@ -729,16 +729,16 @@ class PyListObj:
|
||||
obj.ptr = PyList_New(0)
|
||||
return obj
|
||||
|
||||
def __getitem__(self, idx: t.CSizeT) -> PyObject | t.CPtr:
|
||||
def __getitem__(self, idx: sizet) -> PyObject | t.CPtr:
|
||||
return PyList_GetItem(self.ptr, idx)
|
||||
|
||||
def __setitem__(self, idx: t.CSizeT, val: PyObject | t.CPtr):
|
||||
def __setitem__(self, idx: sizet, val: PyObject | t.CPtr):
|
||||
PyList_SetItem(self.ptr, idx, val)
|
||||
|
||||
def __len__(self) -> t.CSizeT:
|
||||
def __len__(self) -> sizet:
|
||||
return PyList_Size(self.ptr)
|
||||
|
||||
def append(self, item: PyObject | t.CPtr) -> t.CInt:
|
||||
def append(self, item: PyObject | t.CPtr) -> int:
|
||||
return PyList_Append(self.ptr, item)
|
||||
|
||||
def dec_ref(self):
|
||||
@@ -764,13 +764,13 @@ class PyDictObj:
|
||||
def __setitem__(self, key: PyObject | t.CPtr, val: PyObject | t.CPtr):
|
||||
PyDict_SetItem(self.ptr, key, val)
|
||||
|
||||
def __len__(self) -> t.CSizeT:
|
||||
def __len__(self) -> sizet:
|
||||
return PyDict_Size(self.ptr)
|
||||
|
||||
def get_string(self, key: t.CChar | t.CPtr) -> PyObject | t.CPtr:
|
||||
def get_string(self, key: char | t.CPtr) -> PyObject | t.CPtr:
|
||||
return PyDict_GetItemString(self.ptr, key)
|
||||
|
||||
def set_string(self, key: t.CChar | t.CPtr, val: PyObject | t.CPtr):
|
||||
def set_string(self, key: char | t.CPtr, val: PyObject | t.CPtr):
|
||||
PyDict_SetItemString(self.ptr, key, val)
|
||||
|
||||
def dec_ref(self):
|
||||
|
||||
@@ -26,7 +26,7 @@ def test_long_operations():
|
||||
testcheck.check(py_str != 0, "PyObject_Str != NULL", "PyObject_Str != NULL")
|
||||
|
||||
# 获取 C 字符串
|
||||
c_str: t.CChar | CPtr = cpython.PyUnicode_AsUTF8(py_str)
|
||||
c_str: char | CPtr = cpython.PyUnicode_AsUTF8(py_str)
|
||||
testcheck.check(c_str != 0, "PyUnicode_AsUTF8 != NULL", "PyUnicode_AsUTF8 != NULL")
|
||||
printf(" PyLong_FromLong(12345) -> str = %s\n", c_str)
|
||||
|
||||
@@ -63,7 +63,7 @@ def test_string_operations():
|
||||
testcheck.check(py_s1 != 0, "PyUnicode_FromString != NULL", "PyUnicode_FromString != NULL")
|
||||
|
||||
# 获取 UTF8
|
||||
utf8: t.CChar | CPtr = cpython.PyUnicode_AsUTF8(py_s1)
|
||||
utf8: char | CPtr = cpython.PyUnicode_AsUTF8(py_s1)
|
||||
testcheck.check(utf8 != 0, "AsUTF8 != NULL", "AsUTF8 != NULL")
|
||||
printf(" PyUnicode_FromString -> %s\n", utf8)
|
||||
|
||||
@@ -74,7 +74,7 @@ def test_string_operations():
|
||||
# 字符串拼接
|
||||
py_s2: cpython.PyObject | CPtr = cpython.PyUnicode_FromString(" World")
|
||||
py_concat: cpython.PyObject | CPtr = cpython.PyUnicode_Concat(py_s1, py_s2)
|
||||
concat_utf8: t.CChar | CPtr = cpython.PyUnicode_AsUTF8(py_concat)
|
||||
concat_utf8: char | CPtr = cpython.PyUnicode_AsUTF8(py_concat)
|
||||
testcheck.check(py_concat != 0, "Concat != NULL", "Concat != NULL")
|
||||
printf(" Concat -> %s\n", concat_utf8)
|
||||
|
||||
@@ -148,7 +148,7 @@ def test_dict_operations():
|
||||
# 获取值
|
||||
got_val: cpython.PyObject | CPtr = cpython.PyDict_GetItem(py_dict, py_key1)
|
||||
testcheck.check(got_val != 0, "GetItem(name) != NULL", "GetItem(name) != NULL")
|
||||
got_str: t.CChar | CPtr = cpython.PyUnicode_AsUTF8(got_val)
|
||||
got_str: char | CPtr = cpython.PyUnicode_AsUTF8(got_val)
|
||||
testcheck.check(got_str != 0, "name == Viper", "name == Viper")
|
||||
printf(" dict['name'] = %s\n", got_str)
|
||||
|
||||
@@ -278,7 +278,7 @@ def test_operator_overload():
|
||||
testcheck.check(sa != 0 and sb != 0, "PyUnicodeObj.from_string != NULL", "PyUnicodeObj.from_string != NULL")
|
||||
|
||||
sc: cpython.PyUnicodeObj | CPtr = sa + sb
|
||||
sc_utf8: t.CChar | CPtr = sc.as_utf8()
|
||||
sc_utf8: char | CPtr = sc.as_utf8()
|
||||
testcheck.check(sc_utf8 != 0, "PyUnicodeObj concat != NULL", "PyUnicodeObj concat != NULL")
|
||||
if sc_utf8 != 0:
|
||||
printf(" PyUnicodeObj 'Hello' + ' World' = %s\n", sc_utf8)
|
||||
@@ -302,13 +302,13 @@ def test_operator_overload():
|
||||
lst.append(e3)
|
||||
testcheck.check(len(lst) == 3, "PyListObj len == 3", "PyListObj len == 3")
|
||||
|
||||
item0: cpython.PyObject | CPtr = lst[t.CSizeT(0)]
|
||||
item0: cpython.PyObject | CPtr = lst[sizet(0)]
|
||||
testcheck.check(cpython.PyLong_AsLong(item0) == 100, "PyListObj lst[0] == 100", "PyListObj lst[0] == 100")
|
||||
|
||||
# __setitem__
|
||||
e4: cpython.PyObject | CPtr = cpython.PyLong_FromLong(999)
|
||||
lst[t.CSizeT(1)] = e4
|
||||
item1: cpython.PyObject | CPtr = lst[t.CSizeT(1)]
|
||||
lst[sizet(1)] = e4
|
||||
item1: cpython.PyObject | CPtr = lst[sizet(1)]
|
||||
testcheck.check(cpython.PyLong_AsLong(item1) == 999, "PyListObj lst[1] = 999", "PyListObj lst[1] = 999")
|
||||
|
||||
cpython.Py_DecRef(e4)
|
||||
@@ -327,7 +327,7 @@ def test_operator_overload():
|
||||
testcheck.check(len(dct) == 1, "PyDictObj len == 1", "PyDictObj len == 1")
|
||||
|
||||
got_lang: cpython.PyObject | CPtr = dct[dk1]
|
||||
got_str: t.CChar | CPtr = cpython.PyUnicode_AsUTF8(got_lang)
|
||||
got_str: char | CPtr = cpython.PyUnicode_AsUTF8(got_lang)
|
||||
testcheck.check(got_str != 0, "PyDictObj dct['lang'] == Viper", "PyDictObj dct['lang'] == Viper")
|
||||
if got_str != 0:
|
||||
printf(" PyDictObj dct['lang'] = %s\n", got_str)
|
||||
|
||||
@@ -7,7 +7,7 @@ def bump(v: char) -> char:
|
||||
return char(v + 1)
|
||||
|
||||
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
# 1) char 注解:char = t.CChar = i8(标量内置类型,非指针)
|
||||
ch: char = 65
|
||||
stdio.printf("1 char annot: %d (expect 65)\n", int(ch))
|
||||
|
||||
@@ -5,48 +5,48 @@ import t, c
|
||||
|
||||
|
||||
class SimpleData():
|
||||
x: t.CInt
|
||||
y: t.CInt
|
||||
x: int
|
||||
y: int
|
||||
|
||||
|
||||
class Point3D():
|
||||
x: t.CFloat
|
||||
y: t.CFloat
|
||||
z: t.CFloat
|
||||
x: float
|
||||
y: float
|
||||
z: float
|
||||
|
||||
|
||||
class Student():
|
||||
name: t.CChar | t.CPtr
|
||||
age: t.CInt
|
||||
score: t.CInt
|
||||
name: char | t.CPtr
|
||||
age: int
|
||||
score: int
|
||||
|
||||
def __init__(self, n: t.CChar | t.CPtr, a: t.CInt, s: t.CInt):
|
||||
def __init__(self, n: char | t.CPtr, a: int, s: int):
|
||||
self.name = n
|
||||
self.age = a
|
||||
self.score = s
|
||||
|
||||
def get_age(self) -> t.CInt:
|
||||
def get_age(self) -> int:
|
||||
return self.age
|
||||
|
||||
def get_score(self) -> t.CInt:
|
||||
def get_score(self) -> int:
|
||||
return self.score
|
||||
|
||||
|
||||
class Counter():
|
||||
value: t.CInt
|
||||
value: int
|
||||
|
||||
def __init__(self, initial: t.CInt):
|
||||
def __init__(self, initial: int):
|
||||
self.value = initial
|
||||
|
||||
def increment(self):
|
||||
self.value += 1
|
||||
|
||||
def get_value(self) -> t.CInt:
|
||||
def get_value(self) -> int:
|
||||
return self.value
|
||||
|
||||
|
||||
class StackObj():
|
||||
data: t.CInt
|
||||
data: int
|
||||
next_ptr: t.CPtr
|
||||
|
||||
|
||||
@@ -111,7 +111,7 @@ def TestHeapAllocation():
|
||||
|
||||
def TestHeapObjectWithInit():
|
||||
stdio.printf("=== Test Heap Object with Init ===\n")
|
||||
mem_size: t.CSizeT = 256
|
||||
mem_size: sizet = 256
|
||||
ptr: t.CPtr = stdlib.malloc(mem_size)
|
||||
if ptr != 0:
|
||||
stdio.printf("Allocated %d bytes\n", mem_size)
|
||||
@@ -156,8 +156,8 @@ def TestClassWithBitFields():
|
||||
|
||||
def TestIntArray():
|
||||
stdio.printf("=== Test Int Array ===\n")
|
||||
arr: t.CArray[t.CInt, 5] = t.CArray[t.CInt, 5]()
|
||||
i: t.CInt = 0
|
||||
arr: t.CArray[int, 5] = t.CArray[int, 5]()
|
||||
i: int = 0
|
||||
while i < 5:
|
||||
arr[i] = i * 10
|
||||
i += 1
|
||||
@@ -169,12 +169,12 @@ def TestIntArray():
|
||||
|
||||
def TestFloatArray():
|
||||
stdio.printf("=== Test Float Array ===\n")
|
||||
farr: t.CArray[t.CFloat, 4] = t.CArray[t.CFloat, 4]()
|
||||
farr: t.CArray[float, 4] = t.CArray[float, 4]()
|
||||
farr[0] = 1.5
|
||||
farr[1] = 2.5
|
||||
farr[2] = 3.5
|
||||
farr[3] = 4.5
|
||||
i: t.CInt = 0
|
||||
i: int = 0
|
||||
while i < 4:
|
||||
stdio.printf("farr[%d]=%.1f\n", i, farr[i])
|
||||
i += 1
|
||||
@@ -182,7 +182,7 @@ def TestFloatArray():
|
||||
|
||||
def TestCharArray():
|
||||
stdio.printf("=== Test Char Array (String) ===\n")
|
||||
str_arr: t.CArray[t.CChar, 32] = t.CArray[t.CChar, 32]()
|
||||
str_arr: t.CArray[char, 32] = t.CArray[char, 32]()
|
||||
str_arr[0] = 'H'
|
||||
str_arr[1] = 'e'
|
||||
str_arr[2] = 'l'
|
||||
@@ -194,15 +194,15 @@ def TestCharArray():
|
||||
|
||||
def TestNestedArray():
|
||||
stdio.printf("=== Test Nested Array (Array of Arrays) ===\n")
|
||||
row0: t.CArray[t.CInt, 3] = t.CArray[t.CInt, 3]()
|
||||
row1: t.CArray[t.CInt, 3] = t.CArray[t.CInt, 3]()
|
||||
row0: t.CArray[int, 3] = t.CArray[int, 3]()
|
||||
row1: t.CArray[int, 3] = t.CArray[int, 3]()
|
||||
row0[0] = 0
|
||||
row0[1] = 1
|
||||
row0[2] = 2
|
||||
row1[0] = 10
|
||||
row1[1] = 11
|
||||
row1[2] = 12
|
||||
i: t.CInt = 0
|
||||
i: int = 0
|
||||
while i < 3:
|
||||
stdio.printf("row0[%d]=%d ", i, row0[i])
|
||||
i += 1
|
||||
@@ -217,7 +217,7 @@ def TestNestedArray():
|
||||
def TestArrayWithStruct():
|
||||
stdio.printf("=== Test Array with Struct ===\n")
|
||||
points: t.CArray[SimpleData, 3] = t.CArray[SimpleData, 3]()
|
||||
i: t.CInt = 0
|
||||
i: int = 0
|
||||
while i < 3:
|
||||
points[i].x = i * 10
|
||||
points[i].y = i * 100
|
||||
@@ -230,11 +230,11 @@ def TestArrayWithStruct():
|
||||
|
||||
def TestArrayPointer():
|
||||
stdio.printf("=== Test Array Pointer ===\n")
|
||||
data: t.CArray[t.CInt, 8] = t.CArray[t.CInt, 8]()
|
||||
data: t.CArray[int, 8] = t.CArray[int, 8]()
|
||||
data[0] = 100
|
||||
data[1] = 200
|
||||
data[2] = 300
|
||||
ptr: t.CInt | t.CPtr = data
|
||||
ptr: int | t.CPtr = data
|
||||
stdio.printf("ptr[0]=%d\n", ptr[0])
|
||||
stdio.printf("ptr[1]=%d\n", ptr[1])
|
||||
stdio.printf("ptr[2]=%d\n", ptr[2])
|
||||
|
||||
@@ -3,7 +3,7 @@ import testcheck
|
||||
import class_test
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("ClassArrayTest: 类与数组测试")
|
||||
|
||||
testcheck.section("CLASS TESTS")
|
||||
|
||||
@@ -33,7 +33,7 @@ def test_closure_call():
|
||||
testcheck.check(v == 1, "f() first call = 1", "expect 1")
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("ClosureCallTest: t.CPtr function pointer call")
|
||||
test_closure_call()
|
||||
return testcheck.end()
|
||||
+20
-20
@@ -5,7 +5,7 @@ import testcheck
|
||||
# ============================================================
|
||||
# Test 1: global 在嵌套函数中
|
||||
# ============================================================
|
||||
g_val: t.CInt = 100
|
||||
g_val: int = 100
|
||||
|
||||
def outer_modify_global():
|
||||
global g_val
|
||||
@@ -26,7 +26,7 @@ def test_global_in_nested():
|
||||
# ============================================================
|
||||
def test_nonlocal_multi_level():
|
||||
testcheck.section("Test 2: nonlocal multi-level")
|
||||
x: t.CInt = 1
|
||||
x: int = 1
|
||||
def level1():
|
||||
nonlocal x
|
||||
x += 10
|
||||
@@ -44,13 +44,13 @@ def test_nonlocal_multi_level():
|
||||
# ============================================================
|
||||
# Test 3: global 和 nonlocal 混合
|
||||
# ============================================================
|
||||
g_mixed: t.CInt = 0
|
||||
g_mixed: int = 0
|
||||
|
||||
def test_global_nonlocal_mixed():
|
||||
testcheck.section("Test 3: global + nonlocal mixed")
|
||||
global g_mixed
|
||||
g_mixed = 0
|
||||
local_var: t.CInt = 0
|
||||
local_var: int = 0
|
||||
def modify_both():
|
||||
nonlocal local_var
|
||||
global g_mixed
|
||||
@@ -65,10 +65,10 @@ def test_global_nonlocal_mixed():
|
||||
# ============================================================
|
||||
def test_lambda_multi_capture():
|
||||
testcheck.section("Test 4: lambda multi-capture")
|
||||
a: t.CInt = 10
|
||||
b: t.CInt = 20
|
||||
a: int = 10
|
||||
b: int = 20
|
||||
f = lambda: a + b
|
||||
r: t.CInt = f()
|
||||
r: int = f()
|
||||
testcheck.check(r == 30, "lambda multi-capture (a+b == 30)", "lambda multi-capture (expect 30)")
|
||||
|
||||
# ============================================================
|
||||
@@ -76,9 +76,9 @@ def test_lambda_multi_capture():
|
||||
# ============================================================
|
||||
def test_lambda_arg_capture():
|
||||
testcheck.section("Test 5: lambda arg + capture")
|
||||
base: t.CInt = 100
|
||||
base: int = 100
|
||||
add = lambda x: base + x
|
||||
r: t.CInt = add(42)
|
||||
r: int = add(42)
|
||||
testcheck.check(r == 142, "lambda arg+capture (100+42 == 142)", "lambda arg+capture (expect 142)")
|
||||
|
||||
# ============================================================
|
||||
@@ -86,12 +86,12 @@ def test_lambda_arg_capture():
|
||||
# ============================================================
|
||||
def test_nested_return():
|
||||
testcheck.section("Test 6: nested function return")
|
||||
x: t.CInt = 5
|
||||
def double_x() -> t.CInt:
|
||||
x: int = 5
|
||||
def double_x() -> int:
|
||||
nonlocal x
|
||||
x = x * 2
|
||||
return x
|
||||
r: t.CInt = double_x()
|
||||
r: int = double_x()
|
||||
testcheck.check(r == 10 and x == 10, "nested return (r==10 x==10)", "nested return (expect r=10 x=10)")
|
||||
|
||||
# ============================================================
|
||||
@@ -99,8 +99,8 @@ def test_nested_return():
|
||||
# ============================================================
|
||||
def test_nonlocal_loop():
|
||||
testcheck.section("Test 7: nonlocal with loop")
|
||||
total: t.CInt = 0
|
||||
def accumulate(n: t.CInt):
|
||||
total: int = 0
|
||||
def accumulate(n: int):
|
||||
nonlocal total
|
||||
for i in range(n):
|
||||
total += i
|
||||
@@ -112,7 +112,7 @@ def test_nonlocal_loop():
|
||||
# ============================================================
|
||||
# Test 8: global 数组操作
|
||||
# ============================================================
|
||||
g_arr: t.CArray[t.CInt, 4] = [0]
|
||||
g_arr: t.CArray[int, 4] = [0]
|
||||
|
||||
def test_global_array():
|
||||
testcheck.section("Test 8: global array")
|
||||
@@ -121,7 +121,7 @@ def test_global_array():
|
||||
g_arr[1] = 20
|
||||
g_arr[2] = 30
|
||||
g_arr[3] = 40
|
||||
total: t.CInt = g_arr[0] + g_arr[1] + g_arr[2] + g_arr[3]
|
||||
total: int = g_arr[0] + g_arr[1] + g_arr[2] + g_arr[3]
|
||||
testcheck.check(total == 100, "global array (total == 100)", "global array (expect 100)")
|
||||
|
||||
# ============================================================
|
||||
@@ -129,8 +129,8 @@ def test_global_array():
|
||||
# ============================================================
|
||||
def test_nested_conditional():
|
||||
testcheck.section("Test 9: nested conditional call")
|
||||
result: t.CInt = 0
|
||||
def set_result(val: t.CInt):
|
||||
result: int = 0
|
||||
def set_result(val: int):
|
||||
nonlocal result
|
||||
result = val
|
||||
if 1:
|
||||
@@ -146,10 +146,10 @@ def test_lambda_chain():
|
||||
testcheck.section("Test 10: lambda chain")
|
||||
f1 = lambda: 10
|
||||
f2 = lambda: 20
|
||||
r: t.CInt = f1() + f2()
|
||||
r: int = f1() + f2()
|
||||
testcheck.check(r == 30, "lambda chain (10+20 == 30)", "lambda chain (expect 30)")
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("ClosureAdvancedTest: 高级闭包测试")
|
||||
test_global_in_nested()
|
||||
test_nonlocal_multi_level()
|
||||
|
||||
+34
-34
@@ -7,8 +7,8 @@ import testcheck
|
||||
# ============================================================
|
||||
def test_nonlocal_conditional():
|
||||
testcheck.section("Test 1: nonlocal in conditional branches")
|
||||
x: t.CInt = 0
|
||||
def modify(flag: t.CInt):
|
||||
x: int = 0
|
||||
def modify(flag: int):
|
||||
nonlocal x
|
||||
if flag:
|
||||
x += 10
|
||||
@@ -24,12 +24,12 @@ def test_nonlocal_conditional():
|
||||
# ============================================================
|
||||
def test_nonlocal_multi_var():
|
||||
testcheck.section("Test 2: multiple nonlocal variables")
|
||||
a: t.CInt = 1
|
||||
b: t.CInt = 2
|
||||
c_val: t.CInt = 3
|
||||
a: int = 1
|
||||
b: int = 2
|
||||
c_val: int = 3
|
||||
def swap_add():
|
||||
nonlocal a, b, c_val
|
||||
tmp: t.CInt = a
|
||||
tmp: int = a
|
||||
a = b
|
||||
b = c_val
|
||||
c_val = tmp
|
||||
@@ -39,13 +39,13 @@ def test_nonlocal_multi_var():
|
||||
# ============================================================
|
||||
# Test 3: global 在多个函数中交叉修改
|
||||
# ============================================================
|
||||
g_counter: t.CInt = 0
|
||||
g_counter: int = 0
|
||||
|
||||
def inc_global():
|
||||
global g_counter
|
||||
g_counter += 1
|
||||
|
||||
def add_global(n: t.CInt):
|
||||
def add_global(n: int):
|
||||
global g_counter
|
||||
g_counter += n
|
||||
|
||||
@@ -64,13 +64,13 @@ def test_global_cross_functions():
|
||||
# ============================================================
|
||||
def test_nested_ref_capture():
|
||||
testcheck.section("Test 4: nested function ref capture")
|
||||
arr: t.CArray[t.CInt, 4] = [0]
|
||||
arr: t.CArray[int, 4] = [0]
|
||||
def fill():
|
||||
nonlocal arr
|
||||
for i in range(4):
|
||||
arr[i] = (i + 1) * 10
|
||||
fill()
|
||||
total: t.CInt = arr[0] + arr[1] + arr[2] + arr[3]
|
||||
total: int = arr[0] + arr[1] + arr[2] + arr[3]
|
||||
testcheck.check(total == 100, "ref capture (total == 100)", "ref capture (expect 100)")
|
||||
|
||||
# ============================================================
|
||||
@@ -78,11 +78,11 @@ def test_nested_ref_capture():
|
||||
# ============================================================
|
||||
def test_lambda_capture_then_modify():
|
||||
testcheck.section("Test 5: lambda capture then modify")
|
||||
x: t.CInt = 10
|
||||
x: int = 10
|
||||
f = lambda: x
|
||||
r1: t.CInt = f()
|
||||
r1: int = f()
|
||||
x = 20
|
||||
r2: t.CInt = f()
|
||||
r2: int = f()
|
||||
testcheck.check(r1 == 10 and r2 == 10, "lambda value capture (before==10 after==10)", "lambda value capture (expect 10 10)")
|
||||
|
||||
# ============================================================
|
||||
@@ -90,9 +90,9 @@ def test_lambda_capture_then_modify():
|
||||
# ============================================================
|
||||
def test_nonlocal_loop_accumulate():
|
||||
testcheck.section("Test 6: nonlocal with loop accumulate")
|
||||
sum_val: t.CInt = 0
|
||||
count: t.CInt = 0
|
||||
def add_numbers(n: t.CInt):
|
||||
sum_val: int = 0
|
||||
count: int = 0
|
||||
def add_numbers(n: int):
|
||||
nonlocal sum_val, count
|
||||
for i in range(1, n + 1):
|
||||
sum_val += i
|
||||
@@ -106,9 +106,9 @@ def test_nonlocal_loop_accumulate():
|
||||
# ============================================================
|
||||
def test_deep_nested_vars():
|
||||
testcheck.section("Test 7: deep nested different vars")
|
||||
a: t.CInt = 0
|
||||
b: t.CInt = 0
|
||||
c_val: t.CInt = 0
|
||||
a: int = 0
|
||||
b: int = 0
|
||||
c_val: int = 0
|
||||
def level1():
|
||||
nonlocal a
|
||||
a += 1
|
||||
@@ -127,14 +127,14 @@ def test_deep_nested_vars():
|
||||
# ============================================================
|
||||
# Test 8: global + nonlocal 在同一嵌套函数中
|
||||
# ============================================================
|
||||
g_state: t.CInt = 0
|
||||
g_state: int = 0
|
||||
|
||||
def test_global_nonlocal_same_func():
|
||||
testcheck.section("Test 8: global+nonlocal in same nested func")
|
||||
global g_state
|
||||
g_state = 0
|
||||
local_state: t.CInt = 0
|
||||
def worker(n: t.CInt):
|
||||
local_state: int = 0
|
||||
def worker(n: int):
|
||||
nonlocal local_state
|
||||
global g_state
|
||||
for i in range(n):
|
||||
@@ -148,10 +148,10 @@ def test_global_nonlocal_same_func():
|
||||
# ============================================================
|
||||
def test_lambda_default_and_capture():
|
||||
testcheck.section("Test 9: lambda with arg and capture")
|
||||
base: t.CInt = 100
|
||||
base: int = 100
|
||||
multiply = lambda x: base * x
|
||||
r1: t.CInt = multiply(3)
|
||||
r2: t.CInt = multiply(5)
|
||||
r1: int = multiply(3)
|
||||
r2: int = multiply(5)
|
||||
testcheck.check(r1 == 300 and r2 == 500, "lambda arg+capture (100*3==300 100*5==500)", "lambda arg+capture (expect 300 500)")
|
||||
|
||||
# ============================================================
|
||||
@@ -159,8 +159,8 @@ def test_lambda_default_and_capture():
|
||||
# ============================================================
|
||||
def test_nested_accumulate():
|
||||
testcheck.section("Test 10: nested function accumulate")
|
||||
total: t.CInt = 0
|
||||
def add_val(n: t.CInt):
|
||||
total: int = 0
|
||||
def add_val(n: int):
|
||||
nonlocal total
|
||||
total += n
|
||||
add_val(10)
|
||||
@@ -173,10 +173,10 @@ def test_nested_accumulate():
|
||||
# ============================================================
|
||||
def test_nonlocal_while():
|
||||
testcheck.section("Test 11: nonlocal in while loop")
|
||||
result: t.CInt = 0
|
||||
def countdown(n: t.CInt):
|
||||
result: int = 0
|
||||
def countdown(n: int):
|
||||
nonlocal result
|
||||
i: t.CInt = n
|
||||
i: int = n
|
||||
while i > 0:
|
||||
result += i
|
||||
i -= 1
|
||||
@@ -187,15 +187,15 @@ def test_nonlocal_while():
|
||||
# Test 12: 嵌套函数修改结构体字段
|
||||
# ============================================================
|
||||
class Point:
|
||||
x: t.CInt
|
||||
y: t.CInt
|
||||
x: int
|
||||
y: int
|
||||
|
||||
def test_nested_modify_struct():
|
||||
testcheck.section("Test 12: nested modify struct")
|
||||
p: Point = Point()
|
||||
p.x = 0
|
||||
p.y = 0
|
||||
def translate(dx: t.CInt, dy: t.CInt):
|
||||
def translate(dx: int, dy: int):
|
||||
nonlocal p
|
||||
p.x += dx
|
||||
p.y += dy
|
||||
@@ -203,7 +203,7 @@ def test_nested_modify_struct():
|
||||
translate(5, 15)
|
||||
testcheck.check(p.x == 15 and p.y == 35, "nested struct (x==15 y==35)", "nested struct (expect 15 35)")
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("ClosureTest2: Advanced Closure/Lambda/Global/Nonlocal")
|
||||
test_nonlocal_conditional()
|
||||
test_nonlocal_multi_var()
|
||||
|
||||
@@ -28,12 +28,12 @@ async def task() -> int:
|
||||
return 99
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
n: t.CInt = 0
|
||||
def main() -> int:
|
||||
n: int = 0
|
||||
for i in range(3):
|
||||
tt: coro.Coroutine = coro.Coroutine(*&task())
|
||||
r: t.CInt = coro.coro_run(tt)
|
||||
e: t.CInt = coro.coro_exception(tt)
|
||||
r: int = coro.coro_run(tt)
|
||||
e: int = coro.coro_exception(tt)
|
||||
m: t.CPtr = coro.coro_exception_msg(tt)
|
||||
stdio.printf("[%d] r = %d, exc = %d, msg = %s\n", i, r, e, m)
|
||||
coro.coro_destroy(tt)
|
||||
|
||||
+38
-38
@@ -18,10 +18,10 @@ import testcheck
|
||||
# ============================================================
|
||||
|
||||
# @log 装饰器:打印函数进入/退出,返回 1(正常调用一次)
|
||||
def log(ctx: t.CPtr, func_name: str, phase: t.CInt,
|
||||
def log(ctx: t.CPtr, func_name: str, phase: int,
|
||||
args_ptr: t.CPtr,
|
||||
ret_ptr: t.CPtr,
|
||||
decor_args_ptr: t.CPtr) -> t.CInt | t.CExport:
|
||||
decor_args_ptr: t.CPtr) -> int | t.CExport:
|
||||
if phase == 0:
|
||||
printf("[LOG] >> %s enter\n", func_name)
|
||||
return 1
|
||||
@@ -30,10 +30,10 @@ def log(ctx: t.CPtr, func_name: str, phase: t.CInt,
|
||||
return 0
|
||||
|
||||
# @trace 装饰器:详细追踪
|
||||
def trace(ctx: t.CPtr, func_name: str, phase: t.CInt,
|
||||
def trace(ctx: t.CPtr, func_name: str, phase: int,
|
||||
args_ptr: t.CPtr,
|
||||
ret_ptr: t.CPtr,
|
||||
decor_args_ptr: t.CPtr) -> t.CInt | t.CExport:
|
||||
decor_args_ptr: t.CPtr) -> int | t.CExport:
|
||||
if phase == 0:
|
||||
printf("[TRACE] calling %s...\n", func_name)
|
||||
return 1
|
||||
@@ -45,27 +45,27 @@ def trace(ctx: t.CPtr, func_name: str, phase: t.CInt,
|
||||
# 注意:理想情况下应使用 ctx 栈帧局部上下文替代全局变量,
|
||||
# 但 Viper 当前前端尚不支持 i8* 到 i32* 的指针转型,
|
||||
# 因此暂时使用全局变量演示计时逻辑
|
||||
_timing_tmp: t.CInt = 0
|
||||
_timing_tmp: int = 0
|
||||
|
||||
def timing(ctx: t.CPtr, func_name: str, phase: t.CInt,
|
||||
def timing(ctx: t.CPtr, func_name: str, phase: int,
|
||||
args_ptr: t.CPtr,
|
||||
ret_ptr: t.CPtr,
|
||||
decor_args_ptr: t.CPtr) -> t.CInt | t.CExport:
|
||||
decor_args_ptr: t.CPtr) -> int | t.CExport:
|
||||
global _timing_tmp
|
||||
if phase == 0:
|
||||
_timing_tmp = 100
|
||||
printf("[TIMING] %s start at t=%d\n", func_name, _timing_tmp)
|
||||
return 1
|
||||
else:
|
||||
elapsed: t.CInt = 105 - _timing_tmp
|
||||
elapsed: int = 105 - _timing_tmp
|
||||
printf("[TIMING] %s took %d ms\n", func_name, elapsed)
|
||||
return 0
|
||||
|
||||
# @repeat 装饰器(带参数,流程劫持):循环调用原函数 N 次
|
||||
def repeat(ctx: t.CPtr, func_name: str, phase: t.CInt,
|
||||
def repeat(ctx: t.CPtr, func_name: str, phase: int,
|
||||
args_ptr: t.CPtr,
|
||||
ret_ptr: t.CPtr,
|
||||
decor_args_ptr: t.CPtr) -> t.CInt | t.CExport:
|
||||
decor_args_ptr: t.CPtr) -> int | t.CExport:
|
||||
if phase == 0:
|
||||
printf("[REPEAT] %s will run 3 times\n", func_name)
|
||||
return 3
|
||||
@@ -74,12 +74,12 @@ def repeat(ctx: t.CPtr, func_name: str, phase: t.CInt,
|
||||
return 0
|
||||
|
||||
# @skip 装饰器:跳过原函数调用(流程劫持,返回 0)
|
||||
_skip_count: t.CInt = 0
|
||||
_skip_count: int = 0
|
||||
|
||||
def skip(ctx: t.CPtr, func_name: str, phase: t.CInt,
|
||||
def skip(ctx: t.CPtr, func_name: str, phase: int,
|
||||
args_ptr: t.CPtr,
|
||||
ret_ptr: t.CPtr,
|
||||
decor_args_ptr: t.CPtr) -> t.CInt | t.CExport:
|
||||
decor_args_ptr: t.CPtr) -> int | t.CExport:
|
||||
global _skip_count
|
||||
if phase == 0:
|
||||
_skip_count = _skip_count + 1
|
||||
@@ -90,12 +90,12 @@ def skip(ctx: t.CPtr, func_name: str, phase: t.CInt,
|
||||
return 0
|
||||
|
||||
# @count_calls 装饰器:统计函数被调用次数(递归保护测试用)
|
||||
_call_count: t.CInt = 0
|
||||
_call_count: int = 0
|
||||
|
||||
def count_calls(ctx: t.CPtr, func_name: str, phase: t.CInt,
|
||||
def count_calls(ctx: t.CPtr, func_name: str, phase: int,
|
||||
args_ptr: t.CPtr,
|
||||
ret_ptr: t.CPtr,
|
||||
decor_args_ptr: t.CPtr) -> t.CInt | t.CExport:
|
||||
decor_args_ptr: t.CPtr) -> int | t.CExport:
|
||||
global _call_count
|
||||
if phase == 0:
|
||||
_call_count = _call_count + 1
|
||||
@@ -111,7 +111,7 @@ def count_calls(ctx: t.CPtr, func_name: str, phase: t.CInt,
|
||||
# ============================================================
|
||||
|
||||
@log
|
||||
def add(a: t.CInt, b: t.CInt) -> t.CInt | t.CExport:
|
||||
def add(a: int, b: int) -> int | t.CExport:
|
||||
return a + b
|
||||
|
||||
|
||||
@@ -122,7 +122,7 @@ def add(a: t.CInt, b: t.CInt) -> t.CInt | t.CExport:
|
||||
|
||||
@log
|
||||
@trace
|
||||
def multiply(a: t.CInt, b: t.CInt) -> t.CInt | t.CExport:
|
||||
def multiply(a: int, b: int) -> int | t.CExport:
|
||||
return a * b
|
||||
|
||||
|
||||
@@ -131,7 +131,7 @@ def multiply(a: t.CInt, b: t.CInt) -> t.CInt | t.CExport:
|
||||
# ============================================================
|
||||
|
||||
@log
|
||||
def greet(name: str) -> t.CVoid | t.CExport:
|
||||
def greet(name: str) -> void | t.CExport:
|
||||
printf("Hello, %s!\n", name)
|
||||
|
||||
|
||||
@@ -140,7 +140,7 @@ def greet(name: str) -> t.CVoid | t.CExport:
|
||||
# ============================================================
|
||||
|
||||
@log
|
||||
def get_value() -> t.CInt | t.CExport:
|
||||
def get_value() -> int | t.CExport:
|
||||
return 42
|
||||
|
||||
|
||||
@@ -149,7 +149,7 @@ def get_value() -> t.CInt | t.CExport:
|
||||
# ============================================================
|
||||
|
||||
@timing
|
||||
export def compute(x: t.CInt) -> t.CInt:
|
||||
export def compute(x: int) -> int:
|
||||
return x * x + 1
|
||||
|
||||
|
||||
@@ -168,9 +168,9 @@ export def echo(msg: str):
|
||||
|
||||
@timing
|
||||
@log
|
||||
export def power(base: t.CInt, exp: t.CInt) -> t.CInt:
|
||||
result: t.CInt = 1
|
||||
i: t.CInt = 0
|
||||
export def power(base: int, exp: int) -> int:
|
||||
result: int = 1
|
||||
i: int = 0
|
||||
while i < exp:
|
||||
result = result * base
|
||||
i = i + 1
|
||||
@@ -182,7 +182,7 @@ export def power(base: t.CInt, exp: t.CInt) -> t.CInt:
|
||||
# ============================================================
|
||||
|
||||
@skip
|
||||
def dangerous() -> t.CInt | t.CExport:
|
||||
def dangerous() -> int | t.CExport:
|
||||
printf("This should NOT be printed!\n")
|
||||
return 999
|
||||
|
||||
@@ -192,7 +192,7 @@ def dangerous() -> t.CInt | t.CExport:
|
||||
# ============================================================
|
||||
|
||||
@repeat(3)
|
||||
def accumulate(x: t.CInt) -> t.CInt | t.CExport:
|
||||
def accumulate(x: int) -> int | t.CExport:
|
||||
printf(" accumulate(%d)\n", x)
|
||||
return x * 10
|
||||
|
||||
@@ -204,7 +204,7 @@ def accumulate(x: t.CInt) -> t.CInt | t.CExport:
|
||||
# ============================================================
|
||||
|
||||
@count_calls
|
||||
def factorial(n: t.CInt) -> t.CInt | t.CExport:
|
||||
def factorial(n: int) -> int | t.CExport:
|
||||
if n <= 1:
|
||||
return 1
|
||||
return n * factorial(n - 1)
|
||||
@@ -216,7 +216,7 @@ def factorial(n: t.CInt) -> t.CInt | t.CExport:
|
||||
# ============================================================
|
||||
|
||||
@log
|
||||
def fib(n: t.CInt) -> t.CInt | t.CExport:
|
||||
def fib(n: int) -> int | t.CExport:
|
||||
if n <= 1:
|
||||
return n
|
||||
return fib(n - 1) + fib(n - 2)
|
||||
@@ -226,18 +226,18 @@ def fib(n: t.CInt) -> t.CInt | t.CExport:
|
||||
# 主函数
|
||||
# ============================================================
|
||||
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
testcheck.begin("Decorator Test v4")
|
||||
|
||||
# 测试 1:单个 @log
|
||||
testcheck.section("Test 1: single @log")
|
||||
r1: t.CInt = add(3, 4)
|
||||
r1: int = add(3, 4)
|
||||
printf("add(3,4) = %d\n", r1)
|
||||
testcheck.check(r1 == 7, "add(3,4) = 7", "add(3,4) expect 7")
|
||||
|
||||
# 测试 2:链式 @log @trace
|
||||
testcheck.section("Test 2: chained @log @trace")
|
||||
r2: t.CInt = multiply(5, 6)
|
||||
r2: int = multiply(5, 6)
|
||||
printf("multiply(5,6) = %d\n", r2)
|
||||
testcheck.check(r2 == 30, "multiply(5,6) = 30", "multiply(5,6) expect 30")
|
||||
|
||||
@@ -248,13 +248,13 @@ def main() -> t.CInt | t.CExport:
|
||||
|
||||
# 测试 4:无参数
|
||||
testcheck.section("Test 4: @log on no-arg function")
|
||||
r4: t.CInt = get_value()
|
||||
r4: int = get_value()
|
||||
printf("get_value() = %d\n", r4)
|
||||
testcheck.check(r4 == 42, "get_value() = 42", "get_value() expect 42")
|
||||
|
||||
# 测试 5:@timing
|
||||
testcheck.section("Test 5: @timing")
|
||||
r5: t.CInt = compute(7)
|
||||
r5: int = compute(7)
|
||||
printf("compute(7) = %d\n", r5)
|
||||
testcheck.check(r5 == 50, "compute(7) = 50", "compute(7) expect 50")
|
||||
|
||||
@@ -265,19 +265,19 @@ def main() -> t.CInt | t.CExport:
|
||||
|
||||
# 测试 7:链式 @timing @log
|
||||
testcheck.section("Test 7: chained @timing @log")
|
||||
r7: t.CInt = power(2, 10)
|
||||
r7: int = power(2, 10)
|
||||
printf("power(2,10) = %d\n", r7)
|
||||
testcheck.check(r7 == 1024, "power(2,10) = 1024", "power(2,10) expect 1024")
|
||||
|
||||
# 测试 8:@skip — 跳过原函数调用
|
||||
testcheck.section("Test 8: @skip flow hijack")
|
||||
r8: t.CInt = dangerous()
|
||||
r8: int = dangerous()
|
||||
printf("dangerous() = %d (should be 0, skipped)\n", r8)
|
||||
testcheck.check(r8 == 0, "dangerous() skipped = 0", "dangerous() expect 0")
|
||||
|
||||
# 测试 9:@repeat(3) 有返回值
|
||||
testcheck.section("Test 9: @repeat(3) with return value")
|
||||
r9: t.CInt = accumulate(5)
|
||||
r9: int = accumulate(5)
|
||||
printf("accumulate(5) = %d (last iteration result)\n", r9)
|
||||
testcheck.check(r9 == 50, "accumulate(5) = 50", "accumulate(5) expect 50")
|
||||
|
||||
@@ -285,14 +285,14 @@ def main() -> t.CInt | t.CExport:
|
||||
testcheck.section("Test 10: recursive decoration protection")
|
||||
global _call_count
|
||||
_call_count = 0
|
||||
r10: t.CInt = factorial(5)
|
||||
r10: int = factorial(5)
|
||||
printf("factorial(5) = %d (should be 120)\n", r10)
|
||||
printf(" decorator call count = %d (should be 1, not 5)\n", _call_count)
|
||||
testcheck.check(r10 == 120 and _call_count == 1, "factorial(5)=120, calls=1", "factorial(5) expect 120, calls=1")
|
||||
|
||||
# 测试 11:@log 递归保护 — fib
|
||||
testcheck.section("Test 11: @log on recursive fib")
|
||||
r11: t.CInt = fib(6)
|
||||
r11: int = fib(6)
|
||||
printf("fib(6) = %d (should be 8)\n", r11)
|
||||
testcheck.check(r11 == 8, "fib(6) = 8", "fib(6) expect 8")
|
||||
|
||||
|
||||
+10
-10
@@ -6,7 +6,7 @@ import random
|
||||
|
||||
|
||||
# 同模块:单个尾随默认值
|
||||
def local_one(x: int, cap: t.CSizeT = 4096) -> t.CSizeT:
|
||||
def local_one(x: int, cap: sizet = 4096) -> sizet:
|
||||
return cap
|
||||
|
||||
|
||||
@@ -15,35 +15,35 @@ def local_quad(a: int, b: int = 10, c: int = 20, d: int = 30) -> int:
|
||||
return a + b * 100 + c * 10000 + d * 1000000
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("DefaultArgTest: default / named / out-of-order arguments")
|
||||
|
||||
# ① 同模块默认值
|
||||
testcheck.section("same-module defaults")
|
||||
r1: t.CSizeT = local_one(1)
|
||||
r1: sizet = local_one(1)
|
||||
testcheck.check(r1 == 4096, "local_one(1) cap = 4096", "local_one(1) cap != 4096")
|
||||
r2: int = local_quad(1)
|
||||
testcheck.check(r2 == 30201001, "local_quad(1) = 30201001", "local_quad(1) != 30201001")
|
||||
|
||||
# ② 跨模块默认值
|
||||
testcheck.section("cross-module defaults")
|
||||
r3: t.CSizeT = remote.one(1)
|
||||
r3: sizet = remote.one(1)
|
||||
testcheck.check(r3 == 4096, "remote.one(1) cap = 4096", "remote.one(1) cap != 4096")
|
||||
r4: t.CSizeT = remote.write(1, 2, False)
|
||||
r4: sizet = remote.write(1, 2, False)
|
||||
testcheck.check(r4 == 4096, "remote.write(1,2,False) cap = 4096", "remote.write(1,2,False) cap != 4096")
|
||||
|
||||
# ③ 显式覆盖默认值
|
||||
testcheck.section("explicit override")
|
||||
r5: t.CSizeT = remote.one(1, 8)
|
||||
r5: sizet = remote.one(1, 8)
|
||||
testcheck.check(r5 == 8, "remote.one(1,8) cap = 8", "remote.one(1,8) cap != 8")
|
||||
|
||||
# ④ 命名 / 乱序传参
|
||||
testcheck.section("named / out-of-order arguments")
|
||||
r6: t.CSizeT = remote.one(cap = 8, x = 1)
|
||||
r6: sizet = remote.one(cap = 8, x = 1)
|
||||
testcheck.check(r6 == 8, "remote.one(cap = 8, x = 1) = 8", "remote.one(cap = 8, x = 1) != 8")
|
||||
r7: t.CSizeT = remote.one(x = 1, cap = 8)
|
||||
r7: sizet = remote.one(x = 1, cap = 8)
|
||||
testcheck.check(r7 == 8, "remote.one(x = 1, cap = 8) = 8", "remote.one(x = 1, cap = 8) != 8")
|
||||
r8: t.CSizeT = remote.one(x = 1)
|
||||
r8: sizet = remote.one(x = 1)
|
||||
testcheck.check(r8 == 4096, "remote.one(x = 1) cap = 4096", "remote.one(x = 1) cap != 4096")
|
||||
r9: int = remote.many(z = 3, x = 1, y = 2)
|
||||
testcheck.check(r9 == 9, "remote.many(z = 3, x = 1, y = 2) = 9", "remote.many(z = 3, x = 1, y = 2) != 9")
|
||||
@@ -64,7 +64,7 @@ def main() -> t.CInt:
|
||||
# ⑥ include 模块(顶层 .vp)默认值:vrandom.randrange(start, stop, step = 1)
|
||||
# stop-start==1 ⇒ width==1 ⇒ 结果恒为 start;step 未填充时会退化为 0/垃圾
|
||||
testcheck.section("include-module defaults")
|
||||
r15: t.CInt = random.randrange(5, 6)
|
||||
r15: int = random.randrange(5, 6)
|
||||
testcheck.check(r15 == 5, "vrandom.randrange(5,6) = 5 (step default)", "vrandom.randrange(5,6) != 5")
|
||||
|
||||
return testcheck.end()
|
||||
@@ -2,12 +2,12 @@ import t
|
||||
|
||||
|
||||
# 跨模块:单个尾随默认值(对照 includes/json/__writer.vp 的 write 形态)
|
||||
def one(x: int, cap: t.CSizeT = 4096) -> t.CSizeT:
|
||||
def one(x: int, cap: sizet = 4096) -> sizet:
|
||||
return cap
|
||||
|
||||
|
||||
# 跨模块:4 参、最后一个有默认值(与 json.write(pool, val, pretty, cap=4096) 同形)
|
||||
def write(a: int, b: int, pretty: bool, cap: t.CSizeT = 4096) -> t.CSizeT:
|
||||
def write(a: int, b: int, pretty: bool, cap: sizet = 4096) -> sizet:
|
||||
return cap
|
||||
|
||||
|
||||
|
||||
+15
-15
@@ -16,20 +16,20 @@ import testcheck
|
||||
# ============================================================
|
||||
|
||||
|
||||
MAX_SIZE: t.CDefine = 1024
|
||||
MIN_VAL: t.CDefine = 0
|
||||
MAX_VAL: t.CDefine = 100
|
||||
MASK_BYTE: t.CDefine = 0xFF
|
||||
SHIFT_BITS: t.CDefine = 8
|
||||
PI_INT: t.CDefine = 3
|
||||
ENABLED: t.CDefine = 1
|
||||
DISABLED: t.CDefine = 0
|
||||
PAGE_SIZE: t.CDefine = 4096
|
||||
BUFFER_LEN: t.CDefine = 256
|
||||
define MAX_SIZE = 1024
|
||||
define MIN_VAL = 0
|
||||
define MAX_VAL = 100
|
||||
define MASK_BYTE = 0xFF
|
||||
define SHIFT_BITS = 8
|
||||
define PI_INT = 3
|
||||
define ENABLED = 1
|
||||
define DISABLED = 0
|
||||
define PAGE_SIZE = 4096
|
||||
define BUFFER_LEN = 256
|
||||
|
||||
CODE_SEG: t.CDefine | t.CUInt16T = 0x08
|
||||
DATA_SEG: t.CDefine | t.CUInt16T = 0x10
|
||||
STACK_SEG: t.CDefine | t.CUInt16T = 0x20
|
||||
CODE_SEG: t.CDefine | uint16 = 0x08
|
||||
DATA_SEG: t.CDefine | uint16 = 0x10
|
||||
STACK_SEG: t.CDefine | uint16 = 0x20
|
||||
|
||||
|
||||
def MAKE_FLAG(bit: CInt32T) -> t.CDefine:
|
||||
@@ -335,7 +335,7 @@ def test_cifdef_cross_module() -> CInt:
|
||||
return 0
|
||||
|
||||
def test_cifdef_guard() -> CInt:
|
||||
MY_HEADER_GUARD: t.CDefine = 1
|
||||
define MY_HEADER_GUARD = 1
|
||||
if c.CIfndef(MY_HEADER_GUARD):
|
||||
print(0)
|
||||
else:
|
||||
@@ -380,7 +380,7 @@ def test_cifdef_complex() -> CInt:
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
w32.win32console.SetConsoleCP(65001)
|
||||
w32.win32console.SetConsoleOutputCP(65001)
|
||||
|
||||
|
||||
+23
-23
@@ -25,7 +25,7 @@ def main() -> CInt | CExport:
|
||||
d.set_int("alpha", 10)
|
||||
d.set_int("beta", 20)
|
||||
d.set_int("gamma", 30)
|
||||
n: t.CSizeT = len(d)
|
||||
n: sizet = len(d)
|
||||
stdio.printf("len=%lu\n", n)
|
||||
testcheck.check(n == 3, "dict len OK (3)", "dict len FAILED")
|
||||
|
||||
@@ -38,10 +38,10 @@ def main() -> CInt | CExport:
|
||||
stdio.printf("p2=%p\n", p2)
|
||||
p3: t.CPtr = d["gamma"]
|
||||
stdio.printf("p3=%p\n", p3)
|
||||
v1: int = c.Deref((int | t.CPtr)(p1))
|
||||
v1: int = *(int | t.CPtr)(p1)
|
||||
stdio.printf("v1=%d\n", v1)
|
||||
v2: int = c.Deref((int | t.CPtr)(p2))
|
||||
v3: int = c.Deref((int | t.CPtr)(p3))
|
||||
v2: int = *(int | t.CPtr)(p2)
|
||||
v3: int = *(int | t.CPtr)(p3)
|
||||
stdio.printf("alpha=%d beta=%d gamma=%d\n", v1, v2, v3)
|
||||
testcheck.check(v1 == 10, "dict[alpha]==10 OK", "dict[alpha] FAILED")
|
||||
testcheck.check(v2 == 20, "dict[beta]==20 OK", "dict[beta] FAILED")
|
||||
@@ -51,7 +51,7 @@ def main() -> CInt | CExport:
|
||||
testcheck.section("Test 2: 更新已有键")
|
||||
d.set_int("beta", 99)
|
||||
p2b: t.CPtr = d["beta"]
|
||||
v2b: int = c.Deref((int | t.CPtr)(p2b))
|
||||
v2b: int = *(int | t.CPtr)(p2b)
|
||||
stdio.printf("beta(updated)=%d\n", v2b)
|
||||
testcheck.check(v2b == 99, "dict update OK", "dict update FAILED")
|
||||
testcheck.check(len(d) == 3, "dict len still 3 OK", "dict len changed FAILED")
|
||||
@@ -62,14 +62,14 @@ def main() -> CInt | CExport:
|
||||
testcheck.check(gv == None, "dict get missing OK (None)", "dict get missing FAILED")
|
||||
|
||||
gp: t.CPtr = d.get("alpha", None)
|
||||
ga: int = c.Deref((int | t.CPtr)(gp))
|
||||
ga: int = *(int | t.CPtr)(gp)
|
||||
stdio.printf("get(alpha)=%d\n", ga)
|
||||
testcheck.check(ga == 10, "dict get existing OK", "dict get existing FAILED")
|
||||
|
||||
# === Test 4: contains ===
|
||||
testcheck.section("Test 4: contains")
|
||||
has_alpha: t.CInt = d.contains("alpha")
|
||||
has_missing: t.CInt = d.contains("missing")
|
||||
has_alpha: int = d.contains("alpha")
|
||||
has_missing: int = d.contains("missing")
|
||||
stdio.printf("contains(alpha)=%d contains(missing)=%d\n", has_alpha, has_missing)
|
||||
testcheck.check(has_alpha == 1, "contains alpha OK", "contains alpha FAILED")
|
||||
testcheck.check(has_missing == 0, "not contains missing OK", "contains missing FAILED")
|
||||
@@ -79,7 +79,7 @@ def main() -> CInt | CExport:
|
||||
iter_count: int = 0
|
||||
for key in d:
|
||||
kp: t.CPtr = d[key]
|
||||
val: int = c.Deref((int | t.CPtr)(kp))
|
||||
val: int = *(int | t.CPtr)(kp)
|
||||
stdio.printf("dict[%s]=%d\n", key, val)
|
||||
iter_count += 1
|
||||
testcheck.check(iter_count == 3, "dict iter OK (3)", "dict iter FAILED")
|
||||
@@ -90,7 +90,7 @@ def main() -> CInt | CExport:
|
||||
d2.set_str("name", "Alice")
|
||||
d2.set_str("city", "Beijing")
|
||||
d2.set_str("lang", "TransPyC")
|
||||
n2: t.CSizeT = len(d2)
|
||||
n2: sizet = len(d2)
|
||||
stdio.printf("d2 len=%lu\n", n2)
|
||||
testcheck.check(n2 == 3, "dict set_str len OK (3)", "dict set_str len FAILED")
|
||||
|
||||
@@ -125,7 +125,7 @@ def main() -> CInt | CExport:
|
||||
stdio.sprintf(key_buf, "key%d", i)
|
||||
d3.set_int(key_buf, i * 100)
|
||||
i += 1
|
||||
n3: t.CSizeT = len(d3)
|
||||
n3: sizet = len(d3)
|
||||
stdio.printf("d3 len=%lu (after 20 inserts)\n", n3)
|
||||
testcheck.check(n3 == 20, "dict expand OK (20)", "dict expand FAILED")
|
||||
|
||||
@@ -133,14 +133,14 @@ def main() -> CInt | CExport:
|
||||
k5: str = stdlib.malloc(16)
|
||||
stdio.sprintf(k5, "key5")
|
||||
p5: t.CPtr = d3[k5]
|
||||
v5: int = c.Deref((int | t.CPtr)(p5))
|
||||
v5: int = *(int | t.CPtr)(p5)
|
||||
stdio.printf("d3[key5]=%d\n", v5)
|
||||
testcheck.check(v5 == 500, "dict expand key5 OK", "dict expand key5 FAILED")
|
||||
|
||||
k15: str = stdlib.malloc(16)
|
||||
stdio.sprintf(k15, "key15")
|
||||
p15: t.CPtr = d3[k15]
|
||||
v15: int = c.Deref((int | t.CPtr)(p15))
|
||||
v15: int = *(int | t.CPtr)(p15)
|
||||
stdio.printf("d3[key15]=%d\n", v15)
|
||||
testcheck.check(v15 == 1500, "dict expand key15 OK", "dict expand key15 FAILED")
|
||||
|
||||
@@ -165,9 +165,9 @@ def main() -> CInt | CExport:
|
||||
xp: t.CPtr = jd2["x"]
|
||||
yp: t.CPtr = jd2["y"]
|
||||
zp: t.CPtr = jd2["z"]
|
||||
xv: int = c.Deref((int | t.CPtr)(xp))
|
||||
yv: int = c.Deref((int | t.CPtr)(yp))
|
||||
zv: int = c.Deref((int | t.CPtr)(zp))
|
||||
xv: int = *(int | t.CPtr)(xp)
|
||||
yv: int = *(int | t.CPtr)(yp)
|
||||
zv: int = *(int | t.CPtr)(zp)
|
||||
stdio.printf("loads: x=%d y=%d z=%d\n", xv, yv, zv)
|
||||
testcheck.check(xv == 1, "loads x OK", "loads x FAILED")
|
||||
testcheck.check(yv == 2, "loads y OK", "loads y FAILED")
|
||||
@@ -194,8 +194,8 @@ def main() -> CInt | CExport:
|
||||
rt2.loads(pool, rt_str)
|
||||
rta_p: t.CPtr = rt2["a"]
|
||||
rtb_p: t.CPtr = rt2["b"]
|
||||
rta: int = c.Deref((int | t.CPtr)(rta_p))
|
||||
rtb: int = c.Deref((int | t.CPtr)(rtb_p))
|
||||
rta: int = *(int | t.CPtr)(rta_p)
|
||||
rtb: int = *(int | t.CPtr)(rtb_p)
|
||||
stdio.printf("round-trip: a=%d b=%d\n", rta, rtb)
|
||||
testcheck.check(rta == 1, "round-trip a OK", "round-trip a FAILED")
|
||||
testcheck.check(rtb == 2, "round-trip b OK", "round-trip b FAILED")
|
||||
@@ -211,17 +211,17 @@ def main() -> CInt | CExport:
|
||||
sub: dict* = outer["sub"]
|
||||
sa_p: t.CPtr = sub["a"]
|
||||
sb_p: t.CPtr = sub["b"]
|
||||
sa: int = c.Deref((int | t.CPtr)(sa_p))
|
||||
sb: int = c.Deref((int | t.CPtr)(sb_p))
|
||||
sa: int = *(int | t.CPtr)(sa_p)
|
||||
sb: int = *(int | t.CPtr)(sb_p)
|
||||
stdio.printf("nested: sub.a=%d sub.b=%d\n", sa, sb)
|
||||
testcheck.check(sa == 1, "nested sub.a OK", "nested sub.a FAILED")
|
||||
testcheck.check(sb == 2, "nested sub.b OK", "nested sub.b FAILED")
|
||||
|
||||
# === Test 14: get_vtype 类型标签 ===
|
||||
testcheck.section("Test 14: get_vtype 类型标签")
|
||||
vt1: t.CInt = d.get_vtype("alpha")
|
||||
vt2: t.CInt = d2.get_vtype("name")
|
||||
vt3: t.CInt = outer.get_vtype("sub")
|
||||
vt1: int = d.get_vtype("alpha")
|
||||
vt2: int = d2.get_vtype("name")
|
||||
vt3: int = outer.get_vtype("sub")
|
||||
stdio.printf("vtype(alpha)=%d vtype(name)=%d vtype(sub)=%d\n", vt1, vt2, vt3)
|
||||
testcheck.check(vt1 == 1, "vtype int OK", "vtype int FAILED")
|
||||
testcheck.check(vt2 == 4, "vtype str OK", "vtype str FAILED")
|
||||
|
||||
+2
-2
@@ -20,7 +20,7 @@ def no_doc_func() -> int:
|
||||
# 同模块类(有 docstring)
|
||||
class LocalClass:
|
||||
"Local class docstring."
|
||||
value: t.CInt
|
||||
value: int
|
||||
|
||||
def local_method(self) -> int:
|
||||
"Local method docstring."
|
||||
@@ -62,7 +62,7 @@ def test_cross_module_doc():
|
||||
_check_doc_null("remote.no_doc_func", remote.no_doc_func.__doc__)
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("DocTest: __doc__ magic string test")
|
||||
test_local_doc()
|
||||
test_cross_module_doc()
|
||||
|
||||
@@ -8,7 +8,7 @@ def remote_func() -> int:
|
||||
|
||||
class RemoteClass:
|
||||
"Remote class docstring."
|
||||
value: t.CInt
|
||||
value: int
|
||||
|
||||
def remote_method(self) -> int:
|
||||
"Remote method docstring."
|
||||
|
||||
+26
-26
@@ -32,8 +32,8 @@ enum Status:
|
||||
# Test 3: from t import CUnion as un; class X(un)
|
||||
# ============================================================
|
||||
union Data:
|
||||
i_val: t.CInt
|
||||
f_val: t.CFloat
|
||||
i_val: int
|
||||
f_val: float
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -50,16 +50,16 @@ renum Opt:
|
||||
# (注:检测已修复,但成员继承仍需父类先处理)
|
||||
# ============================================================
|
||||
class Parent:
|
||||
a: t.CInt
|
||||
a: int
|
||||
|
||||
def get_a(self) -> t.CInt:
|
||||
def get_a(self) -> int:
|
||||
return self.a
|
||||
|
||||
|
||||
class Child(Parent):
|
||||
b: t.CInt
|
||||
b: int
|
||||
|
||||
def get_sum(self) -> t.CInt:
|
||||
def get_sum(self) -> int:
|
||||
return self.a + self.b
|
||||
|
||||
|
||||
@@ -67,23 +67,23 @@ class Child(Parent):
|
||||
# Test 6: 多层继承 A -> B -> C,CVTable 向上传播
|
||||
# ============================================================
|
||||
class Base:
|
||||
x: t.CInt
|
||||
x: int
|
||||
|
||||
def base_val(self) -> t.CInt:
|
||||
def base_val(self) -> int:
|
||||
return self.x
|
||||
|
||||
|
||||
class Mid(Base):
|
||||
y: t.CInt
|
||||
y: int
|
||||
|
||||
def mid_val(self) -> t.CInt:
|
||||
def mid_val(self) -> int:
|
||||
return self.y
|
||||
|
||||
|
||||
class Leaf(Mid):
|
||||
z: t.CInt
|
||||
z: int
|
||||
|
||||
def leaf_val(self) -> t.CInt:
|
||||
def leaf_val(self) -> int:
|
||||
return self.z
|
||||
|
||||
|
||||
@@ -97,9 +97,9 @@ val: myint = 42
|
||||
# Test 8: BigEndian 字节序
|
||||
# ============================================================
|
||||
class NetHeader:
|
||||
magic: t.CInt | t.BigEndian
|
||||
magic: int | t.BigEndian
|
||||
length: t.CShort | t.BigEndian
|
||||
normal: t.CInt
|
||||
normal: int
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -114,17 +114,17 @@ class NetHeader:
|
||||
# Test 10: import t as tt; class X(tt.CStruct)
|
||||
# ============================================================
|
||||
class TtPoint:
|
||||
x: t.CInt
|
||||
y: t.CInt
|
||||
x: int
|
||||
y: int
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Test 11: import t as tt; @tt.Object 装饰器
|
||||
# ============================================================
|
||||
class TtObject:
|
||||
val: t.CInt
|
||||
val: int
|
||||
|
||||
def get_val(self) -> t.CInt:
|
||||
def get_val(self) -> int:
|
||||
return self.val
|
||||
|
||||
|
||||
@@ -132,37 +132,37 @@ class TtObject:
|
||||
# Test 12: from t import CStruct as cs; class X(cs)
|
||||
# ============================================================
|
||||
class CsPoint:
|
||||
x: t.CInt
|
||||
y: t.CInt
|
||||
x: int
|
||||
y: int
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Test 13: import t as tt; class X(tt.CUnion)
|
||||
# ============================================================
|
||||
union TtUnion:
|
||||
a: t.CInt
|
||||
b: t.CFloat
|
||||
a: int
|
||||
b: float
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Test 14: @tt.Object on class without methods (should fail?)
|
||||
# ============================================================
|
||||
class TtEmptyObject:
|
||||
val: t.CInt
|
||||
val: int
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("EdgeCaseTest: 类型别名与边界情况测试")
|
||||
|
||||
# Test 1: CEnum alias
|
||||
testcheck.section("Test 1: CEnum alias")
|
||||
c: t.CInt = Color.Green
|
||||
c: int = Color.Green
|
||||
stdio.printf("Test1 CEnum alias: %d\n", c)
|
||||
testcheck.ok("CEnum alias (Color.Green=1)")
|
||||
|
||||
# Test 2: module alias + CEnum
|
||||
testcheck.section("Test 2: module alias + CEnum")
|
||||
s: t.CInt = Status.Error
|
||||
s: int = Status.Error
|
||||
stdio.printf("Test2 t as tt.CEnum: %d\n", s)
|
||||
testcheck.ok("t as tt.CEnum (Status.Error=1)")
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ class Result(t.REnum):
|
||||
class Ok:
|
||||
value: CInt
|
||||
class Err:
|
||||
msg: t.CChar | CPtr
|
||||
msg: char | CPtr
|
||||
|
||||
|
||||
class GeoShape(t.REnum):
|
||||
|
||||
@@ -3,7 +3,7 @@ import testcheck
|
||||
import enumtest
|
||||
|
||||
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
testcheck.begin("EnumTest: 枚举类型测试")
|
||||
testcheck.section("Enum")
|
||||
enumtest.enum_main()
|
||||
|
||||
@@ -10,23 +10,23 @@ import testcheck
|
||||
# ============================================================
|
||||
|
||||
# fn: 单参数返回
|
||||
fn add_one(x: t.CInt) -> t.CInt:
|
||||
fn add_one(x: int) -> int:
|
||||
return x + 1
|
||||
|
||||
|
||||
# fun: 双参数返回
|
||||
fun add_two(a: t.CInt, b: t.CInt) -> t.CInt:
|
||||
fun add_two(a: int, b: int) -> int:
|
||||
return a + b
|
||||
|
||||
|
||||
# func: 浮点参数返回
|
||||
func mul_float(a: t.CDouble, b: t.CDouble) -> t.CDouble:
|
||||
func mul_float(a: double, b: double) -> double:
|
||||
return a * b
|
||||
|
||||
|
||||
# function: 内部用 def 定义再调用(别名与 def 混用)
|
||||
function get_ten() -> t.CInt:
|
||||
def inner() -> t.CInt:
|
||||
function get_ten() -> int:
|
||||
def inner() -> int:
|
||||
return 10
|
||||
return inner()
|
||||
|
||||
@@ -42,15 +42,15 @@ fn noop():
|
||||
|
||||
|
||||
# fun 递归
|
||||
fun fact(n: t.CInt) -> t.CInt:
|
||||
fun fact(n: int) -> int:
|
||||
if n <= 1:
|
||||
return 1
|
||||
return n * fact(n - 1)
|
||||
|
||||
|
||||
# func 多语句 + 局部变量
|
||||
func avg3(a: t.CDouble, b: t.CDouble, c: t.CDouble) -> t.CDouble:
|
||||
total: t.CDouble = a + b + c
|
||||
func avg3(a: double, b: double, c: double) -> double:
|
||||
total: double = a + b + c
|
||||
return total / 3.0
|
||||
|
||||
# func12344444 avg3(a: t.CDouble, b: t.CDouble, c: t.CDouble) -> t.CDouble:
|
||||
@@ -58,7 +58,7 @@ func avg3(a: t.CDouble, b: t.CDouble, c: t.CDouble) -> t.CDouble:
|
||||
# return total / 3.0
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("ExpandKeywordsTest: fn/fun/func/function")
|
||||
testcheck.section("function def keywords")
|
||||
|
||||
|
||||
@@ -15,11 +15,11 @@ import testcheck
|
||||
|
||||
# Test 1: t.CExtern | t.CExport - 外部声明函数(pass 体)
|
||||
# 声明一个外部函数,翻译器应生成 declare 而非 define
|
||||
def ExternalDecl(x: t.CInt) -> t.CInt | t.CExtern | t.CExport: pass
|
||||
def ExternalDecl(x: int) -> int | t.CExtern | t.CExport: pass
|
||||
|
||||
|
||||
# Test 2: t.State - 状态声明(等价于 CExtern | CExport)
|
||||
def StateDecl(x: t.CInt) -> t.CInt | t.State: pass
|
||||
def StateDecl(x: int) -> int | t.State: pass
|
||||
|
||||
|
||||
# Test 3: t.State 返回 void
|
||||
@@ -35,7 +35,7 @@ def test_extern_decl():
|
||||
testcheck.check(True, "StateVoidDecl declared (not called)", "expect declared once")
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("Extern2Test: minimal repro - extern redefinition")
|
||||
test_extern_decl()
|
||||
return testcheck.end()
|
||||
+12
-12
@@ -44,7 +44,7 @@ def main() -> CInt | CExport:
|
||||
|
||||
# 直接字段读取: b.__mbuddy__ (应返回 NULL)
|
||||
b_buddy: memhub.MemBuddy | t.CPtr = b.__mbuddy__
|
||||
if t.CInt(b_buddy) == 0:
|
||||
if int(b_buddy) == 0:
|
||||
stdio.printf("mbuddy OK: b.__mbuddy__ is NULL (no pollution)\n")
|
||||
else:
|
||||
stdio.printf("mbuddy FAIL: b.__mbuddy__ polluted!\n")
|
||||
@@ -109,7 +109,7 @@ def main() -> CInt | CExport:
|
||||
s1: str = "a,b,c"
|
||||
s1.__mbuddy__ = bd
|
||||
parts = s1.split(',')
|
||||
n1: t.CSizeT = parts.__len__()
|
||||
n1: sizet = parts.__len__()
|
||||
stdio.printf("split('a,b,c', ',') len=%lu\n", n1)
|
||||
testcheck.check(n1 == 3, "split len OK (3)", "split len FAILED expect 3")
|
||||
p0: str = parts[0]
|
||||
@@ -125,7 +125,7 @@ def main() -> CInt | CExport:
|
||||
s2: str = "hello"
|
||||
s2.__mbuddy__ = bd
|
||||
parts2 = s2.split(',')
|
||||
n2: t.CSizeT = parts2.__len__()
|
||||
n2: sizet = parts2.__len__()
|
||||
stdio.printf("split('hello', ',') len=%lu\n", n2)
|
||||
testcheck.check(n2 == 1, "no-delim len OK (1)", "no-delim len FAILED expect 1")
|
||||
h0: str = parts2.get(0)
|
||||
@@ -136,7 +136,7 @@ def main() -> CInt | CExport:
|
||||
s3: str = "a,,b"
|
||||
s3.__mbuddy__ = bd
|
||||
parts3 = s3.split(',')
|
||||
n3: t.CSizeT = parts3.__len__()
|
||||
n3: sizet = parts3.__len__()
|
||||
stdio.printf("split('a,,b', ',') len=%lu\n", n3)
|
||||
testcheck.check(n3 == 3, "consecutive len OK (3)", "consecutive len FAILED expect 3")
|
||||
e0: str = parts3.get(0)
|
||||
@@ -152,7 +152,7 @@ def main() -> CInt | CExport:
|
||||
s4: str = ""
|
||||
s4.__mbuddy__ = bd
|
||||
parts4 = s4.split(',')
|
||||
n4: t.CSizeT = parts4.__len__()
|
||||
n4: sizet = parts4.__len__()
|
||||
stdio.printf("split('', ',') len=%lu\n", n4)
|
||||
testcheck.check(n4 == 1, "empty len OK (1)", "empty len FAILED expect 1")
|
||||
|
||||
@@ -161,7 +161,7 @@ def main() -> CInt | CExport:
|
||||
s5: str = "hello world foo"
|
||||
s5.__mbuddy__ = bd
|
||||
parts5 = s5.split(' ')
|
||||
n5: t.CSizeT = parts5.__len__()
|
||||
n5: sizet = parts5.__len__()
|
||||
stdio.printf("split('hello world foo', ' ') len=%lu\n", n5)
|
||||
testcheck.check(n5 == 3, "space len OK (3)", "space len FAILED expect 3")
|
||||
w0: str = parts5[0]
|
||||
@@ -177,7 +177,7 @@ def main() -> CInt | CExport:
|
||||
s6: str = "a::b::c"
|
||||
s6.__mbuddy__ = bd
|
||||
parts6 = s6.split("::")
|
||||
n6: t.CSizeT = parts6.__len__()
|
||||
n6: sizet = parts6.__len__()
|
||||
stdio.printf("split('a::b::c', '::') len=%lu\n", n6)
|
||||
testcheck.check(n6 == 3, "multi-colon len OK (3)", "multi-colon len FAILED expect 3")
|
||||
m0: str = parts6[0]
|
||||
@@ -193,7 +193,7 @@ def main() -> CInt | CExport:
|
||||
s7: str = "hello, world, foo"
|
||||
s7.__mbuddy__ = bd
|
||||
parts7 = s7.split(", ")
|
||||
n7: t.CSizeT = parts7.__len__()
|
||||
n7: sizet = parts7.__len__()
|
||||
stdio.printf("split('hello, world, foo', ', ') len=%lu\n", n7)
|
||||
testcheck.check(n7 == 3, "comma-space len OK (3)", "comma-space len FAILED expect 3")
|
||||
cs0: str = parts7[0]
|
||||
@@ -209,7 +209,7 @@ def main() -> CInt | CExport:
|
||||
s8: str = "::a::b::"
|
||||
s8.__mbuddy__ = bd
|
||||
parts8 = s8.split("::")
|
||||
n8: t.CSizeT = parts8.__len__()
|
||||
n8: sizet = parts8.__len__()
|
||||
stdio.printf("split('::a::b::', '::') len=%lu\n", n8)
|
||||
testcheck.check(n8 == 4, "edge len OK (4)", "edge len FAILED expect 4")
|
||||
ed0: str = parts8[0]
|
||||
@@ -232,7 +232,7 @@ def main() -> CInt | CExport:
|
||||
|
||||
# 验证 __mbuddy__ 已自动注入(非 NULL)
|
||||
w_buddy: memhub.MemBuddy | t.CPtr = w_str.__mbuddy__
|
||||
testcheck.check(t.CInt(w_buddy) != 0, "with inject OK: __mbuddy__ auto-injected", "with inject FAIL: __mbuddy__ is NULL")
|
||||
testcheck.check(int(w_buddy) != 0, "with inject OK: __mbuddy__ auto-injected", "with inject FAIL: __mbuddy__ is NULL")
|
||||
|
||||
# upper() 不需要手动设置 __mbuddy__
|
||||
w_upper: str = w_str.upper()
|
||||
@@ -247,14 +247,14 @@ def main() -> CInt | CExport:
|
||||
# split() 不需要手动设置 __mbuddy__
|
||||
w_split_str: str = "x,y,z"
|
||||
w_parts = w_split_str.split(',')
|
||||
w_n: t.CSizeT = len(w_parts)
|
||||
w_n: sizet = len(w_parts)
|
||||
stdio.printf("with split('x,y,z') len=%lu\n", w_n)
|
||||
testcheck.check(w_n == 3, "with split len OK (3)", "with split len FAILED")
|
||||
|
||||
# 验证多个 str 变量都获得注入
|
||||
w_str2: str = "Multiple"
|
||||
w_buddy2: memhub.MemBuddy | t.CPtr = w_str2.__mbuddy__
|
||||
testcheck.check(t.CInt(w_buddy2) != 0, "with multi inject OK", "with multi inject FAIL")
|
||||
testcheck.check(int(w_buddy2) != 0, "with multi inject OK", "with multi inject FAIL")
|
||||
|
||||
test_s: str = "www.gvsds.com"
|
||||
list_s: list[str] | t.CPtr = test_s.split('.')
|
||||
|
||||
@@ -10,7 +10,7 @@ import w32.fileio
|
||||
from w32.fileio import File, FileW, MODE, FRESULT, SEEK_SET, SEEK_CUR, SEEK_END
|
||||
|
||||
|
||||
BUF_SIZE: t.CDefine = 4096
|
||||
define BUF_SIZE = 4096
|
||||
|
||||
|
||||
def fileio_main():
|
||||
@@ -42,13 +42,13 @@ def fileio_main():
|
||||
i: CInt = 0
|
||||
ch: bytes = write_buf
|
||||
while i < BUF_SIZE:
|
||||
if CInt(c.Deref(ch)) == 0:
|
||||
if CInt(*ch) == 0:
|
||||
break
|
||||
write_len = write_len + 1
|
||||
i = i + 1
|
||||
ch = ch + 1
|
||||
|
||||
result: BOOL = w32.win32file.WriteFile(hFile, write_buf, write_len, c.Addr(bytes_written), None)
|
||||
result: BOOL = w32.win32file.WriteFile(hFile, write_buf, write_len, &bytes_written, None)
|
||||
if result == 0:
|
||||
print("WriteFile failed")
|
||||
else:
|
||||
@@ -73,7 +73,7 @@ def fileio_main():
|
||||
return
|
||||
|
||||
read_len: ULONG = 0
|
||||
result = w32.win32file.ReadFile(hFile, read_buf, BUF_SIZE - 1, c.Addr(read_len), None)
|
||||
result = w32.win32file.ReadFile(hFile, read_buf, BUF_SIZE - 1, &read_len, None)
|
||||
if result == 0:
|
||||
print("ReadFile failed")
|
||||
else:
|
||||
@@ -335,7 +335,7 @@ def fileio_chinese_test():
|
||||
print("[chinese] T2: create failed")
|
||||
else:
|
||||
# u"你好世界\n" = 5 WCHARs = 10 bytes (UTF-16LE)
|
||||
w32.win32file.WriteFile(fw2.handle, u"你好世界\n", 10, c.Addr(bytes_written), None)
|
||||
w32.win32file.WriteFile(fw2.handle, u"你好世界\n", 10, &bytes_written, None)
|
||||
viperlib.snprintf(buf, 256, "[chinese] T2: wrote %d WCHAR bytes", bytes_written)
|
||||
print(buf)
|
||||
fw2.close()
|
||||
@@ -357,7 +357,7 @@ def fileio_chinese_test():
|
||||
else:
|
||||
fw3.write_str("ASCII line\n")
|
||||
# u"中文行\n" = 4 WCHARs = 8 bytes (UTF-16LE)
|
||||
w32.win32file.WriteFile(fw3.handle, u"中文行\n", 8, c.Addr(bytes_written), None)
|
||||
w32.win32file.WriteFile(fw3.handle, u"中文行\n", 8, &bytes_written, None)
|
||||
fw3.seek(0, SEEK_SET)
|
||||
n: LONG = fw3.read_all(buf, 512)
|
||||
viperlib.snprintf(buf, 256, "[chinese] T3: total %d bytes", n)
|
||||
@@ -374,7 +374,7 @@ def fileio_chinese_test():
|
||||
print("[chinese] T4: create failed")
|
||||
else:
|
||||
# u"你好,世界!\n" = 7 WCHARs = 14 bytes (UTF-16LE)
|
||||
w32.win32file.WriteFile(fw4.handle, u"你好,世界!\n", 14, c.Addr(bytes_written), None)
|
||||
w32.win32file.WriteFile(fw4.handle, u"你好,世界!\n", 14, &bytes_written, None)
|
||||
viperlib.snprintf(buf, 256, "[chinese] T4: wrote %d WCHAR bytes", bytes_written)
|
||||
print(buf)
|
||||
fw4.close()
|
||||
@@ -386,7 +386,7 @@ def fileio_chinese_test():
|
||||
# Print wide content to console using WriteConsoleW
|
||||
chars_written: ULONG = 0
|
||||
hOut: w32.win32base.HANDLE = w32.win32file.GetStdHandle(w32.win32file.STD_OUTPUT_HANDLE)
|
||||
w32.win32console.WriteConsoleW(hOut, u"你好,世界!\n", 7, c.Addr(chars_written), None)
|
||||
w32.win32console.WriteConsoleW(hOut, u"你好,世界!\n", 7, &chars_written, None)
|
||||
fr4.close()
|
||||
|
||||
w32.win32file.DeleteFileW(u"控制台测试.txt")
|
||||
|
||||
@@ -3,7 +3,7 @@ import testcheck
|
||||
import fileiotest
|
||||
|
||||
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
testcheck.begin("FileIoTest: Win32 FileIO 测试")
|
||||
testcheck.section("Win32 FileIO")
|
||||
fileiotest.fileio_main()
|
||||
|
||||
+25
-25
@@ -9,7 +9,7 @@ import testcheck
|
||||
|
||||
def test_for_in_range():
|
||||
testcheck.section("Test 1: for i in range(n)")
|
||||
s: t.CInt = 0
|
||||
s: int = 0
|
||||
for i in range(10):
|
||||
s += i
|
||||
testcheck.check(s == 45, "range sum OK (45)", "range sum FAILED expect 45")
|
||||
@@ -17,7 +17,7 @@ def test_for_in_range():
|
||||
|
||||
def test_for_in_str():
|
||||
testcheck.section("Test 2: for ch in str")
|
||||
cnt: t.CInt = 0
|
||||
cnt: int = 0
|
||||
for ch in "hello":
|
||||
cnt += 1
|
||||
testcheck.check(cnt == 5, "str iter OK (5)", "str iter FAILED expect 5")
|
||||
@@ -32,7 +32,7 @@ def test_for_in_list():
|
||||
lst.append("y")
|
||||
lst.append("z")
|
||||
lst.append("w")
|
||||
total: t.CInt = 0
|
||||
total: int = 0
|
||||
for v in lst:
|
||||
total += 1
|
||||
testcheck.check(total == 4, "list iter OK (4)", "list iter FAILED expect 4")
|
||||
@@ -51,7 +51,7 @@ def test_zip_list_list():
|
||||
lb.append("1")
|
||||
lb.append("2")
|
||||
lb.append("3")
|
||||
cnt: t.CInt = 0
|
||||
cnt: int = 0
|
||||
for ca, cb in zip(la, lb):
|
||||
stdio.printf("zip[%d]: '%s'='%s'\n", cnt, ca, cb)
|
||||
cnt += 1
|
||||
@@ -67,7 +67,7 @@ def test_zip_range_list():
|
||||
lst.append("p")
|
||||
lst.append("q")
|
||||
lst.append("r")
|
||||
cnt: t.CInt = 0
|
||||
cnt: int = 0
|
||||
for n, v in zip(range(3), lst):
|
||||
stdio.printf("zip range+list[%d]: %d='%s'\n", cnt, n, v)
|
||||
cnt += 1
|
||||
@@ -79,7 +79,7 @@ def test_zip_str_str():
|
||||
testcheck.section("Test 6: zip(str, str)")
|
||||
sa: str = "abc"
|
||||
sb: str = "123"
|
||||
cnt: t.CInt = 0
|
||||
cnt: int = 0
|
||||
for ca, cb in zip(sa, sb):
|
||||
stdio.printf("zip str+str[%d]: '%c'%c\n", cnt, ca, cb)
|
||||
cnt += 1
|
||||
@@ -94,7 +94,7 @@ def test_zip_range_len_list():
|
||||
lst.append("www")
|
||||
lst.append("gvsds")
|
||||
lst.append("com")
|
||||
cnt: t.CInt = 0
|
||||
cnt: int = 0
|
||||
for idx, v in zip(range(len(lst)), lst):
|
||||
stdio.printf("lst[%d]='%s'\n", idx, v)
|
||||
cnt += 1
|
||||
@@ -110,8 +110,8 @@ def test_enumerate_list():
|
||||
lst.append("alpha")
|
||||
lst.append("beta")
|
||||
lst.append("gamma")
|
||||
cnt: t.CInt = 0
|
||||
last_idx: t.CInt = -1
|
||||
cnt: int = 0
|
||||
last_idx: int = -1
|
||||
for idx, v in enumerate(lst):
|
||||
stdio.printf("enum[%d]='%s'\n", idx, v)
|
||||
last_idx = idx
|
||||
@@ -123,8 +123,8 @@ def test_enumerate_list():
|
||||
|
||||
def test_enumerate_str():
|
||||
testcheck.section("Test 9: enumerate(str)")
|
||||
cnt: t.CInt = 0
|
||||
last_idx: t.CInt = -1
|
||||
cnt: int = 0
|
||||
last_idx: int = -1
|
||||
for idx, ch in enumerate("ABCD"):
|
||||
stdio.printf("enum str[%d]='%c'\n", idx, ch)
|
||||
last_idx = idx
|
||||
@@ -135,9 +135,9 @@ def test_enumerate_str():
|
||||
|
||||
def test_enumerate_range():
|
||||
testcheck.section("Test 10: enumerate(range)")
|
||||
cnt: t.CInt = 0
|
||||
last_idx: t.CInt = -1
|
||||
last_val: t.CInt = -1
|
||||
cnt: int = 0
|
||||
last_idx: int = -1
|
||||
last_val: int = -1
|
||||
for idx, v in enumerate(range(5)):
|
||||
stdio.printf("enum range[%d]=%d\n", idx, v)
|
||||
last_idx = idx
|
||||
@@ -150,7 +150,7 @@ def test_enumerate_range():
|
||||
|
||||
def test_for_else_no_break():
|
||||
testcheck.section("Test 11: for-else (迭代耗尽 → 执行 else)")
|
||||
total: t.CInt = 0
|
||||
total: int = 0
|
||||
for i in range(3):
|
||||
total += i
|
||||
else:
|
||||
@@ -160,7 +160,7 @@ def test_for_else_no_break():
|
||||
|
||||
def test_for_else_break():
|
||||
testcheck.section("Test 12: for-else (break → 跳过 else)")
|
||||
found: t.CInt = 0
|
||||
found: int = 0
|
||||
for i in range(10):
|
||||
if i == 4:
|
||||
found = 1
|
||||
@@ -172,7 +172,7 @@ def test_for_else_break():
|
||||
|
||||
def test_for_else_empty_range():
|
||||
testcheck.section("Test 13: for-else (range(0) 空迭代 → 执行 else)")
|
||||
v: t.CInt = 0
|
||||
v: int = 0
|
||||
for i in range(0):
|
||||
v = 1
|
||||
else:
|
||||
@@ -188,8 +188,8 @@ def test_for_else_list():
|
||||
lst.append("a")
|
||||
lst.append("b")
|
||||
lst.append("c")
|
||||
cnt: t.CInt = 0
|
||||
ran_else: t.CInt = 0
|
||||
cnt: int = 0
|
||||
ran_else: int = 0
|
||||
for v in lst:
|
||||
cnt += 1
|
||||
else:
|
||||
@@ -201,8 +201,8 @@ def test_for_else_list():
|
||||
|
||||
def test_while_else_cond_false():
|
||||
testcheck.section("Test 15: while-else (条件变假 → 执行 else)")
|
||||
i: t.CInt = 0
|
||||
acc: t.CInt = 0
|
||||
i: int = 0
|
||||
acc: int = 0
|
||||
while i < 3:
|
||||
acc += i
|
||||
i += 1
|
||||
@@ -213,7 +213,7 @@ def test_while_else_cond_false():
|
||||
|
||||
def test_while_else_zero_iter():
|
||||
testcheck.section("Test 16: while-else (一次都不进循环 → 执行 else)")
|
||||
n: t.CInt = 0
|
||||
n: int = 0
|
||||
while n < 0:
|
||||
n = 99
|
||||
else:
|
||||
@@ -223,8 +223,8 @@ def test_while_else_zero_iter():
|
||||
|
||||
def test_while_else_break():
|
||||
testcheck.section("Test 17: while-else (break → 跳过 else)")
|
||||
i: t.CInt = 0
|
||||
flag: t.CInt = 0
|
||||
i: int = 0
|
||||
flag: int = 0
|
||||
while i < 10:
|
||||
if i == 2:
|
||||
flag = 1
|
||||
@@ -235,7 +235,7 @@ def test_while_else_break():
|
||||
testcheck.check(flag == 1, "while-else break OK (1)", "while-else break FAILED expect 1")
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("ForAndLoopTest: 迭代器与循环测试")
|
||||
|
||||
test_for_in_range()
|
||||
|
||||
@@ -39,7 +39,7 @@ export def main() -> int:
|
||||
# c.Addr(s) 取的是局部变量 s(str = i8*)的地址,结果是 i8**(char**);
|
||||
# 与 INTPTR(= t.CInt | t.CPtr,int*,见 includes/stdint.vp)层数与基座都不同,
|
||||
# 且指针隐式转换已收紧(层数必须相同)⇒ 注解按实际类型写 str | t.CPtr(= i8**)。
|
||||
ptr_var: str | t.CPtr = c.Addr(s)
|
||||
ptr_var: str | t.CPtr = &s
|
||||
val_var: int = 42
|
||||
if c.CIf(ctraits.isptr(ptr_var)):
|
||||
print("ptr_var is pointer")
|
||||
|
||||
+4
-4
@@ -11,7 +11,7 @@ from linkedlist import GSListNode
|
||||
|
||||
@t.NoVTable
|
||||
class Node(GSListNode[Node]):
|
||||
value: t.CInt
|
||||
value: int
|
||||
|
||||
def __init__(self):
|
||||
self.value = 0
|
||||
@@ -33,7 +33,7 @@ def test_node_next_field():
|
||||
n2.value = 20
|
||||
n1.Next = n2
|
||||
next_node: Node = n1.Next
|
||||
v: t.CInt = next_node.value
|
||||
v: int = next_node.value
|
||||
testcheck.check(v == 20, "n1.Next.value = 20", "expect 20")
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ def test_node_chain():
|
||||
c.value = 3
|
||||
a.Next = b
|
||||
b.Next = c
|
||||
sum: t.CInt = a.value
|
||||
sum: int = a.value
|
||||
p: Node = a.Next
|
||||
sum = sum + p.value
|
||||
p = p.Next
|
||||
@@ -55,7 +55,7 @@ def test_node_chain():
|
||||
testcheck.check(sum == 6, "chain sum = 1+2+3 = 6", "expect 6")
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("G3: GSListNode inheritance (F-bounded polymorphism)")
|
||||
test_node_create()
|
||||
test_node_next_field()
|
||||
|
||||
+2
-2
@@ -29,11 +29,11 @@ def caller1_make_chain(pool: memhub.MemBuddy | t.CPtr) -> G4Node | t.CPtr:
|
||||
return a
|
||||
|
||||
|
||||
def caller1_sum_chain(head: G4Node | t.CPtr) -> t.CInt:
|
||||
def caller1_sum_chain(head: G4Node | t.CPtr) -> int:
|
||||
"""遍历链表求和,直接访问 Next 字段"""
|
||||
if head is None:
|
||||
return 0
|
||||
total: t.CInt = head.IntVal
|
||||
total: int = head.IntVal
|
||||
cur: G4Node | t.CPtr = head
|
||||
# 直接访问 Next 字段(不通过 g4node_get_next 访问器)
|
||||
while cur.Next is not None:
|
||||
|
||||
+2
-2
@@ -26,9 +26,9 @@ def caller2_reverse_chain(head: G4Node | t.CPtr) -> G4Node | t.CPtr:
|
||||
return prev
|
||||
|
||||
|
||||
def caller2_count_nodes(head: G4Node | t.CPtr) -> t.CInt:
|
||||
def caller2_count_nodes(head: G4Node | t.CPtr) -> int:
|
||||
"""计算链表节点数"""
|
||||
count: t.CInt = 0
|
||||
count: int = 0
|
||||
cur: G4Node | t.CPtr = head
|
||||
while cur is not None:
|
||||
count = count + 1
|
||||
|
||||
+8
-8
@@ -30,7 +30,7 @@ def test_g4node_create():
|
||||
testcheck.check(False, "new_g4node", "FAIL")
|
||||
return
|
||||
n.IntVal = 42
|
||||
v: t.CInt = n.IntVal
|
||||
v: int = n.IntVal
|
||||
testcheck.check(v == 42, "G4Node.IntVal = 42", "expect 42")
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ def test_g4node_next_field():
|
||||
if next_node is None:
|
||||
testcheck.check(False, "g4node_get_next", "FAIL")
|
||||
return
|
||||
v: t.CInt = next_node.IntVal
|
||||
v: int = next_node.IntVal
|
||||
testcheck.check(v == 20, "n1.Next.IntVal = 20", "expect 20")
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ def test_g4node_chain():
|
||||
c.IntVal = 3
|
||||
g4node_set_next(a, b)
|
||||
g4node_set_next(b, c)
|
||||
sum: t.CInt = a.IntVal
|
||||
sum: int = a.IntVal
|
||||
p: G4Node | t.CPtr = g4node_get_next(a)
|
||||
sum = sum + p.IntVal
|
||||
p = g4node_get_next(p)
|
||||
@@ -95,7 +95,7 @@ def test_caller1_direct_access():
|
||||
if head is None:
|
||||
testcheck.check(False, "caller1_make_chain", "FAIL")
|
||||
return
|
||||
total: t.CInt = caller1.caller1_sum_chain(head)
|
||||
total: int = caller1.caller1_sum_chain(head)
|
||||
stdio.printf("caller1 chain total = %d\n", total)
|
||||
testcheck.check(total == 600, "caller1 sum = 100+200+300 = 600", "expect 600")
|
||||
|
||||
@@ -112,9 +112,9 @@ def test_caller2_reverse():
|
||||
if head is None:
|
||||
testcheck.check(False, "caller1_make_chain", "FAIL")
|
||||
return
|
||||
count_before: t.CInt = caller2.caller2_count_nodes(head)
|
||||
count_before: int = caller2.caller2_count_nodes(head)
|
||||
reversed_head: G4Node | t.CPtr = caller2.caller2_reverse_chain(head)
|
||||
count_after: t.CInt = caller2.caller2_count_nodes(reversed_head)
|
||||
count_after: int = caller2.caller2_count_nodes(reversed_head)
|
||||
stdio.printf("caller2 count before=%d after=%d\n", count_before, count_after)
|
||||
testcheck.check(count_before == 3 and count_after == 3,
|
||||
"caller2 reverse count OK (3,3)", "caller2 count mismatch")
|
||||
@@ -138,12 +138,12 @@ def test_caller3_append():
|
||||
return
|
||||
extra.IntVal = 400
|
||||
head = caller3.caller3_append(head, extra)
|
||||
total: t.CInt = caller1.caller1_sum_chain(head)
|
||||
total: int = caller1.caller1_sum_chain(head)
|
||||
stdio.printf("caller3 after append total = %d\n", total)
|
||||
testcheck.check(total == 1000, "caller3 append sum = 600+400 = 1000", "expect 1000")
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("G4: GSListNode inheritance from includes (Phase1 path)")
|
||||
test_g4node_create()
|
||||
test_g4node_next_field()
|
||||
|
||||
@@ -19,9 +19,9 @@ import memhub
|
||||
class G4Node(GSListNode[G4Node]):
|
||||
Ty: t.CPtr # 模拟 Value.Ty
|
||||
Name: t.CPtr # 模拟 Value.Name
|
||||
IsConst: t.CInt # 模拟 Value.IsConst
|
||||
IntVal: t.CInt64T # 模拟 Value.IntVal
|
||||
FloatVal: t.CDouble # 模拟 Value.FloatVal
|
||||
IsConst: int # 模拟 Value.IsConst
|
||||
IntVal: int64 # 模拟 Value.IntVal
|
||||
FloatVal: double # 模拟 Value.FloatVal
|
||||
|
||||
def __init__(self):
|
||||
self.Ty = None
|
||||
|
||||
+9
-9
@@ -18,7 +18,7 @@ from linkedlist import GSListNode, GSList
|
||||
# G5Node: 继承 GSListNode[G5Node](Phase2 路径,正确特化)
|
||||
@t.NoVTable
|
||||
class G5Node(GSListNode[G5Node]):
|
||||
Value: t.CInt
|
||||
Value: int
|
||||
|
||||
def __init__(self):
|
||||
self.Next = None
|
||||
@@ -28,7 +28,7 @@ class G5Node(GSListNode[G5Node]):
|
||||
# G5ListWrapper: 包装 GSList[G5Node],测试 GSList 字段访问
|
||||
# 注意:GSList[G5Node] 走 Phase2 特化路径
|
||||
# 用 pool 工厂函数分配 GSList,避免栈分配悬垂指针
|
||||
GSLIST_SIZE: t.CDefine = 24 # Head(8) + Tail(8) + Count(8)
|
||||
define GSLIST_SIZE = 24 # Head(8) + Tail(8) + Count(8)
|
||||
|
||||
@t.NoVTable
|
||||
class G5ListWrapper:
|
||||
@@ -51,7 +51,7 @@ def test_g5node_create():
|
||||
testcheck.section("Test 1: G5Node create and field access")
|
||||
n: G5Node = G5Node()
|
||||
n.Value = 42
|
||||
v: t.CInt = n.Value
|
||||
v: int = n.Value
|
||||
testcheck.check(v == 42, "G5Node.Value = 42", "expect 42")
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ def test_g5node_next():
|
||||
if next_node is None:
|
||||
testcheck.check(False, "n1.Next is None", "FAIL")
|
||||
return
|
||||
v: t.CInt = next_node.Value
|
||||
v: int = next_node.Value
|
||||
testcheck.check(v == 20, "n1.Next.Value = 20", "expect 20")
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ def test_gslist_create():
|
||||
# 检查初始状态
|
||||
head: G5Node | t.CPtr = lst.Head
|
||||
tail: G5Node | t.CPtr = lst.Tail
|
||||
count: t.CSizeT = lst.Count
|
||||
count: sizet = lst.Count
|
||||
testcheck.check(head is None, "initial Head is None", "expect None")
|
||||
testcheck.check(tail is None, "initial Tail is None", "expect None")
|
||||
testcheck.check(count == 0, "initial Count = 0", "expect 0")
|
||||
@@ -107,7 +107,7 @@ def test_gslist_append():
|
||||
lst.append(c)
|
||||
|
||||
# 验证 Count
|
||||
count: t.CSizeT = lst.Count
|
||||
count: sizet = lst.Count
|
||||
testcheck.check(count == 3, "Count = 3 after 3 appends", "expect 3")
|
||||
|
||||
# 验证 Head
|
||||
@@ -125,7 +125,7 @@ def test_gslist_append():
|
||||
testcheck.check(tail.Value == 3, "Tail.Value = 3", "expect 3")
|
||||
|
||||
# 遍历链表验证顺序
|
||||
sum: t.CInt = 0
|
||||
sum: int = 0
|
||||
cur: G5Node | t.CPtr = lst.Head
|
||||
while cur is not None:
|
||||
sum = sum + cur.Value
|
||||
@@ -161,12 +161,12 @@ def test_wrapper_list_field():
|
||||
if head is None:
|
||||
testcheck.check(False, "wrapper.List.Head is None", "FAIL")
|
||||
return
|
||||
count: t.CSizeT = wrapper.List.Count
|
||||
count: sizet = wrapper.List.Count
|
||||
testcheck.check(head.Value == 999, "wrapper.List.Head.Value = 999", "expect 999")
|
||||
testcheck.check(count == 1, "wrapper.List.Count = 1", "expect 1")
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("G5: GSList[T] field access (Phase2 path, pool alloc for wrapper)")
|
||||
test_g5node_create()
|
||||
test_g5node_next()
|
||||
|
||||
@@ -15,7 +15,7 @@ import memhub
|
||||
|
||||
@t.NoVTable
|
||||
class G5Node(GSListNode[G5Node]):
|
||||
Value: t.CInt
|
||||
Value: int
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -40,7 +40,7 @@ class G5Container:
|
||||
# ============================================================
|
||||
|
||||
# G5Node 硬编码大小: Next(8) + Value(4) + padding(4) = 16 字节
|
||||
G5NODE_SIZE: t.CDefine = 16
|
||||
define G5NODE_SIZE = 16
|
||||
|
||||
def new_g5node(pool: memhub.MemBuddy | t.CPtr) -> G5Node | t.CPtr:
|
||||
"""从 pool 分配并零初始化一个 G5Node"""
|
||||
@@ -51,7 +51,7 @@ def new_g5node(pool: memhub.MemBuddy | t.CPtr) -> G5Node | t.CPtr:
|
||||
|
||||
|
||||
# GSList 硬编码大小: Head(8) + Tail(8) + Count(8) = 24 字节
|
||||
G5LIST_SIZE: t.CDefine = 24
|
||||
define G5LIST_SIZE = 24
|
||||
|
||||
def new_g5list(pool: memhub.MemBuddy | t.CPtr) -> GSList[G5Node] | t.CPtr:
|
||||
"""从 pool 分配并零初始化一个 GSList 容器(Head/Tail/Count 全零)"""
|
||||
@@ -62,7 +62,7 @@ def new_g5list(pool: memhub.MemBuddy | t.CPtr) -> GSList[G5Node] | t.CPtr:
|
||||
|
||||
|
||||
# G5Container 硬编码大小: List(8) = 8 字节
|
||||
G5CONTAINER_SIZE: t.CDefine = 8
|
||||
define G5CONTAINER_SIZE = 8
|
||||
|
||||
def new_g5container(pool: memhub.MemBuddy | t.CPtr) -> G5Container | t.CPtr:
|
||||
"""从 pool 分配并零初始化一个 G5Container"""
|
||||
@@ -95,7 +95,7 @@ def g5list_get_tail(lst: GSList[G5Node] | t.CPtr) -> G5Node | t.CPtr:
|
||||
return lst.Tail
|
||||
|
||||
|
||||
def g5list_get_count(lst: GSList[G5Node] | t.CPtr) -> t.CSizeT:
|
||||
def g5list_get_count(lst: GSList[G5Node] | t.CPtr) -> sizet:
|
||||
"""获取链表节点数"""
|
||||
if lst is None: return 0
|
||||
return lst.Count
|
||||
@@ -113,7 +113,7 @@ def g5list_set_tail(lst: GSList[G5Node] | t.CPtr, node: G5Node | t.CPtr):
|
||||
lst.Tail = node
|
||||
|
||||
|
||||
def g5list_set_count(lst: GSList[G5Node] | t.CPtr, count: t.CSizeT):
|
||||
def g5list_set_count(lst: GSList[G5Node] | t.CPtr, count: sizet):
|
||||
"""设置链表节点数"""
|
||||
if lst is None: return
|
||||
lst.Count = count
|
||||
@@ -139,12 +139,12 @@ def g5list_append(lst: GSList[G5Node] | t.CPtr, node: G5Node | t.CPtr):
|
||||
# G5Node 访问器
|
||||
# ============================================================
|
||||
|
||||
def g5node_get_value(node: G5Node | t.CPtr) -> t.CInt:
|
||||
def g5node_get_value(node: G5Node | t.CPtr) -> int:
|
||||
if node is None: return 0
|
||||
return node.Value
|
||||
|
||||
|
||||
def g5node_set_value(node: G5Node | t.CPtr, value: t.CInt):
|
||||
def g5node_set_value(node: G5Node | t.CPtr, value: int):
|
||||
if node is None: return
|
||||
node.Value = value
|
||||
|
||||
|
||||
+14
-14
@@ -15,21 +15,21 @@ import atom
|
||||
|
||||
def test_atomic_test_and_set():
|
||||
testcheck.section("Test 1: __atomic_test_and_set")
|
||||
flag: t.CUInt8T = 0
|
||||
result: t.CBool = atom.__atomic_test_and_set(c.Addr(flag), atom.ATOMIC_ACQUIRE)
|
||||
flag: uint8 = 0
|
||||
result: bool = atom.__atomic_test_and_set(&flag, atom.ATOMIC_ACQUIRE)
|
||||
# test_and_set 返回旧值: flag=0 -> 返回 0, flag 变为 1
|
||||
testcheck.check(result == t.CBool(0), "first set returns old value 0", "expect 0")
|
||||
testcheck.check(result == bool(0), "first set returns old value 0", "expect 0")
|
||||
testcheck.check(flag == 1, "flag is 1 after set", "expect 1")
|
||||
|
||||
# 第二次设置应返回 1(旧值已为 1)
|
||||
result2: t.CBool = atom.__atomic_test_and_set(c.Addr(flag), atom.ATOMIC_ACQUIRE)
|
||||
testcheck.check(result2 == t.CBool(1), "second set returns old value 1", "expect 1")
|
||||
result2: bool = atom.__atomic_test_and_set(&flag, atom.ATOMIC_ACQUIRE)
|
||||
testcheck.check(result2 == bool(1), "second set returns old value 1", "expect 1")
|
||||
|
||||
|
||||
def test_atomic_clear():
|
||||
testcheck.section("Test 2: __atomic_clear")
|
||||
flag: t.CUInt8T = 1
|
||||
atom.__atomic_clear(c.Addr(flag), atom.ATOMIC_RELEASE)
|
||||
flag: uint8 = 1
|
||||
atom.__atomic_clear(&flag, atom.ATOMIC_RELEASE)
|
||||
testcheck.check(flag == 0, "flag is 0 after clear", "expect 0")
|
||||
|
||||
|
||||
@@ -42,26 +42,26 @@ def test_atomic_thread_fence():
|
||||
|
||||
def test_atomic_lock_free():
|
||||
testcheck.section("Test 4: __atomic_is_lock_free")
|
||||
flag: t.CUInt8T = 0
|
||||
result: t.CBool = atom.__atomic_is_lock_free(1, c.Addr(flag))
|
||||
testcheck.check(result == t.CBool(1), "1-byte is lock free", "expect 1")
|
||||
flag: uint8 = 0
|
||||
result: bool = atom.__atomic_is_lock_free(1, &flag)
|
||||
testcheck.check(result == bool(1), "1-byte is lock free", "expect 1")
|
||||
|
||||
|
||||
def test_atomic_spinlock():
|
||||
testcheck.section("Test 5: spinlock pattern (test_and_set + clear)")
|
||||
lock: t.CUInt8T = 0
|
||||
lock: uint8 = 0
|
||||
|
||||
# 获取锁
|
||||
while atom.__atomic_test_and_set(c.Addr(lock), atom.ATOMIC_ACQUIRE) == t.CBool(1):
|
||||
while atom.__atomic_test_and_set(&lock, atom.ATOMIC_ACQUIRE) == bool(1):
|
||||
pass
|
||||
testcheck.check(lock == 1, "lock acquired", "expect lock=1")
|
||||
|
||||
# 释放锁
|
||||
atom.__atomic_clear(c.Addr(lock), atom.ATOMIC_RELEASE)
|
||||
atom.__atomic_clear(&lock, atom.ATOMIC_RELEASE)
|
||||
testcheck.check(lock == 0, "lock released", "expect lock=0")
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("G6: atom module (inline asm atomic operations)")
|
||||
test_atomic_test_and_set()
|
||||
test_atomic_clear()
|
||||
|
||||
+4
-4
@@ -38,15 +38,15 @@ def test_value_struct_fields():
|
||||
node.IntVal = 42
|
||||
node.FloatVal = 3.14
|
||||
# 读取验证
|
||||
v: t.CInt = node.IntVal
|
||||
v: int = node.IntVal
|
||||
testcheck.check(v == 42, "Value.IntVal = 42", "expect 42")
|
||||
f: t.CDouble = node.FloatVal
|
||||
f: double = node.FloatVal
|
||||
testcheck.check(f > 3.0 and f < 4.0, "Value.FloatVal = 3.14", "expect ~3.14")
|
||||
c: t.CInt = node.IsConst
|
||||
c: int = node.IsConst
|
||||
testcheck.check(c == 1, "Value.IsConst = 1", "expect 1")
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("G7: Minimal repro - class name 'Value' conflicts with variable")
|
||||
test_value_struct_fields()
|
||||
return testcheck.end()
|
||||
@@ -17,9 +17,9 @@ from linkedlist import GSListNode
|
||||
class Value(GSListNode[Value]):
|
||||
Ty: t.CPtr
|
||||
Name: t.CPtr
|
||||
IsConst: t.CInt
|
||||
IntVal: t.CInt64T
|
||||
FloatVal: t.CDouble
|
||||
IsConst: int
|
||||
IntVal: int64
|
||||
FloatVal: double
|
||||
|
||||
def __init__(self):
|
||||
self.Ty = None
|
||||
|
||||
@@ -119,15 +119,15 @@ def main() -> CInt | CExport:
|
||||
# === 新语法类型强转 (t1|t2)(x) ===
|
||||
testcheck.section("新语法类型强转 (t1|t2)(x)")
|
||||
val_i64: CUInt64T = CUInt64T(42)
|
||||
val_i32 = (t.CInt)(val_i64)
|
||||
val_i32 = (int)(val_i64)
|
||||
print(val_i32)
|
||||
|
||||
ptr_raw = stdlib.malloc(8)
|
||||
ptr_typed = (t.CInt | t.CPtr)(ptr_raw)
|
||||
ptr_typed = (int | t.CPtr)(ptr_raw)
|
||||
viperlib.snprintf(buf, 256, "cast ptr=%p", ptr_typed)
|
||||
print(buf)
|
||||
|
||||
val_f = (t.CDouble)(42)
|
||||
val_f = (double)(42)
|
||||
viperlib.snprintf(buf, 256, "cast float=%.1f", val_f)
|
||||
print(buf)
|
||||
testcheck.ok("新语法类型强转测试完成")
|
||||
|
||||
+17
-17
@@ -10,8 +10,8 @@ def add[T](a: T, b: T) -> T:
|
||||
|
||||
def test_generic_add():
|
||||
testcheck.section("Test 1: generic add")
|
||||
r1: t.CInt = add(3, 5)
|
||||
r2: t.CInt = add(100, 200)
|
||||
r1: int = add(3, 5)
|
||||
r2: int = add(100, 200)
|
||||
testcheck.check(r1 == 8 and r2 == 300, "generic add (3+5=8, 100+200=300)", "generic add expect 8 and 300")
|
||||
|
||||
# ============================================================
|
||||
@@ -22,7 +22,7 @@ def combine[T1, T2](a: T1, b: T2) -> T1:
|
||||
|
||||
def test_generic_combine():
|
||||
testcheck.section("Test 2: generic combine")
|
||||
r: t.CInt = combine(10, 20)
|
||||
r: int = combine(10, 20)
|
||||
testcheck.check(r == 30, "generic combine (10+T1(20)=30)", "generic combine expect 30")
|
||||
|
||||
# ============================================================
|
||||
@@ -35,8 +35,8 @@ def max_val[T](a: T, b: T) -> T:
|
||||
|
||||
def test_generic_max():
|
||||
testcheck.section("Test 3: generic max")
|
||||
r1: t.CInt = max_val(10, 20)
|
||||
r2: t.CInt = max_val(50, 30)
|
||||
r1: int = max_val(10, 20)
|
||||
r2: int = max_val(50, 30)
|
||||
testcheck.check(r1 == 20 and r2 == 50, "generic max (max(10,20)=20, max(50,30)=50)", "generic max expect 20 and 50")
|
||||
|
||||
# ============================================================
|
||||
@@ -57,7 +57,7 @@ class Box[T]():
|
||||
def test_generic_box():
|
||||
testcheck.section("Test 4: generic Box[T]")
|
||||
b = Box(42)
|
||||
v: t.CInt = b.get()
|
||||
v: int = b.get()
|
||||
testcheck.check(v == 42, "Box[int] (get=42)", "Box[int] expect 42")
|
||||
|
||||
# ============================================================
|
||||
@@ -71,13 +71,13 @@ class Pair[T1, T2]():
|
||||
self.first = T1(a)
|
||||
self.second = T2(b)
|
||||
|
||||
def sum_as_int(self) -> t.CInt:
|
||||
return t.CInt(self.first) + t.CInt(self.second)
|
||||
def sum_as_int(self) -> int:
|
||||
return int(self.first) + int(self.second)
|
||||
|
||||
def test_generic_pair():
|
||||
testcheck.section("Test 5: generic Pair[T1,T2]")
|
||||
p = Pair(10, 20)
|
||||
r: t.CInt = p.sum_as_int()
|
||||
r: int = p.sum_as_int()
|
||||
testcheck.check(r == 30, "Pair[int,int] (sum=30)", "Pair[int,int] expect 30")
|
||||
|
||||
# ============================================================
|
||||
@@ -85,10 +85,10 @@ def test_generic_pair():
|
||||
# ============================================================
|
||||
def test_fixed_array():
|
||||
testcheck.section("Test 6: list[T, N] fixed array")
|
||||
arr: t.CArray[t.CInt, 5] = [0]
|
||||
arr: t.CArray[int, 5] = [0]
|
||||
for i in range(5):
|
||||
arr[i] = i * 10
|
||||
total: t.CInt = 0
|
||||
total: int = 0
|
||||
for i in range(5):
|
||||
total += arr[i]
|
||||
# 0+10+20+30+40 = 100
|
||||
@@ -99,7 +99,7 @@ def test_fixed_array():
|
||||
# ============================================================
|
||||
def test_char_array():
|
||||
testcheck.section("Test 7: list[t.CChar, N] char array")
|
||||
buf: t.CArray[t.CChar, 32] = [0]
|
||||
buf: t.CArray[char, 32] = [0]
|
||||
buf[0] = 72 # H
|
||||
buf[1] = 105 # i
|
||||
buf[2] = 0
|
||||
@@ -113,8 +113,8 @@ def identity[T](x: T) -> T:
|
||||
|
||||
def test_generic_identity():
|
||||
testcheck.section("Test 8: generic identity")
|
||||
r1: t.CInt = identity(42)
|
||||
r2: t.CInt = identity(0)
|
||||
r1: int = identity(42)
|
||||
r2: int = identity(0)
|
||||
testcheck.check(r1 == 42 and r2 == 0, "identity (42=42, 0=0)", "identity expect 42 and 0")
|
||||
|
||||
# ============================================================
|
||||
@@ -125,7 +125,7 @@ def double_val[T](x: T) -> T:
|
||||
|
||||
def test_generic_nested():
|
||||
testcheck.section("Test 9: generic nested call")
|
||||
r: t.CInt = double_val(21)
|
||||
r: int = double_val(21)
|
||||
testcheck.check(r == 42, "generic nested (double(21)=42)", "generic nested expect 42")
|
||||
|
||||
# ============================================================
|
||||
@@ -149,10 +149,10 @@ def test_generic_counter():
|
||||
c.increment()
|
||||
c.increment()
|
||||
c.increment()
|
||||
r: t.CInt = c.get_count()
|
||||
r: int = c.get_count()
|
||||
testcheck.check(r == 3, "Counter[int] (count=3)", "Counter[int] expect 3")
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("GenericTest: 泛型测试")
|
||||
test_generic_add()
|
||||
test_generic_combine()
|
||||
|
||||
+44
-44
@@ -11,8 +11,8 @@ def square[T](x: T) -> T:
|
||||
|
||||
def test_generic_square_types():
|
||||
testcheck.section("Test 1: generic square with different types")
|
||||
r1: t.CInt = square(5)
|
||||
r2: t.CInt = square(10)
|
||||
r1: int = square(5)
|
||||
r2: int = square(10)
|
||||
testcheck.check(r1 == 25 and r2 == 100, "square (5^2=25 10^2=100)", "square expect 25 100")
|
||||
|
||||
# ============================================================
|
||||
@@ -27,38 +27,38 @@ def clamp[T](val: T, lo: T, hi: T) -> T:
|
||||
|
||||
def test_generic_clamp():
|
||||
testcheck.section("Test 2: generic clamp")
|
||||
r1: t.CInt = clamp(5, 0, 10)
|
||||
r2: t.CInt = clamp(-3, 0, 10)
|
||||
r3: t.CInt = clamp(15, 0, 10)
|
||||
r1: int = clamp(5, 0, 10)
|
||||
r2: int = clamp(-3, 0, 10)
|
||||
r3: int = clamp(15, 0, 10)
|
||||
testcheck.check(r1 == 5 and r2 == 0 and r3 == 10, "clamp (5 0 10)", "clamp expect 5 0 10")
|
||||
|
||||
# ============================================================
|
||||
# Test 3: 泛型类 - Stack[T]
|
||||
# ============================================================
|
||||
class Stack[T]():
|
||||
data: t.CArray[t.CInt, 16]
|
||||
top: t.CInt
|
||||
data: t.CArray[int, 16]
|
||||
top: int
|
||||
|
||||
def __init__(self):
|
||||
self.top = 0
|
||||
|
||||
def push(self, val: T):
|
||||
self.data[self.top] = t.CInt(val)
|
||||
self.data[self.top] = int(val)
|
||||
self.top += 1
|
||||
|
||||
def pop(self) -> T:
|
||||
self.top -= 1
|
||||
return T(self.data[self.top])
|
||||
|
||||
def is_empty(self) -> t.CInt:
|
||||
def is_empty(self) -> int:
|
||||
if self.top == 0:
|
||||
return 1
|
||||
return 0
|
||||
|
||||
def size_of(self) -> t.CSizeT:
|
||||
def size_of(self) -> sizet:
|
||||
return self.__sizeof__()
|
||||
|
||||
def type_size(self) -> t.CSizeT:
|
||||
def type_size(self) -> sizet:
|
||||
return Stack[T].__sizeof__()
|
||||
|
||||
def test_generic_stack():
|
||||
@@ -69,29 +69,29 @@ def test_generic_stack():
|
||||
s.push(10)
|
||||
s.push(20)
|
||||
s.push(30)
|
||||
r1: t.CInt = s.pop()
|
||||
r2: t.CInt = s.pop()
|
||||
r3: t.CInt = s.pop()
|
||||
r1: int = s.pop()
|
||||
r2: int = s.pop()
|
||||
r3: int = s.pop()
|
||||
testcheck.check(r1 == 30 and r2 == 20 and r3 == 10, "Stack (pop=30 20 10)", "Stack expect 30 20 10")
|
||||
|
||||
# ============================================================
|
||||
# Test 4: 泛型函数 - swap via pointer
|
||||
# ============================================================
|
||||
class IntPair:
|
||||
a: t.CInt
|
||||
b: t.CInt
|
||||
a: int
|
||||
b: int
|
||||
|
||||
def generic_swap(p: IntPair | t.CPtr):
|
||||
tmp: t.CInt = c.Deref(p).a
|
||||
c.Deref(p).a = c.Deref(p).b
|
||||
c.Deref(p).b = tmp
|
||||
tmp: int = (*p).a
|
||||
(*p).a = (*p).b
|
||||
(*p).b = tmp
|
||||
|
||||
def test_generic_swap():
|
||||
testcheck.section("Test 4: generic swap via pointer")
|
||||
p: IntPair = IntPair()
|
||||
p.a = 100
|
||||
p.b = 200
|
||||
generic_swap(c.Addr(p))
|
||||
generic_swap(&p)
|
||||
testcheck.check(p.a == 200 and p.b == 100, "swap (a=200 b=100)", "swap expect 200 100")
|
||||
|
||||
# ============================================================
|
||||
@@ -118,24 +118,24 @@ class Range[T]():
|
||||
def test_generic_range():
|
||||
testcheck.section("Test 5: generic Range[T]")
|
||||
r = Range(0, 10, 1) # 0+1+2+...+9=45
|
||||
s: t.CInt = r.sum_all()
|
||||
s: int = r.sum_all()
|
||||
testcheck.check(s == 45, "Range sum (0..9=45)", "Range sum expect 45")
|
||||
|
||||
# ============================================================
|
||||
# Test 6: 泛型函数 - 数组求和(非泛型数组参数)
|
||||
# ============================================================
|
||||
def array_sum(arr: t.CArray[t.CInt, 8], n: t.CInt) -> t.CInt:
|
||||
result: t.CInt = 0
|
||||
def array_sum(arr: t.CArray[int, 8], n: int) -> int:
|
||||
result: int = 0
|
||||
for i in range(n):
|
||||
result += arr[i]
|
||||
return result
|
||||
|
||||
def test_generic_array_sum():
|
||||
testcheck.section("Test 6: array sum")
|
||||
arr: t.CArray[t.CInt, 8] = [0]
|
||||
arr: t.CArray[int, 8] = [0]
|
||||
for i in range(8):
|
||||
arr[i] = (i + 1) * 10
|
||||
s: t.CInt = array_sum(arr, 8)
|
||||
s: int = array_sum(arr, 8)
|
||||
testcheck.check(s == 360, "array sum (360)", "array sum expect 360")
|
||||
|
||||
# ============================================================
|
||||
@@ -151,31 +151,31 @@ def max_of_three[T](a: T, b: T, c_val: T) -> T:
|
||||
|
||||
def test_generic_max_three():
|
||||
testcheck.section("Test 7: generic max of three")
|
||||
r1: t.CInt = max_of_three(1, 2, 3)
|
||||
r2: t.CInt = max_of_three(10, 30, 20)
|
||||
r3: t.CInt = max_of_three(50, 50, 50)
|
||||
r1: int = max_of_three(1, 2, 3)
|
||||
r2: int = max_of_three(10, 30, 20)
|
||||
r3: int = max_of_three(50, 50, 50)
|
||||
testcheck.check(r1 == 3 and r2 == 30 and r3 == 50, "max3 (3 30 50)", "max3 expect 3 30 50")
|
||||
|
||||
# ============================================================
|
||||
# Test 8: 泛型类 - 带方法的容器
|
||||
# ============================================================
|
||||
class Container[T]():
|
||||
values: t.CArray[t.CInt, 8]
|
||||
size: t.CInt
|
||||
values: t.CArray[int, 8]
|
||||
size: int
|
||||
|
||||
def __init__(self):
|
||||
self.size = 0
|
||||
|
||||
def add(self, v: T):
|
||||
self.values[self.size] = t.CInt(v)
|
||||
self.values[self.size] = int(v)
|
||||
self.size += 1
|
||||
|
||||
def get(self, idx: t.CInt) -> T:
|
||||
def get(self, idx: int) -> T:
|
||||
return T(self.values[idx])
|
||||
|
||||
def contains(self, v: T) -> t.CInt:
|
||||
def contains(self, v: T) -> int:
|
||||
for i in range(self.size):
|
||||
if self.values[i] == t.CInt(v):
|
||||
if self.values[i] == int(v):
|
||||
return 1
|
||||
return 0
|
||||
|
||||
@@ -193,9 +193,9 @@ def test_generic_container():
|
||||
c.add(10)
|
||||
c.add(20)
|
||||
c.add(30)
|
||||
has20: t.CInt = c.contains(20)
|
||||
has99: t.CInt = c.contains(99)
|
||||
total: t.CInt = c.total()
|
||||
has20: int = c.contains(20)
|
||||
has99: int = c.contains(99)
|
||||
total: int = c.total()
|
||||
testcheck.check(has20 == 1 and has99 == 0 and total == 60, "Container (has20=1 has99=0 total=60)", "Container expect 1 0 60")
|
||||
|
||||
# ============================================================
|
||||
@@ -211,8 +211,8 @@ def factorial[T](n: T) -> T:
|
||||
|
||||
def test_generic_factorial():
|
||||
testcheck.section("Test 9: generic factorial")
|
||||
r1: t.CInt = factorial(5)
|
||||
r2: t.CInt = factorial(10)
|
||||
r1: int = factorial(5)
|
||||
r2: int = factorial(10)
|
||||
testcheck.check(r1 == 120 and r2 == 3628800, "factorial (5!=120 10!=3628800)", "factorial expect 120 3628800")
|
||||
|
||||
# ============================================================
|
||||
@@ -236,7 +236,7 @@ def test_generic_accumulator():
|
||||
a.add_val(10)
|
||||
a.add_val(20)
|
||||
a.add_val(30)
|
||||
r: t.CInt = a.get_result()
|
||||
r: int = a.get_result()
|
||||
testcheck.check(r == 60, "Accumulator (result=60)", "Accumulator expect 60")
|
||||
|
||||
# ============================================================
|
||||
@@ -249,15 +249,15 @@ def test_generic_sizeof_bug():
|
||||
# 同 Test 3:无参构造必须显式标注类型实参;Stack[int] = { [16 x i32], i32 } = 68。
|
||||
s = Stack[int]()
|
||||
s.push(10)
|
||||
sz: t.CSizeT = s.__sizeof__()
|
||||
inner_sz: t.CSizeT = s.size_of()
|
||||
type_sz: t.CSizeT = s.type_size()
|
||||
sz: sizet = s.__sizeof__()
|
||||
inner_sz: sizet = s.size_of()
|
||||
type_sz: sizet = s.type_size()
|
||||
stdio.printf("Stack[int] obj.__sizeof__() = %lu, self.__sizeof__() = %lu, Stack[T].__sizeof__() = %lu (expect 68)\n", sz, inner_sz, type_sz)
|
||||
testcheck.check(sz == 68, "obj.__sizeof__() == 68 OK", "obj.__sizeof__() FAILED")
|
||||
testcheck.check(inner_sz == 68, "self.__sizeof__() == 68 OK", "self.__sizeof__() FAILED")
|
||||
testcheck.check(type_sz == 68, "Stack[T].__sizeof__() == 68 OK", "Stack[T].__sizeof__() FAILED")
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("GenericTest2: Advanced Generic Tests")
|
||||
test_generic_square_types()
|
||||
test_generic_clamp()
|
||||
|
||||
@@ -11,7 +11,7 @@ def double[T](x: int) -> int:
|
||||
|
||||
def test_explicit_type_arg():
|
||||
testcheck.section("Test 1: explicit type arg xxx[T](x)")
|
||||
r: t.CInt = double[t.CInt](21)
|
||||
r: int = double[int](21)
|
||||
testcheck.check(r == 42, "double[t.CInt](21) = 42", "expect 42")
|
||||
|
||||
# ============================================================
|
||||
@@ -22,8 +22,8 @@ def identity[T](x: int) -> int:
|
||||
|
||||
def test_identity_explicit():
|
||||
testcheck.section("Test 2: identity[T](x)")
|
||||
r1: t.CInt = identity[t.CInt](10)
|
||||
r2: t.CInt = identity[t.CInt](20)
|
||||
r1: int = identity[int](10)
|
||||
r2: int = identity[int](20)
|
||||
testcheck.check(r1 == 10 and r2 == 20, "identity[t.CInt](10)=10 (20)=20", "expect 10 20")
|
||||
|
||||
# ============================================================
|
||||
@@ -34,7 +34,7 @@ def add_one[T](x: T) -> T:
|
||||
|
||||
def test_add_one_explicit():
|
||||
testcheck.section("Test 3: add_one[T](x) with T param")
|
||||
r: t.CInt = add_one[t.CInt](41)
|
||||
r: int = add_one[int](41)
|
||||
testcheck.check(r == 42, "add_one[t.CInt](41) = 42", "expect 42")
|
||||
|
||||
# ============================================================
|
||||
@@ -43,12 +43,12 @@ def test_add_one_explicit():
|
||||
def test_mixed_inference_explicit():
|
||||
testcheck.section("Test 4: mixed inference and explicit")
|
||||
# 自动推导
|
||||
r1: t.CInt = add_one(99)
|
||||
r1: int = add_one(99)
|
||||
# 手动传
|
||||
r2: t.CInt = add_one[t.CInt](99)
|
||||
r2: int = add_one[int](99)
|
||||
testcheck.check(r1 == 100 and r2 == 100, "add_one(99)=100 add_one[t.CInt](99)=100", "expect 100 100")
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("GenericTest3: 手动传类型参数 xxx[T](x)")
|
||||
test_explicit_type_arg()
|
||||
test_identity_explicit()
|
||||
|
||||
+14
-14
@@ -19,8 +19,8 @@ class Box[T]():
|
||||
|
||||
def test_explicit_box():
|
||||
testcheck.section("Test 1: Box[t.CInt](42)")
|
||||
b = Box[t.CInt](42)
|
||||
v: t.CInt = b.get()
|
||||
b = Box[int](42)
|
||||
v: int = b.get()
|
||||
testcheck.check(v == 42, "Box[t.CInt](42).get() = 42", "expect 42")
|
||||
|
||||
# ============================================================
|
||||
@@ -34,13 +34,13 @@ class Pair[T1, T2]():
|
||||
self.first = T1(a)
|
||||
self.second = T2(b)
|
||||
|
||||
def sum_as_int(self) -> t.CInt:
|
||||
return t.CInt(self.first) + t.CInt(self.second)
|
||||
def sum_as_int(self) -> int:
|
||||
return int(self.first) + int(self.second)
|
||||
|
||||
def test_explicit_pair():
|
||||
testcheck.section("Test 2: Pair[t.CInt, t.CInt](10, 20)")
|
||||
p = Pair[t.CInt, t.CInt](10, 20)
|
||||
r: t.CInt = p.sum_as_int()
|
||||
p = Pair[int, int](10, 20)
|
||||
r: int = p.sum_as_int()
|
||||
testcheck.check(r == 30, "Pair[t.CInt,t.CInt](10,20).sum = 30", "expect 30")
|
||||
|
||||
# ============================================================
|
||||
@@ -58,11 +58,11 @@ class Wrapper[T]():
|
||||
def test_mixed_generic_class():
|
||||
testcheck.section("Test 3: mixed explicit and inferred")
|
||||
# 手动传
|
||||
w1 = Wrapper[t.CInt](100)
|
||||
w1 = Wrapper[int](100)
|
||||
# 自动推导
|
||||
w2 = Wrapper(200)
|
||||
r1: t.CInt = w1.get()
|
||||
r2: t.CInt = w2.get()
|
||||
r1: int = w1.get()
|
||||
r2: int = w2.get()
|
||||
testcheck.check(r1 == 100 and r2 == 200, "Wrapper[t.CInt](100)=100 Wrapper(200)=200", "expect 100 200")
|
||||
|
||||
# ============================================================
|
||||
@@ -82,11 +82,11 @@ class Counter[T]():
|
||||
|
||||
def test_explicit_counter():
|
||||
testcheck.section("Test 4: Counter[t.CInt](0) with methods")
|
||||
c = Counter[t.CInt](0)
|
||||
c = Counter[int](0)
|
||||
c.increment()
|
||||
c.increment()
|
||||
c.increment()
|
||||
r: t.CInt = c.get_count()
|
||||
r: int = c.get_count()
|
||||
testcheck.check(r == 3, "Counter[t.CInt](0) +3 = 3", "expect 3")
|
||||
|
||||
# ============================================================
|
||||
@@ -94,12 +94,12 @@ def test_explicit_counter():
|
||||
# ============================================================
|
||||
def test_explicit_box_set():
|
||||
testcheck.section("Test 5: Box[t.CInt] set method")
|
||||
b = Box[t.CInt](10)
|
||||
b = Box[int](10)
|
||||
b.set(99)
|
||||
v: t.CInt = b.get()
|
||||
v: int = b.get()
|
||||
testcheck.check(v == 99, "Box[t.CInt].set(99) get = 99", "expect 99")
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("GenericTest4: 泛型结构体手动传类型参数")
|
||||
test_explicit_box()
|
||||
test_explicit_pair()
|
||||
|
||||
+14
-14
@@ -12,17 +12,17 @@ import w32.win32console
|
||||
# ==============================================
|
||||
# 工具函数:打印十六进制哈希串
|
||||
# ==============================================
|
||||
def print_hex(buf: t.CUInt8T | t.CPtr, length: t.CInt):
|
||||
def print_hex(buf: uint8 | t.CPtr, length: int):
|
||||
for i in range(length):
|
||||
stdio.printf("%02x", buf[i])
|
||||
stdio.printf("\n")
|
||||
|
||||
|
||||
def default_value_test_function(a: t.CInt, b: t.CInt = 1):
|
||||
def default_value_test_function(a: int, b: int = 1):
|
||||
print(a, b)
|
||||
|
||||
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
w32.win32console.SetConsoleCP(65001)
|
||||
w32.win32console.SetConsoleOutputCP(65001)
|
||||
|
||||
@@ -32,7 +32,7 @@ def main() -> t.CInt | t.CExport:
|
||||
testcheck.section("HASHLIB")
|
||||
plain: str = "hello123"
|
||||
|
||||
md5_buf: t.CArray[t.CUInt8T, hashlib.MD5_DIGEST_LEN]
|
||||
md5_buf: t.CArray[uint8, hashlib.MD5_DIGEST_LEN]
|
||||
mctx = hashlib.md5()
|
||||
mctx.update(plain)
|
||||
mctx.final(md5_buf)
|
||||
@@ -40,7 +40,7 @@ def main() -> t.CInt | t.CExport:
|
||||
print_hex(md5_buf, hashlib.MD5_DIGEST_LEN)
|
||||
testcheck.ok("HASHLIB md5 completed")
|
||||
|
||||
sha1_buf: t.CArray[t.CUInt8T, hashlib.SHA1_DIGEST_LEN]
|
||||
sha1_buf: t.CArray[uint8, hashlib.SHA1_DIGEST_LEN]
|
||||
s1ctx = hashlib.sha1()
|
||||
s1ctx.update(plain)
|
||||
s1ctx.final(sha1_buf)
|
||||
@@ -48,7 +48,7 @@ def main() -> t.CInt | t.CExport:
|
||||
print_hex(sha1_buf, hashlib.SHA1_DIGEST_LEN)
|
||||
testcheck.ok("HASHLIB sha1 completed")
|
||||
|
||||
sha256_buf: t.CArray[t.CUInt8T, hashlib.SHA256_DIGEST_LEN]
|
||||
sha256_buf: t.CArray[uint8, hashlib.SHA256_DIGEST_LEN]
|
||||
s2ctx = hashlib.sha256()
|
||||
s2ctx.update(plain)
|
||||
s2ctx.final(sha256_buf)
|
||||
@@ -56,7 +56,7 @@ def main() -> t.CInt | t.CExport:
|
||||
print_hex(sha256_buf, hashlib.SHA256_DIGEST_LEN)
|
||||
testcheck.ok("HASHLIB sha256 completed")
|
||||
|
||||
sha512_buf: t.CArray[t.CUInt8T, hashlib.SHA512_DIGEST_LEN]
|
||||
sha512_buf: t.CArray[uint8, hashlib.SHA512_DIGEST_LEN]
|
||||
s5ctx = hashlib.sha512()
|
||||
s5ctx.update(plain)
|
||||
s5ctx.final(sha512_buf)
|
||||
@@ -69,11 +69,11 @@ def main() -> t.CInt | t.CExport:
|
||||
|
||||
# ---------- base64 编解码测试 ----------
|
||||
testcheck.section("BASE64")
|
||||
b64_out: t.CArray[t.CChar, 256]
|
||||
b64_dec: t.CArray[t.CUInt8T, 256]
|
||||
b64_out: t.CArray[char, 256]
|
||||
b64_dec: t.CArray[uint8, 256]
|
||||
base64.b64encode(plain, b64_out)
|
||||
print("Base64 编码:", b64_out)
|
||||
dlen: t.CSizeT = base64.b64decode(b64_out, b64_dec)
|
||||
dlen: sizet = base64.b64decode(b64_out, b64_dec)
|
||||
b64_dec[dlen] = 0
|
||||
print("Base64 解码:", b64_dec)
|
||||
testcheck.ok("BASE64 encode/decode completed")
|
||||
@@ -82,7 +82,7 @@ def main() -> t.CInt | t.CExport:
|
||||
testcheck.section("BINASCII")
|
||||
binascii.init_binascii()
|
||||
raw: str = "HelloWorld!"
|
||||
raw_length: t.CInt = 11
|
||||
raw_length: int = 11
|
||||
|
||||
hex_out: str = binascii.b2a_hex(raw, raw_length)
|
||||
if hex_out:
|
||||
@@ -90,7 +90,7 @@ def main() -> t.CInt | t.CExport:
|
||||
stdlib.free(hex_out)
|
||||
testcheck.ok("BINASCII b2a_hex completed")
|
||||
|
||||
crc_val: t.CUnsignedInt = binascii.crc32(raw, raw_length, 0)
|
||||
crc_val: uint = binascii.crc32(raw, raw_length, 0)
|
||||
stdio.printf("CRC32: %u\n", crc_val)
|
||||
testcheck.ok("BINASCII crc32 completed")
|
||||
|
||||
@@ -106,7 +106,7 @@ def main() -> t.CInt | t.CExport:
|
||||
stdlib.free(uu_out)
|
||||
testcheck.ok("BINASCII b2a_uu completed")
|
||||
|
||||
hqx_in: t.CArray[t.CChar, 4] = ['A', 'B', 'C', '\0']
|
||||
hqx_in: t.CArray[char, 4] = ['A', 'B', 'C', '\0']
|
||||
hqx_crc: t.CUnsignedShort = 0
|
||||
hqx_out: str
|
||||
unhqx: str
|
||||
@@ -116,7 +116,7 @@ def main() -> t.CInt | t.CExport:
|
||||
stdlib.free(hqx_out); stdlib.free(unhqx)
|
||||
testcheck.ok("BINASCII hqx completed")
|
||||
|
||||
adler_val: t.CUnsignedInt = binascii.adler32(raw, raw_length, 1)
|
||||
adler_val: uint = binascii.adler32(raw, raw_length, 1)
|
||||
stdio.printf("Adler32: %u\n", adler_val)
|
||||
testcheck.ok("BINASCII adler32 completed")
|
||||
|
||||
|
||||
+22
-22
@@ -26,7 +26,7 @@ def main() -> CInt | CExport:
|
||||
ht.set_int("alpha", 10)
|
||||
ht.set_int("beta", 20)
|
||||
ht.set_int("gamma", 30)
|
||||
n: t.CSizeT = len(ht)
|
||||
n: sizet = len(ht)
|
||||
stdio.printf("len=%lu\n", n)
|
||||
testcheck.check(n == 3, "ht len OK (3)", "ht len FAILED")
|
||||
|
||||
@@ -34,11 +34,11 @@ def main() -> CInt | CExport:
|
||||
# 须给出有元素类型的指针:c.Deref 的宽度只认 pointee 类型,i8*(t.CPtr)恒读
|
||||
# 1 字节,不再按赋值目标注解反推 4 字节。
|
||||
p1: t.CPtr = ht["alpha"]
|
||||
v1: int = c.Deref((int | t.CPtr)(p1))
|
||||
v1: int = *(int | t.CPtr)(p1)
|
||||
p2: t.CPtr = ht["beta"]
|
||||
v2: int = c.Deref((int | t.CPtr)(p2))
|
||||
v2: int = *(int | t.CPtr)(p2)
|
||||
p3: t.CPtr = ht["gamma"]
|
||||
v3: int = c.Deref((int | t.CPtr)(p3))
|
||||
v3: int = *(int | t.CPtr)(p3)
|
||||
stdio.printf("alpha=%d beta=%d gamma=%d\n", v1, v2, v3)
|
||||
testcheck.check(v1 == 10, "ht[alpha]==10 OK", "ht[alpha] FAILED")
|
||||
testcheck.check(v2 == 20, "ht[beta]==20 OK", "ht[beta] FAILED")
|
||||
@@ -48,7 +48,7 @@ def main() -> CInt | CExport:
|
||||
testcheck.section("Test 2: 更新已有键")
|
||||
ht.set_int("beta", 99)
|
||||
p2b: t.CPtr = ht["beta"]
|
||||
v2b: int = c.Deref((int | t.CPtr)(p2b))
|
||||
v2b: int = *(int | t.CPtr)(p2b)
|
||||
stdio.printf("beta(updated)=%d\n", v2b)
|
||||
testcheck.check(v2b == 99, "ht update OK", "ht update FAILED")
|
||||
testcheck.check(len(ht) == 3, "ht len still 3 OK", "ht len changed FAILED")
|
||||
@@ -58,36 +58,36 @@ def main() -> CInt | CExport:
|
||||
gv: t.CPtr = ht.get("missing", None)
|
||||
testcheck.check(gv == None, "ht get missing OK (None)", "ht get missing FAILED")
|
||||
gp: t.CPtr = ht.get("alpha", None)
|
||||
ga: int = c.Deref((int | t.CPtr)(gp))
|
||||
ga: int = *(int | t.CPtr)(gp)
|
||||
stdio.printf("get(alpha)=%d\n", ga)
|
||||
testcheck.check(ga == 10, "ht get existing OK", "ht get existing FAILED")
|
||||
|
||||
# === Test 4: contains ===
|
||||
testcheck.section("Test 4: contains (in)")
|
||||
has_alpha: t.CInt = "alpha" in ht
|
||||
has_missing: t.CInt = "missing" in ht
|
||||
has_alpha: int = "alpha" in ht
|
||||
has_missing: int = "missing" in ht
|
||||
stdio.printf("contains(alpha)=%d contains(missing)=%d\n", has_alpha, has_missing)
|
||||
testcheck.check(has_alpha == 1, "contains alpha OK", "contains alpha FAILED")
|
||||
testcheck.check(has_missing == 0, "not contains missing OK", "contains missing FAILED")
|
||||
|
||||
# === Test 5: 删除 ===
|
||||
testcheck.section("Test 5: 删除 (del)")
|
||||
deleted: t.CInt = ht.__delitem__("beta")
|
||||
deleted: int = ht.__delitem__("beta")
|
||||
stdio.printf("del beta=%d\n", deleted)
|
||||
testcheck.check(deleted == 1, "del beta OK", "del beta FAILED")
|
||||
testcheck.check(len(ht) == 2, "ht len 2 after del OK", "ht len after del FAILED")
|
||||
has_beta: t.CInt = "beta" in ht
|
||||
has_beta: int = "beta" in ht
|
||||
testcheck.check(has_beta == 0, "beta gone OK", "beta still exists FAILED")
|
||||
|
||||
# 删除不存在的 key
|
||||
del_missing: t.CInt = ht.__delitem__("nokey")
|
||||
del_missing: int = ht.__delitem__("nokey")
|
||||
testcheck.check(del_missing == 0, "del missing returns 0 OK", "del missing FAILED")
|
||||
|
||||
# === Test 6: 删除后重新插入 ===
|
||||
testcheck.section("Test 6: 删除后重新插入")
|
||||
ht.set_int("beta", 555)
|
||||
p2c: t.CPtr = ht["beta"]
|
||||
v2c: int = c.Deref((int | t.CPtr)(p2c))
|
||||
v2c: int = *(int | t.CPtr)(p2c)
|
||||
stdio.printf("beta(re-inserted)=%d\n", v2c)
|
||||
testcheck.check(v2c == 555, "ht re-insert beta OK", "ht re-insert beta FAILED")
|
||||
testcheck.check(len(ht) == 3, "ht len 3 after re-insert OK", "ht len after re-insert FAILED")
|
||||
@@ -97,7 +97,7 @@ def main() -> CInt | CExport:
|
||||
iter_count: int = 0
|
||||
for key in ht:
|
||||
kp: t.CPtr = ht[key]
|
||||
val: int = c.Deref((int | t.CPtr)(kp))
|
||||
val: int = *(int | t.CPtr)(kp)
|
||||
stdio.printf("ht[%s]=%d\n", key, val)
|
||||
iter_count += 1
|
||||
testcheck.check(iter_count == 3, "ht iter OK (3)", "ht iter FAILED")
|
||||
@@ -108,7 +108,7 @@ def main() -> CInt | CExport:
|
||||
ht2.set_str("name", "Alice")
|
||||
ht2.set_str("city", "Beijing")
|
||||
ht2.set_str("lang", "TransPyC")
|
||||
n2: t.CSizeT = len(ht2)
|
||||
n2: sizet = len(ht2)
|
||||
stdio.printf("ht2 len=%lu\n", n2)
|
||||
testcheck.check(n2 == 3, "ht set_str len OK (3)", "ht set_str len FAILED")
|
||||
|
||||
@@ -133,7 +133,7 @@ def main() -> CInt | CExport:
|
||||
stdio.sprintf(key_buf, "key%d", i)
|
||||
ht3.set_int(key_buf, i * 100)
|
||||
i += 1
|
||||
n3: t.CSizeT = len(ht3)
|
||||
n3: sizet = len(ht3)
|
||||
stdio.printf("ht3 len=%lu (after 50 inserts)\n", n3)
|
||||
testcheck.check(n3 == 50, "ht expand OK (50)", "ht expand FAILED")
|
||||
|
||||
@@ -141,21 +141,21 @@ def main() -> CInt | CExport:
|
||||
k5: str = stdlib.malloc(16)
|
||||
stdio.sprintf(k5, "key5")
|
||||
p5: t.CPtr = ht3[k5]
|
||||
v5: int = c.Deref((int | t.CPtr)(p5))
|
||||
v5: int = *(int | t.CPtr)(p5)
|
||||
stdio.printf("ht3[key5]=%d\n", v5)
|
||||
testcheck.check(v5 == 500, "ht expand key5 OK", "ht expand key5 FAILED")
|
||||
|
||||
k25: str = stdlib.malloc(16)
|
||||
stdio.sprintf(k25, "key25")
|
||||
p25: t.CPtr = ht3[k25]
|
||||
v25: int = c.Deref((int | t.CPtr)(p25))
|
||||
v25: int = *(int | t.CPtr)(p25)
|
||||
stdio.printf("ht3[key25]=%d\n", v25)
|
||||
testcheck.check(v25 == 2500, "ht expand key25 OK", "ht expand key25 FAILED")
|
||||
|
||||
k49: str = stdlib.malloc(16)
|
||||
stdio.sprintf(k49, "key49")
|
||||
p49: t.CPtr = ht3[k49]
|
||||
v49: int = c.Deref((int | t.CPtr)(p49))
|
||||
v49: int = *(int | t.CPtr)(p49)
|
||||
stdio.printf("ht3[key49]=%d\n", v49)
|
||||
testcheck.check(v49 == 4900, "ht expand key49 OK", "ht expand key49 FAILED")
|
||||
|
||||
@@ -175,7 +175,7 @@ def main() -> CInt | CExport:
|
||||
stdio.sprintf(del_buf, "key%d", j)
|
||||
del ht3[del_buf]
|
||||
j += 1
|
||||
n3b: t.CSizeT = len(ht3)
|
||||
n3b: sizet = len(ht3)
|
||||
stdio.printf("ht3 len=%lu (after 25 deletes)\n", n3b)
|
||||
testcheck.check(n3b == 25, "ht after del OK (25)", "ht after del FAILED")
|
||||
|
||||
@@ -183,14 +183,14 @@ def main() -> CInt | CExport:
|
||||
k30: str = stdlib.malloc(16)
|
||||
stdio.sprintf(k30, "key30")
|
||||
p30: t.CPtr = ht3[k30]
|
||||
v30: int = c.Deref((int | t.CPtr)(p30))
|
||||
v30: int = *(int | t.CPtr)(p30)
|
||||
stdio.printf("ht3[key30]=%d\n", v30)
|
||||
testcheck.check(v30 == 3000, "ht key30 after del OK", "ht key30 after del FAILED")
|
||||
|
||||
# 验证已删除的 key 不存在
|
||||
k0: str = stdlib.malloc(16)
|
||||
stdio.sprintf(k0, "key0")
|
||||
has_k0: t.CInt = k0 in ht3
|
||||
has_k0: int = k0 in ht3
|
||||
testcheck.check(has_k0 == 0, "ht key0 deleted OK", "ht key0 still exists FAILED")
|
||||
|
||||
# === Test 12: 空表操作 ===
|
||||
@@ -199,7 +199,7 @@ def main() -> CInt | CExport:
|
||||
testcheck.check(len(ht4) == 0, "empty ht len 0 OK", "empty ht len FAILED")
|
||||
empty_get: t.CPtr = ht4.get("none", None)
|
||||
testcheck.check(empty_get == None, "empty ht get OK", "empty ht get FAILED")
|
||||
has_none: t.CInt = "none" in ht4
|
||||
has_none: int = "none" in ht4
|
||||
testcheck.check(has_none == 0, "empty ht contains OK", "empty ht contains FAILED")
|
||||
empty_iter: int = 0
|
||||
for ek in ht4:
|
||||
|
||||
+10
-10
@@ -5,8 +5,8 @@ import testcheck
|
||||
|
||||
def test_for_in_string():
|
||||
testcheck.section("Test 1: for-in string iteration")
|
||||
s: t.CChar | t.CPtr = "Hello"
|
||||
result: t.CInt = 0
|
||||
s: char | t.CPtr = "Hello"
|
||||
result: int = 0
|
||||
for ch in s:
|
||||
result += ch
|
||||
# H=72, e=101, l=108, l=108, o=111 => 500
|
||||
@@ -14,9 +14,9 @@ def test_for_in_string():
|
||||
|
||||
def test_for_in_char_ptr():
|
||||
testcheck.section("Test 2: for-in char* iteration")
|
||||
s: t.CChar | t.CPtr = "ABC"
|
||||
chars: t.CArray[t.CInt, 4] = [0]
|
||||
idx: t.CInt = 0
|
||||
s: char | t.CPtr = "ABC"
|
||||
chars: t.CArray[int, 4] = [0]
|
||||
idx: int = 0
|
||||
for ch in s:
|
||||
if idx < 3:
|
||||
chars[idx] = ch
|
||||
@@ -25,16 +25,16 @@ def test_for_in_char_ptr():
|
||||
|
||||
def test_strcpy_for_in():
|
||||
testcheck.section("Test 3: strcpy using for-in")
|
||||
src: t.CChar | t.CPtr = "test"
|
||||
src: char | t.CPtr = "test"
|
||||
# 手动实现 strcpy 用 for-in
|
||||
import w32.win32memory
|
||||
buf: t.CChar | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 12288, 4)
|
||||
if t.CUInt64T(buf) == 0:
|
||||
buf: char | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 12288, 4)
|
||||
if uint64(buf) == 0:
|
||||
stdio.printf("SKIP: VirtualAlloc returned NULL\n")
|
||||
return
|
||||
string.memset(buf, 0, 64)
|
||||
# 用 for-in 复制
|
||||
p: t.CChar | t.CPtr = buf
|
||||
p: char | t.CPtr = buf
|
||||
for ch in src:
|
||||
p[0] = ch
|
||||
p += 1
|
||||
@@ -44,7 +44,7 @@ def test_strcpy_for_in():
|
||||
|
||||
import w32.win32memory
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("IterTest: 指针迭代测试")
|
||||
test_for_in_string()
|
||||
test_for_in_char_ptr()
|
||||
|
||||
+11
-11
@@ -147,26 +147,26 @@ def test_write(pool: memhub.MemPool | t.CPtr):
|
||||
|
||||
# 写整数
|
||||
v1: json.JsonValue | t.CPtr = json.int_val(pool, 42)
|
||||
s1: t.CChar | t.CPtr = json.write(pool, v1, False)
|
||||
s1: char | t.CPtr = json.write(pool, v1, False)
|
||||
testcheck.check(string.strcmp(s1, "42") == 0, "write int 42", "write int 42")
|
||||
|
||||
# 写字符串
|
||||
v2: json.JsonValue | t.CPtr = json.string_val(pool, "hello")
|
||||
s2: t.CChar | t.CPtr = json.write(pool, v2, False)
|
||||
s2: char | t.CPtr = json.write(pool, v2, False)
|
||||
testcheck.check(string.strcmp(s2, '"hello"') == 0, "write string hello", "write string hello")
|
||||
|
||||
# 写布尔
|
||||
v3: json.JsonValue | t.CPtr = json.bool_val(pool, True)
|
||||
s3: t.CChar | t.CPtr = json.write(pool, v3, False)
|
||||
s3: char | t.CPtr = json.write(pool, v3, False)
|
||||
testcheck.check(string.strcmp(s3, "true") == 0, "write bool true", "write bool true")
|
||||
|
||||
v4: json.JsonValue | t.CPtr = json.bool_val(pool, False)
|
||||
s4: t.CChar | t.CPtr = json.write(pool, v4, False)
|
||||
s4: char | t.CPtr = json.write(pool, v4, False)
|
||||
testcheck.check(string.strcmp(s4, "false") == 0, "write bool false", "write bool false")
|
||||
|
||||
# 写 null
|
||||
v5: json.JsonValue | t.CPtr = json.null(pool)
|
||||
s5: t.CChar | t.CPtr = json.write(pool, v5, False)
|
||||
s5: char | t.CPtr = json.write(pool, v5, False)
|
||||
testcheck.check(string.strcmp(s5, "null") == 0, "write null", "write null")
|
||||
|
||||
# 写数组
|
||||
@@ -174,14 +174,14 @@ def test_write(pool: memhub.MemPool | t.CPtr):
|
||||
json.array_append(pool, arr, json.int_val(pool, 1))
|
||||
json.array_append(pool, arr, json.int_val(pool, 2))
|
||||
json.array_append(pool, arr, json.int_val(pool, 3))
|
||||
s6: t.CChar | t.CPtr = json.write(pool, arr, False)
|
||||
s6: char | t.CPtr = json.write(pool, arr, False)
|
||||
testcheck.check(string.strcmp(s6, "[1,2,3]") == 0, "write array [1,2,3]", "write array [1,2,3]")
|
||||
|
||||
# 写对象
|
||||
obj: json.JsonValue | t.CPtr = json.object(pool)
|
||||
json.object_set(pool, obj, "a", json.int_val(pool, 1))
|
||||
json.object_set(pool, obj, "b", json.string_val(pool, "x"))
|
||||
s7: t.CChar | t.CPtr = json.write(pool, obj, False)
|
||||
s7: char | t.CPtr = json.write(pool, obj, False)
|
||||
testcheck.check(s7 != None, "write object non-null", "write object non-null")
|
||||
|
||||
|
||||
@@ -191,7 +191,7 @@ def test_write(pool: memhub.MemPool | t.CPtr):
|
||||
def test_nested(pool: memhub.MemPool | t.CPtr):
|
||||
testcheck.section("Parse Nested JSON (Pythonic API)")
|
||||
|
||||
src: t.CChar | t.CPtr = '{"name": "Viper", "version": 1, "features": ["fast", "safe", "portable"], "nested": {"key": "value", "num": 99}}'
|
||||
src: char | t.CPtr = '{"name": "Viper", "version": 1, "features": ["fast", "safe", "portable"], "nested": {"key": "value", "num": 99}}'
|
||||
root: json.JsonValue | t.CPtr = json.parse(pool, src)
|
||||
testcheck.check(root.is_object(), "nested is_object", "nested is_object")
|
||||
testcheck.check(len(root) == 4, "nested len()==4", "nested len()==4")
|
||||
@@ -262,12 +262,12 @@ def test_escape(pool: memhub.MemPool | t.CPtr):
|
||||
# 解析含转义字符的字符串
|
||||
v1: json.JsonValue | t.CPtr = json.parse(pool, '"hello\\nworld"')
|
||||
testcheck.check(v1.is_string(), "escape \\n is_string", "escape \\n is_string")
|
||||
sv1: t.CChar | t.CPtr = v1.as_string()
|
||||
sv1: char | t.CPtr = v1.as_string()
|
||||
testcheck.check(sv1 != None and sv1[5] == '\n', "escape \\n contains newline", "escape \\n contains newline")
|
||||
|
||||
v2: json.JsonValue | t.CPtr = json.parse(pool, '"tab\\there"')
|
||||
testcheck.check(v2.is_string(), "escape \\t is_string", "escape \\t is_string")
|
||||
sv2: t.CChar | t.CPtr = v2.as_string()
|
||||
sv2: char | t.CPtr = v2.as_string()
|
||||
testcheck.check(sv2 != None and sv2[3] == '\t', "escape \\t contains tab", "escape \\t contains tab")
|
||||
|
||||
v3: json.JsonValue | t.CPtr = json.parse(pool, '"quote\\""')
|
||||
@@ -277,7 +277,7 @@ def test_escape(pool: memhub.MemPool | t.CPtr):
|
||||
# ============================================================
|
||||
# 主函数
|
||||
# ============================================================
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
testcheck.begin("JSON Library Test (Pythonic API)")
|
||||
|
||||
# 使用 mpool 的 bump 分配器
|
||||
|
||||
@@ -33,7 +33,7 @@ def main() -> CInt | CExport:
|
||||
|
||||
# === Test 2: __len__ ===
|
||||
testcheck.section("Test 2: __len__")
|
||||
n: t.CSizeT = nums.__len__()
|
||||
n: sizet = nums.__len__()
|
||||
stdio.printf("len=%lu\n", n)
|
||||
testcheck.check(n == 3, "__len__ OK (3)", "__len__ FAILED expect 3")
|
||||
|
||||
@@ -49,13 +49,13 @@ def main() -> CInt | CExport:
|
||||
popped: CInt = nums.pop()
|
||||
stdio.printf("popped=%d\n", popped)
|
||||
testcheck.check(popped == 30, "pop OK (30)", "pop FAILED expect 30")
|
||||
n2: t.CSizeT = nums.__len__()
|
||||
n2: sizet = nums.__len__()
|
||||
testcheck.check(n2 == 2, "pop len OK (2)", "pop len FAILED expect 2")
|
||||
|
||||
# === Test 5: clear ===
|
||||
testcheck.section("Test 5: clear")
|
||||
nums.clear()
|
||||
n3: t.CSizeT = nums.__len__()
|
||||
n3: sizet = nums.__len__()
|
||||
testcheck.check(n3 == 0, "clear OK (0)", "clear FAILED expect 0")
|
||||
|
||||
# === Test 6: 容量增长 (append 超过初始容量 8) ===
|
||||
@@ -64,7 +64,7 @@ def main() -> CInt | CExport:
|
||||
i: CInt
|
||||
for i in range(20):
|
||||
nums2.append(i * 5)
|
||||
n4: t.CSizeT = nums2.__len__()
|
||||
n4: sizet = nums2.__len__()
|
||||
stdio.printf("after 20 appends: len=%lu\n", n4)
|
||||
testcheck.check(n4 == 20, "grow len OK (20)", "grow len FAILED")
|
||||
ok: CInt = 1
|
||||
|
||||
+19
-19
@@ -1,24 +1,24 @@
|
||||
import t, c
|
||||
|
||||
|
||||
POSMAX: t.CDefine = 100
|
||||
MAX_RETRY: t.CDefine = 5
|
||||
BUFFER_SIZE: t.CDefine = 256
|
||||
PI: t.CDefine = 3.14159
|
||||
EULER: t.CDefine = 2.71828
|
||||
TRUE: t.CDefine = 1
|
||||
FALSE: t.CDefine = 0
|
||||
NULL: t.CDefine = 0
|
||||
define POSMAX = 100
|
||||
define MAX_RETRY = 5
|
||||
define BUFFER_SIZE = 256
|
||||
define PI = 3.14159
|
||||
define EULER = 2.71828
|
||||
define TRUE = 1
|
||||
define FALSE = 0
|
||||
define NULL = 0
|
||||
|
||||
|
||||
MATH_OFFSET: t.CDefine = 10
|
||||
MATH_SCALE: t.CDefine = 2
|
||||
THRESHOLD: t.CDefine = 50
|
||||
LOOP_LIMIT: t.CDefine = 20
|
||||
SHIFT_AMOUNT: t.CDefine = 2
|
||||
MASK_VALUE: t.CDefine = 0xFF
|
||||
BIT_RANGE: t.CDefine = 4
|
||||
EXPONENT_BASE: t.CDefine = 3
|
||||
MODULO_DIVISOR: t.CDefine = 7
|
||||
SCALE_SHIFT: t.CDefine = 4
|
||||
HALF_SCALE: t.CDefine = 0.5
|
||||
define MATH_OFFSET = 10
|
||||
define MATH_SCALE = 2
|
||||
define THRESHOLD = 50
|
||||
define LOOP_LIMIT = 20
|
||||
define SHIFT_AMOUNT = 2
|
||||
define MASK_VALUE = 0xFF
|
||||
define BIT_RANGE = 4
|
||||
define EXPONENT_BASE = 3
|
||||
define MODULO_DIVISOR = 7
|
||||
define SCALE_SHIFT = 4
|
||||
define HALF_SCALE = 0.5
|
||||
@@ -2,32 +2,32 @@ import config
|
||||
import t, c
|
||||
|
||||
|
||||
def ForRangeBasicTest(stop: t.CInt):
|
||||
i: t.CInt = 0
|
||||
def ForRangeBasicTest(stop: int):
|
||||
i: int = 0
|
||||
for i in range(stop):
|
||||
print("For range: ", i)
|
||||
print("Done")
|
||||
|
||||
|
||||
def ForRangeWithStartStop(start: t.CInt, stop: t.CInt, step: t.CInt):
|
||||
i: t.CInt = 0
|
||||
def ForRangeWithStartStop(start: int, stop: int, step: int):
|
||||
i: int = 0
|
||||
for i in range(start, stop, step):
|
||||
print("Range: ", i)
|
||||
print("Done")
|
||||
|
||||
|
||||
def NestedForRangeTest(rows: t.CInt, cols: t.CInt):
|
||||
r: t.CInt = 0
|
||||
c_val: t.CInt = 0
|
||||
def NestedForRangeTest(rows: int, cols: int):
|
||||
r: int = 0
|
||||
c_val: int = 0
|
||||
for r in range(rows):
|
||||
for c_val in range(cols):
|
||||
print("Cell: ", r, c_val)
|
||||
print("Grid done")
|
||||
|
||||
|
||||
def ForWithIfBreakTest(data_size: t.CInt):
|
||||
i: t.CInt = 0
|
||||
found: t.CInt = 0
|
||||
def ForWithIfBreakTest(data_size: int):
|
||||
i: int = 0
|
||||
found: int = 0
|
||||
for i in range(data_size):
|
||||
if i == 5:
|
||||
print("Found at: ", i)
|
||||
@@ -38,9 +38,9 @@ def ForWithIfBreakTest(data_size: t.CInt):
|
||||
print("Not found")
|
||||
|
||||
|
||||
def ForWithIfContinueTest(n: t.CInt):
|
||||
i: t.CInt = 0
|
||||
count: t.CInt = 0
|
||||
def ForWithIfContinueTest(n: int):
|
||||
i: int = 0
|
||||
count: int = 0
|
||||
for i in range(n):
|
||||
if i % 2 == 0:
|
||||
continue
|
||||
@@ -49,9 +49,9 @@ def ForWithIfContinueTest(n: t.CInt):
|
||||
print("Total odd: ", count)
|
||||
|
||||
|
||||
def ForWithElifBranchTest(value: t.CInt):
|
||||
i: t.CInt = 0
|
||||
result: t.CInt = 0
|
||||
def ForWithElifBranchTest(value: int):
|
||||
i: int = 0
|
||||
result: int = 0
|
||||
for i in range(value):
|
||||
if i < 3:
|
||||
result += 1
|
||||
@@ -64,8 +64,8 @@ def ForWithElifBranchTest(value: t.CInt):
|
||||
print("Elif branch result: ", result)
|
||||
|
||||
|
||||
def WhileWithIfElifElseTest(iterations: t.CInt):
|
||||
counter: t.CInt = 0
|
||||
def WhileWithIfElifElseTest(iterations: int):
|
||||
counter: int = 0
|
||||
while counter < iterations:
|
||||
if counter < 2:
|
||||
print("Phase 1: ", counter)
|
||||
@@ -79,10 +79,10 @@ def WhileWithIfElifElseTest(iterations: t.CInt):
|
||||
print("While done")
|
||||
|
||||
|
||||
def WhileWithNestedIfTest(limit: t.CInt):
|
||||
outer: t.CInt = 0
|
||||
def WhileWithNestedIfTest(limit: int):
|
||||
outer: int = 0
|
||||
while outer < limit:
|
||||
inner: t.CInt = 0
|
||||
inner: int = 0
|
||||
while inner < limit:
|
||||
if inner == 2 and outer == 1:
|
||||
print("Target: ", outer, inner)
|
||||
@@ -95,8 +95,8 @@ def WhileWithNestedIfTest(limit: t.CInt):
|
||||
outer += 1
|
||||
|
||||
|
||||
def WhileWithMatchCaseTest(value: t.CInt):
|
||||
result: t.CInt = 0
|
||||
def WhileWithMatchCaseTest(value: int):
|
||||
result: int = 0
|
||||
match value:
|
||||
case 1:
|
||||
result = 100
|
||||
@@ -113,8 +113,8 @@ def WhileWithMatchCaseTest(value: t.CInt):
|
||||
print("Match result: ", result)
|
||||
|
||||
|
||||
def WhileWithMatchCaseNoBreakTest(value: t.CInt):
|
||||
result: t.CInt = 0
|
||||
def WhileWithMatchCaseNoBreakTest(value: int):
|
||||
result: int = 0
|
||||
match value:
|
||||
case 1:
|
||||
result = 10
|
||||
@@ -131,10 +131,10 @@ def WhileWithMatchCaseNoBreakTest(value: t.CInt):
|
||||
print("No break match result: ", result)
|
||||
|
||||
|
||||
def ComplexForWhileMatchTest(outer_limit: t.CInt, inner_limit: t.CInt):
|
||||
i: t.CInt = 0
|
||||
j: t.CInt = 0
|
||||
result: t.CInt = 0
|
||||
def ComplexForWhileMatchTest(outer_limit: int, inner_limit: int):
|
||||
i: int = 0
|
||||
j: int = 0
|
||||
result: int = 0
|
||||
for i in range(outer_limit):
|
||||
j = 0
|
||||
while j < inner_limit:
|
||||
@@ -153,9 +153,9 @@ def ComplexForWhileMatchTest(outer_limit: t.CInt, inner_limit: t.CInt):
|
||||
print("Complex match result: ", result)
|
||||
|
||||
|
||||
def ForWithCaseAndNoBreakTest(n: t.CInt):
|
||||
i: t.CInt = 0
|
||||
result: t.CInt = 0
|
||||
def ForWithCaseAndNoBreakTest(n: int):
|
||||
i: int = 0
|
||||
result: int = 0
|
||||
for i in range(n):
|
||||
match i:
|
||||
case 0:
|
||||
@@ -171,9 +171,9 @@ def ForWithCaseAndNoBreakTest(n: t.CInt):
|
||||
print("NoBreak result: ", result)
|
||||
|
||||
|
||||
def WhileWithBreakConditionTest(limit: t.CInt):
|
||||
i: t.CInt = 0
|
||||
early_exit: t.CInt = 0
|
||||
def WhileWithBreakConditionTest(limit: int):
|
||||
i: int = 0
|
||||
early_exit: int = 0
|
||||
while i < limit:
|
||||
if i == 3:
|
||||
early_exit = 1
|
||||
@@ -185,10 +185,10 @@ def WhileWithBreakConditionTest(limit: t.CInt):
|
||||
i += 1
|
||||
|
||||
|
||||
def NestedWhileWithMultipleBreakPoints(depth: t.CInt, width: t.CInt):
|
||||
d: t.CInt = 0
|
||||
w: t.CInt = 0
|
||||
count: t.CInt = 0
|
||||
def NestedWhileWithMultipleBreakPoints(depth: int, width: int):
|
||||
d: int = 0
|
||||
w: int = 0
|
||||
count: int = 0
|
||||
while d < depth:
|
||||
w = 0
|
||||
while w < width:
|
||||
@@ -202,10 +202,10 @@ def NestedWhileWithMultipleBreakPoints(depth: t.CInt, width: t.CInt):
|
||||
print("Nested break count: ", count)
|
||||
|
||||
|
||||
def ForWithMatchCaseInLoopTest(iterations: t.CInt):
|
||||
i: t.CInt = 0
|
||||
sum_even: t.CInt = 0
|
||||
sum_odd: t.CInt = 0
|
||||
def ForWithMatchCaseInLoopTest(iterations: int):
|
||||
i: int = 0
|
||||
sum_even: int = 0
|
||||
sum_odd: int = 0
|
||||
for i in range(iterations):
|
||||
match i % 3:
|
||||
case 0:
|
||||
@@ -220,9 +220,9 @@ def ForWithMatchCaseInLoopTest(iterations: t.CInt):
|
||||
print("Sum odd: ", sum_odd)
|
||||
|
||||
|
||||
def ComplexLogicWithElifChains(a: t.CInt, b: t.CInt, c_val: t.CInt):
|
||||
i: t.CInt = 0
|
||||
result: t.CInt = 0
|
||||
def ComplexLogicWithElifChains(a: int, b: int, c_val: int):
|
||||
i: int = 0
|
||||
result: int = 0
|
||||
while i < 10:
|
||||
if i < a:
|
||||
if i < b:
|
||||
@@ -244,9 +244,9 @@ def ComplexLogicWithElifChains(a: t.CInt, b: t.CInt, c_val: t.CInt):
|
||||
print("Complex elif chain result: ", result)
|
||||
|
||||
|
||||
def ForRangeWithStepAndCondition(n: t.CInt, step: t.CInt):
|
||||
i: t.CInt = 0
|
||||
count: t.CInt = 0
|
||||
def ForRangeWithStepAndCondition(n: int, step: int):
|
||||
i: int = 0
|
||||
count: int = 0
|
||||
for i in range(0, n, step):
|
||||
if i % 2 == 0:
|
||||
print("Even step: ", i)
|
||||
@@ -259,8 +259,8 @@ def ForRangeWithStepAndCondition(n: t.CInt, step: t.CInt):
|
||||
print("Total steps: ", count)
|
||||
|
||||
|
||||
def MatchCaseWithGuardConditions(value: t.CInt):
|
||||
result: t.CInt = 0
|
||||
def MatchCaseWithGuardConditions(value: int):
|
||||
result: int = 0
|
||||
match value:
|
||||
case 1 if config.TRUE == 1:
|
||||
result = 100
|
||||
@@ -273,9 +273,9 @@ def MatchCaseWithGuardConditions(value: t.CInt):
|
||||
print("Guard match result: ", result)
|
||||
|
||||
|
||||
def WhileWithMultipleMatchCases(iterations: t.CInt):
|
||||
i: t.CInt = 0
|
||||
state: t.CInt = 0
|
||||
def WhileWithMultipleMatchCases(iterations: int):
|
||||
i: int = 0
|
||||
state: int = 0
|
||||
while i < iterations:
|
||||
match state:
|
||||
case 0:
|
||||
@@ -291,10 +291,10 @@ def WhileWithMultipleMatchCases(iterations: t.CInt):
|
||||
i += 1
|
||||
|
||||
|
||||
def ForWhileMixWithBreakAndContinue(n: t.CInt):
|
||||
i: t.CInt = 0
|
||||
j: t.CInt = 0
|
||||
count: t.CInt = 0
|
||||
def ForWhileMixWithBreakAndContinue(n: int):
|
||||
i: int = 0
|
||||
j: int = 0
|
||||
count: int = 0
|
||||
for i in range(n):
|
||||
j = 0
|
||||
while j < n:
|
||||
@@ -308,12 +308,12 @@ def ForWhileMixWithBreakAndContinue(n: t.CInt):
|
||||
print("Mix break continue count: ", count)
|
||||
|
||||
|
||||
def ComplexCaseMatchingWithRanges(start: t.CInt, end: t.CInt):
|
||||
i: t.CInt = 0
|
||||
bucket0: t.CInt = 0
|
||||
bucket1: t.CInt = 0
|
||||
bucket2: t.CInt = 0
|
||||
bucket3: t.CInt = 0
|
||||
def ComplexCaseMatchingWithRanges(start: int, end: int):
|
||||
i: int = 0
|
||||
bucket0: int = 0
|
||||
bucket1: int = 0
|
||||
bucket2: int = 0
|
||||
bucket3: int = 0
|
||||
for i in range(start, end):
|
||||
match i:
|
||||
case _ if i < 10:
|
||||
@@ -330,9 +330,9 @@ def ComplexCaseMatchingWithRanges(start: t.CInt, end: t.CInt):
|
||||
print("Bucket3 (>=30): ", bucket3)
|
||||
|
||||
|
||||
def WhileWithElifInElifChain(limit: t.CInt):
|
||||
i: t.CInt = 0
|
||||
result: t.CInt = 0
|
||||
def WhileWithElifInElifChain(limit: int):
|
||||
i: int = 0
|
||||
result: int = 0
|
||||
while i < limit:
|
||||
if i < 2:
|
||||
if i == 0:
|
||||
@@ -355,10 +355,10 @@ def WhileWithElifInElifChain(limit: t.CInt):
|
||||
i += 1
|
||||
|
||||
|
||||
def ForWithCaseNoBreakNested(inner_limit: t.CInt):
|
||||
i: t.CInt = 0
|
||||
j: t.CInt = 0
|
||||
result: t.CInt = 0
|
||||
def ForWithCaseNoBreakNested(inner_limit: int):
|
||||
i: int = 0
|
||||
j: int = 0
|
||||
result: int = 0
|
||||
for i in range(3):
|
||||
for j in range(inner_limit):
|
||||
match j:
|
||||
@@ -377,9 +377,9 @@ def ForWithCaseNoBreakNested(inner_limit: t.CInt):
|
||||
# 期望 limit=5:i=0 走 _ (+0)、i=1 走 case 1 (+100) 后 break 出 match(循环继续)、
|
||||
# i=2 走 case 2 (+10)、i=3 (+3)、i=4 (+4) ⇒ 117
|
||||
# ============================================================
|
||||
def MatchCaseBreakTest(limit: t.CInt) -> t.CInt:
|
||||
i: t.CInt = 0
|
||||
result: t.CInt = 0
|
||||
def MatchCaseBreakTest(limit: int) -> int:
|
||||
i: int = 0
|
||||
result: int = 0
|
||||
for i in range(limit):
|
||||
match i:
|
||||
case 1:
|
||||
@@ -396,8 +396,8 @@ def MatchCaseBreakTest(limit: t.CInt) -> t.CInt:
|
||||
# switch(C switch 语义):默认不穿透;case 体内写 `fallthrough` 才落到下一个 case。
|
||||
# 期望 value=1 → 1+2+3=6;value=2 → 2+3=5;value=3 → 3;其它 → 77
|
||||
# ============================================================
|
||||
def SwitchCaseFallthroughTest(value: t.CInt) -> t.CInt:
|
||||
result: t.CInt = 0
|
||||
def SwitchCaseFallthroughTest(value: int) -> int:
|
||||
result: int = 0
|
||||
switch value:
|
||||
case 1:
|
||||
result += 1
|
||||
@@ -417,9 +417,9 @@ def SwitchCaseFallthroughTest(value: t.CInt) -> t.CInt:
|
||||
# 期望 limit=5:i=0 走 default (+0)、i=1 走 case 1 (+100) 后 break 出 switch、
|
||||
# i=2 走 case 2 (+10)、i=3 (+3)、i=4 (+4) ⇒ 117
|
||||
# ============================================================
|
||||
def SwitchCaseBreakTest(limit: t.CInt) -> t.CInt:
|
||||
i: t.CInt = 0
|
||||
result: t.CInt = 0
|
||||
def SwitchCaseBreakTest(limit: int) -> int:
|
||||
i: int = 0
|
||||
result: int = 0
|
||||
for i in range(limit):
|
||||
switch i:
|
||||
case 1:
|
||||
@@ -436,8 +436,8 @@ def SwitchCaseBreakTest(limit: t.CInt) -> t.CInt:
|
||||
# switch 多值 case:`case 1 | 2:` 命中同一个臂
|
||||
# 期望 value=1 → 10;value=2 → 10;value=3 → 30;其它 → 99
|
||||
# ============================================================
|
||||
def SwitchMultiValueTest(value: t.CInt) -> t.CInt:
|
||||
result: t.CInt = 0
|
||||
def SwitchMultiValueTest(value: int) -> int:
|
||||
result: int = 0
|
||||
switch value:
|
||||
case 1 | 2:
|
||||
result = 10
|
||||
|
||||
@@ -4,7 +4,7 @@ import logic_test
|
||||
import testcheck
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("LogicFlowTest: For/While/Match/控制流测试")
|
||||
|
||||
testcheck.section("For Range Basic Test (stop=5)")
|
||||
|
||||
+19
-19
@@ -1,24 +1,24 @@
|
||||
import t, c
|
||||
|
||||
|
||||
POSMAX: t.CDefine = 100
|
||||
MAX_RETRY: t.CDefine = 5
|
||||
BUFFER_SIZE: t.CDefine = 256
|
||||
PI: t.CDefine = 3.14159
|
||||
EULER: t.CDefine = 2.71828
|
||||
TRUE: t.CDefine = 1
|
||||
FALSE: t.CDefine = 0
|
||||
NULL: t.CDefine = 0
|
||||
define POSMAX = 100
|
||||
define MAX_RETRY = 5
|
||||
define BUFFER_SIZE = 256
|
||||
define PI = 3.14159
|
||||
define EULER = 2.71828
|
||||
define TRUE = 1
|
||||
define FALSE = 0
|
||||
define NULL = 0
|
||||
|
||||
|
||||
MATH_OFFSET: t.CDefine = 10
|
||||
MATH_SCALE: t.CDefine = 2
|
||||
THRESHOLD: t.CDefine = 50
|
||||
LOOP_LIMIT: t.CDefine = 20
|
||||
SHIFT_AMOUNT: t.CDefine = 2
|
||||
MASK_VALUE: t.CDefine = 0xFF
|
||||
BIT_RANGE: t.CDefine = 4
|
||||
EXPONENT_BASE: t.CDefine = 3
|
||||
MODULO_DIVISOR: t.CDefine = 7
|
||||
SCALE_SHIFT: t.CDefine = 4
|
||||
HALF_SCALE: t.CDefine = 0.5
|
||||
define MATH_OFFSET = 10
|
||||
define MATH_SCALE = 2
|
||||
define THRESHOLD = 50
|
||||
define LOOP_LIMIT = 20
|
||||
define SHIFT_AMOUNT = 2
|
||||
define MASK_VALUE = 0xFF
|
||||
define BIT_RANGE = 4
|
||||
define EXPONENT_BASE = 3
|
||||
define MODULO_DIVISOR = 7
|
||||
define SCALE_SHIFT = 4
|
||||
define HALF_SCALE = 0.5
|
||||
@@ -5,7 +5,7 @@ import test
|
||||
import testcheck
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("LoopMathTest: While/数学/跨模块宏测试")
|
||||
|
||||
testcheck.section("Cross-module macros")
|
||||
|
||||
+56
-56
@@ -2,8 +2,8 @@ import config
|
||||
import t, c
|
||||
|
||||
|
||||
def AboutSizeTWhileTest(length: t.CSizeT):
|
||||
pos: t.CSizeT = 0
|
||||
def AboutSizeTWhileTest(length: sizet):
|
||||
pos: sizet = 0
|
||||
while pos < length:
|
||||
print("Pos: ", pos)
|
||||
if pos > config.POSMAX: break
|
||||
@@ -24,8 +24,8 @@ def AboutSizeTWhileTest(length: t.CSizeT):
|
||||
pos += 1
|
||||
|
||||
|
||||
def MathBasicTest(x: t.CInt, y: t.CInt) -> t.CInt:
|
||||
result: t.CInt = 0
|
||||
def MathBasicTest(x: int, y: int) -> int:
|
||||
result: int = 0
|
||||
result = x + y
|
||||
print("Add: ", result)
|
||||
result = x - y
|
||||
@@ -40,15 +40,15 @@ def MathBasicTest(x: t.CInt, y: t.CInt) -> t.CInt:
|
||||
return result
|
||||
|
||||
|
||||
def MathAdvancedTest(value: t.CInt) -> t.CInt:
|
||||
counter: t.CInt = 0
|
||||
scaled: t.CInt = 0
|
||||
offset: t.CInt = 0
|
||||
def MathAdvancedTest(value: int) -> int:
|
||||
counter: int = 0
|
||||
scaled: int = 0
|
||||
offset: int = 0
|
||||
scaled = value * config.MATH_SCALE
|
||||
print("Scaled: ", scaled)
|
||||
offset = scaled + config.MATH_OFFSET
|
||||
print("Offset: ", offset)
|
||||
threshold: t.CInt = config.THRESHOLD
|
||||
threshold: int = config.THRESHOLD
|
||||
if offset > threshold:
|
||||
print("Above threshold")
|
||||
counter = 1
|
||||
@@ -61,8 +61,8 @@ def MathAdvancedTest(value: t.CInt) -> t.CInt:
|
||||
return counter
|
||||
|
||||
|
||||
def WhileWithElifElseTest(start: t.CInt, end: t.CInt):
|
||||
idx: t.CInt = start
|
||||
def WhileWithElifElseTest(start: int, end: int):
|
||||
idx: int = start
|
||||
while idx < end:
|
||||
if idx < 0:
|
||||
print("Negative: ", idx)
|
||||
@@ -77,10 +77,10 @@ def WhileWithElifElseTest(start: t.CInt, end: t.CInt):
|
||||
idx += 1
|
||||
|
||||
|
||||
def NestedWhileWithMacrosTest(outer_limit: t.CInt, inner_limit: t.CInt):
|
||||
outer: t.CInt = 0
|
||||
inner: t.CInt = 0
|
||||
total_ops: t.CInt = 0
|
||||
def NestedWhileWithMacrosTest(outer_limit: int, inner_limit: int):
|
||||
outer: int = 0
|
||||
inner: int = 0
|
||||
total_ops: int = 0
|
||||
while outer < outer_limit:
|
||||
inner = 0
|
||||
while inner < inner_limit:
|
||||
@@ -92,10 +92,10 @@ def NestedWhileWithMacrosTest(outer_limit: t.CInt, inner_limit: t.CInt):
|
||||
print("Total operations: ", total_ops)
|
||||
|
||||
|
||||
def ComplexConditionTest(a: t.CInt, b: t.CInt, c_val: t.CInt):
|
||||
x: t.CInt = a
|
||||
y: t.CInt = b
|
||||
z: t.CInt = c_val
|
||||
def ComplexConditionTest(a: int, b: int, c_val: int):
|
||||
x: int = a
|
||||
y: int = b
|
||||
z: int = c_val
|
||||
while x < config.LOOP_LIMIT:
|
||||
if x > 0 and y > 0 and z > 0:
|
||||
print("All positive: ", x, y, z)
|
||||
@@ -113,9 +113,9 @@ def ComplexConditionTest(a: t.CInt, b: t.CInt, c_val: t.CInt):
|
||||
z += 1
|
||||
|
||||
|
||||
def RetryLoopTest(retry_count: t.CInt) -> t.CInt:
|
||||
attempt: t.CInt = 0
|
||||
success: t.CInt = 0
|
||||
def RetryLoopTest(retry_count: int) -> int:
|
||||
attempt: int = 0
|
||||
success: int = 0
|
||||
while attempt < retry_count:
|
||||
if attempt < config.MAX_RETRY:
|
||||
print("Attempt: ", attempt, " less than max")
|
||||
@@ -130,12 +130,12 @@ def RetryLoopTest(retry_count: t.CInt) -> t.CInt:
|
||||
return success
|
||||
|
||||
|
||||
def BitwiseOperationsTest(value: t.CInt) -> t.CInt:
|
||||
shifted: t.CInt = 0
|
||||
masked: t.CInt = 0
|
||||
xored: t.CInt = 0
|
||||
anded: t.CInt = 0
|
||||
ored: t.CInt = 0
|
||||
def BitwiseOperationsTest(value: int) -> int:
|
||||
shifted: int = 0
|
||||
masked: int = 0
|
||||
xored: int = 0
|
||||
anded: int = 0
|
||||
ored: int = 0
|
||||
shifted = value << config.SHIFT_AMOUNT
|
||||
print("Left shift: ", shifted)
|
||||
shifted = value >> config.SHIFT_AMOUNT
|
||||
@@ -151,10 +151,10 @@ def BitwiseOperationsTest(value: t.CInt) -> t.CInt:
|
||||
return masked
|
||||
|
||||
|
||||
def CompoundAssignmentMathTest(a: t.CInt, b: t.CInt) -> t.CInt:
|
||||
x: t.CInt = a
|
||||
y: t.CInt = b
|
||||
result: t.CInt = 0
|
||||
def CompoundAssignmentMathTest(a: int, b: int) -> int:
|
||||
x: int = a
|
||||
y: int = b
|
||||
result: int = 0
|
||||
x += y
|
||||
print("x += y: ", x)
|
||||
x -= y
|
||||
@@ -186,10 +186,10 @@ def CompoundAssignmentMathTest(a: t.CInt, b: t.CInt) -> t.CInt:
|
||||
return result
|
||||
|
||||
|
||||
def PowerAndModuloTest(base: t.CInt, exponent: t.CInt) -> t.CInt:
|
||||
result: t.CInt = 1
|
||||
temp: t.CInt = 0
|
||||
i: t.CInt = 0
|
||||
def PowerAndModuloTest(base: int, exponent: int) -> int:
|
||||
result: int = 1
|
||||
temp: int = 0
|
||||
i: int = 0
|
||||
while i < exponent:
|
||||
result *= base
|
||||
i += 1
|
||||
@@ -203,8 +203,8 @@ def PowerAndModuloTest(base: t.CInt, exponent: t.CInt) -> t.CInt:
|
||||
return result
|
||||
|
||||
|
||||
def MixedArithmeticTest(x: t.CInt, y: t.CInt, z: t.CInt) -> t.CInt:
|
||||
result: t.CInt = 0
|
||||
def MixedArithmeticTest(x: int, y: int, z: int) -> int:
|
||||
result: int = 0
|
||||
result = (x + y) * z
|
||||
print("(x+y)*z: ", result)
|
||||
result = x + (y * z)
|
||||
@@ -215,7 +215,7 @@ def MixedArithmeticTest(x: t.CInt, y: t.CInt, z: t.CInt) -> t.CInt:
|
||||
print("x*scale + y*scale: ", result)
|
||||
result = ((x % config.MODULO_DIVISOR) + (y % config.MODULO_DIVISOR)) * config.MATH_SCALE
|
||||
print("(x%%mod + y%%mod)*scale: ", result)
|
||||
temp: t.CInt = 0
|
||||
temp: int = 0
|
||||
temp = x | y & z
|
||||
print("x | y & z: ", temp)
|
||||
temp = (x | y) & z
|
||||
@@ -225,12 +225,12 @@ def MixedArithmeticTest(x: t.CInt, y: t.CInt, z: t.CInt) -> t.CInt:
|
||||
return result
|
||||
|
||||
|
||||
def MathWithWhileLoopTest(start: t.CInt, count: t.CInt) -> t.CInt:
|
||||
idx: t.CInt = 0
|
||||
accumulator: t.CInt = 0
|
||||
multiplier: t.CInt = config.MATH_SCALE
|
||||
def MathWithWhileLoopTest(start: int, count: int) -> int:
|
||||
idx: int = 0
|
||||
accumulator: int = 0
|
||||
multiplier: int = config.MATH_SCALE
|
||||
while idx < count:
|
||||
temp: t.CInt = (start + idx) * multiplier
|
||||
temp: int = (start + idx) * multiplier
|
||||
temp = temp + config.MATH_OFFSET
|
||||
if temp > config.THRESHOLD:
|
||||
temp = config.THRESHOLD
|
||||
@@ -241,11 +241,11 @@ def MathWithWhileLoopTest(start: t.CInt, count: t.CInt) -> t.CInt:
|
||||
return accumulator
|
||||
|
||||
|
||||
def ComplexNestedMathTest(a: t.CInt, b: t.CInt) -> t.CInt:
|
||||
layer1: t.CInt = 0
|
||||
layer2: t.CInt = 0
|
||||
layer3: t.CInt = 0
|
||||
i: t.CInt = 0
|
||||
def ComplexNestedMathTest(a: int, b: int) -> int:
|
||||
layer1: int = 0
|
||||
layer2: int = 0
|
||||
layer3: int = 0
|
||||
i: int = 0
|
||||
layer1 = (a + b) * config.MATH_SCALE
|
||||
print("Layer1: ", layer1)
|
||||
while i < config.BIT_RANGE:
|
||||
@@ -259,9 +259,9 @@ def ComplexNestedMathTest(a: t.CInt, b: t.CInt) -> t.CInt:
|
||||
return layer3
|
||||
|
||||
|
||||
def ConditionalMathChainTest(value: t.CInt) -> t.CInt:
|
||||
result: t.CInt = 0
|
||||
step: t.CInt = 0
|
||||
def ConditionalMathChainTest(value: int) -> int:
|
||||
result: int = 0
|
||||
step: int = 0
|
||||
while step < config.LOOP_LIMIT:
|
||||
if step < 5:
|
||||
result += step * config.MATH_SCALE
|
||||
@@ -279,10 +279,10 @@ def ConditionalMathChainTest(value: t.CInt) -> t.CInt:
|
||||
return result
|
||||
|
||||
|
||||
def BitManipulationMathTest(value: t.CInt) -> t.CInt:
|
||||
original: t.CInt = value
|
||||
nibble: t.CInt = 0
|
||||
result: t.CInt = 0
|
||||
def BitManipulationMathTest(value: int) -> int:
|
||||
original: int = value
|
||||
nibble: int = 0
|
||||
result: int = 0
|
||||
result = (value << config.SHIFT_AMOUNT) | (value >> (8 - config.SHIFT_AMOUNT))
|
||||
print("Rotate left: ", result)
|
||||
result = (value >> config.SHIFT_AMOUNT) | (value << (8 - config.SHIFT_AMOUNT))
|
||||
|
||||
+10
-10
@@ -4,7 +4,7 @@ import testcheck
|
||||
|
||||
def test_for_loop():
|
||||
testcheck.section("Test 1: for loop")
|
||||
sum_val: t.CInt = 0
|
||||
sum_val: int = 0
|
||||
for i in range(10):
|
||||
sum_val += i
|
||||
# 0+1+2+...+9 = 45
|
||||
@@ -12,8 +12,8 @@ def test_for_loop():
|
||||
|
||||
def test_while_loop():
|
||||
testcheck.section("Test 2: while loop")
|
||||
n: t.CInt = 100
|
||||
count: t.CInt = 0
|
||||
n: int = 100
|
||||
count: int = 0
|
||||
while n > 1:
|
||||
if n % 2 == 0:
|
||||
n = n // 2
|
||||
@@ -25,7 +25,7 @@ def test_while_loop():
|
||||
|
||||
def test_nested_loop():
|
||||
testcheck.section("Test 3: nested loop")
|
||||
count: t.CInt = 0
|
||||
count: int = 0
|
||||
for i in range(5):
|
||||
for j in range(5):
|
||||
if i < j:
|
||||
@@ -35,7 +35,7 @@ def test_nested_loop():
|
||||
|
||||
def test_break():
|
||||
testcheck.section("Test 4: break")
|
||||
found: t.CInt = -1
|
||||
found: int = -1
|
||||
for i in range(100):
|
||||
if i * i > 50:
|
||||
found = i
|
||||
@@ -45,7 +45,7 @@ def test_break():
|
||||
|
||||
def test_continue():
|
||||
testcheck.section("Test 5: continue")
|
||||
sum_val: t.CInt = 0
|
||||
sum_val: int = 0
|
||||
for i in range(20):
|
||||
if i % 3 == 0:
|
||||
continue
|
||||
@@ -55,7 +55,7 @@ def test_continue():
|
||||
|
||||
def test_range_step():
|
||||
testcheck.section("Test 6: range with step")
|
||||
sum_val: t.CInt = 0
|
||||
sum_val: int = 0
|
||||
for i in range(0, 20, 3):
|
||||
sum_val += i
|
||||
# 0+3+6+9+12+15+18 = 63
|
||||
@@ -63,13 +63,13 @@ def test_range_step():
|
||||
|
||||
def test_loop_u64():
|
||||
testcheck.section("Test 7: loop with u64 counter")
|
||||
total: t.CUInt64T = 0
|
||||
total: uint64 = 0
|
||||
for i in range(100):
|
||||
total += t.CUInt64T(i)
|
||||
total += uint64(i)
|
||||
# 0+1+2+...+99 = 4950
|
||||
testcheck.check(total == 4950, "u64 loop (total=4950)", "u64 loop (expect 4950)")
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("LoopTest: 循环与控制流基准测试")
|
||||
test_for_loop()
|
||||
test_while_loop()
|
||||
|
||||
+11
-11
@@ -7,7 +7,7 @@ import memhub
|
||||
|
||||
|
||||
# 多态测试: 通过 MemManager 基类指针调用, 验证 vtable 分派到正确子类
|
||||
def test_polymorphic(mgr: memhub.MemManager | t.CPtr, size: t.CSizeT) -> t.CInt:
|
||||
def test_polymorphic(mgr: memhub.MemManager | t.CPtr, size: sizet) -> int:
|
||||
p: t.CPtr = mgr.alloc(size)
|
||||
if p is None:
|
||||
return 0
|
||||
@@ -16,12 +16,12 @@ def test_polymorphic(mgr: memhub.MemManager | t.CPtr, size: t.CSizeT) -> t.CInt:
|
||||
|
||||
|
||||
# 测试 calloc 多态: calloc 是 MemManager 具体方法, 内部调 self.alloc (虚函数)
|
||||
def test_calloc_polymorphic(mgr: memhub.MemManager | t.CPtr) -> t.CInt:
|
||||
def test_calloc_polymorphic(mgr: memhub.MemManager | t.CPtr) -> int:
|
||||
p: t.CPtr = mgr.calloc(4, 8)
|
||||
if p is None:
|
||||
return 0
|
||||
# 验证清零: 读第一个字节应为 0
|
||||
first_byte: t.CUInt8T = t.CUInt8T(c.Deref(t.CUInt64T(p, t.CPtr)))
|
||||
first_byte: uint8 = uint8(*uint64(p, t.CPtr))
|
||||
if first_byte != 0:
|
||||
return 0
|
||||
return 1
|
||||
@@ -42,11 +42,11 @@ def main() -> int:
|
||||
testcheck.check(p1 is not None, "MemPool alloc 100", "FAIL")
|
||||
p2: t.CPtr = pool.alloc(200)
|
||||
testcheck.check(p2 is not None, "MemPool alloc 200", "FAIL")
|
||||
testcheck.check(t.CUInt64T(p1) != t.CUInt64T(p2), "MemPool different ptrs", "FAIL")
|
||||
testcheck.check(uint64(p1) != uint64(p2), "MemPool different ptrs", "FAIL")
|
||||
pool.reset()
|
||||
p3: t.CPtr = pool.alloc(100)
|
||||
testcheck.check(p3 is not None, "MemPool alloc after reset", "FAIL")
|
||||
testcheck.check(t.CUInt64T(p3) == t.CUInt64T(p1), "MemPool reset reuses addr", "FAIL")
|
||||
testcheck.check(uint64(p3) == uint64(p1), "MemPool reset reuses addr", "FAIL")
|
||||
|
||||
# ========== MemSlab (fixed block) ==========
|
||||
testcheck.section("MemSlab (fixed block)")
|
||||
@@ -60,7 +60,7 @@ def main() -> int:
|
||||
slab.free(s1)
|
||||
s4: t.CPtr = slab.alloc(32)
|
||||
testcheck.check(s4 is not None, "MemSlab alloc after free", "FAIL")
|
||||
testcheck.check(t.CUInt64T(s4) == t.CUInt64T(s1), "MemSlab free reuse addr", "FAIL")
|
||||
testcheck.check(uint64(s4) == uint64(s1), "MemSlab free reuse addr", "FAIL")
|
||||
|
||||
# ========== MemBuddy (buddy system) ==========
|
||||
testcheck.section("MemBuddy (buddy system)")
|
||||
@@ -78,17 +78,17 @@ def main() -> int:
|
||||
|
||||
# ========== 多态分派 (核心测试) ==========
|
||||
testcheck.section("polymorphic dispatch")
|
||||
r1: t.CInt = test_polymorphic(pool, 50)
|
||||
r1: int = test_polymorphic(pool, 50)
|
||||
testcheck.check(r1 == 1, "vtable: MemPool.alloc/free via MemManager", "FAIL")
|
||||
r2: t.CInt = test_polymorphic(slab, 32)
|
||||
r2: int = test_polymorphic(slab, 32)
|
||||
testcheck.check(r2 == 1, "vtable: MemSlab.alloc/free via MemManager", "FAIL")
|
||||
r3: t.CInt = test_polymorphic(buddy, 50)
|
||||
r3: int = test_polymorphic(buddy, 50)
|
||||
testcheck.check(r3 == 1, "vtable: MemBuddy.alloc/free via MemManager", "FAIL")
|
||||
|
||||
# calloc 多态 (具体方法调虚函数)
|
||||
rc1: t.CInt = test_calloc_polymorphic(pool)
|
||||
rc1: int = test_calloc_polymorphic(pool)
|
||||
testcheck.check(rc1 == 1, "vtable: calloc dispatches MemPool.alloc", "FAIL")
|
||||
rc2: t.CInt = test_calloc_polymorphic(buddy)
|
||||
rc2: int = test_calloc_polymorphic(buddy)
|
||||
testcheck.check(rc2 == 1, "vtable: calloc dispatches MemBuddy.alloc", "FAIL")
|
||||
|
||||
stdlib.free(arena1)
|
||||
|
||||
@@ -3,7 +3,7 @@ import testcheck
|
||||
import mpooltest
|
||||
|
||||
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
testcheck.begin("MpoolOopTest: MemPool OOP 测试")
|
||||
testcheck.section("MPool OOP")
|
||||
mpooltest.mpool_main()
|
||||
|
||||
+25
-25
@@ -35,8 +35,8 @@ def main() -> CInt | CExport:
|
||||
failed: CInt = 0
|
||||
|
||||
# --- 分配 dump 缓冲区(用于 AST 反向输出测试) ---
|
||||
DUMP_BUF_SIZE: t.CSizeT = 8192
|
||||
dump_buf: t.CChar | CPtr = stdlib.malloc(DUMP_BUF_SIZE)
|
||||
DUMP_BUF_SIZE: sizet = 8192
|
||||
dump_buf: char | CPtr = stdlib.malloc(DUMP_BUF_SIZE)
|
||||
if dump_buf is None:
|
||||
printf("FAIL: dump_buf alloc failed\n")
|
||||
stdlib.free(arena)
|
||||
@@ -120,7 +120,7 @@ def main() -> CInt | CExport:
|
||||
else:
|
||||
body.append(binop)
|
||||
body.append(unary)
|
||||
cnt: t.CSizeT = body.__len__()
|
||||
cnt: sizet = body.__len__()
|
||||
if cnt == 2:
|
||||
passed += 1
|
||||
printf("PASS: list append x2, count=%zu\n", cnt)
|
||||
@@ -210,7 +210,7 @@ def main() -> CInt | CExport:
|
||||
printf("PASS: If, kind=%d\n", if_stmt.kind())
|
||||
|
||||
# --- Test 15: Compare 节点 ---
|
||||
cmp_ops: list[t.CInt] | CPtr = list[t.CInt](pool)
|
||||
cmp_ops: list[int] | CPtr = list[int](pool)
|
||||
cmp_ops.append(OpKind.Lt)
|
||||
cmp_comparators: list[AST | CPtr] | CPtr = list[AST | CPtr](pool, 8)
|
||||
cmp_comparators.append(int_42)
|
||||
@@ -269,7 +269,7 @@ def main() -> CInt | CExport:
|
||||
|
||||
# --- Test 20: Module.children 遍历 ---
|
||||
if mod is not None and mod.children is not None:
|
||||
mod_cnt: t.CSizeT = mod.children.__len__()
|
||||
mod_cnt: sizet = mod.children.__len__()
|
||||
if mod_cnt == 2:
|
||||
passed += 1
|
||||
printf("PASS: Module.children count=%zu (expected 2)\n", mod_cnt)
|
||||
@@ -302,7 +302,7 @@ def main() -> CInt | CExport:
|
||||
|
||||
# --- Test 22: If.children 遍历 (ret + expr_stmt) ---
|
||||
if if_stmt is not None and if_stmt.children is not None:
|
||||
if_cnt: t.CSizeT = if_stmt.children.__len__()
|
||||
if_cnt: sizet = if_stmt.children.__len__()
|
||||
if if_cnt == 2:
|
||||
passed += 1
|
||||
printf("PASS: If.children count=%zu (expected 2)\n", if_cnt)
|
||||
@@ -348,7 +348,7 @@ def main() -> CInt | CExport:
|
||||
|
||||
# --- Test 26: parse 模块的 children 验证 ---
|
||||
if parsed_mod is not None and parsed_mod.children is not None:
|
||||
pmod_cnt: t.CSizeT = parsed_mod.children.__len__()
|
||||
pmod_cnt: sizet = parsed_mod.children.__len__()
|
||||
if pmod_cnt == 1:
|
||||
passed += 1
|
||||
printf("PASS: parsed Module.children count=%zu (expected 1)\n", pmod_cnt)
|
||||
@@ -385,7 +385,7 @@ c = a + b
|
||||
"""
|
||||
multi_mod: Module | CPtr = parse(multi_src, pool)
|
||||
if multi_mod is not None and multi_mod.children is not None:
|
||||
multi_cnt: t.CSizeT = multi_mod.children.__len__()
|
||||
multi_cnt: sizet = multi_mod.children.__len__()
|
||||
if multi_cnt == 3:
|
||||
passed += 1
|
||||
printf("PASS: parse multi-stmt, children=%zu (expected 3)\n", multi_cnt)
|
||||
@@ -402,7 +402,7 @@ c = a + b
|
||||
"""
|
||||
if_mod: Module | CPtr = parse(if_src, pool)
|
||||
if if_mod is not None and if_mod.children is not None:
|
||||
if_cnt2: t.CSizeT = if_mod.children.__len__()
|
||||
if_cnt2: sizet = if_mod.children.__len__()
|
||||
if_k: CInt = if_mod.children.get(0).kind()
|
||||
if if_cnt2 == 1 and if_k == ASTKind.If:
|
||||
passed += 1
|
||||
@@ -420,7 +420,7 @@ c = a + b
|
||||
"""
|
||||
for_mod: Module | CPtr = parse(for_src, pool)
|
||||
if for_mod is not None and for_mod.children is not None:
|
||||
for_cnt: t.CSizeT = for_mod.children.__len__()
|
||||
for_cnt: sizet = for_mod.children.__len__()
|
||||
for_k: CInt = for_mod.children.get(0).kind()
|
||||
if for_cnt == 1 and for_k == ASTKind.For:
|
||||
passed += 1
|
||||
@@ -438,7 +438,7 @@ c = a + b
|
||||
"""
|
||||
while_mod: Module | CPtr = parse(while_src, pool)
|
||||
if while_mod is not None and while_mod.children is not None:
|
||||
while_cnt: t.CSizeT = while_mod.children.__len__()
|
||||
while_cnt: sizet = while_mod.children.__len__()
|
||||
while_k: CInt = while_mod.children.get(0).kind()
|
||||
if while_cnt == 1 and while_k == ASTKind.While:
|
||||
passed += 1
|
||||
@@ -456,7 +456,7 @@ c = a + b
|
||||
"""
|
||||
def_mod: Module | CPtr = parse(def_src, pool)
|
||||
if def_mod is not None and def_mod.children is not None:
|
||||
def_cnt: t.CSizeT = def_mod.children.__len__()
|
||||
def_cnt: sizet = def_mod.children.__len__()
|
||||
def_k: CInt = def_mod.children.get(0).kind()
|
||||
if def_cnt == 1 and def_k == ASTKind.FunctionDef:
|
||||
passed += 1
|
||||
@@ -490,7 +490,7 @@ c = a + b
|
||||
"""
|
||||
nested_mod: Module | CPtr = parse(nested_src, pool)
|
||||
if nested_mod is not None and nested_mod.children is not None:
|
||||
nested_cnt: t.CSizeT = nested_mod.children.__len__()
|
||||
nested_cnt: sizet = nested_mod.children.__len__()
|
||||
nested_k: CInt = nested_mod.children.get(0).kind()
|
||||
if nested_cnt == 1 and nested_k == ASTKind.For:
|
||||
passed += 1
|
||||
@@ -513,7 +513,7 @@ w = z * 2
|
||||
"""
|
||||
mixed_mod: Module | CPtr = parse(mixed_src, pool)
|
||||
if mixed_mod is not None and mixed_mod.children is not None:
|
||||
mixed_cnt: t.CSizeT = mixed_mod.children.__len__()
|
||||
mixed_cnt: sizet = mixed_mod.children.__len__()
|
||||
if mixed_cnt == 4:
|
||||
passed += 1
|
||||
printf("PASS: parse mixed module, children=%zu (expected 4)\n", mixed_cnt)
|
||||
@@ -640,7 +640,7 @@ w = z * 2
|
||||
"""
|
||||
class_mod: Module | CPtr = parse(class_src, pool)
|
||||
if class_mod is not None and class_mod.children is not None:
|
||||
class_cnt: t.CSizeT = class_mod.children.__len__()
|
||||
class_cnt: sizet = class_mod.children.__len__()
|
||||
class_k: CInt = class_mod.children.get(0).kind()
|
||||
if class_cnt == 1 and class_k == ASTKind.ClassDef:
|
||||
passed += 1
|
||||
@@ -660,7 +660,7 @@ except:
|
||||
"""
|
||||
try_mod: Module | CPtr = parse(try_src, pool)
|
||||
if try_mod is not None and try_mod.children is not None:
|
||||
try_cnt: t.CSizeT = try_mod.children.__len__()
|
||||
try_cnt: sizet = try_mod.children.__len__()
|
||||
try_k: CInt = try_mod.children.get(0).kind()
|
||||
if try_cnt == 1 and try_k == ASTKind.Try:
|
||||
passed += 1
|
||||
@@ -678,7 +678,7 @@ from sys import path
|
||||
"""
|
||||
import_mod: Module | CPtr = parse(import_src, pool)
|
||||
if import_mod is not None and import_mod.children is not None:
|
||||
import_cnt: t.CSizeT = import_mod.children.__len__()
|
||||
import_cnt: sizet = import_mod.children.__len__()
|
||||
k0: CInt = import_mod.children.get(0).kind()
|
||||
k1: CInt = import_mod.children.get(1).kind()
|
||||
if import_cnt == 2 and k0 == ASTKind.Import and k1 == ASTKind.ImportFrom:
|
||||
@@ -698,7 +698,7 @@ x += 1
|
||||
"""
|
||||
aug_mod: Module | CPtr = parse(aug_src, pool)
|
||||
if aug_mod is not None and aug_mod.children is not None:
|
||||
aug_cnt: t.CSizeT = aug_mod.children.__len__()
|
||||
aug_cnt: sizet = aug_mod.children.__len__()
|
||||
aug_k: CInt = aug_mod.children.get(1).kind()
|
||||
if aug_cnt == 2 and aug_k == ASTKind.AugAssign:
|
||||
passed += 1
|
||||
@@ -735,7 +735,7 @@ x += 1
|
||||
"""
|
||||
nested_def_mod: Module | CPtr = parse(nested_def_src, pool)
|
||||
if nested_def_mod is not None and nested_def_mod.children is not None:
|
||||
nd_cnt: t.CSizeT = nested_def_mod.children.__len__()
|
||||
nd_cnt: sizet = nested_def_mod.children.__len__()
|
||||
nd_k: CInt = nested_def_mod.children.get(0).kind()
|
||||
if nd_cnt == 1 and nd_k == ASTKind.FunctionDef:
|
||||
passed += 1
|
||||
@@ -791,7 +791,7 @@ else:
|
||||
"""
|
||||
cmix_mod: Module | CPtr = parse(complex_mixed_src, pool)
|
||||
if cmix_mod is not None and cmix_mod.children is not None:
|
||||
cmix_cnt: t.CSizeT = cmix_mod.children.__len__()
|
||||
cmix_cnt: sizet = cmix_mod.children.__len__()
|
||||
dump(cmix_mod, dump_buf, DUMP_BUF_SIZE)
|
||||
printf("--- AST dump of complex mixed ---\n%s\n--- end dump ---\n", dump_buf)
|
||||
cm_def: str = string.strstr(dump_buf, "FunctionDef")
|
||||
@@ -800,7 +800,7 @@ else:
|
||||
cm_bool: str = string.strstr(dump_buf, "BoolOp(")
|
||||
cm_cmp: str = string.strstr(dump_buf, "Compare(")
|
||||
cm_ret: str = string.strstr(dump_buf, "Return(")
|
||||
ok: t.CInt = 0
|
||||
ok: int = 0
|
||||
if cmix_cnt == 3:
|
||||
if cm_def is not None and cm_while is not None:
|
||||
if cm_call is not None and cm_bool is not None:
|
||||
@@ -1524,7 +1524,7 @@ class C(Base1, Base2):
|
||||
"""
|
||||
adef_mod: Module | CPtr = parse(adef_src, pool)
|
||||
if adef_mod is not None and adef_mod.children is not None:
|
||||
adef_cnt: t.CSizeT = adef_mod.children.__len__()
|
||||
adef_cnt: sizet = adef_mod.children.__len__()
|
||||
if adef_cnt == 1:
|
||||
adef_child: AST | CPtr = adef_mod.children.get(0)
|
||||
if adef_child is not None and adef_child.kind() == ASTKind.FunctionDef:
|
||||
@@ -1553,7 +1553,7 @@ class C(Base1, Base2):
|
||||
"""
|
||||
afor_mod: Module | CPtr = parse(afor_src, pool)
|
||||
if afor_mod is not None and afor_mod.children is not None:
|
||||
afor_cnt: t.CSizeT = afor_mod.children.__len__()
|
||||
afor_cnt: sizet = afor_mod.children.__len__()
|
||||
if afor_cnt == 1:
|
||||
afor_child: AST | CPtr = afor_mod.children.get(0)
|
||||
if afor_child is not None and afor_child.kind() == ASTKind.FunctionDef:
|
||||
@@ -1597,7 +1597,7 @@ class C(Base1, Base2):
|
||||
"""
|
||||
awith_mod: Module | CPtr = parse(awith_src, pool)
|
||||
if awith_mod is not None and awith_mod.children is not None:
|
||||
awith_cnt: t.CSizeT = awith_mod.children.__len__()
|
||||
awith_cnt: sizet = awith_mod.children.__len__()
|
||||
if awith_cnt == 1:
|
||||
awith_child: AST | CPtr = awith_mod.children.get(0)
|
||||
if awith_child is not None and awith_child.kind() == ASTKind.FunctionDef:
|
||||
@@ -1673,7 +1673,7 @@ class C(Base1, Base2):
|
||||
"""
|
||||
acombo_mod: Module | CPtr = parse(acombo_src, pool)
|
||||
if acombo_mod is not None and acombo_mod.children is not None:
|
||||
acombo_cnt: t.CSizeT = acombo_mod.children.__len__()
|
||||
acombo_cnt: sizet = acombo_mod.children.__len__()
|
||||
if acombo_cnt == 1:
|
||||
acombo_child: AST | CPtr = acombo_mod.children.get(0)
|
||||
if acombo_child is not None and acombo_child.kind() == ASTKind.FunctionDef:
|
||||
|
||||
@@ -15,14 +15,14 @@ import testcheck
|
||||
# 期望:按实际定义类(BaseA)做前缀,或按最终组合类(Combined)。
|
||||
# ============================================================
|
||||
novirtual class BaseA:
|
||||
a: t.CInt
|
||||
a: int
|
||||
|
||||
def helper(self) -> int:
|
||||
return self.a
|
||||
|
||||
|
||||
novirtual class BaseB:
|
||||
b: t.CInt
|
||||
b: int
|
||||
|
||||
def caller(self) -> int:
|
||||
return self.helper()
|
||||
@@ -52,7 +52,7 @@ def test_cross_mixin_call():
|
||||
# inner2 内写 self.a2(this_adjust 精确到组合类中 a2 字段)。
|
||||
# ============================================================
|
||||
novirtual class MixinA2:
|
||||
a2: t.CInt
|
||||
a2: int
|
||||
|
||||
def inner2(self) -> int:
|
||||
self.a2 = self.a2 + 10
|
||||
@@ -60,14 +60,14 @@ novirtual class MixinA2:
|
||||
|
||||
|
||||
novirtual class MixinB2(MixinA2):
|
||||
b2: t.CInt
|
||||
b2: int
|
||||
|
||||
def mid2(self) -> int:
|
||||
return self.inner2() + self.b2
|
||||
|
||||
|
||||
novirtual class MixinC2:
|
||||
c2: t.CInt
|
||||
c2: int
|
||||
|
||||
def outer2(self) -> int:
|
||||
return self.mid2() + self.c2
|
||||
@@ -97,14 +97,14 @@ def test_multilevel_chain():
|
||||
# DataMixin.get_val 内 self.val 需 this_adjust 到第二父类字段区。
|
||||
# ============================================================
|
||||
novirtual class PtrMixin:
|
||||
name: t.CChar | t.CPtr
|
||||
name: char | t.CPtr
|
||||
|
||||
def get_name(self) -> t.CChar | t.CPtr:
|
||||
def get_name(self) -> char | t.CPtr:
|
||||
return self.name
|
||||
|
||||
|
||||
novirtual class DataMixin:
|
||||
val: t.CInt
|
||||
val: int
|
||||
|
||||
def get_val(self) -> int:
|
||||
return self.val
|
||||
@@ -127,7 +127,7 @@ def test_second_parent_offset():
|
||||
"second parent this_adjust fail")
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("NoVTableCrossMixinTest")
|
||||
test_cross_mixin_call()
|
||||
test_multilevel_chain()
|
||||
|
||||
+16
-16
@@ -14,7 +14,7 @@ import stdlib
|
||||
# 从 LinkedNode* 取回 Node* 需显式向下转型:(Node | t.CPtr)(ptr)
|
||||
# ============================================================
|
||||
class Node(linkedlist.LinkedNode):
|
||||
value: t.CInt
|
||||
value: int
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -167,13 +167,13 @@ def test_insert_ops():
|
||||
root.insert_after(a, d) # [1, 4, 2, 3] 在 a 后插入 d
|
||||
# 遍历验证顺序
|
||||
cur: Node | t.CPtr = (Node | t.CPtr)(root.child)
|
||||
v0: t.CInt = cur.value
|
||||
v0: int = cur.value
|
||||
cur = (Node | t.CPtr)(cur.next)
|
||||
v1: t.CInt = cur.value
|
||||
v1: int = cur.value
|
||||
cur = (Node | t.CPtr)(cur.next)
|
||||
v2: t.CInt = cur.value
|
||||
v2: int = cur.value
|
||||
cur = (Node | t.CPtr)(cur.next)
|
||||
v3: t.CInt = cur.value
|
||||
v3: int = cur.value
|
||||
testcheck.check(v0 == 1 and v1 == 4 and v2 == 2 and v3 == 3,
|
||||
"order 1,4,2,3",
|
||||
"insert order fail")
|
||||
@@ -223,7 +223,7 @@ def test_index_access():
|
||||
"child_at(5)=None",
|
||||
"child_at 5 fail")
|
||||
# count_children
|
||||
cc: t.CSizeT = root.count_children()
|
||||
cc: sizet = root.count_children()
|
||||
testcheck.check(cc == 5,
|
||||
"count_children=5",
|
||||
"count_children fail")
|
||||
@@ -291,7 +291,7 @@ def test_unlink():
|
||||
# 测试 10:SListNode 单向链表(OOP 方法)
|
||||
# ============================================================
|
||||
class SNode(linkedlist.SListNode):
|
||||
value: t.CInt
|
||||
value: int
|
||||
|
||||
|
||||
def test_slist():
|
||||
@@ -358,7 +358,7 @@ def test_slist():
|
||||
def test_sprintf_vararg():
|
||||
testcheck.section("Test 11: viperlib.sprintf *args forwarding")
|
||||
# 测试 %d 单参数
|
||||
buf: t.CChar | t.CPtr = stdlib.malloc(32)
|
||||
buf: char | t.CPtr = stdlib.malloc(32)
|
||||
if buf is None: return
|
||||
buf[0] = 0
|
||||
viperlib.sprintf(buf, "key%d", 42)
|
||||
@@ -366,7 +366,7 @@ def test_sprintf_vararg():
|
||||
"sprintf key42",
|
||||
"sprintf key%d fail")
|
||||
# 测试无参数
|
||||
buf2: t.CChar | t.CPtr = stdlib.malloc(32)
|
||||
buf2: char | t.CPtr = stdlib.malloc(32)
|
||||
if buf2 is None: return
|
||||
buf2[0] = 0
|
||||
viperlib.sprintf(buf2, "hello")
|
||||
@@ -374,7 +374,7 @@ def test_sprintf_vararg():
|
||||
"sprintf hello",
|
||||
"sprintf no-arg fail")
|
||||
# 测试多参数
|
||||
buf3: t.CChar | t.CPtr = stdlib.malloc(32)
|
||||
buf3: char | t.CPtr = stdlib.malloc(32)
|
||||
if buf3 is None: return
|
||||
buf3[0] = 0
|
||||
viperlib.sprintf(buf3, "%d+%d=%d", 1, 2, 3)
|
||||
@@ -401,7 +401,7 @@ novirtual class GSListNode[T]:
|
||||
novirtual class GSList[T]:
|
||||
Head: T | t.CPtr
|
||||
Tail: T | t.CPtr
|
||||
Count: t.CSizeT
|
||||
Count: sizet
|
||||
|
||||
def __init__(self):
|
||||
self.Head = None
|
||||
@@ -418,13 +418,13 @@ novirtual class GSList[T]:
|
||||
self.Tail = node
|
||||
self.Count += 1
|
||||
|
||||
def count(self) -> t.CSizeT:
|
||||
def count(self) -> sizet:
|
||||
return self.Count
|
||||
|
||||
def at(self, index: t.CSizeT) -> T | t.CPtr:
|
||||
def at(self, index: sizet) -> T | t.CPtr:
|
||||
if self.Head is None: return None
|
||||
cur: T | t.CPtr = self.Head
|
||||
i: t.CSizeT = 0
|
||||
i: sizet = 0
|
||||
while cur is not None:
|
||||
if i == index: return cur
|
||||
i += 1
|
||||
@@ -433,7 +433,7 @@ novirtual class GSList[T]:
|
||||
|
||||
|
||||
class GNode(GSListNode[GNode]):
|
||||
Value: t.CInt
|
||||
Value: int
|
||||
|
||||
|
||||
def test_generic_slist():
|
||||
@@ -489,7 +489,7 @@ def test_generic_slist():
|
||||
"a2.Next fail")
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("NoVTableTest: linkedlist 库(@t.NoVTable OOP 方法 + 字段展平继承)")
|
||||
test_append()
|
||||
test_prev_link()
|
||||
|
||||
@@ -3,7 +3,7 @@ import testcheck
|
||||
import test_numpy
|
||||
|
||||
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
testcheck.begin("NumpyTest: numpy 正确性测试")
|
||||
testcheck.section("numpy Correctness Tests")
|
||||
test_numpy.test_numpy_correct()
|
||||
|
||||
+353
-353
File diff suppressed because it is too large.
Load diff
+38
-38
@@ -11,8 +11,8 @@ import testcheck
|
||||
# ============================================================
|
||||
|
||||
# --- Test 1: global 声明对模块级变量的影响 ---
|
||||
_g_val: t.CInt = 0
|
||||
_g_ptr: t.CUInt32T | t.CPtr = None
|
||||
_g_val: int = 0
|
||||
_g_ptr: uint32 | t.CPtr = None
|
||||
|
||||
def test_global_write():
|
||||
"""测试:缺少 global 声明时,赋值是否修改模块级变量"""
|
||||
@@ -30,11 +30,11 @@ def test_global_write_no_decl():
|
||||
|
||||
def test_global_ptr():
|
||||
global _g_ptr
|
||||
buf: t.CUInt32T | t.CPtr = w32.win32memory.VirtualAlloc(None, 256, 0x3000, 0x04)
|
||||
buf: uint32 | t.CPtr = w32.win32memory.VirtualAlloc(None, 256, 0x3000, 0x04)
|
||||
if buf:
|
||||
string.memset(buf, 0, 256)
|
||||
_g_ptr = buf
|
||||
p: t.CUInt32T | t.CPtr = _g_ptr
|
||||
p: uint32 | t.CPtr = _g_ptr
|
||||
p[0] = 0xAABBCCDD
|
||||
p[1] = 0x11223344
|
||||
|
||||
@@ -47,13 +47,13 @@ def test_global_ptr_no_decl():
|
||||
- 修改全局:`global _g_ptr` + **无注解**赋值(见 test_global_ptr)
|
||||
- 独立局部:换成不与全局重名的变量名(本函数)
|
||||
"""
|
||||
local_ptr: t.CUInt32T | t.CPtr = None # 独立局部变量,不触碰全局 _g_ptr
|
||||
local_ptr: uint32 | t.CPtr = None # 独立局部变量,不触碰全局 _g_ptr
|
||||
|
||||
|
||||
# --- Test 2: 指针算术和数组索引 ---
|
||||
def test_pointer_arithmetic():
|
||||
"""测试指针算术:偏移计算是否正确"""
|
||||
buf: t.CUInt32T | t.CPtr = w32.win32memory.VirtualAlloc(None, 256, 0x3000, 0x04)
|
||||
buf: uint32 | t.CPtr = w32.win32memory.VirtualAlloc(None, 256, 0x3000, 0x04)
|
||||
if not buf:
|
||||
testcheck.fail("pointer arithmetic: VirtualAlloc returned NULL")
|
||||
return
|
||||
@@ -61,13 +61,13 @@ def test_pointer_arithmetic():
|
||||
|
||||
# 写入值
|
||||
for i in range(8):
|
||||
buf[i] = t.CUInt32T(i * 100)
|
||||
buf[i] = uint32(i * 100)
|
||||
|
||||
# 读取并验证
|
||||
ok: t.CInt = 1
|
||||
ok: int = 1
|
||||
for i in range(8):
|
||||
v: t.CUInt32T = buf[i]
|
||||
expected: t.CUInt32T = t.CUInt32T(i * 100)
|
||||
v: uint32 = buf[i]
|
||||
expected: uint32 = uint32(i * 100)
|
||||
if v != expected:
|
||||
stdio.printf("buf[%d] = 0x%x, expected 0x%x\n", i, v, expected)
|
||||
ok = 0
|
||||
@@ -77,32 +77,32 @@ def test_pointer_arithmetic():
|
||||
# --- Test 3: 数组退化为指针 ---
|
||||
def test_array_decay():
|
||||
"""测试 list[t.CChar, N] 传递给 t.CConst | str 参数"""
|
||||
arr: t.CArray[t.CChar, 32]
|
||||
string.memset(c.Addr(arr), 0, 32)
|
||||
arr: t.CArray[char, 32]
|
||||
string.memset(&arr, 0, 32)
|
||||
# 手动写入字符串
|
||||
src: str = "Hello"
|
||||
for i in range(5):
|
||||
arr[i] = t.CChar(ord(src[i]))
|
||||
arr[i] = char(ord(src[i]))
|
||||
arr[5] = 0
|
||||
|
||||
# 传递给 print (接受 t.CConst | str)
|
||||
stdio.printf("array decay -> %s\n", c.Addr(arr))
|
||||
stdio.printf("array decay -> %s\n", &arr)
|
||||
testcheck.ok("array decay (Hello)")
|
||||
|
||||
|
||||
# --- Test 4: 指针类型转换 (CVoid/CPtr) ---
|
||||
def test_pointer_cast():
|
||||
"""测试指针与整数之间的类型转换"""
|
||||
buf: t.CUInt32T | t.CPtr = w32.win32memory.VirtualAlloc(None, 256, 0x3000, 0x04)
|
||||
buf: uint32 | t.CPtr = w32.win32memory.VirtualAlloc(None, 256, 0x3000, 0x04)
|
||||
if not buf:
|
||||
testcheck.fail("pointer cast: VirtualAlloc returned NULL")
|
||||
return
|
||||
string.memset(buf, 0, 256)
|
||||
|
||||
# 通过 CVoid 指针写入
|
||||
raw: t.CPtr = t.CPtr(t.CUInt64T(buf))
|
||||
raw: t.CPtr = t.CPtr(uint64(buf))
|
||||
# 将 CVoid 指针转回 CUInt32T 指针
|
||||
p32: t.CUInt32T | t.CPtr = (t.CUInt32T | t.CPtr)(raw)
|
||||
p32: uint32 | t.CPtr = (uint32 | t.CPtr)(raw)
|
||||
p32[0] = 0xDEADBEEF
|
||||
|
||||
# 通过原始指针读取
|
||||
@@ -116,7 +116,7 @@ def test_pointer_cast():
|
||||
# --- Test 5: 指针偏移计算 (byte offset vs element offset) ---
|
||||
def test_pointer_offset():
|
||||
"""测试指针偏移:CUInt8T* + N 应该偏移 N 字节,CUInt32T* + N 应该偏移 N*4 字节"""
|
||||
buf: t.CUInt8T | t.CPtr = w32.win32memory.VirtualAlloc(None, 256, 0x3000, 0x04)
|
||||
buf: uint8 | t.CPtr = w32.win32memory.VirtualAlloc(None, 256, 0x3000, 0x04)
|
||||
if not buf:
|
||||
testcheck.fail("pointer offset: VirtualAlloc returned NULL")
|
||||
return
|
||||
@@ -129,8 +129,8 @@ def test_pointer_offset():
|
||||
buf[3] = 0x44 # 'D'
|
||||
|
||||
# 通过 CUInt32T* 读取(应该读到 0x44434241 on little-endian)
|
||||
p32: t.CUInt32T | t.CPtr = (t.CUInt32T | t.CPtr)(t.CPtr(t.CUInt64T(buf)))
|
||||
val: t.CUInt32T = p32[0]
|
||||
p32: uint32 | t.CPtr = (uint32 | t.CPtr)(t.CPtr(uint64(buf)))
|
||||
val: uint32 = p32[0]
|
||||
|
||||
# little-endian: 0x44434241
|
||||
if val == 0x44434241:
|
||||
@@ -142,9 +142,9 @@ def test_pointer_offset():
|
||||
|
||||
# --- Test 6: 结构体指针访问 ---
|
||||
class TestStruct():
|
||||
a: t.CInt
|
||||
b: t.CInt
|
||||
c: t.CUInt64T
|
||||
a: int
|
||||
b: int
|
||||
c: uint64
|
||||
|
||||
def test_struct_pointer():
|
||||
"""测试结构体指针的成员访问"""
|
||||
@@ -153,7 +153,7 @@ def test_struct_pointer():
|
||||
s.b = 20
|
||||
s.c = 0x123456789ABCDEF0
|
||||
|
||||
p: TestStruct | t.CPtr = c.Addr(s)
|
||||
p: TestStruct | t.CPtr = &s
|
||||
stdio.printf("struct pointer access (a=%d b=%d c=0x%llx)\n", p.a, p.b, p.c)
|
||||
testcheck.check(p.a == 10 and p.b == 20 and p.c == 0x123456789ABCDEF0, "struct pointer access", "struct pointer access mismatch")
|
||||
|
||||
@@ -161,55 +161,55 @@ def test_struct_pointer():
|
||||
# --- Test 7: memcpy/memset 通过指针 ---
|
||||
def test_memcpy_pointers():
|
||||
"""测试 memcpy 在指针之间的数据复制"""
|
||||
src_buf: t.CUInt32T | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 0x3000, 0x04)
|
||||
dst_buf: t.CUInt32T | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 0x3000, 0x04)
|
||||
src_buf: uint32 | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 0x3000, 0x04)
|
||||
dst_buf: uint32 | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 0x3000, 0x04)
|
||||
if not src_buf or not dst_buf:
|
||||
testcheck.fail("memcpy: VirtualAlloc returned NULL")
|
||||
return
|
||||
|
||||
# 初始化 src
|
||||
for i in range(8):
|
||||
src_buf[i] = t.CUInt32T(i + 1000)
|
||||
src_buf[i] = uint32(i + 1000)
|
||||
|
||||
# 复制
|
||||
string.memcpy(t.CPtr(t.CUInt64T(dst_buf)), t.CPtr(t.CUInt64T(src_buf)), 32)
|
||||
string.memcpy(t.CPtr(uint64(dst_buf)), t.CPtr(uint64(src_buf)), 32)
|
||||
|
||||
# 验证
|
||||
ok: t.CInt = 1
|
||||
ok: int = 1
|
||||
for i in range(8):
|
||||
if dst_buf[i] != t.CUInt32T(i + 1000):
|
||||
if dst_buf[i] != uint32(i + 1000):
|
||||
stdio.printf("dst[%d] = %u, expected %u\n", i, dst_buf[i], i + 1000)
|
||||
ok = 0
|
||||
testcheck.check(ok, "memcpy between pointers", "memcpy between pointers failed")
|
||||
|
||||
|
||||
# --- Test 8: 指针作为函数参数 ---
|
||||
def fill_array(arr: t.CUInt32T | t.CPtr, count: t.CInt, val: t.CUInt32T):
|
||||
def fill_array(arr: uint32 | t.CPtr, count: int, val: uint32):
|
||||
for i in range(count):
|
||||
arr[i] = val
|
||||
|
||||
def test_pointer_param():
|
||||
"""测试指针作为函数参数传递"""
|
||||
buf: t.CUInt32T | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 0x3000, 0x04)
|
||||
buf: uint32 | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 0x3000, 0x04)
|
||||
if not buf:
|
||||
testcheck.fail("pointer param: VirtualAlloc returned NULL")
|
||||
return
|
||||
|
||||
fill_array(buf, 8, 0xCAFEBABE)
|
||||
|
||||
ok: t.CInt = 1
|
||||
ok: int = 1
|
||||
for i in range(8):
|
||||
if buf[i] != 0xCAFEBABE:
|
||||
ok = 0
|
||||
testcheck.check(ok, "pointer as function parameter", "pointer as function parameter failed")
|
||||
|
||||
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
w32.win32console.SetConsoleCP(65001)
|
||||
w32.win32console.SetConsoleOutputCP(65001)
|
||||
|
||||
print("你好")
|
||||
l: t.CArray[t.CChar, 2] = 0
|
||||
l: t.CArray[char, 2] = 0
|
||||
for i in "hello":
|
||||
l[0] = i
|
||||
print(l)
|
||||
@@ -219,7 +219,7 @@ def main() -> t.CInt | t.CExport:
|
||||
# # l[0] = i
|
||||
# stdio.printf("0x%llx\n", i)
|
||||
|
||||
k: t.CArray[t.CChar, 12] = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C']
|
||||
k: t.CArray[char, 12] = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C']
|
||||
for i in k:
|
||||
stdio.printf("%c\n", i)
|
||||
|
||||
@@ -239,12 +239,12 @@ def main() -> t.CInt | t.CExport:
|
||||
testcheck.section("Test 1b: global pointer")
|
||||
test_global_ptr()
|
||||
if _g_ptr:
|
||||
p: t.CUInt32T | t.CPtr = _g_ptr
|
||||
p: uint32 | t.CPtr = _g_ptr
|
||||
stdio.printf("_g_ptr[0] = 0x%x (expect 0xAABBCCDD)\n", p[0])
|
||||
stdio.printf("_g_ptr[1] = 0x%x (expect 0x11223344)\n", p[1])
|
||||
testcheck.check(p[0] == 0xAABBCCDD and p[1] == 0x11223344, "global pointer values", "global pointer mismatch")
|
||||
test_global_ptr_no_decl()
|
||||
stdio.printf("After test_global_ptr_no_decl(): _g_ptr = %p (expect 非 NULL:局部遮蔽未改全局)\n", t.CPtr(t.CUInt64T(_g_ptr)))
|
||||
stdio.printf("After test_global_ptr_no_decl(): _g_ptr = %p (expect 非 NULL:局部遮蔽未改全局)\n", t.CPtr(uint64(_g_ptr)))
|
||||
if _g_ptr:
|
||||
testcheck.ok("global ptr no decl (global untouched by local shadow)")
|
||||
else:
|
||||
|
||||
@@ -68,7 +68,7 @@ extern def ProbeCoordByVal(dwSize: w32console.COORD) -> BOOL
|
||||
# 全局小整型先例:ViperApps/ViperOS/VKernel/Kernel/services/desktop.vp:62
|
||||
# (_cursor_buttons: uint8 = 0)
|
||||
# ============================================================
|
||||
U8Sink: t.CUInt8T = 0
|
||||
U8Sink: uint8 = 0
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -78,7 +78,7 @@ U8Sink: t.CUInt8T = 0
|
||||
# def ord(s: t.CChar) -> int:
|
||||
# return s
|
||||
# ============================================================
|
||||
def ProbeOrd(s: t.CChar) -> int:
|
||||
def ProbeOrd(s: char) -> int:
|
||||
return s
|
||||
|
||||
|
||||
@@ -104,9 +104,9 @@ def ProbeMin(a: double, b: double) -> double:
|
||||
# 局部值落全局(global 声明 + 赋值)先例:
|
||||
# Test/ArgparseTest/App/main.vp:17(global _mbuddy)→ :26(_mbuddy = ...)
|
||||
# ============================================================
|
||||
def ProbeU8Literal() -> t.CUInt8T:
|
||||
def ProbeU8Literal() -> uint8:
|
||||
global U8Sink
|
||||
result: t.CUInt8T = 1
|
||||
result: uint8 = 1
|
||||
U8Sink = result
|
||||
return result
|
||||
|
||||
@@ -128,7 +128,7 @@ def ProbeU8Literal() -> t.CUInt8T:
|
||||
# (class Translator: def __init__(self): ...;实例化 TransPyV/App/main.vp:471)
|
||||
# ============================================================
|
||||
class Box:
|
||||
p: t.CChar | t.CPtr
|
||||
p: char | t.CPtr
|
||||
|
||||
def __init__(self):
|
||||
self.p = None
|
||||
@@ -151,7 +151,7 @@ class Box:
|
||||
# ============================================================
|
||||
@t.CExport
|
||||
def main() -> int:
|
||||
Ch: t.CChar = 'A'
|
||||
Ch: char = 'A'
|
||||
BoxInst: Box = Box()
|
||||
BoxInst.Clear()
|
||||
ProbeOrd(Ch)
|
||||
|
||||
@@ -4,7 +4,7 @@ import stdio
|
||||
|
||||
|
||||
# 模块级全局定长数组(rawarray 复刻 t.CArray)
|
||||
g_arr: rawarray[t.CInt, 4] = [10, 20, 30, 40]
|
||||
g_arr: rawarray[int, 4] = [10, 20, 30, 40]
|
||||
|
||||
|
||||
# struct 内嵌定长数组字段
|
||||
@@ -13,7 +13,7 @@ class Ctx:
|
||||
buf: rawarray[uint8, 64]
|
||||
|
||||
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
# 1) 全局数组读取
|
||||
stdio.printf("1 g_arr[0]=%d g_arr[3]=%d (expect 10 40)\n", g_arr[0], g_arr[3])
|
||||
|
||||
|
||||
+202
-202
@@ -10,13 +10,13 @@ import testcheck
|
||||
|
||||
|
||||
# 全局内存池
|
||||
arena: t.CUInt8T | t.CPtr = None
|
||||
arena: uint8 | t.CPtr = None
|
||||
pool: memhub.MemPool | t.CPtr = None
|
||||
|
||||
# 外部函数: clock() 用于性能计时
|
||||
def clock() -> t.CLong | t.CExtern: pass
|
||||
|
||||
CLOCK_PER_SEC: t.CDefine = 1000
|
||||
define CLOCK_PER_SEC = 1000
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -25,43 +25,43 @@ CLOCK_PER_SEC: t.CDefine = 1000
|
||||
|
||||
def test_avx2_add_sub_mul_div():
|
||||
testcheck.section("AVX2 add/sub/mul/div 4d")
|
||||
a: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
a.data[0] = t.CDouble(1.0)
|
||||
a.data[1] = t.CDouble(2.0)
|
||||
a.data[2] = t.CDouble(3.0)
|
||||
a.data[3] = t.CDouble(4.0)
|
||||
a: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
a.data[0] = double(1.0)
|
||||
a.data[1] = double(2.0)
|
||||
a.data[2] = double(3.0)
|
||||
a.data[3] = double(4.0)
|
||||
|
||||
b: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
b.data[0] = t.CDouble(5.0)
|
||||
b.data[1] = t.CDouble(6.0)
|
||||
b.data[2] = t.CDouble(7.0)
|
||||
b.data[3] = t.CDouble(8.0)
|
||||
b: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
b.data[0] = double(5.0)
|
||||
b.data[1] = double(6.0)
|
||||
b.data[2] = double(7.0)
|
||||
b.data[3] = double(8.0)
|
||||
|
||||
out: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
out: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
|
||||
# add
|
||||
vipersimd.simd_add4d(a.data, b.data, out.data)
|
||||
testcheck.check(out.data[0] == t.CDouble(6.0), "add[0]==6", "add[0]==6")
|
||||
testcheck.check(out.data[1] == t.CDouble(8.0), "add[1]==8", "add[1]==8")
|
||||
testcheck.check(out.data[2] == t.CDouble(10.0), "add[2]==10", "add[2]==10")
|
||||
testcheck.check(out.data[3] == t.CDouble(12.0), "add[3]==12", "add[3]==12")
|
||||
testcheck.check(out.data[0] == double(6.0), "add[0]==6", "add[0]==6")
|
||||
testcheck.check(out.data[1] == double(8.0), "add[1]==8", "add[1]==8")
|
||||
testcheck.check(out.data[2] == double(10.0), "add[2]==10", "add[2]==10")
|
||||
testcheck.check(out.data[3] == double(12.0), "add[3]==12", "add[3]==12")
|
||||
|
||||
# sub
|
||||
vipersimd.simd_sub4d(a.data, b.data, out.data)
|
||||
testcheck.check(out.data[0] == t.CDouble(-4.0), "sub[0]==-4", "sub[0]==-4")
|
||||
testcheck.check(out.data[3] == t.CDouble(-4.0), "sub[3]==-4", "sub[3]==-4")
|
||||
testcheck.check(out.data[0] == double(-4.0), "sub[0]==-4", "sub[0]==-4")
|
||||
testcheck.check(out.data[3] == double(-4.0), "sub[3]==-4", "sub[3]==-4")
|
||||
|
||||
# mul
|
||||
vipersimd.simd_mul4d(a.data, b.data, out.data)
|
||||
testcheck.check(out.data[0] == t.CDouble(5.0), "mul[0]==5", "mul[0]==5")
|
||||
testcheck.check(out.data[1] == t.CDouble(12.0), "mul[1]==12", "mul[1]==12")
|
||||
testcheck.check(out.data[2] == t.CDouble(21.0), "mul[2]==21", "mul[2]==21")
|
||||
testcheck.check(out.data[3] == t.CDouble(32.0), "mul[3]==32", "mul[3]==32")
|
||||
testcheck.check(out.data[0] == double(5.0), "mul[0]==5", "mul[0]==5")
|
||||
testcheck.check(out.data[1] == double(12.0), "mul[1]==12", "mul[1]==12")
|
||||
testcheck.check(out.data[2] == double(21.0), "mul[2]==21", "mul[2]==21")
|
||||
testcheck.check(out.data[3] == double(32.0), "mul[3]==32", "mul[3]==32")
|
||||
|
||||
# div
|
||||
vipersimd.simd_div4d(b.data, a.data, out.data)
|
||||
testcheck.check(out.data[0] == t.CDouble(5.0), "div[0]==5", "div[0]==5")
|
||||
testcheck.check(out.data[1] == t.CDouble(3.0), "div[1]==3", "div[1]==3")
|
||||
testcheck.check(out.data[0] == double(5.0), "div[0]==5", "div[0]==5")
|
||||
testcheck.check(out.data[1] == double(3.0), "div[1]==3", "div[1]==3")
|
||||
|
||||
a.delete()
|
||||
b.delete()
|
||||
@@ -70,34 +70,34 @@ def test_avx2_add_sub_mul_div():
|
||||
|
||||
def test_avx2_neg_abs_sqrt():
|
||||
testcheck.section("AVX2 neg/abs/sqrt 4d")
|
||||
a: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
a.data[0] = t.CDouble(1.0)
|
||||
a.data[1] = t.CDouble(-4.0)
|
||||
a.data[2] = t.CDouble(9.0)
|
||||
a.data[3] = t.CDouble(-16.0)
|
||||
a: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
a.data[0] = double(1.0)
|
||||
a.data[1] = double(-4.0)
|
||||
a.data[2] = double(9.0)
|
||||
a.data[3] = double(-16.0)
|
||||
|
||||
out: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
out: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
|
||||
# neg
|
||||
vipersimd.simd_neg4d(a.data, out.data)
|
||||
testcheck.check(out.data[0] == t.CDouble(-1.0), "neg[0]==-1", "neg[0]==-1")
|
||||
testcheck.check(out.data[1] == t.CDouble(4.0), "neg[1]==4", "neg[1]==4")
|
||||
testcheck.check(out.data[2] == t.CDouble(-9.0), "neg[2]==-9", "neg[2]==-9")
|
||||
testcheck.check(out.data[3] == t.CDouble(16.0), "neg[3]==16", "neg[3]==16")
|
||||
testcheck.check(out.data[0] == double(-1.0), "neg[0]==-1", "neg[0]==-1")
|
||||
testcheck.check(out.data[1] == double(4.0), "neg[1]==4", "neg[1]==4")
|
||||
testcheck.check(out.data[2] == double(-9.0), "neg[2]==-9", "neg[2]==-9")
|
||||
testcheck.check(out.data[3] == double(16.0), "neg[3]==16", "neg[3]==16")
|
||||
|
||||
# abs
|
||||
vipersimd.simd_abs4d(a.data, out.data)
|
||||
testcheck.check(out.data[0] == t.CDouble(1.0), "abs[0]==1", "abs[0]==1")
|
||||
testcheck.check(out.data[1] == t.CDouble(4.0), "abs[1]==4", "abs[1]==4")
|
||||
testcheck.check(out.data[2] == t.CDouble(9.0), "abs[2]==9", "abs[2]==9")
|
||||
testcheck.check(out.data[3] == t.CDouble(16.0), "abs[3]==16", "abs[3]==16")
|
||||
testcheck.check(out.data[0] == double(1.0), "abs[0]==1", "abs[0]==1")
|
||||
testcheck.check(out.data[1] == double(4.0), "abs[1]==4", "abs[1]==4")
|
||||
testcheck.check(out.data[2] == double(9.0), "abs[2]==9", "abs[2]==9")
|
||||
testcheck.check(out.data[3] == double(16.0), "abs[3]==16", "abs[3]==16")
|
||||
|
||||
# sqrt
|
||||
vipersimd.simd_sqrt4d(out.data, out.data)
|
||||
testcheck.check(out.data[0] == t.CDouble(1.0), "sqrt[0]==1", "sqrt[0]==1")
|
||||
testcheck.check(out.data[1] == t.CDouble(2.0), "sqrt[1]==2", "sqrt[1]==2")
|
||||
testcheck.check(out.data[2] == t.CDouble(3.0), "sqrt[2]==3", "sqrt[2]==3")
|
||||
testcheck.check(out.data[3] == t.CDouble(4.0), "sqrt[3]==4", "sqrt[3]==4")
|
||||
testcheck.check(out.data[0] == double(1.0), "sqrt[0]==1", "sqrt[0]==1")
|
||||
testcheck.check(out.data[1] == double(2.0), "sqrt[1]==2", "sqrt[1]==2")
|
||||
testcheck.check(out.data[2] == double(3.0), "sqrt[2]==3", "sqrt[2]==3")
|
||||
testcheck.check(out.data[3] == double(4.0), "sqrt[3]==4", "sqrt[3]==4")
|
||||
|
||||
a.delete()
|
||||
out.delete()
|
||||
@@ -105,31 +105,31 @@ def test_avx2_neg_abs_sqrt():
|
||||
|
||||
def test_avx2_min_max():
|
||||
testcheck.section("AVX2 min/max 4d")
|
||||
a: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
a.data[0] = t.CDouble(1.0)
|
||||
a.data[1] = t.CDouble(8.0)
|
||||
a.data[2] = t.CDouble(3.0)
|
||||
a.data[3] = t.CDouble(6.0)
|
||||
a: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
a.data[0] = double(1.0)
|
||||
a.data[1] = double(8.0)
|
||||
a.data[2] = double(3.0)
|
||||
a.data[3] = double(6.0)
|
||||
|
||||
b: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
b.data[0] = t.CDouble(5.0)
|
||||
b.data[1] = t.CDouble(2.0)
|
||||
b.data[2] = t.CDouble(7.0)
|
||||
b.data[3] = t.CDouble(4.0)
|
||||
b: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
b.data[0] = double(5.0)
|
||||
b.data[1] = double(2.0)
|
||||
b.data[2] = double(7.0)
|
||||
b.data[3] = double(4.0)
|
||||
|
||||
out: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
out: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
|
||||
vipersimd.simd_min4d(a.data, b.data, out.data)
|
||||
testcheck.check(out.data[0] == t.CDouble(1.0), "min[0]==1", "min[0]==1")
|
||||
testcheck.check(out.data[1] == t.CDouble(2.0), "min[1]==2", "min[1]==2")
|
||||
testcheck.check(out.data[2] == t.CDouble(3.0), "min[2]==3", "min[2]==3")
|
||||
testcheck.check(out.data[3] == t.CDouble(4.0), "min[3]==4", "min[3]==4")
|
||||
testcheck.check(out.data[0] == double(1.0), "min[0]==1", "min[0]==1")
|
||||
testcheck.check(out.data[1] == double(2.0), "min[1]==2", "min[1]==2")
|
||||
testcheck.check(out.data[2] == double(3.0), "min[2]==3", "min[2]==3")
|
||||
testcheck.check(out.data[3] == double(4.0), "min[3]==4", "min[3]==4")
|
||||
|
||||
vipersimd.simd_max4d(a.data, b.data, out.data)
|
||||
testcheck.check(out.data[0] == t.CDouble(5.0), "max[0]==5", "max[0]==5")
|
||||
testcheck.check(out.data[1] == t.CDouble(8.0), "max[1]==8", "max[1]==8")
|
||||
testcheck.check(out.data[2] == t.CDouble(7.0), "max[2]==7", "max[2]==7")
|
||||
testcheck.check(out.data[3] == t.CDouble(6.0), "max[3]==6", "max[3]==6")
|
||||
testcheck.check(out.data[0] == double(5.0), "max[0]==5", "max[0]==5")
|
||||
testcheck.check(out.data[1] == double(8.0), "max[1]==8", "max[1]==8")
|
||||
testcheck.check(out.data[2] == double(7.0), "max[2]==7", "max[2]==7")
|
||||
testcheck.check(out.data[3] == double(6.0), "max[3]==6", "max[3]==6")
|
||||
|
||||
a.delete()
|
||||
b.delete()
|
||||
@@ -138,25 +138,25 @@ def test_avx2_min_max():
|
||||
|
||||
def test_avx2_scalar_ops():
|
||||
testcheck.section("AVX2 scalar broadcast ops")
|
||||
a: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
a.data[0] = t.CDouble(1.0)
|
||||
a.data[1] = t.CDouble(2.0)
|
||||
a.data[2] = t.CDouble(3.0)
|
||||
a.data[3] = t.CDouble(4.0)
|
||||
a: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
a.data[0] = double(1.0)
|
||||
a.data[1] = double(2.0)
|
||||
a.data[2] = double(3.0)
|
||||
a.data[3] = double(4.0)
|
||||
|
||||
s: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 1)
|
||||
s.data[0] = t.CDouble(10.0)
|
||||
s: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 1)
|
||||
s.data[0] = double(10.0)
|
||||
|
||||
out: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
out: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
|
||||
vipersimd.simd_mul_scalar4d(a.data, s.data, out.data)
|
||||
testcheck.check(out.data[0] == t.CDouble(10.0), "mul_scalar[0]==10", "mul_scalar[0]==10")
|
||||
testcheck.check(out.data[1] == t.CDouble(20.0), "mul_scalar[1]==20", "mul_scalar[1]==20")
|
||||
testcheck.check(out.data[3] == t.CDouble(40.0), "mul_scalar[3]==40", "mul_scalar[3]==40")
|
||||
testcheck.check(out.data[0] == double(10.0), "mul_scalar[0]==10", "mul_scalar[0]==10")
|
||||
testcheck.check(out.data[1] == double(20.0), "mul_scalar[1]==20", "mul_scalar[1]==20")
|
||||
testcheck.check(out.data[3] == double(40.0), "mul_scalar[3]==40", "mul_scalar[3]==40")
|
||||
|
||||
vipersimd.simd_add_scalar4d(a.data, s.data, out.data)
|
||||
testcheck.check(out.data[0] == t.CDouble(11.0), "add_scalar[0]==11", "add_scalar[0]==11")
|
||||
testcheck.check(out.data[3] == t.CDouble(14.0), "add_scalar[3]==14", "add_scalar[3]==14")
|
||||
testcheck.check(out.data[0] == double(11.0), "add_scalar[0]==11", "add_scalar[0]==11")
|
||||
testcheck.check(out.data[3] == double(14.0), "add_scalar[3]==14", "add_scalar[3]==14")
|
||||
|
||||
a.delete()
|
||||
s.delete()
|
||||
@@ -165,25 +165,25 @@ def test_avx2_scalar_ops():
|
||||
|
||||
def test_avx2_hsum_dot():
|
||||
testcheck.section("AVX2 hsum/dot 4d")
|
||||
a: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
a.data[0] = t.CDouble(1.0)
|
||||
a.data[1] = t.CDouble(2.0)
|
||||
a.data[2] = t.CDouble(3.0)
|
||||
a.data[3] = t.CDouble(4.0)
|
||||
a: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
a.data[0] = double(1.0)
|
||||
a.data[1] = double(2.0)
|
||||
a.data[2] = double(3.0)
|
||||
a.data[3] = double(4.0)
|
||||
|
||||
b: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
b.data[0] = t.CDouble(5.0)
|
||||
b.data[1] = t.CDouble(6.0)
|
||||
b.data[2] = t.CDouble(7.0)
|
||||
b.data[3] = t.CDouble(8.0)
|
||||
b: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
b.data[0] = double(5.0)
|
||||
b.data[1] = double(6.0)
|
||||
b.data[2] = double(7.0)
|
||||
b.data[3] = double(8.0)
|
||||
|
||||
out: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 1)
|
||||
out: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 1)
|
||||
|
||||
vipersimd.simd_hsum4d(a.data, out.data)
|
||||
testcheck.check(out.data[0] == t.CDouble(10.0), "hsum==10", "hsum==10")
|
||||
testcheck.check(out.data[0] == double(10.0), "hsum==10", "hsum==10")
|
||||
|
||||
vipersimd.simd_dot4d(a.data, b.data, out.data)
|
||||
testcheck.check(out.data[0] == t.CDouble(70.0), "dot==70", "dot==70")
|
||||
testcheck.check(out.data[0] == double(70.0), "dot==70", "dot==70")
|
||||
|
||||
a.delete()
|
||||
b.delete()
|
||||
@@ -192,27 +192,27 @@ def test_avx2_hsum_dot():
|
||||
|
||||
def test_avx2_fma():
|
||||
testcheck.section("AVX2 FMA 4d")
|
||||
a: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
a.data[0] = t.CDouble(1.0)
|
||||
a.data[1] = t.CDouble(2.0)
|
||||
a.data[2] = t.CDouble(3.0)
|
||||
a.data[3] = t.CDouble(4.0)
|
||||
a: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
a.data[0] = double(1.0)
|
||||
a.data[1] = double(2.0)
|
||||
a.data[2] = double(3.0)
|
||||
a.data[3] = double(4.0)
|
||||
|
||||
b: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
b.data[0] = t.CDouble(5.0)
|
||||
b.data[1] = t.CDouble(6.0)
|
||||
b.data[2] = t.CDouble(7.0)
|
||||
b.data[3] = t.CDouble(8.0)
|
||||
b: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
b.data[0] = double(5.0)
|
||||
b.data[1] = double(6.0)
|
||||
b.data[2] = double(7.0)
|
||||
b.data[3] = double(8.0)
|
||||
|
||||
c_val: numpy.ndarray[t.CDouble] | t.CPtr = numpy.ones(pool, 4)
|
||||
c_val: numpy.ndarray[double] | t.CPtr = numpy.ones(pool, 4)
|
||||
|
||||
out: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
out: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
|
||||
vipersimd.simd_fma4d(a.data, b.data, c_val.data, out.data)
|
||||
testcheck.check(out.data[0] == t.CDouble(6.0), "fma[0]==6", "fma[0]==6")
|
||||
testcheck.check(out.data[1] == t.CDouble(13.0), "fma[1]==13", "fma[1]==13")
|
||||
testcheck.check(out.data[2] == t.CDouble(22.0), "fma[2]==22", "fma[2]==22")
|
||||
testcheck.check(out.data[3] == t.CDouble(33.0), "fma[3]==33", "fma[3]==33")
|
||||
testcheck.check(out.data[0] == double(6.0), "fma[0]==6", "fma[0]==6")
|
||||
testcheck.check(out.data[1] == double(13.0), "fma[1]==13", "fma[1]==13")
|
||||
testcheck.check(out.data[2] == double(22.0), "fma[2]==22", "fma[2]==22")
|
||||
testcheck.check(out.data[3] == double(33.0), "fma[3]==33", "fma[3]==33")
|
||||
|
||||
a.delete()
|
||||
b.delete()
|
||||
@@ -226,53 +226,53 @@ def test_avx2_fma():
|
||||
|
||||
def test_batch_array_ops():
|
||||
testcheck.section("Batch array operations")
|
||||
n: t.CSizeT = 16
|
||||
a: numpy.ndarray[t.CDouble] | t.CPtr = numpy.arange(pool, t.CDouble(1.0), t.CDouble(17.0), t.CDouble(1.0))
|
||||
b: numpy.ndarray[t.CDouble] | t.CPtr = numpy.full(pool, 16, t.CDouble(2.0))
|
||||
out: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 16)
|
||||
n: sizet = 16
|
||||
a: numpy.ndarray[double] | t.CPtr = numpy.arange(pool, double(1.0), double(17.0), double(1.0))
|
||||
b: numpy.ndarray[double] | t.CPtr = numpy.full(pool, 16, double(2.0))
|
||||
out: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 16)
|
||||
|
||||
# add array
|
||||
vipersimd.simd_add_array(a.data, b.data, out.data, n)
|
||||
testcheck.check(out.data[0] == t.CDouble(3.0), "add_arr[0]==3", "add_arr[0]==3")
|
||||
testcheck.check(out.data[15] == t.CDouble(18.0), "add_arr[15]==18", "add_arr[15]==18")
|
||||
testcheck.check(out.data[0] == double(3.0), "add_arr[0]==3", "add_arr[0]==3")
|
||||
testcheck.check(out.data[15] == double(18.0), "add_arr[15]==18", "add_arr[15]==18")
|
||||
|
||||
# mul array
|
||||
vipersimd.simd_mul_array(a.data, b.data, out.data, n)
|
||||
testcheck.check(out.data[0] == t.CDouble(2.0), "mul_arr[0]==2", "mul_arr[0]==2")
|
||||
testcheck.check(out.data[3] == t.CDouble(8.0), "mul_arr[3]==8", "mul_arr[3]==8")
|
||||
testcheck.check(out.data[0] == double(2.0), "mul_arr[0]==2", "mul_arr[0]==2")
|
||||
testcheck.check(out.data[3] == double(8.0), "mul_arr[3]==8", "mul_arr[3]==8")
|
||||
|
||||
# sqrt array
|
||||
c: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
c.data[0] = t.CDouble(4.0)
|
||||
c.data[1] = t.CDouble(9.0)
|
||||
c.data[2] = t.CDouble(16.0)
|
||||
c.data[3] = t.CDouble(25.0)
|
||||
out4: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
vipersimd.simd_sqrt_array(c.data, out4.data, t.CSizeT(4))
|
||||
testcheck.check(out4.data[0] == t.CDouble(2.0), "sqrt_arr[0]==2", "sqrt_arr[0]==2")
|
||||
testcheck.check(out4.data[3] == t.CDouble(5.0), "sqrt_arr[3]==5", "sqrt_arr[3]==5")
|
||||
c: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
c.data[0] = double(4.0)
|
||||
c.data[1] = double(9.0)
|
||||
c.data[2] = double(16.0)
|
||||
c.data[3] = double(25.0)
|
||||
out4: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
vipersimd.simd_sqrt_array(c.data, out4.data, sizet(4))
|
||||
testcheck.check(out4.data[0] == double(2.0), "sqrt_arr[0]==2", "sqrt_arr[0]==2")
|
||||
testcheck.check(out4.data[3] == double(5.0), "sqrt_arr[3]==5", "sqrt_arr[3]==5")
|
||||
|
||||
# abs array
|
||||
d: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
d.data[0] = t.CDouble(-1.0)
|
||||
d.data[1] = t.CDouble(-2.0)
|
||||
d.data[2] = t.CDouble(3.0)
|
||||
d.data[3] = t.CDouble(-4.0)
|
||||
vipersimd.simd_abs_array(d.data, out4.data, t.CSizeT(4))
|
||||
testcheck.check(out4.data[0] == t.CDouble(1.0), "abs_arr[0]==1", "abs_arr[0]==1")
|
||||
testcheck.check(out4.data[1] == t.CDouble(2.0), "abs_arr[1]==2", "abs_arr[1]==2")
|
||||
testcheck.check(out4.data[3] == t.CDouble(4.0), "abs_arr[3]==4", "abs_arr[3]==4")
|
||||
d: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
d.data[0] = double(-1.0)
|
||||
d.data[1] = double(-2.0)
|
||||
d.data[2] = double(3.0)
|
||||
d.data[3] = double(-4.0)
|
||||
vipersimd.simd_abs_array(d.data, out4.data, sizet(4))
|
||||
testcheck.check(out4.data[0] == double(1.0), "abs_arr[0]==1", "abs_arr[0]==1")
|
||||
testcheck.check(out4.data[1] == double(2.0), "abs_arr[1]==2", "abs_arr[1]==2")
|
||||
testcheck.check(out4.data[3] == double(4.0), "abs_arr[3]==4", "abs_arr[3]==4")
|
||||
|
||||
# dot array
|
||||
e: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 4)
|
||||
e.data[0] = t.CDouble(1.0)
|
||||
e.data[1] = t.CDouble(2.0)
|
||||
e.data[2] = t.CDouble(3.0)
|
||||
e.data[3] = t.CDouble(4.0)
|
||||
f: numpy.ndarray[t.CDouble] | t.CPtr = numpy.ones(pool, 4)
|
||||
out1: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, 1)
|
||||
vipersimd.simd_dot_array(e.data, f.data, t.CSizeT(4), out1.data)
|
||||
testcheck.check(out1.data[0] == t.CDouble(10.0), "dot_arr==10", "dot_arr==10")
|
||||
e: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 4)
|
||||
e.data[0] = double(1.0)
|
||||
e.data[1] = double(2.0)
|
||||
e.data[2] = double(3.0)
|
||||
e.data[3] = double(4.0)
|
||||
f: numpy.ndarray[double] | t.CPtr = numpy.ones(pool, 4)
|
||||
out1: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, 1)
|
||||
vipersimd.simd_dot_array(e.data, f.data, sizet(4), out1.data)
|
||||
testcheck.check(out1.data[0] == double(10.0), "dot_arr==10", "dot_arr==10")
|
||||
|
||||
a.delete()
|
||||
b.delete()
|
||||
@@ -293,99 +293,99 @@ def test_llvmir_scalar():
|
||||
testcheck.section("LLVMIR precise scalar ops")
|
||||
|
||||
# sqrt
|
||||
r: t.CDouble = vipersimd.simd_sqrt(t.CDouble(4.0))
|
||||
testcheck.check(r == t.CDouble(2.0), "sqrt(4)==2", "sqrt(4)==2")
|
||||
r: double = vipersimd.simd_sqrt(double(4.0))
|
||||
testcheck.check(r == double(2.0), "sqrt(4)==2", "sqrt(4)==2")
|
||||
|
||||
# fabs
|
||||
r = vipersimd.simd_fabs(t.CDouble(-3.5))
|
||||
testcheck.check(r == t.CDouble(3.5), "fabs(-3.5)==3.5", "fabs(-3.5)==3.5")
|
||||
r = vipersimd.simd_fabs(double(-3.5))
|
||||
testcheck.check(r == double(3.5), "fabs(-3.5)==3.5", "fabs(-3.5)==3.5")
|
||||
|
||||
# floor
|
||||
r = vipersimd.simd_floor(t.CDouble(3.7))
|
||||
testcheck.check(r == t.CDouble(3.0), "floor(3.7)==3", "floor(3.7)==3")
|
||||
r = vipersimd.simd_floor(double(3.7))
|
||||
testcheck.check(r == double(3.0), "floor(3.7)==3", "floor(3.7)==3")
|
||||
|
||||
# ceil
|
||||
r = vipersimd.simd_ceil(t.CDouble(3.2))
|
||||
testcheck.check(r == t.CDouble(4.0), "ceil(3.2)==4", "ceil(3.2)==4")
|
||||
r = vipersimd.simd_ceil(double(3.2))
|
||||
testcheck.check(r == double(4.0), "ceil(3.2)==4", "ceil(3.2)==4")
|
||||
|
||||
# round
|
||||
r = vipersimd.simd_round(t.CDouble(3.5))
|
||||
testcheck.check(r == t.CDouble(4.0), "round(3.5)==4", "round(3.5)==4")
|
||||
r = vipersimd.simd_round(double(3.5))
|
||||
testcheck.check(r == double(4.0), "round(3.5)==4", "round(3.5)==4")
|
||||
|
||||
# trunc
|
||||
r = vipersimd.simd_trunc(t.CDouble(3.9))
|
||||
testcheck.check(r == t.CDouble(3.0), "trunc(3.9)==3", "trunc(3.9)==3")
|
||||
r = vipersimd.simd_trunc(double(3.9))
|
||||
testcheck.check(r == double(3.0), "trunc(3.9)==3", "trunc(3.9)==3")
|
||||
|
||||
# fma: 2*3+1 = 7
|
||||
r = vipersimd.simd_fma(t.CDouble(2.0), t.CDouble(3.0), t.CDouble(1.0))
|
||||
testcheck.check(r == t.CDouble(7.0), "fma(2,3,1)==7", "fma(2,3,1)==7")
|
||||
r = vipersimd.simd_fma(double(2.0), double(3.0), double(1.0))
|
||||
testcheck.check(r == double(7.0), "fma(2,3,1)==7", "fma(2,3,1)==7")
|
||||
|
||||
# copysign
|
||||
r = vipersimd.simd_copysign(t.CDouble(3.0), t.CDouble(-1.0))
|
||||
testcheck.check(r == t.CDouble(-3.0), "copysign(3,-1)==-3", "copysign(3,-1)==-3")
|
||||
r = vipersimd.simd_copysign(double(3.0), double(-1.0))
|
||||
testcheck.check(r == double(-3.0), "copysign(3,-1)==-3", "copysign(3,-1)==-3")
|
||||
|
||||
# neg
|
||||
r = vipersimd.simd_neg(t.CDouble(1.5))
|
||||
testcheck.check(r == t.CDouble(-1.5), "neg(1.5)==-1.5", "neg(1.5)==-1.5")
|
||||
r = vipersimd.simd_neg(double(1.5))
|
||||
testcheck.check(r == double(-1.5), "neg(1.5)==-1.5", "neg(1.5)==-1.5")
|
||||
|
||||
# minnum
|
||||
r = vipersimd.simd_minnum(t.CDouble(2.0), t.CDouble(3.0))
|
||||
testcheck.check(r == t.CDouble(2.0), "minnum(2,3)==2", "minnum(2,3)==2")
|
||||
r = vipersimd.simd_minnum(double(2.0), double(3.0))
|
||||
testcheck.check(r == double(2.0), "minnum(2,3)==2", "minnum(2,3)==2")
|
||||
|
||||
# maxnum
|
||||
r = vipersimd.simd_maxnum(t.CDouble(2.0), t.CDouble(3.0))
|
||||
testcheck.check(r == t.CDouble(3.0), "maxnum(2,3)==3", "maxnum(2,3)==3")
|
||||
r = vipersimd.simd_maxnum(double(2.0), double(3.0))
|
||||
testcheck.check(r == double(3.0), "maxnum(2,3)==3", "maxnum(2,3)==3")
|
||||
|
||||
# exp
|
||||
r = vipersimd.simd_exp(t.CDouble(1.0))
|
||||
testcheck.check(r > t.CDouble(2.71) and r < t.CDouble(2.72), "exp(1)~=2.718", "exp(1)~=2.718")
|
||||
r = vipersimd.simd_exp(double(1.0))
|
||||
testcheck.check(r > double(2.71) and r < double(2.72), "exp(1)~=2.718", "exp(1)~=2.718")
|
||||
|
||||
# log
|
||||
r = vipersimd.simd_log(t.CDouble(2.718281828459045))
|
||||
testcheck.check(r > t.CDouble(0.999) and r < t.CDouble(1.001), "log(e)~=1", "log(e)~=1")
|
||||
r = vipersimd.simd_log(double(2.718281828459045))
|
||||
testcheck.check(r > double(0.999) and r < double(1.001), "log(e)~=1", "log(e)~=1")
|
||||
|
||||
# sin
|
||||
r = vipersimd.simd_sin(t.CDouble(0.0))
|
||||
testcheck.check(r > t.CDouble(-0.001) and r < t.CDouble(0.001), "sin(0)~=0", "sin(0)~=0")
|
||||
r = vipersimd.simd_sin(double(0.0))
|
||||
testcheck.check(r > double(-0.001) and r < double(0.001), "sin(0)~=0", "sin(0)~=0")
|
||||
|
||||
# cos
|
||||
r = vipersimd.simd_cos(t.CDouble(0.0))
|
||||
testcheck.check(r > t.CDouble(0.999) and r < t.CDouble(1.001), "cos(0)~=1", "cos(0)~=1")
|
||||
r = vipersimd.simd_cos(double(0.0))
|
||||
testcheck.check(r > double(0.999) and r < double(1.001), "cos(0)~=1", "cos(0)~=1")
|
||||
|
||||
# pow
|
||||
r = vipersimd.simd_pow(t.CDouble(2.0), t.CDouble(10.0))
|
||||
testcheck.check(r == t.CDouble(1024.0), "pow(2,10)==1024", "pow(2,10)==1024")
|
||||
r = vipersimd.simd_pow(double(2.0), double(10.0))
|
||||
testcheck.check(r == double(1024.0), "pow(2,10)==1024", "pow(2,10)==1024")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 4. 性能基准测试: SIMD vs 标量
|
||||
# ============================================================
|
||||
|
||||
N_ELEM: t.CDefine = 40000
|
||||
N_ITER: t.CDefine = 50000
|
||||
define N_ELEM = 40000
|
||||
define N_ITER = 50000
|
||||
|
||||
def scalar_add_array(a: t.CPtr, b: t.CPtr, out: t.CPtr, n: t.CSizeT):
|
||||
i: t.CSizeT = 0
|
||||
da: t.CDouble | t.CPtr = a
|
||||
db: t.CDouble | t.CPtr = b
|
||||
dout: t.CDouble | t.CPtr = out
|
||||
def scalar_add_array(a: t.CPtr, b: t.CPtr, out: t.CPtr, n: sizet):
|
||||
i: sizet = 0
|
||||
da: double | t.CPtr = a
|
||||
db: double | t.CPtr = b
|
||||
dout: double | t.CPtr = out
|
||||
while i < n:
|
||||
dout[i] = da[i] + db[i]
|
||||
i += 1
|
||||
|
||||
def scalar_mul_array(a: t.CPtr, b: t.CPtr, out: t.CPtr, n: t.CSizeT):
|
||||
i: t.CSizeT = 0
|
||||
da: t.CDouble | t.CPtr = a
|
||||
db: t.CDouble | t.CPtr = b
|
||||
dout: t.CDouble | t.CPtr = out
|
||||
def scalar_mul_array(a: t.CPtr, b: t.CPtr, out: t.CPtr, n: sizet):
|
||||
i: sizet = 0
|
||||
da: double | t.CPtr = a
|
||||
db: double | t.CPtr = b
|
||||
dout: double | t.CPtr = out
|
||||
while i < n:
|
||||
dout[i] = da[i] * db[i]
|
||||
i += 1
|
||||
|
||||
def scalar_sqrt_array(a: t.CPtr, out: t.CPtr, n: t.CSizeT):
|
||||
i: t.CSizeT = 0
|
||||
da: t.CDouble | t.CPtr = a
|
||||
dout: t.CDouble | t.CPtr = out
|
||||
def scalar_sqrt_array(a: t.CPtr, out: t.CPtr, n: sizet):
|
||||
i: sizet = 0
|
||||
da: double | t.CPtr = a
|
||||
dout: double | t.CPtr = out
|
||||
while i < n:
|
||||
dout[i] = vipersimd.simd_sqrt(da[i])
|
||||
i += 1
|
||||
@@ -393,15 +393,15 @@ def scalar_sqrt_array(a: t.CPtr, out: t.CPtr, n: t.CSizeT):
|
||||
def benchmark_simd_vs_scalar():
|
||||
testcheck.section("Benchmark: SIMD vs Scalar")
|
||||
|
||||
a: numpy.ndarray[t.CDouble] | t.CPtr = numpy.full(pool, N_ELEM, t.CDouble(1.5))
|
||||
b: numpy.ndarray[t.CDouble] | t.CPtr = numpy.full(pool, N_ELEM, t.CDouble(2.5))
|
||||
out: numpy.ndarray[t.CDouble] | t.CPtr = numpy.zeros(pool, N_ELEM)
|
||||
a: numpy.ndarray[double] | t.CPtr = numpy.full(pool, N_ELEM, double(1.5))
|
||||
b: numpy.ndarray[double] | t.CPtr = numpy.full(pool, N_ELEM, double(2.5))
|
||||
out: numpy.ndarray[double] | t.CPtr = numpy.zeros(pool, N_ELEM)
|
||||
|
||||
# --- SIMD add benchmark ---
|
||||
t0: t.CLong = clock()
|
||||
iter: t.CInt = 0
|
||||
iter: int = 0
|
||||
while iter < N_ITER:
|
||||
vipersimd.simd_add_array(a.data, b.data, out.data, t.CSizeT(N_ELEM))
|
||||
vipersimd.simd_add_array(a.data, b.data, out.data, sizet(N_ELEM))
|
||||
iter += 1
|
||||
t1: t.CLong = clock()
|
||||
simd_add_ms: t.CLong = t1 - t0
|
||||
@@ -410,14 +410,14 @@ def benchmark_simd_vs_scalar():
|
||||
t0 = clock()
|
||||
iter = 0
|
||||
while iter < N_ITER:
|
||||
scalar_add_array(a.data, b.data, out.data, t.CSizeT(N_ELEM))
|
||||
scalar_add_array(a.data, b.data, out.data, sizet(N_ELEM))
|
||||
iter += 1
|
||||
t1 = clock()
|
||||
scalar_add_ms: t.CLong = t1 - t0
|
||||
|
||||
printf(" ADD: SIMD=%ldms Scalar=%ldms", simd_add_ms, scalar_add_ms)
|
||||
if scalar_add_ms > 0:
|
||||
printf(" speedup=%.1fx\n", t.CDouble(scalar_add_ms) / t.CDouble(simd_add_ms))
|
||||
printf(" speedup=%.1fx\n", double(scalar_add_ms) / double(simd_add_ms))
|
||||
else:
|
||||
printf(" speedup=N/A\n")
|
||||
|
||||
@@ -425,7 +425,7 @@ def benchmark_simd_vs_scalar():
|
||||
t0 = clock()
|
||||
iter = 0
|
||||
while iter < N_ITER:
|
||||
vipersimd.simd_mul_array(a.data, b.data, out.data, t.CSizeT(N_ELEM))
|
||||
vipersimd.simd_mul_array(a.data, b.data, out.data, sizet(N_ELEM))
|
||||
iter += 1
|
||||
t1 = clock()
|
||||
simd_mul_ms: t.CLong = t1 - t0
|
||||
@@ -434,14 +434,14 @@ def benchmark_simd_vs_scalar():
|
||||
t0 = clock()
|
||||
iter = 0
|
||||
while iter < N_ITER:
|
||||
scalar_mul_array(a.data, b.data, out.data, t.CSizeT(N_ELEM))
|
||||
scalar_mul_array(a.data, b.data, out.data, sizet(N_ELEM))
|
||||
iter += 1
|
||||
t1 = clock()
|
||||
scalar_mul_ms: t.CLong = t1 - t0
|
||||
|
||||
printf(" MUL: SIMD=%ldms Scalar=%ldms", simd_mul_ms, scalar_mul_ms)
|
||||
if scalar_mul_ms > 0:
|
||||
printf(" speedup=%.1fx\n", t.CDouble(scalar_mul_ms) / t.CDouble(simd_mul_ms))
|
||||
printf(" speedup=%.1fx\n", double(scalar_mul_ms) / double(simd_mul_ms))
|
||||
else:
|
||||
printf(" speedup=N/A\n")
|
||||
|
||||
@@ -449,7 +449,7 @@ def benchmark_simd_vs_scalar():
|
||||
t0 = clock()
|
||||
iter = 0
|
||||
while iter < N_ITER:
|
||||
vipersimd.simd_sqrt_array(a.data, out.data, t.CSizeT(N_ELEM))
|
||||
vipersimd.simd_sqrt_array(a.data, out.data, sizet(N_ELEM))
|
||||
iter += 1
|
||||
t1 = clock()
|
||||
simd_sqrt_ms: t.CLong = t1 - t0
|
||||
@@ -458,19 +458,19 @@ def benchmark_simd_vs_scalar():
|
||||
t0 = clock()
|
||||
iter = 0
|
||||
while iter < N_ITER:
|
||||
scalar_sqrt_array(a.data, out.data, t.CSizeT(N_ELEM))
|
||||
scalar_sqrt_array(a.data, out.data, sizet(N_ELEM))
|
||||
iter += 1
|
||||
t1 = clock()
|
||||
scalar_sqrt_ms: t.CLong = t1 - t0
|
||||
|
||||
printf(" SQRT: SIMD=%ldms Scalar=%ldms", simd_sqrt_ms, scalar_sqrt_ms)
|
||||
if scalar_sqrt_ms > 0:
|
||||
printf(" speedup=%.1fx\n", t.CDouble(scalar_sqrt_ms) / t.CDouble(simd_sqrt_ms))
|
||||
printf(" speedup=%.1fx\n", double(scalar_sqrt_ms) / double(simd_sqrt_ms))
|
||||
else:
|
||||
printf(" speedup=N/A\n")
|
||||
|
||||
# 验证结果正确性
|
||||
testcheck.check(out.data[0] > t.CDouble(0.0), "bench result[0] valid", "bench result[0] valid")
|
||||
testcheck.check(out.data[0] > double(0.0), "bench result[0] valid", "bench result[0] valid")
|
||||
|
||||
a.delete()
|
||||
b.delete()
|
||||
@@ -481,7 +481,7 @@ def benchmark_simd_vs_scalar():
|
||||
# Main
|
||||
# ============================================================
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
global arena, pool
|
||||
|
||||
arena = calloc(4096 * 1024, 1) # 4MB arena
|
||||
|
||||
+21
-21
@@ -19,37 +19,37 @@ def main() -> int:
|
||||
# ---------- 默认精度(核心正确性) ----------
|
||||
testcheck.section("default precision")
|
||||
|
||||
v1: t.CDouble = 1.0
|
||||
v1: double = 1.0
|
||||
viperlib.snprintf(buf, 64, "%a", v1)
|
||||
testcheck.info(buf)
|
||||
testcheck.check(string.strcmp(buf, "0x1p+0") == 0, "%a 1.0 -> 0x1p+0", "FAIL 1.0")
|
||||
|
||||
v2: t.CDouble = 2.0
|
||||
v2: double = 2.0
|
||||
viperlib.snprintf(buf, 64, "%a", v2)
|
||||
testcheck.info(buf)
|
||||
testcheck.check(string.strcmp(buf, "0x1p+1") == 0, "%a 2.0 -> 0x1p+1", "FAIL 2.0")
|
||||
|
||||
v_half: t.CDouble = 0.5
|
||||
v_half: double = 0.5
|
||||
viperlib.snprintf(buf, 64, "%a", v_half)
|
||||
testcheck.info(buf)
|
||||
testcheck.check(string.strcmp(buf, "0x1p-1") == 0, "%a 0.5 -> 0x1p-1", "FAIL 0.5")
|
||||
|
||||
v3: t.CDouble = 3.0
|
||||
v3: double = 3.0
|
||||
viperlib.snprintf(buf, 64, "%a", v3)
|
||||
testcheck.info(buf)
|
||||
testcheck.check(string.strcmp(buf, "0x1.8p+1") == 0, "%a 3.0 -> 0x1.8p+1", "FAIL 3.0")
|
||||
|
||||
v_pi: t.CDouble = 3.14
|
||||
v_pi: double = 3.14
|
||||
viperlib.snprintf(buf, 64, "%a", v_pi)
|
||||
testcheck.info(buf)
|
||||
testcheck.check(string.strcmp(buf, "0x1.91eb851eb851fp+1") == 0, "%a 3.14 -> 0x1.91eb851eb851fp+1", "FAIL 3.14")
|
||||
|
||||
v0: t.CDouble = 0.0
|
||||
v0: double = 0.0
|
||||
viperlib.snprintf(buf, 64, "%a", v0)
|
||||
testcheck.info(buf)
|
||||
testcheck.check(string.strcmp(buf, "0x0p+0") == 0, "%a 0.0 -> 0x0p+0", "FAIL 0.0")
|
||||
|
||||
vn1: t.CDouble = -1.0
|
||||
vn1: double = -1.0
|
||||
viperlib.snprintf(buf, 64, "%a", vn1)
|
||||
testcheck.info(buf)
|
||||
testcheck.check(string.strcmp(buf, "-0x1p+0") == 0, "%a -1.0 -> -0x1p+0", "FAIL -1.0")
|
||||
@@ -92,25 +92,25 @@ def main() -> int:
|
||||
testcheck.section("inf/nan")
|
||||
|
||||
# 构造 +inf: bit pattern 0x7FF0000000000000
|
||||
inf_bits: t.CUInt64T = 0x7FF0000000000000
|
||||
inf_val: t.CDouble = 0.0
|
||||
c.Load(c.Addr(inf_val), c.Addr(inf_bits))
|
||||
inf_bits: uint64 = 0x7FF0000000000000
|
||||
inf_val: double = 0.0
|
||||
*(&inf_val) = *(&inf_bits)
|
||||
viperlib.snprintf(buf, 64, "%a", inf_val)
|
||||
testcheck.info(buf)
|
||||
testcheck.check(string.strcmp(buf, "inf") == 0, "%a +inf -> inf", "FAIL +inf")
|
||||
|
||||
# 构造 -inf: bit pattern 0xFFF0000000000000
|
||||
ninf_bits: t.CUInt64T = 0xFFF0000000000000
|
||||
ninf_val: t.CDouble = 0.0
|
||||
c.Load(c.Addr(ninf_val), c.Addr(ninf_bits))
|
||||
ninf_bits: uint64 = 0xFFF0000000000000
|
||||
ninf_val: double = 0.0
|
||||
*(&ninf_val) = *(&ninf_bits)
|
||||
viperlib.snprintf(buf, 64, "%a", ninf_val)
|
||||
testcheck.info(buf)
|
||||
testcheck.check(string.strcmp(buf, "-inf") == 0, "%a -inf -> -inf", "FAIL -inf")
|
||||
|
||||
# 构造 nan: bit pattern 0x7FF8000000000000
|
||||
nan_bits: t.CUInt64T = 0x7FF8000000000000
|
||||
nan_val: t.CDouble = 0.0
|
||||
c.Load(c.Addr(nan_val), c.Addr(nan_bits))
|
||||
nan_bits: uint64 = 0x7FF8000000000000
|
||||
nan_val: double = 0.0
|
||||
*(&nan_val) = *(&nan_bits)
|
||||
viperlib.snprintf(buf, 64, "%a", nan_val)
|
||||
testcheck.info(buf)
|
||||
testcheck.check(string.strcmp(buf, "nan") == 0, "%a nan -> nan", "FAIL nan")
|
||||
@@ -127,8 +127,8 @@ def main() -> int:
|
||||
# ============================================================
|
||||
testcheck.section("viperlib %g bug diagnosis")
|
||||
|
||||
v_pi17: t.CDouble = 3.1415926535897931
|
||||
v_e17: t.CDouble = 2.7182818284590455
|
||||
v_pi17: double = 3.1415926535897931
|
||||
v_e17: double = 2.7182818284590455
|
||||
|
||||
# T1: 同一参数 %.17g vs %a(复现;%a 对则说明值本身正确)
|
||||
viperlib.snprintf(buf, 128, "T1 %.17g|%a", v_pi17, v_pi17)
|
||||
@@ -182,9 +182,9 @@ def main() -> int:
|
||||
testcheck.check(string.strcmp(buf, "R1 1024|4096|255") == 0, "R1 3-const-int (1024|4096|255)", "R1 FAIL (第2变参被误读)")
|
||||
|
||||
# R2: 3 个运行时变量 int(排除常量折叠差异)
|
||||
ia: t.CInt = 1024
|
||||
ib: t.CInt = 4096
|
||||
ic: t.CInt = 255
|
||||
ia: int = 1024
|
||||
ib: int = 4096
|
||||
ic: int = 255
|
||||
viperlib.snprintf(buf, 128, "R2 %d|%d|%d", ia, ib, ic)
|
||||
testcheck.info(buf)
|
||||
testcheck.check(string.strcmp(buf, "R2 1024|4096|255") == 0, "R2 3-var-int (1024|4096|255)", "R2 FAIL (第2变参被误读)")
|
||||
|
||||
@@ -5,26 +5,26 @@ import c
|
||||
# Test: class with inline list[struct, N] field
|
||||
|
||||
class Inner:
|
||||
code: t.CUnsignedInt
|
||||
bits: t.CInt
|
||||
code: uint
|
||||
bits: int
|
||||
|
||||
class Container:
|
||||
items: t.CArray[Inner, 10]
|
||||
count: t.CInt
|
||||
count: int
|
||||
|
||||
def __init__(self):
|
||||
self.count = 0
|
||||
|
||||
def fill(self):
|
||||
for i in range(10):
|
||||
self.items[i].code = t.CUnsignedInt(i * 100)
|
||||
self.items[i].code = uint(i * 100)
|
||||
self.items[i].bits = i
|
||||
self.count += 1
|
||||
|
||||
def check(self):
|
||||
ok: t.CInt = 1
|
||||
ok: int = 1
|
||||
for i in range(10):
|
||||
if self.items[i].code != t.CUnsignedInt(i * 100):
|
||||
if self.items[i].code != uint(i * 100):
|
||||
stdio.printf("FAIL: items[%d].code=%u expect %d\n", i, self.items[i].code, i * 100)
|
||||
ok = 0
|
||||
if self.items[i].bits != i:
|
||||
@@ -35,7 +35,7 @@ class Container:
|
||||
else:
|
||||
stdio.printf("FAIL: inline list[struct, N] in Container\n")
|
||||
|
||||
def inline_array_test() -> t.CInt:
|
||||
def inline_array_test() -> int:
|
||||
stdio.printf("=== InlineArrayTest ===\n")
|
||||
c1 = Container()
|
||||
c1.fill()
|
||||
|
||||
+54
-54
@@ -10,10 +10,10 @@ import inline_test
|
||||
# ============================================================
|
||||
def test_string_ptr_iter():
|
||||
testcheck.section("Test 1: string pointer iteration")
|
||||
s: t.CChar | t.CPtr = "Hello"
|
||||
p: t.CChar | t.CPtr = s
|
||||
count: t.CInt = 0
|
||||
while c.Deref(p) != 0:
|
||||
s: char | t.CPtr = "Hello"
|
||||
p: char | t.CPtr = s
|
||||
count: int = 0
|
||||
while *p != 0:
|
||||
count += 1
|
||||
p += 1
|
||||
testcheck.check(count == 5, "ptr iter (count=5)", "ptr iter (count expect 5)")
|
||||
@@ -23,11 +23,11 @@ def test_string_ptr_iter():
|
||||
# ============================================================
|
||||
def test_string_ascii_sum():
|
||||
testcheck.section("Test 2: string ASCII sum")
|
||||
s: t.CChar | t.CPtr = "ABC"
|
||||
p: t.CChar | t.CPtr = s
|
||||
total: t.CInt = 0
|
||||
while c.Deref(p) != 0:
|
||||
total += t.CInt(c.Deref(p))
|
||||
s: char | t.CPtr = "ABC"
|
||||
p: char | t.CPtr = s
|
||||
total: int = 0
|
||||
while *p != 0:
|
||||
total += int(*p)
|
||||
p += 1
|
||||
# A=65, B=66, C=67 => 198
|
||||
testcheck.check(total == 198, "ASCII sum (total=198)", "ASCII sum (total expect 198)")
|
||||
@@ -37,15 +37,15 @@ def test_string_ascii_sum():
|
||||
# ============================================================
|
||||
def test_manual_strcpy():
|
||||
testcheck.section("Test 3: manual strcpy via pointers")
|
||||
src: t.CChar | t.CPtr = "Test"
|
||||
dst: t.CArray[t.CChar, 32] = [0]
|
||||
sp: t.CChar | t.CPtr = src
|
||||
dp: t.CChar | t.CPtr = c.Addr(dst)
|
||||
while c.Deref(sp) != 0:
|
||||
c.Set(c.Deref(dp), c.Deref(sp))
|
||||
src: char | t.CPtr = "Test"
|
||||
dst: t.CArray[char, 32] = [0]
|
||||
sp: char | t.CPtr = src
|
||||
dp: char | t.CPtr = &dst
|
||||
while *sp != 0:
|
||||
*dp = *sp
|
||||
sp += 1
|
||||
dp += 1
|
||||
c.Set(c.Deref(dp), 0)
|
||||
*dp = 0
|
||||
testcheck.check(dst[0] == 84 and dst[1] == 101 and dst[2] == 115 and dst[3] == 116, "manual strcpy (T=84 e=101 s=115 t=116)", "manual strcpy (expect T=84 e=101 s=115 t=116)")
|
||||
|
||||
# ============================================================
|
||||
@@ -53,14 +53,14 @@ def test_manual_strcpy():
|
||||
# ============================================================
|
||||
def test_ptr_offset_compare():
|
||||
testcheck.section("Test 4: pointer offset and compare")
|
||||
arr: t.CArray[t.CInt, 5] = [0]
|
||||
arr: t.CArray[int, 5] = [0]
|
||||
for i in range(5):
|
||||
arr[i] = i * 10
|
||||
p: t.CInt | t.CPtr = c.Addr(arr)
|
||||
start: t.CInt | t.CPtr = p
|
||||
total: t.CInt = 0
|
||||
p: int | t.CPtr = &arr
|
||||
start: int | t.CPtr = p
|
||||
total: int = 0
|
||||
while p != start + 5:
|
||||
total += c.Deref(p)
|
||||
total += *p
|
||||
p += 1
|
||||
testcheck.check(total == 100, "ptr offset (total=100)", "ptr offset (total expect 100)")
|
||||
|
||||
@@ -69,10 +69,10 @@ def test_ptr_offset_compare():
|
||||
# ============================================================
|
||||
def test_manual_strlen():
|
||||
testcheck.section("Test 5: manual strlen")
|
||||
s: t.CChar | t.CPtr = "Hello World!"
|
||||
p: t.CChar | t.CPtr = s
|
||||
length: t.CSizeT = 0
|
||||
while c.Deref(p) != 0:
|
||||
s: char | t.CPtr = "Hello World!"
|
||||
p: char | t.CPtr = s
|
||||
length: sizet = 0
|
||||
while *p != 0:
|
||||
length += 1
|
||||
p += 1
|
||||
testcheck.check(length == 12, "manual strlen (len=12)", "manual strlen (len expect 12)")
|
||||
@@ -82,22 +82,22 @@ def test_manual_strlen():
|
||||
# ============================================================
|
||||
def test_reverse_string_ptr():
|
||||
testcheck.section("Test 6: reverse string via pointer")
|
||||
src: t.CChar | t.CPtr = "abcd"
|
||||
dst: t.CArray[t.CChar, 32] = [0]
|
||||
src: char | t.CPtr = "abcd"
|
||||
dst: t.CArray[char, 32] = [0]
|
||||
# Find end of src
|
||||
p: t.CChar | t.CPtr = src
|
||||
length: t.CInt = 0
|
||||
while c.Deref(p) != 0:
|
||||
p: char | t.CPtr = src
|
||||
length: int = 0
|
||||
while *p != 0:
|
||||
length += 1
|
||||
p += 1
|
||||
# Copy in reverse
|
||||
dp: t.CChar | t.CPtr = c.Addr(dst)
|
||||
dp: char | t.CPtr = &dst
|
||||
p = src + length - 1
|
||||
while p >= src:
|
||||
c.Set(c.Deref(dp), c.Deref(p))
|
||||
*dp = *p
|
||||
dp += 1
|
||||
p -= 1
|
||||
c.Set(c.Deref(dp), 0)
|
||||
*dp = 0
|
||||
# "abcd" reversed = "dcba" = 100,99,98,97
|
||||
testcheck.check(dst[0] == 100 and dst[1] == 99 and dst[2] == 98 and dst[3] == 97, "reverse string (d=100 c=99 b=98 a=97)", "reverse string (expect d=100 c=99 b=98 a=97)")
|
||||
|
||||
@@ -106,11 +106,11 @@ def test_reverse_string_ptr():
|
||||
# ============================================================
|
||||
def test_double_pointer():
|
||||
testcheck.section("Test 7: double pointer")
|
||||
x: t.CInt = 42
|
||||
px: t.CInt | t.CPtr = c.Addr(x)
|
||||
ppx: t.CInt | t.CPtr | t.CPtr = c.Addr(px)
|
||||
x: int = 42
|
||||
px: int | t.CPtr = &x
|
||||
ppx: int | t.CPtr | t.CPtr = &px
|
||||
# Read through double pointer
|
||||
val: t.CInt = c.Deref(c.Deref(ppx))
|
||||
val: int = *(*ppx)
|
||||
testcheck.check(val == 42, "double pointer (val=42)", "double pointer (val expect 42)")
|
||||
|
||||
# ============================================================
|
||||
@@ -118,12 +118,12 @@ def test_double_pointer():
|
||||
# ============================================================
|
||||
def test_ptr_arithmetic():
|
||||
testcheck.section("Test 8: pointer arithmetic")
|
||||
arr: t.CArray[t.CInt, 8] = [0]
|
||||
arr: t.CArray[int, 8] = [0]
|
||||
for i in range(8):
|
||||
arr[i] = (i + 1) * (i + 1)
|
||||
p: t.CInt | t.CPtr = c.Addr(arr)
|
||||
p: int | t.CPtr = &arr
|
||||
# Access arr[3] via pointer: p + 3
|
||||
val: t.CInt = c.Deref(p + 3)
|
||||
val: int = *(p + 3)
|
||||
# arr[3] = 4*4 = 16
|
||||
testcheck.check(val == 16, "ptr arithmetic (arr[3]=16)", "ptr arithmetic (arr[3] expect 16)")
|
||||
|
||||
@@ -132,18 +132,18 @@ def test_ptr_arithmetic():
|
||||
# ============================================================
|
||||
def test_manual_strcmp():
|
||||
testcheck.section("Test 9: manual strcmp via pointers")
|
||||
s1: t.CChar | t.CPtr = "Hello"
|
||||
s2: t.CChar | t.CPtr = "Hello"
|
||||
p1: t.CChar | t.CPtr = s1
|
||||
p2: t.CChar | t.CPtr = s2
|
||||
equal: t.CInt = 1
|
||||
while c.Deref(p1) != 0 and c.Deref(p2) != 0:
|
||||
if c.Deref(p1) != c.Deref(p2):
|
||||
s1: char | t.CPtr = "Hello"
|
||||
s2: char | t.CPtr = "Hello"
|
||||
p1: char | t.CPtr = s1
|
||||
p2: char | t.CPtr = s2
|
||||
equal: int = 1
|
||||
while *p1 != 0 and *p2 != 0:
|
||||
if *p1 != *p2:
|
||||
equal = 0
|
||||
break
|
||||
p1 += 1
|
||||
p2 += 1
|
||||
if c.Deref(p1) != c.Deref(p2):
|
||||
if *p1 != *p2:
|
||||
equal = 0
|
||||
testcheck.check(equal == 1, "manual strcmp (equal=1)", "manual strcmp (equal expect 1)")
|
||||
|
||||
@@ -151,21 +151,21 @@ def test_manual_strcmp():
|
||||
# Test 10: 结构体指针访问
|
||||
# ============================================================
|
||||
class Vec2:
|
||||
x: t.CInt
|
||||
y: t.CInt
|
||||
x: int
|
||||
y: int
|
||||
|
||||
def test_struct_ptr_access():
|
||||
testcheck.section("Test 10: struct pointer access")
|
||||
v: Vec2 = Vec2()
|
||||
v.x = 10
|
||||
v.y = 20
|
||||
p: Vec2 | t.CPtr = c.Addr(v)
|
||||
p: Vec2 | t.CPtr = &v
|
||||
# Modify through pointer
|
||||
c.Deref(p).x = 100
|
||||
c.Deref(p).y = 200
|
||||
(*p).x = 100
|
||||
(*p).y = 200
|
||||
testcheck.check(v.x == 100 and v.y == 200, "struct ptr (x=100 y=200)", "struct ptr (x y expect 100 200)")
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("StringIterTest: String/Pointer Iteration Tests")
|
||||
test_string_ptr_iter()
|
||||
test_string_ascii_sum()
|
||||
|
||||
+23
-23
@@ -6,74 +6,74 @@ import w32.win32memory
|
||||
|
||||
def test_strlen():
|
||||
testcheck.section("Test 1: strlen")
|
||||
s: t.CChar | t.CPtr = "Hello, World!"
|
||||
length: t.CUInt64T = string.strlen(s)
|
||||
s: char | t.CPtr = "Hello, World!"
|
||||
length: uint64 = string.strlen(s)
|
||||
testcheck.check(length == 13, "strlen (len=13)", "strlen (expect 13)")
|
||||
|
||||
def test_strcpy():
|
||||
testcheck.section("Test 2: strcpy")
|
||||
buf: t.CChar | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 12288, 4)
|
||||
if t.CUInt64T(buf) == 0:
|
||||
buf: char | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 12288, 4)
|
||||
if uint64(buf) == 0:
|
||||
stdio.printf("SKIP: VirtualAlloc returned NULL\n")
|
||||
return
|
||||
string.memset(buf, 0, 64)
|
||||
string.strcpy(buf, "test string")
|
||||
cmp_result: t.CInt = string.strcmp(buf, "test string")
|
||||
cmp_result: int = string.strcmp(buf, "test string")
|
||||
testcheck.check(cmp_result == 0, "strcpy (result=test string)", "strcpy (cmp mismatch)")
|
||||
|
||||
def test_strcat():
|
||||
testcheck.section("Test 3: strcat (via memcpy)")
|
||||
buf: t.CChar | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 12288, 4)
|
||||
if t.CUInt64T(buf) == 0:
|
||||
buf: char | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 12288, 4)
|
||||
if uint64(buf) == 0:
|
||||
stdio.printf("SKIP: VirtualAlloc returned NULL\n")
|
||||
return
|
||||
string.memset(buf, 0, 64)
|
||||
# 手动拼接: 先拷贝 "Hello",再拷贝 " World"
|
||||
hello: t.CChar | t.CPtr = "Hello"
|
||||
world: t.CChar | t.CPtr = " World"
|
||||
hello: char | t.CPtr = "Hello"
|
||||
world: char | t.CPtr = " World"
|
||||
string.memcpy(buf, hello, 5)
|
||||
string.memcpy(t.CPtr(t.CUInt64T(buf) + 5), world, 6)
|
||||
cmp_result: t.CInt = string.strcmp(buf, "Hello World")
|
||||
string.memcpy(t.CPtr(uint64(buf) + 5), world, 6)
|
||||
cmp_result: int = string.strcmp(buf, "Hello World")
|
||||
testcheck.check(cmp_result == 0, "strcat via memcpy", "strcat via memcpy (cmp mismatch)")
|
||||
|
||||
def test_strcmp():
|
||||
testcheck.section("Test 4: strcmp")
|
||||
r1: t.CInt = string.strcmp("abc", "abc")
|
||||
r2: t.CInt = string.strcmp("abc", "abd")
|
||||
r3: t.CInt = string.strcmp("abd", "abc")
|
||||
r1: int = string.strcmp("abc", "abc")
|
||||
r2: int = string.strcmp("abc", "abd")
|
||||
r3: int = string.strcmp("abd", "abc")
|
||||
testcheck.check(r1 == 0 and r2 < 0 and r3 > 0, "strcmp (eq=0 lt<0 gt>0)", "strcmp (expect eq=0 lt<0 gt>0)")
|
||||
|
||||
def test_strncpy():
|
||||
testcheck.section("Test 5: strncpy")
|
||||
buf: t.CChar | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 12288, 4)
|
||||
if t.CUInt64T(buf) == 0:
|
||||
buf: char | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 12288, 4)
|
||||
if uint64(buf) == 0:
|
||||
stdio.printf("SKIP: VirtualAlloc returned NULL\n")
|
||||
return
|
||||
string.memset(buf, 0, 64)
|
||||
string.strncpy(buf, "ABCDEFGHIJ", 5)
|
||||
cmp_result: t.CInt = string.strcmp(buf, "ABCDE")
|
||||
cmp_result: int = string.strcmp(buf, "ABCDE")
|
||||
testcheck.check(cmp_result == 0, "strncpy (result=ABCDE)", "strncpy (cmp mismatch)")
|
||||
|
||||
def test_char_access():
|
||||
testcheck.section("Test 6: char access")
|
||||
s: t.CChar | t.CPtr = "ABCDE"
|
||||
val: t.CUInt8T = s[2] # 'C' = 67
|
||||
s: char | t.CPtr = "ABCDE"
|
||||
val: uint8 = s[2] # 'C' = 67
|
||||
testcheck.check(val == 67, "char access (s[2]=67='C')", "char access (s[2] expect 67)")
|
||||
|
||||
def test_snprintf():
|
||||
testcheck.section("Test 7: snprintf")
|
||||
buf: t.CChar | t.CPtr = w32.win32memory.VirtualAlloc(None, 128, 12288, 4)
|
||||
if t.CUInt64T(buf) == 0:
|
||||
buf: char | t.CPtr = w32.win32memory.VirtualAlloc(None, 128, 12288, 4)
|
||||
if uint64(buf) == 0:
|
||||
stdio.printf("SKIP: VirtualAlloc returned NULL\n")
|
||||
return
|
||||
string.memset(buf, 0, 128)
|
||||
stdio.snprintf(buf, 128, "value=%d hex=0x%x str=%s", 42, 255, "test")
|
||||
cmp_result: t.CInt = string.strcmp(buf, "value=42 hex=0xff str=test")
|
||||
cmp_result: int = string.strcmp(buf, "value=42 hex=0xff str=test")
|
||||
testcheck.check(cmp_result == 0, "snprintf (result=value=42 hex=0xff str=test)", "snprintf (result mismatch)")
|
||||
|
||||
import w32.win32memory
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("StringTest: 字符串操作基准测试")
|
||||
test_strlen()
|
||||
test_strcpy()
|
||||
|
||||
+10
-10
@@ -5,15 +5,15 @@ import testcheck
|
||||
|
||||
# 定义结构体
|
||||
class Point():
|
||||
x: t.CInt
|
||||
y: t.CInt
|
||||
x: int
|
||||
y: int
|
||||
|
||||
class Rect():
|
||||
origin: Point
|
||||
size: Point
|
||||
|
||||
class Node():
|
||||
value: t.CInt
|
||||
value: int
|
||||
next: t.CPtr # Node* 类型
|
||||
|
||||
def test_struct_basic():
|
||||
@@ -38,7 +38,7 @@ def test_struct_pointer():
|
||||
p.x = 42
|
||||
p.y = 84
|
||||
# 取结构体指针
|
||||
pp: Point | t.CPtr = t.CPtr(t.CUInt64T(p))
|
||||
pp: Point | t.CPtr = t.CPtr(uint64(p))
|
||||
# 通过指针修改
|
||||
pp.x = 100
|
||||
pp.y = 200
|
||||
@@ -50,17 +50,17 @@ def test_struct_param():
|
||||
p: Point = Point()
|
||||
p.x = 5
|
||||
p.y = 15
|
||||
sum_val: t.CInt = point_sum(p)
|
||||
sum_val: int = point_sum(p)
|
||||
testcheck.check(sum_val == 20, "struct param (sum=20)", "struct param (sum expect 20)")
|
||||
|
||||
def point_sum(p: Point) -> t.CInt:
|
||||
def point_sum(p: Point) -> int:
|
||||
return p.x + p.y
|
||||
|
||||
def test_struct_array():
|
||||
testcheck.section("Test 5: struct array")
|
||||
# 分配结构体数组
|
||||
buf: t.CUInt8T | t.CPtr = w32.win32memory.VirtualAlloc(None, 256, 12288, 4)
|
||||
if t.CUInt64T(buf) == 0:
|
||||
buf: uint8 | t.CPtr = w32.win32memory.VirtualAlloc(None, 256, 12288, 4)
|
||||
if uint64(buf) == 0:
|
||||
stdio.printf("SKIP: VirtualAlloc returned NULL\n")
|
||||
return
|
||||
string.memset(buf, 0, 256)
|
||||
@@ -70,12 +70,12 @@ def test_struct_array():
|
||||
pts[0].y = 2
|
||||
pts[1].x = 3
|
||||
pts[1].y = 4
|
||||
total: t.CInt = pts[0].x + pts[0].y + pts[1].x + pts[1].y
|
||||
total: int = pts[0].x + pts[0].y + pts[1].x + pts[1].y
|
||||
testcheck.check(total == 10, "struct array (total=10)", "struct array (total expect 10)")
|
||||
|
||||
import w32.win32memory
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("StructTest: 结构体操作基准测试")
|
||||
test_struct_basic()
|
||||
test_struct_nested()
|
||||
|
||||
@@ -15,7 +15,7 @@ import syslibtest_impl
|
||||
|
||||
|
||||
# MBuddy arena 大小:1MB
|
||||
ARENA_SIZE: t.CDefine = 1048576
|
||||
define ARENA_SIZE = 1048576
|
||||
|
||||
|
||||
def main() -> CInt | CExport:
|
||||
|
||||
@@ -32,7 +32,7 @@ def os_isdir(path: str) -> bool:
|
||||
return os._posix.isdir(path)
|
||||
|
||||
|
||||
def os_getsize(path: str) -> t.CInt64T:
|
||||
def os_getsize(path: str) -> int64:
|
||||
"""返回文件大小(字节,跨平台)。失败返回 -1。"""
|
||||
if platmacro.IS_WINDOWS:
|
||||
return os._win32.getsize(path)
|
||||
|
||||
@@ -19,11 +19,11 @@ import w32.win32process
|
||||
|
||||
|
||||
# 测试用临时文件/目录名前缀
|
||||
TEST_DIR: t.CDefine = "__sylibtest_dir__"
|
||||
TEST_FILE: t.CDefine = "__sylibtest_file.txt"
|
||||
TEST_COPY: t.CDefine = "__sylibtest_copy.txt"
|
||||
TEST_TREE: t.CDefine = "__sylibtest_tree__"
|
||||
TEST_MOVE: t.CDefine = "__sylibtest_moved.txt"
|
||||
define TEST_DIR = "__sylibtest_dir__"
|
||||
define TEST_FILE = "__sylibtest_file.txt"
|
||||
define TEST_COPY = "__sylibtest_copy.txt"
|
||||
define TEST_TREE = "__sylibtest_tree__"
|
||||
define TEST_MOVE = "__sylibtest_moved.txt"
|
||||
|
||||
|
||||
# =============================================================================
|
||||
@@ -128,7 +128,7 @@ def run() -> CInt:
|
||||
testcheck.section("os.path 路径操作")
|
||||
|
||||
# sep
|
||||
sep_char: t.CChar = os.path.sep()
|
||||
sep_char: char = os.path.sep()
|
||||
viperlib.snprintf(buf, 512, "sep = %c", sep_char)
|
||||
testcheck.info(buf)
|
||||
|
||||
@@ -198,8 +198,8 @@ def run() -> CInt:
|
||||
testcheck.check(os_backend.os_exists(TEST_COPY), "copyfile: dst exists OK", "copyfile: dst not exists")
|
||||
|
||||
# 验证拷贝内容一致(检查文件大小)
|
||||
src_size: t.CInt64T = os_backend.os_getsize(TEST_FILE)
|
||||
dst_size: t.CInt64T = os_backend.os_getsize(TEST_COPY)
|
||||
src_size: int64 = os_backend.os_getsize(TEST_FILE)
|
||||
dst_size: int64 = os_backend.os_getsize(TEST_COPY)
|
||||
viperlib.snprintf(buf, 512, "src_size=%lld dst_size=%lld", src_size, dst_size)
|
||||
testcheck.info(buf)
|
||||
testcheck.check(src_size == dst_size, "copyfile: same size OK", "copyfile: size mismatch")
|
||||
|
||||
@@ -4,10 +4,10 @@ import t, c
|
||||
import testcheck
|
||||
|
||||
|
||||
def add_inline(a: t.CInt, b: t.CInt) -> t.CDefine:
|
||||
def add_inline(a: int, b: int) -> t.CDefine:
|
||||
return a + b
|
||||
|
||||
def mul_inline(a: t.CInt, b: t.CInt) -> t.CDefine:
|
||||
def mul_inline(a: int, b: int) -> t.CDefine:
|
||||
return a * b
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ def raise_timeout():
|
||||
raise TimeoutError("operation timed out")
|
||||
|
||||
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
w32.win32console.SetConsoleCP(65001)
|
||||
w32.win32console.SetConsoleOutputCP(65001)
|
||||
|
||||
@@ -136,23 +136,23 @@ def main() -> t.CInt | t.CExport:
|
||||
testcheck.fail("Test 10: caught by generic except")
|
||||
|
||||
testcheck.section("Test LLVMIR: inline LLVM IR add")
|
||||
x: t.CInt = 10
|
||||
y: t.CInt = 20
|
||||
r: t.CInt
|
||||
x: int = 10
|
||||
y: int = 20
|
||||
r: int
|
||||
c.LLVMIR(f"{c.LOut(r)} = add i32 {c.LInp(x)}, {c.LInp(y)}")
|
||||
print("LLVMIR add result:", r)
|
||||
testcheck.check(r == 30, "LLVMIR add (10+20=30)", "LLVMIR add result mismatch")
|
||||
|
||||
testcheck.section("Test CDefine function macro")
|
||||
s: t.CInt = add_inline(3, 4)
|
||||
s: int = add_inline(3, 4)
|
||||
print("add_inline(3, 4) =", s)
|
||||
testcheck.check(s == 7, "add_inline(3, 4) = 7", "add_inline result mismatch")
|
||||
m: t.CInt = mul_inline(5, 6)
|
||||
m: int = mul_inline(5, 6)
|
||||
print("mul_inline(5, 6) =", m)
|
||||
testcheck.check(m == 30, "mul_inline(5, 6) = 30", "mul_inline result mismatch")
|
||||
|
||||
testcheck.section("Test LLVMIR with LOut")
|
||||
out_val: t.CInt = 0
|
||||
out_val: int = 0
|
||||
c.LLVMIR(f"{c.LOut(out_val)} = add i32 {c.LInp(x)}, {c.LInp(y)}")
|
||||
print("LLVMIR LOut result:", out_val)
|
||||
testcheck.check(out_val == 30, "LLVMIR LOut (10+20=30)", "LLVMIR LOut result mismatch")
|
||||
|
||||
+37
-37
@@ -19,18 +19,18 @@ import vthreading
|
||||
# ============================================================
|
||||
# 共享状态(模块级全局,跨线程读写)
|
||||
# ============================================================
|
||||
_shared_count: t.CInt = 0 # Lock 并发测试共享计数器
|
||||
_evt_done: t.CInt = 0 # Event 测试完成标志
|
||||
_cond_ready: t.CInt = 0 # Condition 测试就绪标志
|
||||
_rw_value: t.CInt = 0 # RWLock 测试共享值
|
||||
_main_tid: t.CUInt32T = 0 # 主线程 ID
|
||||
_shared_count: int = 0 # Lock 并发测试共享计数器
|
||||
_evt_done: int = 0 # Event 测试完成标志
|
||||
_cond_ready: int = 0 # Condition 测试就绪标志
|
||||
_rw_value: int = 0 # RWLock 测试共享值
|
||||
_main_tid: uint32 = 0 # 主线程 ID
|
||||
|
||||
# 并发规模常量
|
||||
THREAD_NUM: t.CInt = 4
|
||||
LOCK_ITER: t.CInt = 1000
|
||||
RW_ITER: t.CInt = 100
|
||||
TLS_NUM: t.CInt = 4
|
||||
SYS_ITER: t.CInt = 10
|
||||
THREAD_NUM: int = 4
|
||||
LOCK_ITER: int = 1000
|
||||
RW_ITER: int = 100
|
||||
TLS_NUM: int = 4
|
||||
SYS_ITER: int = 10
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -45,10 +45,10 @@ def _basic_worker(arg: t.CPtr) -> t.CPtr:
|
||||
|
||||
# 传参: 通过 arg 指针自增 100 次(c.Deref/c.DerefAs 读写)
|
||||
def _increment_worker(arg: t.CPtr) -> t.CPtr:
|
||||
ip: t.CInt | t.CPtr = (t.CInt | t.CPtr)(arg)
|
||||
i: t.CInt
|
||||
ip: int | t.CPtr = (int | t.CPtr)(arg)
|
||||
i: int
|
||||
for i in range(100):
|
||||
c.DerefAs(ip, c.Deref(ip) + 1)
|
||||
c.DerefAs(ip, *ip + 1)
|
||||
return NULL
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ def _lock_worker(arg: t.CPtr) -> t.CPtr:
|
||||
def _event_worker(arg: t.CPtr) -> t.CPtr:
|
||||
ev: vthreading.Event | t.CPtr = (vthreading.Event | t.CPtr)(arg)
|
||||
global _evt_done
|
||||
r: t.CInt = ev.wait(5000)
|
||||
r: int = ev.wait(5000)
|
||||
if r == 1:
|
||||
_evt_done = 1
|
||||
return NULL
|
||||
@@ -77,7 +77,7 @@ def _event_worker(arg: t.CPtr) -> t.CPtr:
|
||||
def _cond_consumer(arg: t.CPtr) -> t.CPtr:
|
||||
cond: vthreading.Condition | t.CPtr = (vthreading.Condition | t.CPtr)(arg)
|
||||
global _cond_ready
|
||||
tries: t.CInt = 0
|
||||
tries: int = 0
|
||||
cond.acquire()
|
||||
while _cond_ready == 0 and tries < 100:
|
||||
cond.wait(100)
|
||||
@@ -102,10 +102,10 @@ def _cond_producer(arg: t.CPtr) -> t.CPtr:
|
||||
def _rw_reader(arg: t.CPtr) -> t.CPtr:
|
||||
rwl: vthreading.RWLock | t.CPtr = (vthreading.RWLock | t.CPtr)(arg)
|
||||
global _rw_value
|
||||
i: t.CInt
|
||||
i: int
|
||||
for i in range(RW_ITER * 10):
|
||||
rwl.acquire_read()
|
||||
v: t.CInt = _rw_value
|
||||
v: int = _rw_value
|
||||
rwl.release_read()
|
||||
return NULL
|
||||
|
||||
@@ -114,7 +114,7 @@ def _rw_reader(arg: t.CPtr) -> t.CPtr:
|
||||
def _rw_writer(arg: t.CPtr) -> t.CPtr:
|
||||
rwl: vthreading.RWLock | t.CPtr = (vthreading.RWLock | t.CPtr)(arg)
|
||||
global _rw_value
|
||||
i: t.CInt
|
||||
i: int
|
||||
for i in range(RW_ITER):
|
||||
rwl.acquire_write()
|
||||
_rw_value += 1
|
||||
@@ -125,38 +125,38 @@ def _rw_writer(arg: t.CPtr) -> t.CPtr:
|
||||
# TLS: 每线程 set/get 自校验(存入自身线程 ID 再读回比对)
|
||||
def _tls_worker(arg: t.CPtr) -> t.CPtr:
|
||||
tls: vthreading.local = vthreading.local()
|
||||
tls.set(t.CPtr(t.CUInt64T(vthreading.get_current_thread_id())))
|
||||
tid_val: t.CUInt64T = t.CUInt64T(tls.get())
|
||||
ok: t.CInt = 0
|
||||
if tid_val == t.CUInt64T(vthreading.get_current_thread_id()):
|
||||
tls.set(t.CPtr(uint64(vthreading.get_current_thread_id())))
|
||||
tid_val: uint64 = uint64(tls.get())
|
||||
ok: int = 0
|
||||
if tid_val == uint64(vthreading.get_current_thread_id()):
|
||||
ok = 1
|
||||
tls.free()
|
||||
return t.CPtr(t.CUInt64T(ok))
|
||||
return t.CPtr(uint64(ok))
|
||||
|
||||
|
||||
# 线程 ID 隔离: 工作线程 ID 必须与主线程不同
|
||||
def _tid_worker(arg: t.CPtr) -> t.CPtr:
|
||||
global _main_tid
|
||||
if vthreading.get_current_thread_id() == _main_tid:
|
||||
return t.CPtr(t.CUInt64T(0))
|
||||
return t.CPtr(t.CUInt64T(1))
|
||||
return t.CPtr(uint64(0))
|
||||
return t.CPtr(uint64(1))
|
||||
|
||||
|
||||
# stdlib.system 多线程并发: 每线程循环调 C 运行时 system(),统计失败次数
|
||||
def _system_worker(arg: t.CPtr) -> t.CPtr:
|
||||
i: t.CInt
|
||||
fails: t.CInt = 0
|
||||
i: int
|
||||
fails: int = 0
|
||||
for i in range(SYS_ITER):
|
||||
r: t.CInt = stdlib.system("echo ok > NUL")
|
||||
r: int = stdlib.system("echo ok > NUL")
|
||||
if r != 0:
|
||||
fails += 1
|
||||
return t.CPtr(t.CUInt64T(fails))
|
||||
return t.CPtr(uint64(fails))
|
||||
|
||||
|
||||
# ============================================================
|
||||
# main
|
||||
# ============================================================
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
testcheck.begin("ThreadingTest: vthreading 专项测试")
|
||||
|
||||
# ========== Thread: start/join/is_alive/get_exit_code ==========
|
||||
@@ -172,8 +172,8 @@ def main() -> t.CInt | t.CExport:
|
||||
|
||||
# ========== Thread: 通过 arg 传参 ==========
|
||||
testcheck.section("Thread: arg 传参")
|
||||
cnt: t.CInt = 0
|
||||
th2: vthreading.Thread = vthreading.Thread(_increment_worker, c.Addr(cnt))
|
||||
cnt: int = 0
|
||||
th2: vthreading.Thread = vthreading.Thread(_increment_worker, &cnt)
|
||||
th2.start()
|
||||
testcheck.check(th2.join(5000) != FALSE, "join 正常返回", "join 超时")
|
||||
th2.close()
|
||||
@@ -190,10 +190,10 @@ def main() -> t.CInt | t.CExport:
|
||||
t1.start()
|
||||
t2.start()
|
||||
t3.start()
|
||||
j0: t.CInt = t0.join(10000)
|
||||
j1: t.CInt = t1.join(10000)
|
||||
j2: t.CInt = t2.join(10000)
|
||||
j3: t.CInt = t3.join(10000)
|
||||
j0: int = t0.join(10000)
|
||||
j1: int = t1.join(10000)
|
||||
j2: int = t2.join(10000)
|
||||
j3: int = t3.join(10000)
|
||||
t0.close()
|
||||
t1.close()
|
||||
t2.close()
|
||||
@@ -247,7 +247,7 @@ def main() -> t.CInt | t.CExport:
|
||||
|
||||
# ========== local: TLS 线程局部存储 ==========
|
||||
testcheck.section("local: TLS 线程局部存储")
|
||||
i_t: t.CInt
|
||||
i_t: int
|
||||
for i_t in range(TLS_NUM):
|
||||
th_t: vthreading.Thread = vthreading.Thread(_tls_worker, NULL)
|
||||
th_t.start()
|
||||
|
||||
+53
-53
@@ -13,61 +13,61 @@ import testcheck
|
||||
|
||||
# --- Test 1: CUInt8T -> CUInt32T 零扩展 (zext) ---
|
||||
def test_zext_u8_u32():
|
||||
v: t.CUInt8T = 200 # 0xC8, 如果 sign-extend 会变成 0xFFFFFFC8
|
||||
wide: t.CUInt32T = t.CUInt32T(v)
|
||||
v: uint8 = 200 # 0xC8, 如果 sign-extend 会变成 0xFFFFFFC8
|
||||
wide: uint32 = uint32(v)
|
||||
testcheck.check(wide == 200, "zext u8->u32 (200)", "zext u8->u32 (expected 200)")
|
||||
|
||||
|
||||
# --- Test 2: CInt8T -> CInt32T 符号扩展 (sext) ---
|
||||
def test_sext_i8_i32():
|
||||
v: t.CInt8T = -50 # 0xCE
|
||||
wide: t.CInt32T = t.CInt32T(v)
|
||||
v: int8 = -50 # 0xCE
|
||||
wide: int32 = int32(v)
|
||||
testcheck.check(wide == -50, "sext i8->i32 (-50)", "sext i8->i32 (expected -50)")
|
||||
|
||||
|
||||
# --- Test 3: CUInt32T -> CUInt64T 零扩展 ---
|
||||
def test_zext_u32_u64():
|
||||
v: t.CUInt32T = 0x80000000 # 最高位为1
|
||||
wide: t.CUInt64T = t.CUInt64T(v)
|
||||
v: uint32 = 0x80000000 # 最高位为1
|
||||
wide: uint64 = uint64(v)
|
||||
testcheck.check(wide == 0x80000000, "zext u32->u64 (0x80000000)", "zext u32->u64 (expected 0x80000000)")
|
||||
|
||||
|
||||
# --- Test 4: CInt32T -> CInt64T 符号扩展 ---
|
||||
def test_sext_i32_i64():
|
||||
v: t.CInt32T = -1 # 0xFFFFFFFF
|
||||
wide: t.CInt64T = t.CInt64T(v)
|
||||
v: int32 = -1 # 0xFFFFFFFF
|
||||
wide: int64 = int64(v)
|
||||
testcheck.check(wide == -1, "sext i32->i64 (-1)", "sext i32->i64 (expected -1)")
|
||||
|
||||
|
||||
# --- Test 5: CUInt64T -> CUInt32T 截断 (trunc) ---
|
||||
def test_trunc_u64_u32():
|
||||
v: t.CUInt64T = 0x123456789ABCDEF0
|
||||
narrow: t.CUInt32T = t.CUInt32T(v)
|
||||
v: uint64 = 0x123456789ABCDEF0
|
||||
narrow: uint32 = uint32(v)
|
||||
testcheck.check(narrow == 0x9ABCDEF0, "trunc u64->u32 (0x9ABCDEF0)", "trunc u64->u32 (expected 0x9ABCDEF0)")
|
||||
|
||||
|
||||
# --- Test 6: 有符号/无符号混合运算 ---
|
||||
def test_mixed_signed_unsigned():
|
||||
a: t.CInt = -10
|
||||
b: t.CUInt32T = 20
|
||||
a: int = -10
|
||||
b: uint32 = 20
|
||||
# C 中有符号/无符号混合运算,有符号会转为无符号
|
||||
# -10 作为 unsigned 是 0xFFFFFFF6 = 4294967286
|
||||
# 4294967286 + 20 = 4294967306 (overflow to 10 on u32)
|
||||
result: t.CUInt32T = t.CUInt32T(a) + b
|
||||
stdio.printf(" mixed signed+unsigned: %u (C behavior: %u)\n", result, t.CUInt32T(-10) + 20)
|
||||
result: uint32 = uint32(a) + b
|
||||
stdio.printf(" mixed signed+unsigned: %u (C behavior: %u)\n", result, uint32(-10) + 20)
|
||||
testcheck.ok("mixed signed+unsigned (C behavior)")
|
||||
|
||||
|
||||
# --- Test 7: CDefine 常量在运算中的行为 ---
|
||||
VAL_32BIT: t.CDefine = 0x80000000
|
||||
VAL_NEG: t.CDefine = -1
|
||||
VAL_BIG: t.CDefine = 0xFFFFFFFF
|
||||
define VAL_32BIT = 0x80000000
|
||||
define VAL_NEG = -1
|
||||
define VAL_BIG = 0xFFFFFFFF
|
||||
|
||||
def test_cdefine_values():
|
||||
"""测试 CDefine 常量值是否正确"""
|
||||
v1: t.CUInt32T = t.CUInt32T(VAL_32BIT)
|
||||
v2: t.CInt = VAL_NEG
|
||||
v3: t.CUInt32T = t.CUInt32T(VAL_BIG)
|
||||
v1: uint32 = uint32(VAL_32BIT)
|
||||
v2: int = VAL_NEG
|
||||
v3: uint32 = uint32(VAL_BIG)
|
||||
stdio.printf(" CDefine: 0x80000000=%u, -1=%d, 0xFFFFFFFF=%u\n", v1, v2, v3)
|
||||
testcheck.ok("CDefine constants")
|
||||
|
||||
@@ -76,30 +76,30 @@ def test_cdefine_values():
|
||||
def test_bitops_width():
|
||||
"""测试位运算是否保持正确类型宽度"""
|
||||
# 左移
|
||||
v: t.CUInt32T = 1
|
||||
shifted: t.CUInt32T = v << 31 # 应该是 0x80000000
|
||||
v: uint32 = 1
|
||||
shifted: uint32 = v << 31 # 应该是 0x80000000
|
||||
testcheck.check(shifted == 0x80000000, "bit shift (1<<31 = 0x80000000)", "bit shift (expected 0x80000000)")
|
||||
|
||||
# 右移
|
||||
back: t.CUInt32T = shifted >> 31 # 应该是 1
|
||||
back: uint32 = shifted >> 31 # 应该是 1
|
||||
testcheck.check(back == 1, "bit shift (0x80000000>>31 = 1)", "bit shift (expected 1)")
|
||||
|
||||
|
||||
# --- Test 9: 整数除法与取模 (无符号) ---
|
||||
def test_unsigned_divmod():
|
||||
a: t.CUInt32T = 100
|
||||
b: t.CUInt32T = 7
|
||||
q: t.CUInt32T = a // b
|
||||
r: t.CUInt32T = a % b
|
||||
a: uint32 = 100
|
||||
b: uint32 = 7
|
||||
q: uint32 = a // b
|
||||
r: uint32 = a % b
|
||||
testcheck.check(q == 14 and r == 2, "unsigned div/mod (100//7=14, 100%7=2)", "unsigned div/mod (expected 14,2)")
|
||||
|
||||
|
||||
# --- Test 10: 整数除法与取模 (有符号负数) ---
|
||||
def test_signed_divmod_neg():
|
||||
a: t.CInt = -100
|
||||
b: t.CInt = 7
|
||||
q: t.CInt = a // b
|
||||
r: t.CInt = a % b
|
||||
a: int = -100
|
||||
b: int = 7
|
||||
q: int = a // b
|
||||
r: int = a % b
|
||||
# C 语言: -100/7 = -14, -100%7 = -2
|
||||
# Python: -100//7 = -15, -100%7 = 5
|
||||
# TransPyC 应该遵循 C 语义
|
||||
@@ -109,60 +109,60 @@ def test_signed_divmod_neg():
|
||||
|
||||
# --- Test 11: 比较运算返回值 ---
|
||||
def test_comparison_types():
|
||||
a: t.CInt = 10
|
||||
b: t.CInt = 20
|
||||
c_val: t.CInt = 10
|
||||
lt: t.CInt = 1 if a < b else 0
|
||||
eq: t.CInt = 1 if a == c_val else 0
|
||||
gt: t.CInt = 1 if b > a else 0
|
||||
a: int = 10
|
||||
b: int = 20
|
||||
c_val: int = 10
|
||||
lt: int = 1 if a < b else 0
|
||||
eq: int = 1 if a == c_val else 0
|
||||
gt: int = 1 if b > a else 0
|
||||
testcheck.check(lt == 1 and eq == 1 and gt == 1, "comparison operations", "comparison operations failed")
|
||||
|
||||
|
||||
# --- Test 12: 指针与整数互转 ---
|
||||
def test_ptr_int_cast():
|
||||
buf: t.CUInt32T | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 0x3000, 0x04)
|
||||
buf: uint32 | t.CPtr = w32.win32memory.VirtualAlloc(None, 64, 0x3000, 0x04)
|
||||
if not buf:
|
||||
testcheck.fail("VirtualAlloc returned NULL")
|
||||
return
|
||||
# 指针转整数
|
||||
addr: t.CUInt64T = t.CUInt64T(buf)
|
||||
addr: uint64 = uint64(buf)
|
||||
stdio.printf(" ptr->int: addr=0x%lx\n", addr)
|
||||
# 整数转指针
|
||||
p2: t.CUInt32T | t.CPtr = (t.CUInt32T | t.CPtr)(addr)
|
||||
p2: uint32 | t.CPtr = (uint32 | t.CPtr)(addr)
|
||||
p2[0] = 0x12345678
|
||||
testcheck.check(buf[0] == 0x12345678, "ptr<->int roundtrip", "ptr<->int roundtrip failed")
|
||||
|
||||
|
||||
# --- Test 13: CUInt64T 乘法溢出行为 ---
|
||||
def test_u64_mul():
|
||||
a: t.CUInt64T = 1000
|
||||
b: t.CUInt64T = 1000
|
||||
c_val: t.CUInt64T = a * b
|
||||
a: uint64 = 1000
|
||||
b: uint64 = 1000
|
||||
c_val: uint64 = a * b
|
||||
testcheck.check(c_val == 1000000, "u64 mul (1000*1000=1000000)", "u64 mul (expected 1000000)")
|
||||
|
||||
|
||||
# --- Test 14: bool 运算 (and/or) ---
|
||||
def test_bool_ops():
|
||||
a: t.CInt = 5
|
||||
b: t.CInt = 0
|
||||
c_val: t.CInt = 3
|
||||
a: int = 5
|
||||
b: int = 0
|
||||
c_val: int = 3
|
||||
# Python `and`/`or` 是短路求值
|
||||
r1: t.CInt = a and c_val # 5 and 3 -> 在 C 中应该是 (5 && 3) = 1
|
||||
r2: t.CInt = b or c_val # 0 or 3 -> 在 C 中应该是 (0 || 3) = 1
|
||||
r1: int = a and c_val # 5 and 3 -> 在 C 中应该是 (5 && 3) = 1
|
||||
r2: int = b or c_val # 0 or 3 -> 在 C 中应该是 (0 || 3) = 1
|
||||
stdio.printf(" bool: 5 and 3 = %d, 0 or 3 = %d (expect 1,1 in C)\n", r1, r2)
|
||||
testcheck.ok("bool ops (C semantics)")
|
||||
|
||||
|
||||
# --- Test 15: 条件表达式 (三元运算符) ---
|
||||
def test_ternary():
|
||||
a: t.CInt = 10
|
||||
b: t.CInt = 20
|
||||
max_val: t.CInt = a if a > b else b
|
||||
min_val: t.CInt = a if a < b else b
|
||||
a: int = 10
|
||||
b: int = 20
|
||||
max_val: int = a if a > b else b
|
||||
min_val: int = a if a < b else b
|
||||
testcheck.check(max_val == 20 and min_val == 10, "ternary (max=20 min=10)", "ternary (expected 20,10)")
|
||||
|
||||
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
w32.win32console.SetConsoleCP(65001)
|
||||
w32.win32console.SetConsoleOutputCP(65001)
|
||||
|
||||
|
||||
@@ -9,13 +9,13 @@ import testcheck
|
||||
# VRandomTest - 硬件随机数生成 + 标准分布函数测试
|
||||
# ============================================================
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("VRandomTest: Hardware RNG + Distributions")
|
||||
|
||||
# --- Test 1: RDRAND basic ---
|
||||
testcheck.section("Test 1: RDRAND basic")
|
||||
r32: t.CUInt32T = vrandom.rdrand32()
|
||||
r64: t.CUInt64T = vrandom.rdrand64()
|
||||
r32: uint32 = vrandom.rdrand32()
|
||||
r64: uint64 = vrandom.rdrand64()
|
||||
stdio.printf(" rdrand32() = 0x%08x\n", r32)
|
||||
stdio.printf(" rdrand64() = 0x%016llx\n", r64)
|
||||
testcheck.ok("RDRAND basic")
|
||||
@@ -23,7 +23,7 @@ def main() -> t.CInt:
|
||||
# --- Test 2: randint ---
|
||||
testcheck.section("Test 2: randint(1, 100)")
|
||||
for _ in range(5):
|
||||
v: t.CInt = vrandom.randint(1, 100)
|
||||
v: int = vrandom.randint(1, 100)
|
||||
stdio.printf(" randint(1,100) = %d\n", v)
|
||||
testcheck.ok("randint range check")
|
||||
|
||||
@@ -37,14 +37,14 @@ def main() -> t.CInt:
|
||||
# --- Test 4: getrandbits ---
|
||||
testcheck.section("Test 4: getrandbits(8)")
|
||||
for _ in range(3):
|
||||
b: t.CUInt64T = vrandom.getrandbits(8)
|
||||
b: uint64 = vrandom.getrandbits(8)
|
||||
stdio.printf(" getrandbits(8) = 0x%02llx\n", b)
|
||||
testcheck.ok("getrandbits width check")
|
||||
|
||||
# --- Test 5: random() [0,1) ---
|
||||
testcheck.section("Test 5: random()")
|
||||
for _ in range(3):
|
||||
f: t.CDouble = vrandom.random()
|
||||
f: double = vrandom.random()
|
||||
stdio.printf(" random() = %f\n", f)
|
||||
testcheck.ok("random() in [0,1)")
|
||||
|
||||
|
||||
+72
-72
@@ -14,13 +14,13 @@ import w32.win32console
|
||||
def test_snprintf_u8():
|
||||
"""测试 CUInt8T 值通过 t.CUnsignedInt() 传递给 %u"""
|
||||
testcheck.section("Test 1: %u 格式化小整数 (CUInt8T -> CUnsignedInt)")
|
||||
hr: t.CUInt8T = 14
|
||||
mn: t.CUInt8T = 30
|
||||
sc: t.CUInt8T = 59
|
||||
buf: t.CArray[t.CChar, 64]
|
||||
string.memset(c.Addr(buf), 0, 64)
|
||||
viperlib.snprintf(c.Addr(buf), 64, "%02u:%02u:%02u", t.CUnsignedInt(hr), t.CUnsignedInt(mn), t.CUnsignedInt(sc))
|
||||
stdio.printf("Test1 (CUInt8T->%%u): [%s] (expect 14:30:59)\n", c.Addr(buf))
|
||||
hr: uint8 = 14
|
||||
mn: uint8 = 30
|
||||
sc: uint8 = 59
|
||||
buf: t.CArray[char, 64]
|
||||
string.memset(&buf, 0, 64)
|
||||
viperlib.snprintf(&buf, 64, "%02u:%02u:%02u", uint(hr), uint(mn), uint(sc))
|
||||
stdio.printf("Test1 (CUInt8T->%%u): [%s] (expect 14:30:59)\n", &buf)
|
||||
testcheck.ok("CUInt8T -> %u (expect 14:30:59)")
|
||||
|
||||
|
||||
@@ -28,11 +28,11 @@ def test_snprintf_u8():
|
||||
def test_snprintf_u16():
|
||||
"""测试 CUInt16T 值通过 t.CUnsignedInt() 传递给 %u"""
|
||||
testcheck.section("Test 2: %u 格式化 CUInt16T")
|
||||
yr: t.CUInt16T = 2026
|
||||
buf: t.CArray[t.CChar, 64]
|
||||
string.memset(c.Addr(buf), 0, 64)
|
||||
viperlib.snprintf(c.Addr(buf), 64, "%04u", t.CUnsignedInt(yr))
|
||||
stdio.printf("Test2 (CUInt16T->%%u): [%s] (expect 2026)\n", c.Addr(buf))
|
||||
yr: uint16 = 2026
|
||||
buf: t.CArray[char, 64]
|
||||
string.memset(&buf, 0, 64)
|
||||
viperlib.snprintf(&buf, 64, "%04u", uint(yr))
|
||||
stdio.printf("Test2 (CUInt16T->%%u): [%s] (expect 2026)\n", &buf)
|
||||
testcheck.ok("CUInt16T -> %u (expect 2026)")
|
||||
|
||||
|
||||
@@ -40,11 +40,11 @@ def test_snprintf_u16():
|
||||
def test_snprintf_u64():
|
||||
"""测试 CUInt64T 值传递给 %lu"""
|
||||
testcheck.section("Test 3: %lu 格式化 CUInt64T")
|
||||
val: t.CUInt64T = 1234567890123
|
||||
buf: t.CArray[t.CChar, 64]
|
||||
string.memset(c.Addr(buf), 0, 64)
|
||||
viperlib.snprintf(c.Addr(buf), 64, "%lu", val)
|
||||
stdio.printf("Test3 (CUInt64T->%%lu): [%s] (expect 1234567890123)\n", c.Addr(buf))
|
||||
val: uint64 = 1234567890123
|
||||
buf: t.CArray[char, 64]
|
||||
string.memset(&buf, 0, 64)
|
||||
viperlib.snprintf(&buf, 64, "%lu", val)
|
||||
stdio.printf("Test3 (CUInt64T->%%lu): [%s] (expect 1234567890123)\n", &buf)
|
||||
testcheck.ok("CUInt64T -> %lu (expect 1234567890123)")
|
||||
|
||||
|
||||
@@ -52,33 +52,33 @@ def test_snprintf_u64():
|
||||
def test_snprintf_d_neg():
|
||||
"""测试 %d 格式化负整数"""
|
||||
testcheck.section("Test 4: %d 格式化负数")
|
||||
val: t.CInt = -42
|
||||
buf: t.CArray[t.CChar, 64]
|
||||
string.memset(c.Addr(buf), 0, 64)
|
||||
viperlib.snprintf(c.Addr(buf), 64, "%d", val)
|
||||
stdio.printf("Test4 (CInt->%%d neg): [%s] (expect -42)\n", c.Addr(buf))
|
||||
val: int = -42
|
||||
buf: t.CArray[char, 64]
|
||||
string.memset(&buf, 0, 64)
|
||||
viperlib.snprintf(&buf, 64, "%d", val)
|
||||
stdio.printf("Test4 (CInt->%%d neg): [%s] (expect -42)\n", &buf)
|
||||
testcheck.ok("CInt -> %d neg (expect -42)")
|
||||
|
||||
|
||||
# --- Test 5: %d 格式化正数 ---
|
||||
def test_snprintf_d_pos():
|
||||
testcheck.section("Test 5: %d 格式化正数")
|
||||
val: t.CInt = 42
|
||||
buf: t.CArray[t.CChar, 64]
|
||||
string.memset(c.Addr(buf), 0, 64)
|
||||
viperlib.snprintf(c.Addr(buf), 64, "%d", val)
|
||||
stdio.printf("Test5 (CInt->%%d pos): [%s] (expect 42)\n", c.Addr(buf))
|
||||
val: int = 42
|
||||
buf: t.CArray[char, 64]
|
||||
string.memset(&buf, 0, 64)
|
||||
viperlib.snprintf(&buf, 64, "%d", val)
|
||||
stdio.printf("Test5 (CInt->%%d pos): [%s] (expect 42)\n", &buf)
|
||||
testcheck.ok("CInt -> %d pos (expect 42)")
|
||||
|
||||
|
||||
# --- Test 6: %x 格式化十六进制 ---
|
||||
def test_snprintf_x():
|
||||
testcheck.section("Test 6: %x 格式化十六进制")
|
||||
val: t.CUInt32T = 0xDEADBEEF
|
||||
buf: t.CArray[t.CChar, 64]
|
||||
string.memset(c.Addr(buf), 0, 64)
|
||||
viperlib.snprintf(c.Addr(buf), 64, "0x%08x", val)
|
||||
stdio.printf("Test6 (%%x): [%s] (expect 0xdeadbeef)\n", c.Addr(buf))
|
||||
val: uint32 = 0xDEADBEEF
|
||||
buf: t.CArray[char, 64]
|
||||
string.memset(&buf, 0, 64)
|
||||
viperlib.snprintf(&buf, 64, "0x%08x", val)
|
||||
stdio.printf("Test6 (%%x): [%s] (expect 0xdeadbeef)\n", &buf)
|
||||
testcheck.ok("%x hex (expect 0xdeadbeef)")
|
||||
|
||||
|
||||
@@ -86,18 +86,18 @@ def test_snprintf_x():
|
||||
def test_snprintf_mixed():
|
||||
"""模拟 desktop.py 的时间格式化"""
|
||||
testcheck.section("Test 7: 混合格式化 (模拟 desktop.py 时间格式)")
|
||||
hr: t.CUInt8T = 14
|
||||
mn: t.CUInt8T = 5
|
||||
sc: t.CUInt8T = 9
|
||||
day: t.CUInt8T = 14
|
||||
mon: t.CUInt8T = 6
|
||||
yr: t.CUInt16T = 2026
|
||||
buf: t.CArray[t.CChar, 64]
|
||||
string.memset(c.Addr(buf), 0, 64)
|
||||
viperlib.snprintf(c.Addr(buf), 64, "%04u-%02u-%02u %02u:%02u:%02u",
|
||||
t.CUnsignedInt(yr), t.CUnsignedInt(mon), t.CUnsignedInt(day),
|
||||
t.CUnsignedInt(hr), t.CUnsignedInt(mn), t.CUnsignedInt(sc))
|
||||
stdio.printf("Test7 (time format): [%s] (expect 2026-06-14 14:05:09)\n", c.Addr(buf))
|
||||
hr: uint8 = 14
|
||||
mn: uint8 = 5
|
||||
sc: uint8 = 9
|
||||
day: uint8 = 14
|
||||
mon: uint8 = 6
|
||||
yr: uint16 = 2026
|
||||
buf: t.CArray[char, 64]
|
||||
string.memset(&buf, 0, 64)
|
||||
viperlib.snprintf(&buf, 64, "%04u-%02u-%02u %02u:%02u:%02u",
|
||||
uint(yr), uint(mon), uint(day),
|
||||
uint(hr), uint(mn), uint(sc))
|
||||
stdio.printf("Test7 (time format): [%s] (expect 2026-06-14 14:05:09)\n", &buf)
|
||||
testcheck.ok("time format (expect 2026-06-14 14:05:09)")
|
||||
|
||||
|
||||
@@ -106,7 +106,7 @@ def test_printf_variadic():
|
||||
"""测试 printf 直接输出 variadic 参数"""
|
||||
testcheck.section("Test 8: printf 直接输出 variadic")
|
||||
stdio.printf("Test8 (printf direct): %u %d %lu 0x%x (expect 100 -50 999999999 0xcafe)\n",
|
||||
t.CUnsignedInt(100), -50, t.CUInt64T(999999999), 0xCAFE)
|
||||
uint(100), -50, uint64(999999999), 0xCAFE)
|
||||
testcheck.ok("printf direct variadic (expect 100 -50 999999999 0xcafe)")
|
||||
|
||||
|
||||
@@ -114,35 +114,35 @@ def test_printf_variadic():
|
||||
def test_snprintf_multi_lu():
|
||||
"""测试多个 %lu 连续(模拟 perf 日志格式)"""
|
||||
testcheck.section("Test 9: 多个 %lu 连续")
|
||||
v1: t.CUInt64T = 16
|
||||
v2: t.CUInt64T = 2
|
||||
v3: t.CUInt64T = 11
|
||||
buf: t.CArray[t.CChar, 128]
|
||||
string.memset(c.Addr(buf), 0, 128)
|
||||
viperlib.snprintf(c.Addr(buf), 128, "wall=%lu work=%lu render=%lu", v1, v2, v3)
|
||||
stdio.printf("Test9 (multi %%lu): [%s] (expect wall=16 work=2 render=11)\n", c.Addr(buf))
|
||||
v1: uint64 = 16
|
||||
v2: uint64 = 2
|
||||
v3: uint64 = 11
|
||||
buf: t.CArray[char, 128]
|
||||
string.memset(&buf, 0, 128)
|
||||
viperlib.snprintf(&buf, 128, "wall=%lu work=%lu render=%lu", v1, v2, v3)
|
||||
stdio.printf("Test9 (multi %%lu): [%s] (expect wall=16 work=2 render=11)\n", &buf)
|
||||
testcheck.ok("multi %lu (expect wall=16 work=2 render=11)")
|
||||
|
||||
|
||||
# --- Test 10: %u 格式化 0 ---
|
||||
def test_snprintf_zero():
|
||||
testcheck.section("Test 10: %u 格式化 0")
|
||||
val: t.CUInt32T = 0
|
||||
buf: t.CArray[t.CChar, 64]
|
||||
string.memset(c.Addr(buf), 0, 64)
|
||||
viperlib.snprintf(c.Addr(buf), 64, "%u", val)
|
||||
stdio.printf("Test10 (%%u zero): [%s] (expect 0)\n", c.Addr(buf))
|
||||
val: uint32 = 0
|
||||
buf: t.CArray[char, 64]
|
||||
string.memset(&buf, 0, 64)
|
||||
viperlib.snprintf(&buf, 64, "%u", val)
|
||||
stdio.printf("Test10 (%%u zero): [%s] (expect 0)\n", &buf)
|
||||
testcheck.ok("%u zero (expect 0)")
|
||||
|
||||
|
||||
# --- Test 11: %u 格式化大值 ---
|
||||
def test_snprintf_large():
|
||||
testcheck.section("Test 11: %u 格式化大值")
|
||||
val: t.CUInt32T = 4294967295 # 0xFFFFFFFF
|
||||
buf: t.CArray[t.CChar, 64]
|
||||
string.memset(c.Addr(buf), 0, 64)
|
||||
viperlib.snprintf(c.Addr(buf), 64, "%u", val)
|
||||
stdio.printf("Test11 (%%u max): [%s] (expect 4294967295)\n", c.Addr(buf))
|
||||
val: uint32 = 4294967295 # 0xFFFFFFFF
|
||||
buf: t.CArray[char, 64]
|
||||
string.memset(&buf, 0, 64)
|
||||
viperlib.snprintf(&buf, 64, "%u", val)
|
||||
stdio.printf("Test11 (%%u max): [%s] (expect 4294967295)\n", &buf)
|
||||
testcheck.ok("%u max (expect 4294967295)")
|
||||
|
||||
|
||||
@@ -150,19 +150,19 @@ def test_snprintf_large():
|
||||
def test_snprintf_u8_edge():
|
||||
"""测试 CUInt8T 边界值"""
|
||||
testcheck.section("Test 12: CUnsignedInt cast from CUInt8T edge values")
|
||||
v0: t.CUInt8T = 0
|
||||
v127: t.CUInt8T = 127
|
||||
v128: t.CUInt8T = 128
|
||||
v255: t.CUInt8T = 255
|
||||
buf: t.CArray[t.CChar, 64]
|
||||
string.memset(c.Addr(buf), 0, 64)
|
||||
viperlib.snprintf(c.Addr(buf), 64, "%u %u %u %u",
|
||||
t.CUnsignedInt(v0), t.CUnsignedInt(v127), t.CUnsignedInt(v128), t.CUnsignedInt(v255))
|
||||
stdio.printf("Test12 (CUInt8T edge): [%s] (expect 0 127 128 255)\n", c.Addr(buf))
|
||||
v0: uint8 = 0
|
||||
v127: uint8 = 127
|
||||
v128: uint8 = 128
|
||||
v255: uint8 = 255
|
||||
buf: t.CArray[char, 64]
|
||||
string.memset(&buf, 0, 64)
|
||||
viperlib.snprintf(&buf, 64, "%u %u %u %u",
|
||||
uint(v0), uint(v127), uint(v128), uint(v255))
|
||||
stdio.printf("Test12 (CUInt8T edge): [%s] (expect 0 127 128 255)\n", &buf)
|
||||
testcheck.ok("CUInt8T edge (expect 0 127 128 255)")
|
||||
|
||||
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
w32.win32console.SetConsoleCP(65001)
|
||||
w32.win32console.SetConsoleOutputCP(65001)
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import testcheck
|
||||
import vectortest
|
||||
|
||||
|
||||
def main() -> t.CInt | t.CExport:
|
||||
def main() -> int | t.CExport:
|
||||
testcheck.begin("VectorGenericTest: Vector 泛型测试")
|
||||
testcheck.section("Vector 泛型")
|
||||
vectortest.vector_main()
|
||||
|
||||
@@ -5,7 +5,7 @@ import stdlib
|
||||
import vector
|
||||
import memhub
|
||||
|
||||
POOL_SIZE: t.CDefine = 4096
|
||||
define POOL_SIZE = 4096
|
||||
|
||||
def vector_main() -> CInt:
|
||||
buf: str = stdlib.malloc(256)
|
||||
|
||||
+37
-37
@@ -10,8 +10,8 @@ import testcheck
|
||||
import t, c
|
||||
|
||||
|
||||
def fill_data(data: BYTEPTR, size: t.CSizeT, seed: t.CSizeT, repeating: t.CInt):
|
||||
i: t.CSizeT
|
||||
def fill_data(data: BYTEPTR, size: sizet, seed: sizet, repeating: int):
|
||||
i: sizet
|
||||
for i in range(size):
|
||||
if repeating:
|
||||
data[i] = BYTE(65 + (i % 3))
|
||||
@@ -19,7 +19,7 @@ def fill_data(data: BYTEPTR, size: t.CSizeT, seed: t.CSizeT, repeating: t.CInt):
|
||||
data[i] = BYTE((i * 31 + seed * 17 + (i * i) % 251) % 256)
|
||||
|
||||
|
||||
def huffman_probe(seed: t.CSizeT, size: t.CSizeT, repeating: t.CInt):
|
||||
def huffman_probe(seed: sizet, size: sizet, repeating: int):
|
||||
"""对 roundtrip 的同一份数据直接用 zhuff 复算字面量码表并打印分布。
|
||||
|
||||
背景:随机数据的 comp 远小于其字面量熵下限(250 字节数据熵下限约 221 字节,
|
||||
@@ -31,9 +31,9 @@ def huffman_probe(seed: t.CSizeT, size: t.CSizeT, repeating: t.CInt):
|
||||
"""
|
||||
data: BYTEPTR = BYTEPTR(stdlib.malloc(size))
|
||||
fill_data(data, size, seed, repeating)
|
||||
freqs: t.CArray[t.CInt, 288]
|
||||
freqs: t.CArray[int, 288]
|
||||
string.memset(freqs, 0, freqs.__sizeof__())
|
||||
i: t.CSizeT
|
||||
i: sizet
|
||||
for i in range(size):
|
||||
freqs[data[i]] += 1
|
||||
freqs[256] = 1
|
||||
@@ -41,13 +41,13 @@ def huffman_probe(seed: t.CSizeT, size: t.CSizeT, repeating: t.CInt):
|
||||
tree = zhuff.zhuff_tree()
|
||||
tree.build_codes(freqs, 257, 15)
|
||||
|
||||
hist: t.CArray[t.CInt, 16]
|
||||
hist: t.CArray[int, 16]
|
||||
string.memset(hist, 0, hist.__sizeof__())
|
||||
active: t.CInt = 0
|
||||
no_code: t.CInt = 0
|
||||
sum15: t.CInt = 0
|
||||
k: t.CInt
|
||||
bits: t.CInt
|
||||
active: int = 0
|
||||
no_code: int = 0
|
||||
sum15: int = 0
|
||||
k: int
|
||||
bits: int
|
||||
for k in range(257):
|
||||
bits = tree.codes[k].bits
|
||||
if freqs[k] > 0 and bits == 0:
|
||||
@@ -66,7 +66,7 @@ def huffman_probe(seed: t.CSizeT, size: t.CSizeT, repeating: t.CInt):
|
||||
stdlib.free(data)
|
||||
|
||||
|
||||
def count_freqs_probe(seed: t.CSizeT, size: t.CSizeT, repeating: t.CInt):
|
||||
def count_freqs_probe(seed: sizet, size: sizet, repeating: int):
|
||||
"""调用真实的 zdeflate_count_freqs,与朴素直方图对照。
|
||||
|
||||
上面 huffman_probe 证明码表层正确,则 comp 远小于熵下限只能来自
|
||||
@@ -80,8 +80,8 @@ def count_freqs_probe(seed: t.CSizeT, size: t.CSizeT, repeating: t.CInt):
|
||||
data: BYTEPTR = BYTEPTR(stdlib.malloc(size))
|
||||
fill_data(data, size, seed, repeating)
|
||||
|
||||
lit: t.CArray[t.CInt, 288]
|
||||
dist: t.CArray[t.CInt, 32]
|
||||
lit: t.CArray[int, 288]
|
||||
dist: t.CArray[int, 32]
|
||||
string.memset(lit, 0, lit.__sizeof__())
|
||||
string.memset(dist, 0, dist.__sizeof__())
|
||||
|
||||
@@ -94,29 +94,29 @@ def count_freqs_probe(seed: t.CSizeT, size: t.CSizeT, repeating: t.CInt):
|
||||
# (-56 >= 128 恒假),既导致 count 阶段 lit_freqs[负数] 写到数组之前(漏计),
|
||||
# 也让 encode_symbol(data[pos]) 收到负 symbol 被静默丢弃 ⇒ 码流截断。
|
||||
up: UINT8PTR = UINT8PTR(data)
|
||||
ge8_up: t.CInt = 0
|
||||
ge8_bp: t.CInt = 0
|
||||
i: t.CSizeT
|
||||
ge8_up: int = 0
|
||||
ge8_bp: int = 0
|
||||
i: sizet
|
||||
for i in range(size):
|
||||
if up[i] >= 128: ge8_up += 1
|
||||
if data[i] >= 128: ge8_bp += 1
|
||||
testcheck.info(f"[countprobe] >=128 计数: UINT8PTR={ge8_up} BYTEPTR={ge8_bp} "
|
||||
f"(两者应相等且≈一半)")
|
||||
|
||||
sum_lit: t.CInt = 0
|
||||
active: t.CInt = 0
|
||||
k: t.CInt
|
||||
sum_lit: int = 0
|
||||
active: int = 0
|
||||
k: int
|
||||
for k in range(288):
|
||||
sum_lit += lit[k]
|
||||
if k < 256 and lit[k] > 0:
|
||||
active += 1
|
||||
sum_dist: t.CInt = 0
|
||||
sum_dist: int = 0
|
||||
for k in range(32):
|
||||
sum_dist += dist[k]
|
||||
hlit: t.CInt = 286
|
||||
hlit: int = 286
|
||||
while hlit > 257 and lit[hlit - 1] == 0:
|
||||
hlit -= 1
|
||||
hdist: t.CInt = 30
|
||||
hdist: int = 30
|
||||
while hdist > 1 and dist[hdist - 1] == 0:
|
||||
hdist -= 1
|
||||
|
||||
@@ -127,23 +127,23 @@ def count_freqs_probe(seed: t.CSizeT, size: t.CSizeT, repeating: t.CInt):
|
||||
stdlib.free(data)
|
||||
|
||||
|
||||
def roundtrip(seed: t.CSizeT, size: t.CSizeT, repeating: t.CInt, wbits: t.CInt) -> t.CInt:
|
||||
def roundtrip(seed: sizet, size: sizet, repeating: int, wbits: int) -> int:
|
||||
data: BYTEPTR = BYTEPTR(stdlib.malloc(size))
|
||||
fill_data(data, size, seed, repeating)
|
||||
|
||||
out_len: t.CSizeT = 0
|
||||
out_len: sizet = 0
|
||||
comp: BYTEPTR = pyzlib.compress(None, data, size,
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, wbits, c.Addr(out_len))
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, wbits, &out_len)
|
||||
if not comp:
|
||||
testcheck.fail(f"seed={seed} size={size} rep={repeating} wbits={wbits}: "
|
||||
f"compress 失败 err={pyzlib.get_error_code()} {pyzlib.get_error()}")
|
||||
stdlib.free(data)
|
||||
return -1
|
||||
|
||||
dec_len: t.CSizeT = 0
|
||||
dec_len: sizet = 0
|
||||
dec: BYTEPTR = pyzlib.decompress(None, comp, out_len, wbits,
|
||||
pyzlib.DEF_BUF_SIZE, c.Addr(dec_len))
|
||||
ok: t.CInt = 1
|
||||
pyzlib.DEF_BUF_SIZE, &dec_len)
|
||||
ok: int = 1
|
||||
if not dec:
|
||||
ok = 0
|
||||
testcheck.fail(f"seed={seed} size={size} rep={repeating} wbits={wbits}: "
|
||||
@@ -162,7 +162,7 @@ def roundtrip(seed: t.CSizeT, size: t.CSizeT, repeating: t.CInt, wbits: t.CInt)
|
||||
return 0 if ok else -1
|
||||
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("ZlibDbg: zlib 多 seed/size/wbits 往返")
|
||||
|
||||
# 先跑码表探针:定位 comp 远小于熵下限的根因(码表异常 / 还是别处)
|
||||
@@ -178,19 +178,19 @@ def main() -> t.CInt:
|
||||
count_freqs_probe(0, 256, 1)
|
||||
|
||||
testcheck.section("随机数据 (wbits=15)")
|
||||
sizes: t.CArray[t.CSizeT, None] = [250, 255, 256, 257, 260, 300, 500, 1000, 4096, 20000]
|
||||
n: t.CInt
|
||||
sizes: t.CArray[sizet, None] = [250, 255, 256, 257, 260, 300, 500, 1000, 4096, 20000]
|
||||
n: int
|
||||
for n in range(10):
|
||||
roundtrip(t.CSizeT(n), sizes[n], 0, pyzlib.MAX_WBITS)
|
||||
roundtrip(sizet(n), sizes[n], 0, pyzlib.MAX_WBITS)
|
||||
|
||||
testcheck.section("重复数据 (wbits=15)")
|
||||
sizes2: t.CArray[t.CSizeT, None] = [256, 257, 300, 1000, 20000]
|
||||
sizes2: t.CArray[sizet, None] = [256, 257, 300, 1000, 20000]
|
||||
for n in range(5):
|
||||
roundtrip(t.CSizeT(n), sizes2[n], 1, pyzlib.MAX_WBITS)
|
||||
roundtrip(sizet(n), sizes2[n], 1, pyzlib.MAX_WBITS)
|
||||
|
||||
testcheck.section("gzip 容器 (wbits=31)")
|
||||
sizes3: t.CArray[t.CSizeT, None] = [300, 1000]
|
||||
sizes3: t.CArray[sizet, None] = [300, 1000]
|
||||
for n in range(2):
|
||||
roundtrip(t.CSizeT(n), sizes3[n], 0, pyzlib.MAX_WBITS + 16)
|
||||
roundtrip(sizet(n), sizes3[n], 0, pyzlib.MAX_WBITS + 16)
|
||||
|
||||
return testcheck.end()
|
||||
@@ -7,7 +7,7 @@ import w32.win32memory
|
||||
import c
|
||||
import testcheck
|
||||
|
||||
def main() -> t.CInt:
|
||||
def main() -> int:
|
||||
testcheck.begin("ZlibTest: Zlib 压缩库测试")
|
||||
tpz.main123456()
|
||||
testcheck.ok("zlib test_pyzlib completed")
|
||||
|
||||
+135
-135
@@ -9,9 +9,9 @@ import string
|
||||
import t, c
|
||||
|
||||
|
||||
test_passed: t.CInt = 0
|
||||
test_failed: t.CInt = 0
|
||||
def check(name: str, condition: t.CInt, detail: str):
|
||||
test_passed: int = 0
|
||||
test_failed: int = 0
|
||||
def check(name: str, condition: int, detail: str):
|
||||
global test_passed, test_failed
|
||||
if condition:
|
||||
test_passed += 1
|
||||
@@ -20,12 +20,12 @@ def check(name: str, condition: t.CInt, detail: str):
|
||||
test_failed += 1
|
||||
printf(" [FAIL] %s -- %s\n", name, detail if detail else "")
|
||||
|
||||
def print_hex_test(data: BYTEPTR, length: t.CSizeT, max_show: t.CSizeT):
|
||||
def print_hex_test(data: BYTEPTR, length: sizet, max_show: sizet):
|
||||
if not data or length == 0:
|
||||
printf("(empty)\n")
|
||||
return
|
||||
show: t.CSizeT = max_show if (length > max_show) else length
|
||||
i: t.CSizeT
|
||||
show: sizet = max_show if (length > max_show) else length
|
||||
i: sizet
|
||||
for i in range(show):
|
||||
printf("%02X ", data[i])
|
||||
if length > max_show:
|
||||
@@ -63,28 +63,28 @@ def test_compress_decompress():
|
||||
section_header("compress / decompress")
|
||||
|
||||
inp: str = "Hello, World! This is a test of zlib compression and decompression."
|
||||
input_length: t.CSizeT = strlen(inp)
|
||||
input_length: sizet = strlen(inp)
|
||||
printf(" Input (%zu bytes): \"%s\"\n", input_length, inp)
|
||||
|
||||
out_length: t.CSizeT = 0
|
||||
out_length: sizet = 0
|
||||
compressed: BYTEPTR = pyzlib.compress(None, BYTEPTR(inp), input_length,
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, &out_length)
|
||||
check("compress returns non-None", compressed != None, "compress returned None")
|
||||
check("compress output size > 0", out_length > 0, "compressed size is 0")
|
||||
check("compress output produced", out_length > 0, "compressed size is 0")
|
||||
|
||||
printf(" Compressed (%zu bytes): ", out_length)
|
||||
print_hex_test(compressed, out_length, 32)
|
||||
printf(" Compression ratio: %.1f%%\n", t.CDouble(out_length) / input_length * 100)
|
||||
printf(" Compression ratio: %.1f%%\n", double(out_length) / input_length * 100)
|
||||
|
||||
dec_length: t.CSizeT = 0
|
||||
dec_length: sizet = 0
|
||||
decompressed: BYTEPTR = pyzlib.decompress(None, compressed, out_length,
|
||||
pyzlib.MAX_WBITS, pyzlib.DEF_BUF_SIZE, c.Addr(dec_length))
|
||||
pyzlib.MAX_WBITS, pyzlib.DEF_BUF_SIZE, &dec_length)
|
||||
check("decompress returns non-None", decompressed != None, "decompress returned None")
|
||||
check("decompress output size matches input", dec_length == input_length, "size mismatch")
|
||||
check("decompress output matches input", decompressed != None and string.memcmp(decompressed, inp, input_length) == 0, "content mismatch")
|
||||
|
||||
printf(" Decompressed (%zu bytes): \"%.*s\"\n", dec_length, t.CInt(dec_length), str(decompressed))
|
||||
printf(" Decompressed (%zu bytes): \"%.*s\"\n", dec_length, int(dec_length), str(decompressed))
|
||||
|
||||
stdlib.free(compressed)
|
||||
stdlib.free(decompressed)
|
||||
@@ -95,35 +95,35 @@ def test_compress_levels():
|
||||
section_header("Compression Levels")
|
||||
|
||||
inp: str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||||
input_length: t.CSizeT = strlen(inp)
|
||||
input_length: sizet = strlen(inp)
|
||||
printf(" Input (%zu bytes): \"%s\"\n", input_length, inp)
|
||||
|
||||
out_length: t.CSizeT = 0
|
||||
out_length: sizet = 0
|
||||
|
||||
c0: BYTEPTR = pyzlib.compress(None, BYTEPTR(inp), input_length,
|
||||
pyzlib.Z_NO_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
|
||||
pyzlib.Z_NO_COMPRESSION, pyzlib.MAX_WBITS, &out_length)
|
||||
check("level 0 compress OK", c0 != None, "level 0 returned None")
|
||||
printf(" Level 0 (Z_NO_COMPRESSION): %zu bytes\n", out_length)
|
||||
length0: t.CSizeT = out_length
|
||||
length0: sizet = out_length
|
||||
stdlib.free(c0)
|
||||
|
||||
c1: BYTEPTR = pyzlib.compress(None, BYTEPTR(inp), input_length,
|
||||
pyzlib.Z_BEST_SPEED, pyzlib.MAX_WBITS, c.Addr(out_length))
|
||||
pyzlib.Z_BEST_SPEED, pyzlib.MAX_WBITS, &out_length)
|
||||
check("level 1 compress OK", c1 != None, "level 1 returned None")
|
||||
printf(" Level 1 (Z_BEST_SPEED) : %zu bytes\n", out_length)
|
||||
stdlib.free(c1)
|
||||
|
||||
c6: BYTEPTR = pyzlib.compress(None, BYTEPTR(inp), input_length,
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, &out_length)
|
||||
check("level -1 compress OK", c6 != None, "default level returned None")
|
||||
printf(" Level -1 (DEFAULT) : %zu bytes\n", out_length)
|
||||
stdlib.free(c6)
|
||||
|
||||
c9: BYTEPTR = pyzlib.compress(None, BYTEPTR(inp), input_length,
|
||||
pyzlib.Z_BEST_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
|
||||
pyzlib.Z_BEST_COMPRESSION, pyzlib.MAX_WBITS, &out_length)
|
||||
check("level 9 compress OK", c9 != None, "level 9 returned None")
|
||||
printf(" Level 9 (Z_BEST_COMPRESS) : %zu bytes\n", out_length)
|
||||
length9: t.CSizeT = out_length
|
||||
length9: sizet = out_length
|
||||
stdlib.free(c9)
|
||||
|
||||
check("level 9 smaller than level 0", length9 < length0, "level 9 not smaller than level 0")
|
||||
@@ -139,7 +139,7 @@ def test_compressobj():
|
||||
printf(" Part 1: \"%s\"\n", part1)
|
||||
printf(" Part 2: \"%s\"\n", part2)
|
||||
|
||||
out_length: t.CSizeT = 0
|
||||
out_length: sizet = 0
|
||||
|
||||
s: pyzlib.Compress | t.CPtr = pyzlib.compressobj(None, pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.DEFLATED,
|
||||
pyzlib.MAX_WBITS, pyzlib.DEF_MEM_LEVEL,
|
||||
@@ -147,11 +147,11 @@ def test_compressobj():
|
||||
check("compressobj created", s != None, "compressobj is None")
|
||||
print_separator()
|
||||
|
||||
c1: BYTEPTR = s.compress(BYTEPTR(part1), strlen(part1), c.Addr(out_length))
|
||||
c1: BYTEPTR = s.compress(BYTEPTR(part1), strlen(part1), &out_length)
|
||||
check("compress part1 OK", c1 != None, "compress part1 failed")
|
||||
printf(" Compressed part1: %zu bytes -> ", out_length)
|
||||
print_hex_test(c1, out_length, 16)
|
||||
total: t.CSizeT = out_length
|
||||
total: sizet = out_length
|
||||
all: BYTEPTR = None
|
||||
if out_length > 0 and c1:
|
||||
all = BYTEPTR(stdlib.malloc(total))
|
||||
@@ -159,7 +159,7 @@ def test_compressobj():
|
||||
stdlib.free(c1)
|
||||
|
||||
c2: BYTEPTR = s.compress(BYTEPTR(part2),
|
||||
strlen(part2), c.Addr(out_length))
|
||||
strlen(part2), &out_length)
|
||||
check("compress part2 OK", c2 != None, "compress part2 failed")
|
||||
printf(" Compressed part2: %zu bytes -> ", out_length)
|
||||
print_hex_test(c2, out_length, 16)
|
||||
@@ -171,7 +171,7 @@ def test_compressobj():
|
||||
total += out_length
|
||||
stdlib.free(c2)
|
||||
|
||||
c3: BYTEPTR = s.flush(pyzlib.Z_FINISH, c.Addr(out_length))
|
||||
c3: BYTEPTR = s.flush(pyzlib.Z_FINISH, &out_length)
|
||||
check("flush (Z_FINISH) OK", c3 != None, "flush failed")
|
||||
printf(" Flush result : %zu bytes -> ", out_length)
|
||||
print_hex_test(c3, out_length, 16)
|
||||
@@ -186,14 +186,14 @@ def test_compressobj():
|
||||
print_separator()
|
||||
|
||||
if all:
|
||||
dec_length: t.CSizeT = 0
|
||||
dec: BYTEPTR = pyzlib.decompress(None, all, total, pyzlib.MAX_WBITS, pyzlib.DEF_BUF_SIZE, c.Addr(dec_length))
|
||||
dec_length: sizet = 0
|
||||
dec: BYTEPTR = pyzlib.decompress(None, all, total, pyzlib.MAX_WBITS, pyzlib.DEF_BUF_SIZE, &dec_length)
|
||||
check("decompress incremental OK", dec != None, "decompress returned None")
|
||||
check("decompress incremental size", dec != None and dec_length == strlen(part1) + strlen(part2), "size mismatch")
|
||||
check("decompress incremental content",
|
||||
dec != None and string.memcmp(dec, "Hello, World!", dec_length) == 0, "content mismatch")
|
||||
if dec:
|
||||
printf(" Decompressed: \"%.*s\" (%zu bytes)\n", t.CInt(dec_length), str(dec), dec_length)
|
||||
printf(" Decompressed: \"%.*s\" (%zu bytes)\n", int(dec_length), str(dec), dec_length)
|
||||
stdlib.free(dec)
|
||||
stdlib.free(all)
|
||||
|
||||
@@ -204,12 +204,12 @@ def test_decompressobj():
|
||||
section_header("decompressobj")
|
||||
|
||||
inp: str = "Test data for decompress object."
|
||||
input_length: t.CSizeT = strlen(inp)
|
||||
input_length: sizet = strlen(inp)
|
||||
printf(" Input (%zu bytes): \"%s\"\n", input_length, inp)
|
||||
|
||||
out_length: t.CSizeT = 0
|
||||
out_length: sizet = 0
|
||||
compressed: BYTEPTR = pyzlib.compress(None, BYTEPTR(inp), input_length,
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, &out_length)
|
||||
printf(" Compressed: %zu bytes\n", out_length)
|
||||
|
||||
d: pyzlib.Decompress | t.CPtr = pyzlib.decompressobj(None, pyzlib.MAX_WBITS, None, 0)
|
||||
@@ -217,16 +217,16 @@ def test_decompressobj():
|
||||
check("eof is false initially", d.eof == 0, "eof should be 0")
|
||||
print_separator()
|
||||
|
||||
dec_length: t.CSizeT = 0
|
||||
dec_length: sizet = 0
|
||||
dec: BYTEPTR = d.decompress(compressed, out_length,
|
||||
0, c.Addr(dec_length))
|
||||
0, &dec_length)
|
||||
check("decompress OK", dec != None, "decompress returned None")
|
||||
check("decompress size", dec != None and dec_length == input_length, "size mismatch")
|
||||
check("decompress content", dec != None and string.memcmp(dec, inp, input_length) == 0, "content mismatch")
|
||||
check("eof is true after stream end", d.eof == 1, "eof should be 1")
|
||||
|
||||
if dec:
|
||||
printf(" Decompressed (%zu bytes): \"%.*s\"\n", dec_length, t.CInt(dec_length), str(dec))
|
||||
printf(" Decompressed (%zu bytes): \"%.*s\"\n", dec_length, int(dec_length), str(dec))
|
||||
printf(" eof = %d\n", d.eof)
|
||||
|
||||
stdlib.free(dec)
|
||||
@@ -238,35 +238,35 @@ def test_decompressobj_max_length():
|
||||
section_header("decompressobj max_length")
|
||||
|
||||
inp: str = "This is a longer string for testing max_length parameter in decompress."
|
||||
input_length: t.CSizeT = strlen(inp)
|
||||
input_length: sizet = strlen(inp)
|
||||
printf(" Input (%zu bytes): \"%s\"\n", input_length, inp)
|
||||
|
||||
out_length: t.CSizeT = 0
|
||||
out_length: sizet = 0
|
||||
compressed: BYTEPTR = pyzlib.compress(None, BYTEPTR(inp), input_length,
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, &out_length)
|
||||
printf(" Compressed: %zu bytes\n", out_length)
|
||||
|
||||
d: pyzlib.Decompress | t.CPtr = pyzlib.decompressobj(None, pyzlib.MAX_WBITS, None, 0)
|
||||
|
||||
dec_length: t.CSizeT = 0
|
||||
dec_length: sizet = 0
|
||||
dec: BYTEPTR = d.decompress(compressed, out_length,
|
||||
10, c.Addr(dec_length))
|
||||
10, &dec_length)
|
||||
check("max_length decompress OK", dec != None, "decompress returned None")
|
||||
check("max_length limits output", dec_length <= 10, "output exceeded max_length")
|
||||
if dec:
|
||||
printf(" First chunk (max_length=10): \"%.*s\" (%zu bytes)\n", t.CInt(dec_length), str(dec), dec_length)
|
||||
printf(" First chunk (max_length=10): \"%.*s\" (%zu bytes)\n", int(dec_length), str(dec), dec_length)
|
||||
stdlib.free(dec)
|
||||
|
||||
tail_length: t.CSizeT = 0
|
||||
tail: BYTEPTR = d.unconsumed_tail(c.Addr(tail_length))
|
||||
tail_length: sizet = 0
|
||||
tail: BYTEPTR = d.unconsumed_tail(&tail_length)
|
||||
check("unconsumed_tail exists", tail != None or tail_length == 0, "no unconsumed_tail")
|
||||
printf(" unconsumed_tail: %zu bytes remaining\n", tail_length)
|
||||
printf(" eof = %d\n", d.eof)
|
||||
|
||||
if tail_length > 0 or not d.eof:
|
||||
flushed: BYTEPTR = d.flush(pyzlib.DEF_BUF_SIZE, c.Addr(dec_length))
|
||||
flushed: BYTEPTR = d.flush(pyzlib.DEF_BUF_SIZE, &dec_length)
|
||||
check("flush after max_length OK", flushed != None, "flush returned None")
|
||||
if flushed: printf(" Flushed (%zu bytes): \"%.*s\"\n", dec_length, t.CInt(dec_length), str(flushed))
|
||||
if flushed: printf(" Flushed (%zu bytes): \"%.*s\"\n", dec_length, int(dec_length), str(flushed))
|
||||
stdlib.free(flushed)
|
||||
|
||||
printf(" eof after flush = %d\n", d.eof)
|
||||
@@ -280,15 +280,15 @@ def test_decompressobj_unused_data():
|
||||
section_header("decompressobj unused_data")
|
||||
|
||||
inp: str = "Hello"
|
||||
input_length: t.CSizeT = strlen(inp)
|
||||
input_length: sizet = strlen(inp)
|
||||
printf(" Input: \"%s\"\n", inp)
|
||||
|
||||
out_length: t.CSizeT = 0
|
||||
out_length: sizet = 0
|
||||
compressed: BYTEPTR = pyzlib.compress(None, BYTEPTR(inp), input_length,
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, &out_length)
|
||||
printf(" Compressed: %zu bytes\n", out_length)
|
||||
|
||||
total_length: t.CSizeT = out_length + 5
|
||||
total_length: sizet = out_length + 5
|
||||
combined: BYTEPTR = BYTEPTR(stdlib.malloc(total_length))
|
||||
string.memcpy(combined, compressed, out_length)
|
||||
string.memcpy(combined + out_length, "EXTRA", 5)
|
||||
@@ -297,22 +297,22 @@ def test_decompressobj_unused_data():
|
||||
|
||||
d: pyzlib.Decompress | t.CPtr = pyzlib.decompressobj(None, pyzlib.MAX_WBITS, None, 0)
|
||||
|
||||
dec_length: t.CSizeT = 0
|
||||
dec_length: sizet = 0
|
||||
dec: BYTEPTR = d.decompress(combined, total_length,
|
||||
0, c.Addr(dec_length))
|
||||
0, &dec_length)
|
||||
check("decompress with extra OK", dec != None, "decompress returned None")
|
||||
check("eof after stream end", d.eof == 1, "eof should be 1")
|
||||
if dec:
|
||||
printf(" Decompressed: \"%.*s\" (%zu bytes)\n", t.CInt(dec_length), str(dec), dec_length)
|
||||
printf(" Decompressed: \"%.*s\" (%zu bytes)\n", int(dec_length), str(dec), dec_length)
|
||||
stdlib.free(dec)
|
||||
|
||||
print_separator()
|
||||
|
||||
unused_length: t.CSizeT = 0
|
||||
unused: BYTEPTR = d.unused_data(c.Addr(unused_length))
|
||||
unused_length: sizet = 0
|
||||
unused: BYTEPTR = d.unused_data(&unused_length)
|
||||
check("unused_data exists", unused != None and unused_length > 0, "no unused_data")
|
||||
check("unused_data is EXTRA", unused_length == 5 and unused != None and string.memcmp(unused, "EXTRA", 5) == 0, "unused_data mismatch")
|
||||
printf(" unused_data (%zu bytes): \"%.*s\"\n", unused_length, t.CInt(unused_length), str(unused))
|
||||
printf(" unused_data (%zu bytes): \"%.*s\"\n", unused_length, int(unused_length), str(unused))
|
||||
|
||||
d.delete()
|
||||
stdlib.free(combined)
|
||||
@@ -323,14 +323,14 @@ def test_compress_copy():
|
||||
section_header("Compress.copy()")
|
||||
|
||||
inp: str = "Copy test data for compress object"
|
||||
input_length: t.CSizeT = strlen(inp)
|
||||
input_length: sizet = strlen(inp)
|
||||
printf(" Input: \"%s\"\n", inp)
|
||||
|
||||
out_length: t.CSizeT = 0
|
||||
out_length: sizet = 0
|
||||
c1: pyzlib.Compress | t.CPtr = pyzlib.compressobj(None, pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.DEFLATED,
|
||||
pyzlib.MAX_WBITS, pyzlib.DEF_MEM_LEVEL,
|
||||
pyzlib.Z_DEFAULT_STRATEGY, None, 0)
|
||||
c1.compress(BYTEPTR(inp), input_length, c.Addr(out_length))
|
||||
c1.compress(BYTEPTR(inp), input_length, &out_length)
|
||||
printf(" Original: compressed %zu bytes so far\n", out_length)
|
||||
|
||||
c2: pyzlib.Compress | t.CPtr = c1.copy()
|
||||
@@ -339,15 +339,15 @@ def test_compress_copy():
|
||||
|
||||
print_separator()
|
||||
|
||||
f1: BYTEPTR = c1.flush(pyzlib.Z_FINISH, c.Addr(out_length))
|
||||
f1: BYTEPTR = c1.flush(pyzlib.Z_FINISH, &out_length)
|
||||
check("flush original OK", f1 != None, "flush original failed")
|
||||
length1: t.CSizeT = out_length
|
||||
length1: sizet = out_length
|
||||
printf(" Original flush: %zu bytes\n", length1)
|
||||
stdlib.free(f1)
|
||||
|
||||
f2: BYTEPTR = c2.flush(pyzlib.Z_FINISH, c.Addr(out_length))
|
||||
f2: BYTEPTR = c2.flush(pyzlib.Z_FINISH, &out_length)
|
||||
check("flush copy OK", f2 != None, "flush copy failed")
|
||||
length2: t.CSizeT = out_length
|
||||
length2: sizet = out_length
|
||||
printf(" Copy flush : %zu bytes\n", length2)
|
||||
stdlib.free(f2)
|
||||
|
||||
@@ -362,12 +362,12 @@ def test_decompress_copy():
|
||||
section_header("Decompress.copy()")
|
||||
|
||||
inp: str = "Decompress copy test"
|
||||
input_length: t.CSizeT = strlen(inp)
|
||||
input_length: sizet = strlen(inp)
|
||||
printf(" Input: \"%s\"\n", inp)
|
||||
|
||||
out_length: t.CSizeT = 0
|
||||
out_length: sizet = 0
|
||||
compressed: BYTEPTR = pyzlib.compress(None, BYTEPTR(inp), input_length,
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, &out_length)
|
||||
printf(" Compressed: %zu bytes\n", out_length)
|
||||
|
||||
d1: pyzlib.Decompress | t.CPtr = pyzlib.decompressobj(None, pyzlib.MAX_WBITS, None, 0)
|
||||
@@ -377,18 +377,18 @@ def test_decompress_copy():
|
||||
|
||||
print_separator()
|
||||
|
||||
dec_length1: t.CSizeT = 0
|
||||
dec_length2: t.CSizeT = 0
|
||||
dec_length1: sizet = 0
|
||||
dec_length2: sizet = 0
|
||||
dec1: BYTEPTR = d1.decompress(compressed, out_length,
|
||||
0, c.Addr(dec_length1))
|
||||
0, &dec_length1)
|
||||
dec2: BYTEPTR = d2.decompress(compressed, out_length,
|
||||
0, c.Addr(dec_length2))
|
||||
0, &dec_length2)
|
||||
check("decompress copy output size", dec_length1 == dec_length2, "sizes differ")
|
||||
check("decompress copy output content",
|
||||
dec1 and dec2 and string.memcmp(dec1, dec2, dec_length1) == 0, "content differs")
|
||||
|
||||
if dec1: printf(" Original: \"%.*s\" (%zu bytes)\n", t.CInt(dec_length1), str(dec1), dec_length1)
|
||||
if dec2: printf(" Copy : \"%.*s\" (%zu bytes)\n", t.CInt(dec_length2), str(dec2), dec_length2)
|
||||
if dec1: printf(" Original: \"%.*s\" (%zu bytes)\n", int(dec_length1), str(dec1), dec_length1)
|
||||
if dec2: printf(" Copy : \"%.*s\" (%zu bytes)\n", int(dec_length2), str(dec2), dec_length2)
|
||||
|
||||
stdlib.free(dec1)
|
||||
stdlib.free(dec2)
|
||||
@@ -435,18 +435,18 @@ def test_crc32():
|
||||
def test_empty_compress():
|
||||
section_header("Empty data compress/decompress")
|
||||
|
||||
out_length: t.CSizeT = 0
|
||||
out_length: sizet = 0
|
||||
compressed: BYTEPTR = pyzlib.compress(None, BYTEPTR(""), 0,
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, c.Addr(out_length))
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.MAX_WBITS, &out_length)
|
||||
check("compress empty OK", compressed != None, "compress empty returned None")
|
||||
check("compress empty output > 0", out_length > 0, "compressed empty is 0 bytes")
|
||||
printf(" Empty input compressed: %zu bytes (header only)\n", out_length)
|
||||
printf(" Hex: ")
|
||||
print_hex_test(compressed, out_length, 32)
|
||||
|
||||
dec_length: t.CSizeT = 0
|
||||
dec_length: sizet = 0
|
||||
decompressed: BYTEPTR = pyzlib.decompress(None, compressed, out_length,
|
||||
pyzlib.MAX_WBITS, pyzlib.DEF_BUF_SIZE, c.Addr(dec_length))
|
||||
pyzlib.MAX_WBITS, pyzlib.DEF_BUF_SIZE, &dec_length)
|
||||
check("decompress empty OK", decompressed != None, "decompress empty returned None")
|
||||
check("decompress empty size == 0", dec_length == 0, "decompressed size != 0")
|
||||
printf(" Decompressed back: %zu bytes\n", dec_length)
|
||||
@@ -460,27 +460,27 @@ def test_gzip_format():
|
||||
section_header("Gzip format (wbits=31)")
|
||||
|
||||
inp: str = "Gzip format test"
|
||||
input_length: t.CSizeT = strlen(inp)
|
||||
input_length: sizet = strlen(inp)
|
||||
printf(" Input: \"%s\" (%zu bytes)\n", inp, input_length)
|
||||
|
||||
gzip_wbits: t.CInt = pyzlib.MAX_WBITS + 16
|
||||
gzip_wbits: int = pyzlib.MAX_WBITS + 16
|
||||
printf(" wbits = MAX_WBITS + 16 = %d\n", gzip_wbits)
|
||||
|
||||
out_length: t.CSizeT = 0
|
||||
out_length: sizet = 0
|
||||
compressed: BYTEPTR = pyzlib.compress(None, BYTEPTR(inp), input_length,
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, gzip_wbits, c.Addr(out_length))
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, gzip_wbits, &out_length)
|
||||
check("gzip compress OK", compressed != None, "gzip compress failed")
|
||||
printf(" Gzip compressed: %zu bytes\n", out_length)
|
||||
printf(" Header bytes: ")
|
||||
print_hex_test(compressed, 4 if (out_length > 4) else out_length, 4)
|
||||
|
||||
dec_length: t.CSizeT = 0
|
||||
dec_length: sizet = 0
|
||||
decompressed: BYTEPTR = pyzlib.decompress(None, compressed, out_length,
|
||||
gzip_wbits, pyzlib.DEF_BUF_SIZE, c.Addr(dec_length))
|
||||
gzip_wbits, pyzlib.DEF_BUF_SIZE, &dec_length)
|
||||
check("gzip decompress OK", decompressed != None, "gzip decompress failed")
|
||||
check("gzip decompress size", dec_length == input_length, "size mismatch")
|
||||
check("gzip decompress content", decompressed != None and string.memcmp(decompressed, inp, input_length) == 0, "content mismatch")
|
||||
if decompressed: printf(" Decompressed: \"%.*s\" (%zu bytes)\n", t.CInt(dec_length), str(decompressed), dec_length)
|
||||
if decompressed: printf(" Decompressed: \"%.*s\" (%zu bytes)\n", int(dec_length), str(decompressed), dec_length)
|
||||
|
||||
stdlib.free(compressed)
|
||||
stdlib.free(decompressed)
|
||||
@@ -491,25 +491,25 @@ def test_raw_deflate():
|
||||
section_header("Raw deflate (wbits=-15)")
|
||||
|
||||
inp: str = "Raw deflate test"
|
||||
input_length: t.CSizeT = strlen(inp)
|
||||
input_length: sizet = strlen(inp)
|
||||
printf(" Input: \"%s\" (%zu bytes)\n", inp, input_length)
|
||||
|
||||
raw_wbits: t.CInt = -pyzlib.MAX_WBITS
|
||||
raw_wbits: int = -pyzlib.MAX_WBITS
|
||||
printf(" wbits = -MAX_WBITS = %d\n", raw_wbits)
|
||||
|
||||
out_length: t.CSizeT = 0
|
||||
out_length: sizet = 0
|
||||
compressed: BYTEPTR = pyzlib.compress(None, BYTEPTR(inp), input_length,
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, raw_wbits, c.Addr(out_length))
|
||||
pyzlib.Z_DEFAULT_COMPRESSION, raw_wbits, &out_length)
|
||||
check("raw deflate compress OK", compressed != None, "raw deflate compress failed")
|
||||
printf(" Raw compressed: %zu bytes\n", out_length)
|
||||
|
||||
dec_length: t.CSizeT = 0
|
||||
dec_length: sizet = 0
|
||||
decompressed: BYTEPTR = pyzlib.decompress(None, compressed, out_length,
|
||||
raw_wbits, pyzlib.DEF_BUF_SIZE, c.Addr(dec_length))
|
||||
raw_wbits, pyzlib.DEF_BUF_SIZE, &dec_length)
|
||||
check("raw deflate decompress OK", decompressed != None, "raw deflate decompress failed")
|
||||
check("raw deflate decompress size", dec_length == input_length, "size mismatch")
|
||||
check("raw deflate decompress content", decompressed != None and string.memcmp(decompressed, inp, input_length) == 0, "content mismatch")
|
||||
if decompressed: printf(" Decompressed: \"%.*s\" (%zu bytes)\n", t.CInt(dec_length), str(decompressed), dec_length)
|
||||
if decompressed: printf(" Decompressed: \"%.*s\" (%zu bytes)\n", int(dec_length), str(decompressed), dec_length)
|
||||
|
||||
stdlib.free(compressed)
|
||||
stdlib.free(decompressed)
|
||||
@@ -521,11 +521,11 @@ def test_zdict():
|
||||
|
||||
dict: str = "common words that appear frequently in the data"
|
||||
inp: str = "common words that appear frequently"
|
||||
input_length: t.CSizeT = strlen(inp)
|
||||
input_length: sizet = strlen(inp)
|
||||
printf(" Dictionary: \"%s\" (%zu bytes)\n", dict, strlen(dict))
|
||||
printf(" Input : \"%s\" (%zu bytes)\n", inp, input_length)
|
||||
|
||||
out_length: t.CSizeT = 0
|
||||
out_length: sizet = 0
|
||||
s: pyzlib.Compress | t.CPtr = pyzlib.compressobj(None, pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.DEFLATED,
|
||||
pyzlib.MAX_WBITS, pyzlib.DEF_MEM_LEVEL,
|
||||
pyzlib.Z_DEFAULT_STRATEGY,
|
||||
@@ -533,28 +533,28 @@ def test_zdict():
|
||||
check("compressobj with zdict OK", s != None, "compressobj with zdict failed")
|
||||
|
||||
comp_data: BYTEPTR = s.compress(BYTEPTR(inp),
|
||||
input_length, c.Addr(out_length))
|
||||
input_length, &out_length)
|
||||
check("compress with zdict OK", comp_data != None, "compress with zdict failed")
|
||||
printf(" Compressed with zdict: %zu bytes\n", out_length)
|
||||
stdlib.free(comp_data)
|
||||
|
||||
flush_data: BYTEPTR = s.flush(pyzlib.Z_FINISH, c.Addr(out_length))
|
||||
flush_data: BYTEPTR = s.flush(pyzlib.Z_FINISH, &out_length)
|
||||
check("flush with zdict OK", flush_data != None, "flush with zdict failed")
|
||||
printf(" Flush: %zu bytes\n", out_length)
|
||||
stdlib.free(flush_data)
|
||||
|
||||
print_separator()
|
||||
|
||||
total_comp: t.CSizeT = out_length
|
||||
total_comp: sizet = out_length
|
||||
s.delete()
|
||||
|
||||
s = pyzlib.compressobj(None, pyzlib.Z_DEFAULT_COMPRESSION, pyzlib.DEFLATED,
|
||||
pyzlib.MAX_WBITS, pyzlib.DEF_MEM_LEVEL,
|
||||
pyzlib.Z_DEFAULT_STRATEGY, None, 0)
|
||||
comp_no_dict: BYTEPTR = s.compress(BYTEPTR(inp),
|
||||
input_length, c.Addr(out_length))
|
||||
flush_no_dict: BYTEPTR = s.flush(pyzlib.Z_FINISH, c.Addr(out_length))
|
||||
no_dict_total: t.CSizeT = 0
|
||||
input_length, &out_length)
|
||||
flush_no_dict: BYTEPTR = s.flush(pyzlib.Z_FINISH, &out_length)
|
||||
no_dict_total: sizet = 0
|
||||
if comp_no_dict: no_dict_total += out_length
|
||||
if flush_no_dict: no_dict_total += out_length
|
||||
printf(" Without zdict: ~%zu bytes compressed\n", no_dict_total)
|
||||
@@ -576,9 +576,9 @@ def test_huffman_tree():
|
||||
check("fixed lit tree count == 288", lit_tree.count == 288, "count mismatch")
|
||||
check("fixed lit tree max_bits == 9", lit_tree.max_bits == 9, "max_bits mismatch")
|
||||
|
||||
has_8bit: t.CInt = 0
|
||||
has_9bit: t.CInt = 0
|
||||
has_7bit: t.CInt = 0
|
||||
has_8bit: int = 0
|
||||
has_9bit: int = 0
|
||||
has_7bit: int = 0
|
||||
for i in range(143 + 1):
|
||||
if lit_tree.codes[i].bits == 8:
|
||||
has_8bit += 1
|
||||
@@ -605,7 +605,7 @@ def test_huffman_tree():
|
||||
check("fixed dist tree count == 32", dist_tree.count == 32, "count mismatch")
|
||||
check("fixed dist tree max_bits == 5", dist_tree.max_bits == 5, "max_bits mismatch")
|
||||
|
||||
all_5bit: t.CInt = 1
|
||||
all_5bit: int = 1
|
||||
for i in range(32):
|
||||
if dist_tree.codes[i].bits != 5:
|
||||
all_5bit = 0
|
||||
@@ -613,7 +613,7 @@ def test_huffman_tree():
|
||||
printf(" All 32 distance codes: 5 bits each\n")
|
||||
|
||||
printf("\n --- Dynamic Huffman tree from frequencies ---\n")
|
||||
dyn_freqs: t.CArray[t.CInt, 256]
|
||||
dyn_freqs: t.CArray[int, 256]
|
||||
string.memset(dyn_freqs, 0, dyn_freqs.__sizeof__())
|
||||
dyn_freqs['A'] = 50
|
||||
dyn_freqs['B'] = 25
|
||||
@@ -629,8 +629,8 @@ def test_huffman_tree():
|
||||
check("dynamic tree count == 257", dyn_tree.count == 257, "count mismatch")
|
||||
check("dynamic tree max_bits <= 15", dyn_tree.max_bits <= 15, "max_bits overflow")
|
||||
|
||||
total_codes: t.CInt = 0
|
||||
max_length_found: t.CInt = 0
|
||||
total_codes: int = 0
|
||||
max_length_found: int = 0
|
||||
for i in range(257):
|
||||
if dyn_tree.codes[i].bits > 0:
|
||||
total_codes += 1
|
||||
@@ -644,7 +644,7 @@ def test_huffman_tree():
|
||||
|
||||
printf(" Code assignments:\n")
|
||||
names: t.CArray[str, None] = ["A","B","C","D","E","F"] # ä¸ä¸ªé½æ?char* çæ°ç»?
|
||||
syms: t.CArray[t.CInt, None] = ['A','B','C','D','E','F']
|
||||
syms: t.CArray[int, None] = ['A','B','C','D','E','F']
|
||||
for i in range(6):
|
||||
printf(" '%s' (freq=%3d): code=0x%04X, bits=%d\n",
|
||||
names[i], dyn_freqs[syms[i]],
|
||||
@@ -655,15 +655,15 @@ def test_huffman_tree():
|
||||
|
||||
printf(" EOB (freq=1): code=0x%04X, bits=%d\n",
|
||||
dyn_tree.codes[256].code, dyn_tree.codes[256].bits)
|
||||
a_bits: t.CInt = dyn_tree.codes['A'].bits
|
||||
f_bits: t.CInt = dyn_tree.codes['F'].bits
|
||||
a_bits: int = dyn_tree.codes['A'].bits
|
||||
f_bits: int = dyn_tree.codes['F'].bits
|
||||
check("high-freq symbol has shorter code", a_bits <= f_bits, "A should be <= F")
|
||||
printf(" High-freq 'A' (%d bits) <= low-freq 'F' (%d bits): %s\n",
|
||||
a_bits, f_bits, "YES" if (a_bits <= f_bits) else "NO")
|
||||
|
||||
printf("\n --- Huffman encode/decode roundtrip ---\n")
|
||||
|
||||
rt_freqs: t.CArray[t.CInt, 288]
|
||||
rt_freqs: t.CArray[int, 288]
|
||||
string.memset(rt_freqs, 0, rt_freqs.__sizeof__())
|
||||
rt_freqs['H'] = 10
|
||||
rt_freqs['e'] = 8
|
||||
@@ -680,15 +680,15 @@ def test_huffman_tree():
|
||||
enc_tree.build_codes(rt_freqs, 257, 15)
|
||||
|
||||
dec_tree = zhuff.zhuff_decode_tree()
|
||||
dec_tree.build_decode_tree(c.Addr(enc_tree))
|
||||
dec_tree.build_decode_tree(&enc_tree)
|
||||
|
||||
writer = zdef.zbit_writer(None)
|
||||
|
||||
symbols: t.CArray[t.CInt, None] = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', 256]
|
||||
num_symbols: t.CInt = 13
|
||||
symbols: t.CArray[int, None] = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', 256]
|
||||
num_symbols: int = 13
|
||||
|
||||
for i in range(num_symbols):
|
||||
enc_tree.encode_symbol(symbols[i], c.Addr(writer))
|
||||
enc_tree.encode_symbol(symbols[i], &writer)
|
||||
|
||||
reader = zdef.zbit_reader()
|
||||
reader.buf = writer.buf
|
||||
@@ -696,9 +696,9 @@ def test_huffman_tree():
|
||||
reader.byte_pos = 0
|
||||
reader.bit_pos = 0
|
||||
|
||||
roundtrip_ok: t.CInt = 1
|
||||
roundtrip_ok: int = 1
|
||||
for i in range(num_symbols):
|
||||
decoded: t.CInt = dec_tree.decode_symbol(c.Addr(reader))
|
||||
decoded: int = dec_tree.decode_symbol(&reader)
|
||||
if decoded != symbols[i]:
|
||||
roundtrip_ok = 0
|
||||
printf(" MISMATCH at symbol %d: expected %d, got %d\n", i, symbols[i], decoded)
|
||||
@@ -710,7 +710,7 @@ def test_huffman_tree():
|
||||
stdlib.free(writer.buf)
|
||||
|
||||
printf("\n --- Overflow handling (many symbols, limited max_bits) ---\n")
|
||||
of_freqs: t.CArray[t.CInt, 256]
|
||||
of_freqs: t.CArray[int, 256]
|
||||
for i in range(256):
|
||||
of_freqs[i] = 1
|
||||
of_freqs[256] = 1
|
||||
@@ -718,14 +718,14 @@ def test_huffman_tree():
|
||||
of_tree = zhuff.zhuff_tree()
|
||||
of_tree.build_codes(of_freqs, 257, 15)
|
||||
|
||||
overflow_ok: t.CInt = 1
|
||||
overflow_ok: int = 1
|
||||
for i in range(257):
|
||||
if of_tree.codes[i].bits > 15 or of_tree.codes[i].bits < 0:
|
||||
overflow_ok = 0
|
||||
break
|
||||
check("all code lengthgths <= 15 with 257 symbols", overflow_ok, "code lengthgth overflow")
|
||||
|
||||
bl_count: t.CArray[t.CInt, 16] = [0]
|
||||
bl_count: t.CArray[int, 16] = [0]
|
||||
for i in range(257):
|
||||
if of_tree.codes[i].bits > 0:
|
||||
bl_count[of_tree.codes[i].bits] += 1
|
||||
@@ -735,13 +735,13 @@ def test_huffman_tree():
|
||||
printf(" %2d bits: %3d codes\n", i, bl_count[i])
|
||||
|
||||
dt = zhuff.zhuff_decode_tree()
|
||||
dt.build_decode_tree(c.Addr(of_tree))
|
||||
dt.build_decode_tree(&of_tree)
|
||||
|
||||
w = zdef.zbit_writer(None)
|
||||
of_tree.encode_symbol(0, c.Addr(w))
|
||||
of_tree.encode_symbol(128, c.Addr(w))
|
||||
of_tree.encode_symbol(255, c.Addr(w))
|
||||
of_tree.encode_symbol(256, c.Addr(w))
|
||||
of_tree.encode_symbol(0, &w)
|
||||
of_tree.encode_symbol(128, &w)
|
||||
of_tree.encode_symbol(255, &w)
|
||||
of_tree.encode_symbol(256, &w)
|
||||
|
||||
r = zdef.zbit_reader()
|
||||
r.buf = w.buf
|
||||
@@ -749,10 +749,10 @@ def test_huffman_tree():
|
||||
r.byte_pos = 0
|
||||
r.bit_pos = 0
|
||||
|
||||
s0: t.CInt = dt.decode_symbol(c.Addr(r))
|
||||
s1: t.CInt = dt.decode_symbol(c.Addr(r))
|
||||
s2: t.CInt = dt.decode_symbol(c.Addr(r))
|
||||
s3: t.CInt = dt.decode_symbol(c.Addr(r))
|
||||
s0: int = dt.decode_symbol(&r)
|
||||
s1: int = dt.decode_symbol(&r)
|
||||
s2: int = dt.decode_symbol(&r)
|
||||
s3: int = dt.decode_symbol(&r)
|
||||
|
||||
check("overflow roundtrip: symbol 0", s0 == 0, "decode mismatch")
|
||||
check("overflow roundtrip: symbol 128", s1 == 128, "decode mismatch")
|
||||
@@ -766,7 +766,7 @@ def test_huffman_tree():
|
||||
# 与 ZlibDbg 的失败形态(码表把部分符号编成无码位/错码位)直接对齐。
|
||||
w2 = zdef.zbit_writer(None)
|
||||
for i in range(257):
|
||||
of_tree.encode_symbol(i, c.Addr(w2))
|
||||
of_tree.encode_symbol(i, &w2)
|
||||
|
||||
r2 = zdef.zbit_reader()
|
||||
r2.buf = w2.buf
|
||||
@@ -774,9 +774,9 @@ def test_huffman_tree():
|
||||
r2.byte_pos = 0
|
||||
r2.bit_pos = 0
|
||||
|
||||
full_ok: t.CInt = 1
|
||||
full_ok: int = 1
|
||||
for i in range(257):
|
||||
got: t.CInt = dt.decode_symbol(c.Addr(r2))
|
||||
got: int = dt.decode_symbol(&r2)
|
||||
if got != i:
|
||||
full_ok = 0
|
||||
printf(" FULL ROUNDTRIP MISMATCH at %d: got %d\n", i, got)
|
||||
@@ -786,7 +786,7 @@ def test_huffman_tree():
|
||||
|
||||
|
||||
printf("\n --- Kraft inequality check ---\n")
|
||||
kf_freqs: t.CArray[t.CInt, 256]
|
||||
kf_freqs: t.CArray[int, 256]
|
||||
string.memset(kf_freqs, 0, kf_freqs.__sizeof__())
|
||||
kf_freqs['X'] = 100
|
||||
kf_freqs['Y'] = 50
|
||||
@@ -796,10 +796,10 @@ def test_huffman_tree():
|
||||
kf_tree = zhuff.zhuff_tree()
|
||||
kf_tree.build_codes(kf_freqs, 257, 15)
|
||||
|
||||
kraft_sum: t.CDouble = 0.0
|
||||
kraft_sum: double = 0.0
|
||||
for i in range(257):
|
||||
if kf_tree.codes[i].bits > 0:
|
||||
kraft_sum += 1.0 / (t.CDouble(ULONGLONG(1) << kf_tree.codes[i].bits))
|
||||
kraft_sum += 1.0 / (double(ULONGLONG(1) << kf_tree.codes[i].bits))
|
||||
check("Kraft inequality: sum <= 1.0", kraft_sum <= 1.0 + 1e-9, "Kraft violated")
|
||||
printf(" Kraft sum = %.10f (must be <= 1.0)\n", kraft_sum)
|
||||
|
||||
@@ -809,11 +809,11 @@ def test_huffman_tree():
|
||||
def test_error_handling():
|
||||
section_header("Error handling")
|
||||
|
||||
out_length: t.CSizeT = 0
|
||||
out_length: sizet = 0
|
||||
printf(" Trying to decompress garbage data...\n")
|
||||
|
||||
result: BYTEPTR = pyzlib.decompress(None, BYTEPTR("garbage"), 7,
|
||||
pyzlib.MAX_WBITS, pyzlib.DEF_BUF_SIZE, c.Addr(out_length))
|
||||
pyzlib.MAX_WBITS, pyzlib.DEF_BUF_SIZE, &out_length)
|
||||
check("decompress garbage returns None", result == None, "should have returned None")
|
||||
printf(" Error code : %d\n", pyzlib.get_error_code())
|
||||
printf(" Error message: \"%s\"\n", pyzlib.get_error())
|
||||
@@ -869,7 +869,7 @@ def test_constants():
|
||||
section_footer()
|
||||
|
||||
|
||||
def main123456() -> t.CInt:
|
||||
def main123456() -> int:
|
||||
printf("==============================================\n")
|
||||
printf(" Python zlib - C Implementation Tests\n")
|
||||
printf("==============================================\n")
|
||||
|
||||
Reference in new issue
Block a user