Files
Viper_RegressionTesting/NewTest/App/main.vp
T
TermiNexus 9eb037ee8f test(new): NewTest 增加“stack 生命期缺省=slife”对照用例;README 同步
新增 (3) `new stack Point(7,8)`(不写 slife)与 (1) 显式 slife 等价,专门验证缺省规则;文件头补上完整缺省表:省略来源→heap,省略生命期→stack 为 slife、heap/memgr 为 hlife。
2026-10-08 18:21:13 +08:00

58 lines
2.3 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from stdint import *
import w32.win32console
import t, c
from t import CInt, CExport
import stdio
import stdlib
import memhub
# =============================================================================
# M2.4 `new` 描述符分配:三来源各自落地不同(IR 差异见下方注释)
# stack → 帧内 alloca(无 malloc 调用,随帧失效)
# heap → call i8* @malloc(i64 sizeof) + bitcast 到 T*
# memgr → call i8* @<Mgr>.alloc(i64 sizeof) + bitcast 到 T*
# 本工程做冒烟验证:能编译、能跑出正确字段值。
# 描述符顺序无关;**缺省规则**(D3 / §3.2):
# 省略来源 → heap
# 省略生命期 → 由**来源**决定:stack → slife(帧生命期),heap / memgr → hlife
# 于是:`new stack Point(7,8)` ≡ `new stack slife Point(7,8)`(stack 默认 slife)
# `new Point(3,4)` ≡ `new heap hlife Point(3,4)`(完全省略即堆 + 自由生命期)
# =============================================================================
novirtual class Point:
x: int
y: int
def main() -> CInt | CExport:
w32.win32console.SetConsoleCP(65001)
w32.win32console.SetConsoleOutputCP(65001)
# (1) stack:等价既有写法 &Point(1, 2),生命期随帧
p1: Point* = new stack slife Point(1, 2)
stdio.printf("stack: %d %d\n", p1.x, p1.y)
# (2) heap:malloc(sizeof(Point)) + 构造(生命期默认 hlife)
p2: Point* = new heap Point(3, 4)
stdio.printf("heap : %d %d\n", p2.x, p2.y)
# (3) stack + **生命期缺省** → slife(与 (1) 显式写 slife 等价,专门验证缺省规则)
p3: Point* = new stack Point(7, 8)
stdio.printf("stack默认slife: %d %d\n", p3.x, p3.y)
# (4) memgr(x):从 memhub 管理器取存储(管理器构造方式见 Test/MemhubTest)
arena: bytes = stdlib.malloc(65536)
m: memhub.MemBuddy = memhub.MemBuddy(arena, 65536)
p4: Point* = new memgr(m) hlife Point(5, 6)
stdio.printf("memgr: %d %d\n", p4.x, p4.y)
stdlib.free(arena)
# 非法组合(应报 LifetimeError)——要验证时打开其中一条:
# 1) 语义矛盾:bad: Point* = new stack hlife Point(7, 8)
# 2) 多来源 :new stack heap Point(7, 8) → 解析期报错
# 3) 多生命期:new heap slife hlife Point(7, 8) → 解析期报错
return 0