diff --git a/argparse.vp b/argparse.vp index 3a48287..37b9ed8 100644 --- a/argparse.vp +++ b/argparse.vp @@ -428,7 +428,7 @@ class ArgumentParser: # release — Release ParsedArgs and all internal resources # ============================================================ -def release(args: rawptr[ParsedArgs]): +def release(args: ParsedArgs*): """Free ParsedArgs object and its inner HashTable resources.""" if args is None: return if args.__mbuddy__ is None: return diff --git a/ast/__init__.vp b/ast/__init__.vp index 5124876..01e3e97 100644 --- a/ast/__init__.vp +++ b/ast/__init__.vp @@ -69,7 +69,7 @@ _mbuddy: memhub.MemBuddy* # ============================================================ # Common API: parse # ============================================================ -def parse(src: str, pool: rawptr[memhub.MemManager]) -> rawptr[AST]: +def parse(src: str, pool: memhub.MemManager*) -> AST*: """Parse Python source code, return the AST Module node. Parameters: @@ -81,16 +81,16 @@ def parse(src: str, pool: rawptr[memhub.MemManager]) -> rawptr[AST]: """ if src is None or pool is None: return None _init_tables(pool) - lx: rawptr[Lexer] = new_lexer(pool) + lx: Lexer* = new_lexer(pool) if lx is None: return None _lexer_init(lx, src, pool) - tokens: rawptr[Token] = tokenize(lx) + tokens: Token* = tokenize(lx) if tokens is None: return None - tree: rawptr[AST] = parse_tokens(pool, tokens) + tree: AST* = parse_tokens(pool, tokens) return tree -def parse_expression(src: str, pool: rawptr[memhub.MemManager]) -> rawptr[Expression]: +def parse_expression(src: str, pool: memhub.MemManager*) -> Expression*: """Parse a single expression, return the Expression node. Parameters: @@ -102,13 +102,13 @@ def parse_expression(src: str, pool: rawptr[memhub.MemManager]) -> rawptr[Expres """ if src is None or pool is None: return None _init_tables(pool) - lx: rawptr[Lexer] = new_lexer(pool) + lx: Lexer* = new_lexer(pool) if lx is None: return None _lexer_init(lx, src, pool) - tokens: rawptr[Token] = tokenize(lx) + tokens: Token* = tokenize(lx) if tokens is None: return None - ps: rawptr[Parser] = new_parser(pool) + ps: Parser* = new_parser(pool) if ps is None: return None _parser_init(ps, tokens, pool) - body: rawptr[AST] = _parse_test(ps) + body: AST* = _parse_test(ps) return Expression(pool, body) diff --git a/ast/astaux.vp b/ast/astaux.vp index 19e33c9..9b7dc16 100644 --- a/ast/astaux.vp +++ b/ast/astaux.vp @@ -14,15 +14,15 @@ from .base import ( # ============================================================ class ExceptHandler(AST): """ExceptHandler(type: AST, name: str)""" - type: rawptr[AST] + type: AST* name: str - def __new__(self, pool: rawptr[memhub.MemManager], type: rawptr[AST], name: str): - ptr: rawptr[ExceptHandler] = pool.alloc(ExceptHandler.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, type: AST*, name: str): + ptr: ExceptHandler* = pool.alloc(ExceptHandler.__sizeof__()) if ptr: string.memset(ptr, 0, ExceptHandler.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], type: rawptr[AST], name: str): + def __init__(self, pool: memhub.MemManager*, type: AST*, name: str): _init_ast(self, pool, 0, 0) self.type = type self.name = _copy_str(pool, name) @@ -53,26 +53,26 @@ class ExceptHandler(AST): class Arguments(AST): """Arguments(args: list[AST | CPtr], vararg: AST, kwarg: AST, defaults: list[AST | CPtr], kw_defaults: list[AST | CPtr])""" - args: rawptr[list[rawptr[AST]]] - vararg: rawptr[AST] - kwarg: rawptr[AST] - defaults: rawptr[list[rawptr[AST]]] - kw_defaults: rawptr[list[rawptr[AST]]] + args: list[AST*]* + vararg: AST* + kwarg: AST* + defaults: list[AST*]* + kw_defaults: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - args: rawptr[list[rawptr[AST]]], - vararg: rawptr[AST], kwarg: rawptr[AST], - defaults: rawptr[list[rawptr[AST]]], - kw_defaults: rawptr[list[rawptr[AST]]]): - ptr: rawptr[Arguments] = pool.alloc(Arguments.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + args: list[AST*]*, + vararg: AST*, kwarg: AST*, + defaults: list[AST*]*, + kw_defaults: list[AST*]*): + ptr: Arguments* = pool.alloc(Arguments.__sizeof__()) if ptr: string.memset(ptr, 0, Arguments.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - args: rawptr[list[rawptr[AST]]], - vararg: rawptr[AST], kwarg: rawptr[AST], - defaults: rawptr[list[rawptr[AST]]], - kw_defaults: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + args: list[AST*]*, + vararg: AST*, kwarg: AST*, + defaults: list[AST*]*, + kw_defaults: list[AST*]*): _init_ast(self, pool, 0, 0) self.args = args self.vararg = vararg @@ -117,14 +117,14 @@ class Arguments(AST): class Arg(AST): """Arg(arg: str, annotation: AST)""" arg: str - annotation: rawptr[AST] + annotation: AST* - def __new__(self, pool: rawptr[memhub.MemManager], arg: str, annotation: rawptr[AST]): - ptr: rawptr[Arg] = pool.alloc(Arg.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, arg: str, annotation: AST*): + ptr: Arg* = pool.alloc(Arg.__sizeof__()) if ptr: string.memset(ptr, 0, Arg.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], arg: str, annotation: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, arg: str, annotation: AST*): _init_ast(self, pool, 0, 0) self.arg = _copy_str(pool, arg) self.annotation = annotation @@ -153,14 +153,14 @@ class Arg(AST): class Keyword(AST): """Keyword(arg: str, value: AST)""" arg: str - value: rawptr[AST] + value: AST* - def __new__(self, pool: rawptr[memhub.MemManager], arg: str, value: rawptr[AST]): - ptr: rawptr[Keyword] = pool.alloc(Keyword.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, arg: str, value: AST*): + ptr: Keyword* = pool.alloc(Keyword.__sizeof__()) if ptr: string.memset(ptr, 0, Keyword.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], arg: str, value: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, arg: str, value: AST*): _init_ast(self, pool, 0, 0) self.arg = _copy_str(pool, arg) self.value = value @@ -191,12 +191,12 @@ class Alias(AST): name: str asname: str - def __new__(self, pool: rawptr[memhub.MemManager], name: str, asname: str): - ptr: rawptr[Alias] = pool.alloc(Alias.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, name: str, asname: str): + ptr: Alias* = pool.alloc(Alias.__sizeof__()) if ptr: string.memset(ptr, 0, Alias.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], + def __init__(self, pool: memhub.MemManager*, name: str, asname: str): _init_ast(self, pool, 0, 0) self.name = _copy_str(pool, name) @@ -223,16 +223,16 @@ class Alias(AST): class WithItem(AST): """WithItem(context_expr: AST, optional_vars: AST)""" - context_expr: rawptr[AST] - optional_vars: rawptr[AST] + context_expr: AST* + optional_vars: AST* - def __new__(self, pool: rawptr[memhub.MemManager], context_expr: rawptr[AST], optional_vars: rawptr[AST]): - ptr: rawptr[WithItem] = pool.alloc(WithItem.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, context_expr: AST*, optional_vars: AST*): + ptr: WithItem* = pool.alloc(WithItem.__sizeof__()) if ptr: string.memset(ptr, 0, WithItem.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - context_expr: rawptr[AST], optional_vars: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + context_expr: AST*, optional_vars: AST*): _init_ast(self, pool, 0, 0) self.context_expr = context_expr self.optional_vars = optional_vars @@ -264,22 +264,22 @@ class WithItem(AST): class Comprehension(AST): """Comprehension(target: AST, iter: AST, ifs: list[AST | CPtr], is_async: CInt)""" - target: rawptr[AST] - iter: rawptr[AST] - ifs: rawptr[list[rawptr[AST]]] + target: AST* + iter: AST* + ifs: list[AST*]* is_async: int - def __new__(self, pool: rawptr[memhub.MemManager], - target: rawptr[AST], iter: rawptr[AST], - ifs: rawptr[list[rawptr[AST]]], is_async: int): - ptr: rawptr[Comprehension] = pool.alloc(Comprehension.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + target: AST*, iter: AST*, + ifs: list[AST*]*, is_async: int): + ptr: Comprehension* = pool.alloc(Comprehension.__sizeof__()) if ptr: string.memset(ptr, 0, Comprehension.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - target: rawptr[AST], iter: rawptr[AST], - ifs: rawptr[list[rawptr[AST]]], is_async: int): + def __init__(self, pool: memhub.MemManager*, + target: AST*, iter: AST*, + ifs: list[AST*]*, is_async: int): _init_ast(self, pool, 0, 0) self.target = target self.iter = iter diff --git a/ast/base.vp b/ast/base.vp index 01f740e..5639543 100644 --- a/ast/base.vp +++ b/ast/base.vp @@ -104,7 +104,7 @@ enum ASTFlag: # ============================================================ # Helper Functions # ============================================================ -def _copy_str(pool: rawptr[memhub.MemManager], src: str) -> str: +def _copy_str(pool: memhub.MemManager*, src: str) -> str: """Allocate and copy a C string from pool.""" if src is None: return None slen: sizet = string.strlen(src) @@ -114,7 +114,7 @@ def _copy_str(pool: rawptr[memhub.MemManager], src: str) -> str: return buf -def _set_pos(node: rawptr[AST], lineno: int, col_offset: int, end_lineno: int, end_col_offset: int): +def _set_pos(node: AST*, lineno: int, col_offset: int, end_lineno: int, end_col_offset: int): if node is None: return node.lineno = lineno node.col_offset = col_offset @@ -122,7 +122,7 @@ def _set_pos(node: rawptr[AST], lineno: int, col_offset: int, end_lineno: int, e node.end_col_offset = end_col_offset -def _inherit_pos(node: rawptr[AST], ref: rawptr[AST]): +def _inherit_pos(node: AST*, ref: AST*): if node is None or ref is None: return node.lineno = ref.lineno node.col_offset = ref.col_offset @@ -130,7 +130,7 @@ def _inherit_pos(node: rawptr[AST], ref: rawptr[AST]): node.end_col_offset = ref.end_col_offset -def _init_ast(node: rawptr[AST], pool: rawptr[memhub.MemManager], lineno: int, col: int): +def _init_ast(node: AST*, pool: memhub.MemManager*, lineno: int, col: int): """Initialize AST base fields.""" node.parent = None node.pool = pool @@ -141,16 +141,16 @@ def _init_ast(node: rawptr[AST], pool: rawptr[memhub.MemManager], lineno: int, c node.children = None -def _set_parent_list(lst: list[rawptr[AST]]*, parent: rawptr[AST]): +def _set_parent_list(lst: list[AST*]*, parent: AST*): """Set list children parent pointers.""" if lst is None: return for i in range(lst.__len__()): - child: rawptr[AST] = lst.get(i) + child: AST* = lst.get(i) if child is not None: child.parent = parent -def _append_child(lst: list[rawptr[AST]]*, node: rawptr[AST], - pool: rawptr[memhub.MemManager]): +def _append_child(lst: list[AST*]*, node: AST*, + pool: memhub.MemManager*): """Append child nodes to a list (module-level function, to avoid conflicts with the AST.append method name). Call this function within the AST.append method to bypass the compiler mistaking list.append for a virtual function call to AST.append when doing type inference.""" @@ -276,7 +276,7 @@ def _op_name(op: int) -> str: return "NoneOp" -def _dump_list(lst: list[rawptr[AST]]*, buf: str, size: sizet, pos: sizet) -> sizet: +def _dump_list(lst: list[AST*]*, buf: str, size: sizet, pos: sizet) -> sizet: """Traverse a list[AST | CPtr] container, polymorphically dump each element.""" if lst is None: pos = _emit(buf, size, pos, "[]") @@ -284,7 +284,7 @@ def _dump_list(lst: list[rawptr[AST]]*, buf: str, size: sizet, pos: sizet) -> si pos = _emit(buf, size, pos, "[") for i in range(lst.__len__()): if i > 0: pos = _emit(buf, size, pos, ", ") - child: rawptr[AST] = lst.get(i) + child: AST* = lst.get(i) if child is not None: pos = child.dump(buf, size, pos) pos = _emit(buf, size, pos, "]") return pos @@ -295,7 +295,7 @@ def _dump_op_list(lst: t.CPtr, buf: str, size: sizet, pos: sizet) -> sizet: if lst is None: pos = _emit(buf, size, pos, "[]") return pos - ops_list: rawptr[list[int]] = (rawptr[list[int]])(lst) + ops_list: list[int]* = (list[int]*)(lst) pos = _emit(buf, size, pos, "[") for i in range(ops_list.__len__()): if i > 0: pos = _emit(buf, size, pos, ", ") @@ -322,13 +322,13 @@ virtual class AST: end_lineno/end_col_offset: Ending position children: List of child nodes (body block, added via append) """ - parent: rawptr[AST] - pool: rawptr[memhub.MemManager] + parent: AST* + pool: memhub.MemManager* lineno: int col_offset: int end_lineno: int end_col_offset: int - children: list[rawptr[AST]]* + children: list[AST*]* def kind(self) -> int: """Returns the node type (ASTKind value), overridden by subclasses""" @@ -347,7 +347,7 @@ virtual class AST: Current implementation is empty. override this method to dispatch to visitor.visit_X(self)""" pass - def append(self, node: rawptr[AST]): + def append(self, node: AST*): """Append node to the children list. Used for parser to build statement blocks: module.append(stmt), if_node.append(stmt), etc. @@ -356,7 +356,7 @@ virtual class AST: Note: list[AST|CPtr] is currently stored by value (compiler limitation), so you must set node.parent before appending, so the parent in the copy is correct.""" if self is None or node is None: return - if self.children is None: self.children = list[rawptr[AST]](self.pool, 8) + if self.children is None: self.children = list[AST*](self.pool, 8) node.parent = self _append_child(self.children, node, self.pool) @@ -386,7 +386,7 @@ virtual class ExprNode(AST): # ============================================================ # Module dump function (for ast.dump(node, buf, size)) # ============================================================ -def dump(node: rawptr[AST], buf: str, size: sizet): +def dump(node: AST*, buf: str, size: sizet): """Serialize AST node to buf (with capacity size)""" if node is None or buf is None or size == 0: return buf[0] = '\0' diff --git a/ast/exprs.vp b/ast/exprs.vp index 1b7aa32..3dac91d 100644 --- a/ast/exprs.vp +++ b/ast/exprs.vp @@ -20,12 +20,12 @@ class Name(ExprNode): id: str ctx: int - def __new__(self, pool: rawptr[memhub.MemManager], id: str, ctx: int): - ptr: rawptr[Name] = pool.alloc(Name.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, id: str, ctx: int): + ptr: Name* = pool.alloc(Name.__sizeof__()) if ptr: string.memset(ptr, 0, Name.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], id: str, ctx: int): + def __init__(self, pool: memhub.MemManager*, id: str, ctx: int): _init_ast(self, pool, 0, 0) self.id = _copy_str(pool, id) self.ctx = ctx @@ -50,25 +50,25 @@ class Name(ExprNode): return pos -def name_get_id(node: rawptr[Name]) -> str: +def name_get_id(node: Name*) -> str: """Get Name.id field (cross-module accessor; guards against stub field-access pitfalls)""" if node is None: return None return node.id -def constant_get_str_val(node: rawptr[Constant]) -> str: +def constant_get_str_val(node: Constant*) -> str: """Get Constant.str_val field (cross-module accessor)""" if node is None: return None return node.str_val -def binop_get_left(node: rawptr[BinOp]) -> rawptr[AST]: +def binop_get_left(node: BinOp*) -> AST*: """Get BinOp.left field (cross-module accessor)""" if node is None: return None return node.left -def binop_get_right(node: rawptr[BinOp]) -> rawptr[AST]: +def binop_get_right(node: BinOp*) -> AST*: """Get BinOp.right field (cross-module accessor)""" if node is None: return None return node.right @@ -85,16 +85,16 @@ class Constant(ExprNode): str_val: str const_kind: int - def __new__(self, pool: rawptr[memhub.MemManager], + def __new__(self, pool: memhub.MemManager*, const_kind: int, int_val: int64, float_val: double, str_val: str, lineno: int, col: int): - ptr: rawptr[Constant] = pool.alloc(Constant.__sizeof__()) + ptr: Constant* = pool.alloc(Constant.__sizeof__()) if ptr: string.memset(ptr, 0, Constant.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], + def __init__(self, pool: memhub.MemManager*, const_kind: int, int_val: int64, float_val: double, str_val: str, lineno: int, col: int): @@ -148,18 +148,18 @@ class Constant(ExprNode): class BinOp(ExprNode): """BinOp(left: AST, op: OpKind, right: AST)""" - left: rawptr[AST] + left: AST* op: int - right: rawptr[AST] + right: AST* - def __new__(self, pool: rawptr[memhub.MemManager], - left: rawptr[AST], op: int, right: rawptr[AST]): - ptr: rawptr[BinOp] = pool.alloc(BinOp.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + left: AST*, op: int, right: AST*): + ptr: BinOp* = pool.alloc(BinOp.__sizeof__()) if ptr: string.memset(ptr, 0, BinOp.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - left: rawptr[AST], op: int, right: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + left: AST*, op: int, right: AST*): _init_ast(self, pool, 0, 0) self.left = left self.op = op @@ -195,16 +195,16 @@ class BinOp(ExprNode): class UnaryOp(ExprNode): """UnaryOp(op: OpKind, operand: AST)""" op: int - operand: rawptr[AST] + operand: AST* - def __new__(self, pool: rawptr[memhub.MemManager], - op: int, operand: rawptr[AST]): - ptr: rawptr[UnaryOp] = pool.alloc(UnaryOp.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + op: int, operand: AST*): + ptr: UnaryOp* = pool.alloc(UnaryOp.__sizeof__()) if ptr: string.memset(ptr, 0, UnaryOp.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - op: int, operand: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + op: int, operand: AST*): _init_ast(self, pool, 0, 0) self.op = op self.operand = operand @@ -233,22 +233,22 @@ class UnaryOp(ExprNode): class Compare(ExprNode): """Compare(left: AST, ops: list[CInt], comparators: list[AST | CPtr])""" - left: rawptr[AST] + left: AST* ops: t.CPtr - comparators: rawptr[list[rawptr[AST]]] + comparators: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - left: rawptr[AST], + def __new__(self, pool: memhub.MemManager*, + left: AST*, ops: t.CPtr, - comparators: rawptr[list[rawptr[AST]]]): - ptr: rawptr[Compare] = pool.alloc(Compare.__sizeof__()) + comparators: list[AST*]*): + ptr: Compare* = pool.alloc(Compare.__sizeof__()) if ptr: string.memset(ptr, 0, Compare.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - left: rawptr[AST], + def __init__(self, pool: memhub.MemManager*, + left: AST*, ops: t.CPtr, - comparators: rawptr[list[rawptr[AST]]]): + comparators: list[AST*]*): _init_ast(self, pool, 0, 0) self.left = left self.ops = ops @@ -281,25 +281,25 @@ class Compare(ExprNode): class Call(ExprNode): """Call(func: AST, args: list[AST | CPtr], keywords: list[AST | CPtr])""" - func: rawptr[AST] - args: rawptr[list[rawptr[AST]]] - keywords: rawptr[list[rawptr[AST]]] + func: AST* + args: list[AST*]* + keywords: list[AST*]* # Value-position `volatile f()` / `volatile S()` prefix marker (see _IsVolatileCallPrefix): # 1 = result/temp slot accessed volatile (struct writes too). Appended last: offsets unchanged. IsVolatile: int - def __new__(self, pool: rawptr[memhub.MemManager], - func: rawptr[AST], - args: rawptr[list[rawptr[AST]]], - keywords: rawptr[list[rawptr[AST]]]): - ptr: rawptr[Call] = pool.alloc(Call.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + func: AST*, + args: list[AST*]*, + keywords: list[AST*]*): + ptr: Call* = pool.alloc(Call.__sizeof__()) if ptr: string.memset(ptr, 0, Call.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - func: rawptr[AST], - args: rawptr[list[rawptr[AST]]], - keywords: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + func: AST*, + args: list[AST*]*, + keywords: list[AST*]*): _init_ast(self, pool, 0, 0) self.func = func self.args = args @@ -333,18 +333,18 @@ class Call(ExprNode): class BoolOp(ExprNode): """BoolOp(op: CInt, values: list[AST | CPtr])""" op: int - values: rawptr[list[rawptr[AST]]] + values: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], + def __new__(self, pool: memhub.MemManager*, op: int, - values: rawptr[list[rawptr[AST]]]): - ptr: rawptr[BoolOp] = pool.alloc(BoolOp.__sizeof__()) + values: list[AST*]*): + ptr: BoolOp* = pool.alloc(BoolOp.__sizeof__()) if ptr: string.memset(ptr, 0, BoolOp.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], + def __init__(self, pool: memhub.MemManager*, op: int, - values: rawptr[list[rawptr[AST]]]): + values: list[AST*]*): _init_ast(self, pool, 0, 0) self.op = op self.values = values @@ -371,17 +371,17 @@ class BoolOp(ExprNode): class Lambda(ExprNode): """Lambda(args: AST, body: AST)""" - args: rawptr[AST] - body: rawptr[AST] + args: AST* + body: AST* - def __new__(self, pool: rawptr[memhub.MemManager], - args: rawptr[AST], body: rawptr[AST]): - ptr: rawptr[Lambda] = pool.alloc(Lambda.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + args: AST*, body: AST*): + ptr: Lambda* = pool.alloc(Lambda.__sizeof__()) if ptr: string.memset(ptr, 0, Lambda.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - args: rawptr[AST], body: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + args: AST*, body: AST*): _init_ast(self, pool, 0, 0) self.args = args self.body = body @@ -413,20 +413,20 @@ class Lambda(ExprNode): class IfExp(ExprNode): """IfExp(test: AST, body: AST, orelse: AST)""" - test: rawptr[AST] - body: rawptr[AST] - orelse: rawptr[AST] + test: AST* + body: AST* + orelse: AST* - def __new__(self, pool: rawptr[memhub.MemManager], - test: rawptr[AST], body: rawptr[AST], - orelse: rawptr[AST]): - ptr: rawptr[IfExp] = pool.alloc(IfExp.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + test: AST*, body: AST*, + orelse: AST*): + ptr: IfExp* = pool.alloc(IfExp.__sizeof__()) if ptr: string.memset(ptr, 0, IfExp.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - test: rawptr[AST], body: rawptr[AST], - orelse: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + test: AST*, body: AST*, + orelse: AST*): _init_ast(self, pool, 0, 0) self.test = test self.body = body @@ -464,19 +464,19 @@ class IfExp(ExprNode): class Dict(ExprNode): """Dict(keys: list[AST | CPtr], values: list[AST | CPtr])""" - keys: rawptr[list[rawptr[AST]]] - values: rawptr[list[rawptr[AST]]] + keys: list[AST*]* + values: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - keys: rawptr[list[rawptr[AST]]], - values: rawptr[list[rawptr[AST]]]): - ptr: rawptr[Dict] = pool.alloc(Dict.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + keys: list[AST*]*, + values: list[AST*]*): + ptr: Dict* = pool.alloc(Dict.__sizeof__()) if ptr: string.memset(ptr, 0, Dict.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - keys: rawptr[list[rawptr[AST]]], - values: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + keys: list[AST*]*, + values: list[AST*]*): _init_ast(self, pool, 0, 0) self.keys = keys self.values = values @@ -504,16 +504,16 @@ class Dict(ExprNode): class Set(ExprNode): """Set(elts: list[AST | CPtr])""" - elts: rawptr[list[rawptr[AST]]] + elts: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - elts: rawptr[list[rawptr[AST]]]): - ptr: rawptr[Set] = pool.alloc(Set.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + elts: list[AST*]*): + ptr: Set* = pool.alloc(Set.__sizeof__()) if ptr: string.memset(ptr, 0, Set.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - elts: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + elts: list[AST*]*): _init_ast(self, pool, 0, 0) self.elts = elts _set_parent_list(elts, self) @@ -537,19 +537,19 @@ class Set(ExprNode): class ListComp(ExprNode): """ListComp(elt: AST, generators: list[AST | CPtr])""" - elt: rawptr[AST] - generators: rawptr[list[rawptr[AST]]] + elt: AST* + generators: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - elt: rawptr[AST], - generators: rawptr[list[rawptr[AST]]]): - ptr: rawptr[ListComp] = pool.alloc(ListComp.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + elt: AST*, + generators: list[AST*]*): + ptr: ListComp* = pool.alloc(ListComp.__sizeof__()) if ptr: string.memset(ptr, 0, ListComp.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - elt: rawptr[AST], - generators: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + elt: AST*, + generators: list[AST*]*): _init_ast(self, pool, 0, 0) self.elt = elt self.generators = generators @@ -579,19 +579,19 @@ class ListComp(ExprNode): class SetComp(ExprNode): """SetComp(elt: AST, generators: list[AST | CPtr])""" - elt: rawptr[AST] - generators: rawptr[list[rawptr[AST]]] + elt: AST* + generators: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - elt: rawptr[AST], - generators: rawptr[list[rawptr[AST]]]): - ptr: rawptr[SetComp] = pool.alloc(SetComp.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + elt: AST*, + generators: list[AST*]*): + ptr: SetComp* = pool.alloc(SetComp.__sizeof__()) if ptr: string.memset(ptr, 0, SetComp.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - elt: rawptr[AST], - generators: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + elt: AST*, + generators: list[AST*]*): _init_ast(self, pool, 0, 0) self.elt = elt self.generators = generators @@ -621,20 +621,20 @@ class SetComp(ExprNode): class DictComp(ExprNode): """DictComp(key: AST, value: AST, generators: list[AST | CPtr])""" - key: rawptr[AST] - value: rawptr[AST] - generators: rawptr[list[rawptr[AST]]] + key: AST* + value: AST* + generators: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - key: rawptr[AST], value: rawptr[AST], - generators: rawptr[list[rawptr[AST]]]): - ptr: rawptr[DictComp] = pool.alloc(DictComp.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + key: AST*, value: AST*, + generators: list[AST*]*): + ptr: DictComp* = pool.alloc(DictComp.__sizeof__()) if ptr: string.memset(ptr, 0, DictComp.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - key: rawptr[AST], value: rawptr[AST], - generators: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + key: AST*, value: AST*, + generators: list[AST*]*): _init_ast(self, pool, 0, 0) self.key = key self.value = value @@ -670,19 +670,19 @@ class DictComp(ExprNode): class GeneratorExp(ExprNode): """GeneratorExp(elt: AST, generators: list[AST | CPtr])""" - elt: rawptr[AST] - generators: rawptr[list[rawptr[AST]]] + elt: AST* + generators: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - elt: rawptr[AST], - generators: rawptr[list[rawptr[AST]]]): - ptr: rawptr[GeneratorExp] = pool.alloc(GeneratorExp.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + elt: AST*, + generators: list[AST*]*): + ptr: GeneratorExp* = pool.alloc(GeneratorExp.__sizeof__()) if ptr: string.memset(ptr, 0, GeneratorExp.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - elt: rawptr[AST], - generators: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + elt: AST*, + generators: list[AST*]*): _init_ast(self, pool, 0, 0) self.elt = elt self.generators = generators @@ -712,14 +712,14 @@ class GeneratorExp(ExprNode): class Await(ExprNode): """Await(value: AST)""" - value: rawptr[AST] + value: AST* - def __new__(self, pool: rawptr[memhub.MemManager], value: rawptr[AST]): - ptr: rawptr[Await] = pool.alloc(Await.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, value: AST*): + ptr: Await* = pool.alloc(Await.__sizeof__()) if ptr: string.memset(ptr, 0, Await.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], value: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, value: AST*): _init_ast(self, pool, 0, 0) self.value = value @@ -745,14 +745,14 @@ class Await(ExprNode): class Yield(ExprNode): """Yield(value: AST)""" - value: rawptr[AST] + value: AST* - def __new__(self, pool: rawptr[memhub.MemManager], value: rawptr[AST]): - ptr: rawptr[Yield] = pool.alloc(Yield.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, value: AST*): + ptr: Yield* = pool.alloc(Yield.__sizeof__()) if ptr: string.memset(ptr, 0, Yield.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], value: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, value: AST*): _init_ast(self, pool, 0, 0) self.value = value @@ -778,14 +778,14 @@ class Yield(ExprNode): class YieldFrom(ExprNode): """YieldFrom(value: AST)""" - value: rawptr[AST] + value: AST* - def __new__(self, pool: rawptr[memhub.MemManager], value: rawptr[AST]): - ptr: rawptr[YieldFrom] = pool.alloc(YieldFrom.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, value: AST*): + ptr: YieldFrom* = pool.alloc(YieldFrom.__sizeof__()) if ptr: string.memset(ptr, 0, YieldFrom.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], value: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, value: AST*): _init_ast(self, pool, 0, 0) self.value = value @@ -811,20 +811,20 @@ class YieldFrom(ExprNode): class FormattedValue(ExprNode): """FormattedValue(value: AST, conversion: CInt, format_spec: AST)""" - value: rawptr[AST] + value: AST* conversion: int - format_spec: rawptr[AST] + format_spec: AST* - def __new__(self, pool: rawptr[memhub.MemManager], - value: rawptr[AST], conversion: int, - format_spec: rawptr[AST]): - ptr: rawptr[FormattedValue] = pool.alloc(FormattedValue.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + value: AST*, conversion: int, + format_spec: AST*): + ptr: FormattedValue* = pool.alloc(FormattedValue.__sizeof__()) if ptr: string.memset(ptr, 0, FormattedValue.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - value: rawptr[AST], conversion: int, - format_spec: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + value: AST*, conversion: int, + format_spec: AST*): _init_ast(self, pool, 0, 0) self.value = value self.conversion = conversion @@ -859,16 +859,16 @@ class FormattedValue(ExprNode): class JoinedStr(ExprNode): """JoinedStr(values: list[AST | CPtr])""" - values: rawptr[list[rawptr[AST]]] + values: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], values: rawptr[list[rawptr[AST]]]): - ptr: rawptr[JoinedStr] = pool.alloc(JoinedStr.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, values: list[AST*]*): + ptr: JoinedStr* = pool.alloc(JoinedStr.__sizeof__()) if ptr: string.memset(ptr, 0, JoinedStr.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - values: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + values: list[AST*]*): _init_ast(self, pool, 0, 0) self.values = values _set_parent_list(values, self) @@ -892,18 +892,18 @@ class JoinedStr(ExprNode): class Attribute(ExprNode): """Attribute(value: AST, attr: str, ctx: CInt)""" - value: rawptr[AST] + value: AST* attr: str ctx: int - def __new__(self, pool: rawptr[memhub.MemManager], - value: rawptr[AST], attr: str, ctx: int): - ptr: rawptr[Attribute] = pool.alloc(Attribute.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + value: AST*, attr: str, ctx: int): + ptr: Attribute* = pool.alloc(Attribute.__sizeof__()) if ptr: string.memset(ptr, 0, Attribute.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - value: rawptr[AST], attr: str, ctx: int): + def __init__(self, pool: memhub.MemManager*, + value: AST*, attr: str, ctx: int): _init_ast(self, pool, 0, 0) self.value = value self.attr = _copy_str(pool, attr) @@ -933,13 +933,13 @@ class Attribute(ExprNode): # Field accessors (guard against cross-module stub field-access pitfalls): other modules reading # ast.Attribute fields directly may get a wrong stub GEP and crash, so they use these accessors. # ============================================================ -def attribute_get_value(node: rawptr[Attribute]) -> rawptr[AST]: +def attribute_get_value(node: Attribute*) -> AST*: """Get Attribute.value field (cross-module accessor)""" if node is None: return None return node.value -def attribute_get_attr(node: rawptr[Attribute]) -> str: +def attribute_get_attr(node: Attribute*) -> str: """Get Attribute.attr field (cross-module accessor)""" if node is None: return None return node.attr @@ -951,18 +951,18 @@ def attribute_get_attr(node: rawptr[Attribute]) -> str: class Subscript(ExprNode): """Subscript(value: AST, slice: AST, ctx: CInt)""" - value: rawptr[AST] - slice: rawptr[AST] + value: AST* + slice: AST* ctx: int - def __new__(self, pool: rawptr[memhub.MemManager], - value: rawptr[AST], slice: rawptr[AST], ctx: int): - ptr: rawptr[Subscript] = pool.alloc(Subscript.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + value: AST*, slice: AST*, ctx: int): + ptr: Subscript* = pool.alloc(Subscript.__sizeof__()) if ptr: string.memset(ptr, 0, Subscript.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - value: rawptr[AST], slice: rawptr[AST], ctx: int): + def __init__(self, pool: memhub.MemManager*, + value: AST*, slice: AST*, ctx: int): _init_ast(self, pool, 0, 0) self.value = value self.slice = slice @@ -997,17 +997,17 @@ class Subscript(ExprNode): class Starred(ExprNode): """Starred(value: AST, ctx: CInt)""" - value: rawptr[AST] + value: AST* ctx: int - def __new__(self, pool: rawptr[memhub.MemManager], - value: rawptr[AST], ctx: int): - ptr: rawptr[Starred] = pool.alloc(Starred.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + value: AST*, ctx: int): + ptr: Starred* = pool.alloc(Starred.__sizeof__()) if ptr: string.memset(ptr, 0, Starred.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - value: rawptr[AST], ctx: int): + def __init__(self, pool: memhub.MemManager*, + value: AST*, ctx: int): _init_ast(self, pool, 0, 0) self.value = value self.ctx = ctx @@ -1036,17 +1036,17 @@ class Starred(ExprNode): class List(ExprNode): """List(elts: list[AST | CPtr], ctx: CInt)""" - elts: rawptr[list[rawptr[AST]]] + elts: list[AST*]* ctx: int - def __new__(self, pool: rawptr[memhub.MemManager], - elts: rawptr[list[rawptr[AST]]], ctx: int): - ptr: rawptr[List] = pool.alloc(List.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + elts: list[AST*]*, ctx: int): + ptr: List* = pool.alloc(List.__sizeof__()) if ptr: string.memset(ptr, 0, List.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - elts: rawptr[list[rawptr[AST]]], ctx: int): + def __init__(self, pool: memhub.MemManager*, + elts: list[AST*]*, ctx: int): _init_ast(self, pool, 0, 0) self.elts = elts self.ctx = ctx @@ -1073,17 +1073,17 @@ class List(ExprNode): class Tuple(ExprNode): """Tuple(elts: list[AST | CPtr], ctx: CInt)""" - elts: rawptr[list[rawptr[AST]]] + elts: list[AST*]* ctx: int - def __new__(self, pool: rawptr[memhub.MemManager], - elts: rawptr[list[rawptr[AST]]], ctx: int): - ptr: rawptr[Tuple] = pool.alloc(Tuple.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + elts: list[AST*]*, ctx: int): + ptr: Tuple* = pool.alloc(Tuple.__sizeof__()) if ptr: string.memset(ptr, 0, Tuple.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - elts: rawptr[list[rawptr[AST]]], ctx: int): + def __init__(self, pool: memhub.MemManager*, + elts: list[AST*]*, ctx: int): _init_ast(self, pool, 0, 0) self.elts = elts self.ctx = ctx @@ -1110,20 +1110,20 @@ class Tuple(ExprNode): class Slice(ExprNode): """Slice(lower: AST, upper: AST, step: AST)""" - lower: rawptr[AST] - upper: rawptr[AST] - step: rawptr[AST] + lower: AST* + upper: AST* + step: AST* - def __new__(self, pool: rawptr[memhub.MemManager], - lower: rawptr[AST], upper: rawptr[AST], - step: rawptr[AST]): - ptr: rawptr[Slice] = pool.alloc(Slice.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + lower: AST*, upper: AST*, + step: AST*): + ptr: Slice* = pool.alloc(Slice.__sizeof__()) if ptr: string.memset(ptr, 0, Slice.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - lower: rawptr[AST], upper: rawptr[AST], - step: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + lower: AST*, upper: AST*, + step: AST*): _init_ast(self, pool, 0, 0) self.lower = lower self.upper = upper @@ -1161,17 +1161,17 @@ class Slice(ExprNode): class NamedExpr(ExprNode): """NamedExpr(target: AST, value: AST)""" - target: rawptr[AST] - value: rawptr[AST] + target: AST* + value: AST* - def __new__(self, pool: rawptr[memhub.MemManager], - target: rawptr[AST], value: rawptr[AST]): - ptr: rawptr[NamedExpr] = pool.alloc(NamedExpr.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + target: AST*, value: AST*): + ptr: NamedExpr* = pool.alloc(NamedExpr.__sizeof__()) if ptr: string.memset(ptr, 0, NamedExpr.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - target: rawptr[AST], value: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + target: AST*, value: AST*): _init_ast(self, pool, 0, 0) self.target = target self.value = value @@ -1205,12 +1205,12 @@ class OpNode(AST): """OpNode(op: CInt)""" op: int - def __new__(self, pool: rawptr[memhub.MemManager], op: int): - ptr: rawptr[OpNode] = pool.alloc(OpNode.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, op: int): + ptr: OpNode* = pool.alloc(OpNode.__sizeof__()) if ptr: string.memset(ptr, 0, OpNode.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], op: int): + def __init__(self, pool: memhub.MemManager*, op: int): _init_ast(self, pool, 0, 0) self.op = op diff --git a/ast/lexer.vp b/ast/lexer.vp index b57f34b..6503fa8 100644 --- a/ast/lexer.vp +++ b/ast/lexer.vp @@ -307,17 +307,17 @@ class Lexer: len: sizet # Source code length lineno: int # Current line number (1-based) col: int # Current column number (0-based) - pool: rawptr[memhub.MemManager] # Memory pool - indent_stack: rawptr[int] # Indent stack (int array, allocated from pool) + pool: memhub.MemManager* # Memory pool + indent_stack: int* # Indent stack (int array, allocated from pool) indent_top: int # Stack top (-1 for empty stack) paren_depth: int # Paren depth (>0 for no TokenType.NewLine) - tokens_head: rawptr[Token] # token list head - tokens_tail: rawptr[Token] # token list tail + tokens_head: Token* # token list head + tokens_tail: Token* # token list tail at_line_start: int # 1=line start (need indent) error_count: int # Error count - def __new__(self, pool: rawptr[memhub.MemManager]): - ptr: rawptr[Lexer] = pool.alloc(Lexer.__sizeof__()) + def __new__(self, pool: memhub.MemManager*): + ptr: Lexer* = pool.alloc(Lexer.__sizeof__()) if ptr == None: # Pool exhausted: fail-fast instead of returning NULL (downstream would treat NULL as a valid Lexer) stdio.printf("[AST] Lexer 分配失败:内存池已耗尽(need=%zu 字节)\n", @@ -328,12 +328,12 @@ class Lexer: return ptr -def new_lexer(pool: rawptr[memhub.MemManager]) -> rawptr[Lexer]: +def new_lexer(pool: memhub.MemManager*) -> Lexer*: """Allocate from the pool and return a Lexer (cross-module safe wrapper)""" return Lexer(pool) -def _lexer_init(lx: rawptr[Lexer], src: str, pool: rawptr[memhub.MemManager]): +def _lexer_init(lx: Lexer*, src: str, pool: memhub.MemManager*): """Initialize Lexer""" if lx == None: return lx.src = src @@ -366,19 +366,19 @@ def _lexer_init(lx: rawptr[Lexer], src: str, pool: rawptr[memhub.MemManager]): # Auxiliary Functions # ============================================================ -def _peek(lx: rawptr[Lexer], offset: sizet) -> char: +def _peek(lx: Lexer*, offset: sizet) -> char: """Peek character at position pos+offset, return '\0' if out of bounds""" p: sizet = lx.pos + offset if p >= lx.len: return '\0' return lx.src[p] -def _peek_cur(lx: rawptr[Lexer]) -> char: +def _peek_cur(lx: Lexer*) -> char: if lx.pos >= lx.len: return '\0' return lx.src[lx.pos] -def _advance(lx: rawptr[Lexer]) -> char: +def _advance(lx: Lexer*) -> char: """Advance one character, return the character""" if lx.pos >= lx.len: return '\0' ch: char = lx.src[lx.pos] @@ -433,7 +433,7 @@ def _is_space(ch: char) -> int: return 0 -def _emit(lx: rawptr[Lexer], tok: rawptr[Token]): +def _emit(lx: Lexer*, tok: Token*): """Append token to token list""" if tok == None: return if lx.tokens_head == None: @@ -444,9 +444,9 @@ def _emit(lx: rawptr[Lexer], tok: rawptr[Token]): lx.tokens_tail = tok -def _make_op_token(lx: rawptr[Lexer], op_id: int, length: int, - lineno: int, col: int) -> rawptr[Token]: - tok: rawptr[Token] = new_token(lx.pool, TokenType.Op, lineno, col) +def _make_op_token(lx: Lexer*, op_id: int, length: int, + lineno: int, col: int) -> Token*: + tok: Token* = new_token(lx.pool, TokenType.Op, lineno, col) if tok == None: return None tok.op_subtype = op_id tok.end_col_offset = col + length @@ -457,7 +457,7 @@ def _make_op_token(lx: rawptr[Lexer], op_id: int, length: int, # Indent Handling # ============================================================ -def _handle_indent(lx: rawptr[Lexer]): +def _handle_indent(lx: Lexer*): """Handle line start indent, generate TokenType.Indent/TokenType.Dedent. Skip empty lines and comment lines.""" # Skip empty lines and comment lines @@ -544,12 +544,12 @@ def _handle_indent(lx: rawptr[Lexer]): return lx.indent_top += 1 lx.indent_stack[lx.indent_top] = indent - tok: rawptr[Token] = new_token(lx.pool, TokenType.Indent, lx.lineno, 0) + tok: Token* = new_token(lx.pool, TokenType.Indent, lx.lineno, 0) _emit(lx, tok) else: while indent < lx.indent_stack[lx.indent_top] and lx.indent_top > 0: lx.indent_top -= 1 - tok: rawptr[Token] = new_token(lx.pool, TokenType.Dedent, lx.lineno, 0) + tok: Token* = new_token(lx.pool, TokenType.Dedent, lx.lineno, 0) _emit(lx, tok) lx.at_line_start = 0 @@ -558,7 +558,7 @@ def _handle_indent(lx: rawptr[Lexer]): # Identifier/Keyword Handling # ============================================================ -def _read_name(lx: rawptr[Lexer]): +def _read_name(lx: Lexer*): start: sizet = lx.pos start_lineno: int = lx.lineno start_col: int = lx.col @@ -570,7 +570,7 @@ def _read_name(lx: rawptr[Lexer]): else: break length: sizet = lx.pos - start - tok: rawptr[Token] = new_token(lx.pool, TokenType.Name, start_lineno, start_col) + tok: Token* = new_token(lx.pool, TokenType.Name, start_lineno, start_col) if tok == None: return token_set_str(lx.pool, tok, lx.src, start, length) tok.end_lineno = lx.lineno @@ -585,7 +585,7 @@ def _read_name(lx: rawptr[Lexer]): # Number Handling # ============================================================ -def _read_number(lx: rawptr[Lexer]): +def _read_number(lx: Lexer*): start: sizet = lx.pos start_lineno: int = lx.lineno start_col: int = lx.col @@ -688,11 +688,11 @@ def _read_number(lx: rawptr[Lexer]): _emit_number(lx, start, start_lineno, start_col, is_float, is_complex, 0) -def _emit_number(lx: rawptr[Lexer], start: sizet, +def _emit_number(lx: Lexer*, start: sizet, start_lineno: int, start_col: int, is_float: int, is_complex: int, is_hex: int): length: sizet = lx.pos - start - tok: rawptr[Token] = new_token(lx.pool, TokenType.Number, start_lineno, start_col) + tok: Token* = new_token(lx.pool, TokenType.Number, start_lineno, start_col) if tok == None: return token_set_str(lx.pool, tok, lx.src, start, length) tok.is_float = is_float @@ -715,7 +715,7 @@ def _emit_number(lx: rawptr[Lexer], start: sizet, # String Handling # ============================================================ -def _read_string(lx: rawptr[Lexer]): +def _read_string(lx: Lexer*): """Read string literal. Supports prefixes: r, b, u, f, rb, br, rf, fr (case insensitive) Supports quotes: ', ", ''', @@ -875,7 +875,7 @@ def _read_string(lx: rawptr[Lexer]): lx.col += 1 # Create token - tok: rawptr[Token] = new_token(lx.pool, TokenType.String, start_lineno, start_col) + tok: Token* = new_token(lx.pool, TokenType.String, start_lineno, start_col) if tok == None: return content_len: sizet = content_end - content_buf_start # esc_len: Actual bytes after escaping (used to check single character) @@ -968,16 +968,16 @@ def _read_string(lx: rawptr[Lexer]): # Operator Matching # ============================================================ -def _read_operator(lx: rawptr[Lexer]): +def _read_operator(lx: Lexer*): """Greedy match operator""" start_lineno: int = lx.lineno start_col: int = lx.col remaining: sizet = lx.len - lx.pos # Traverse operator table, find longest match - best_entry: rawptr[OpEntry] = None + best_entry: OpEntry* = None best_len: int = 0 - cur: rawptr[OpEntry] = _op_head + cur: OpEntry* = _op_head while cur != None: if cur.length <= int(remaining): # Compare cur.name with src[pos:pos+cur.length] @@ -1006,7 +1006,7 @@ def _read_operator(lx: rawptr[Lexer]): if lx.paren_depth > 0: lx.paren_depth -= 1 - tok: rawptr[Token] = _make_op_token(lx, best_entry.op_id, best_entry.length, + tok: Token* = _make_op_token(lx, best_entry.op_id, best_entry.length, start_lineno, start_col) if tok == None: return token_set_str(lx.pool, tok, lx.src, lx.pos, sizet(best_len)) @@ -1019,7 +1019,7 @@ def _read_operator(lx: rawptr[Lexer]): # Main Lexical Analysis Entry Point # ============================================================ -def tokenize(lx: rawptr[Lexer]) -> rawptr[Token]: +def tokenize(lx: Lexer*) -> Token*: """Execute tokenization, return token list head""" if lx == None: return None while lx.pos < lx.len: @@ -1037,11 +1037,11 @@ def tokenize(lx: rawptr[Lexer]) -> rawptr[Token]: if ch == '\n': if lx.paren_depth > 0: # # In bi brackets, generates TokenType.Nl - tok: rawptr[Token] = new_token(lx.pool, TokenType.Nl, lx.lineno, lx.col) + tok: Token* = new_token(lx.pool, TokenType.Nl, lx.lineno, lx.col) _emit(lx, tok) else: # Logical new line - tok: rawptr[Token] = new_token(lx.pool, TokenType.NewLine, lx.lineno, lx.col) + tok: Token* = new_token(lx.pool, TokenType.NewLine, lx.lineno, lx.col) _emit(lx, tok) lx.at_line_start = 1 lx.pos += 1 @@ -1116,17 +1116,17 @@ def tokenize(lx: rawptr[Lexer]) -> rawptr[Token]: # End of file: generate TokenType.NewLine (if there's content) if lx.tokens_tail != None: if lx.tokens_tail.type != TokenType.NewLine and lx.tokens_tail.type != TokenType.Nl: - tok: rawptr[Token] = new_token(lx.pool, TokenType.NewLine, lx.lineno, lx.col) + tok: Token* = new_token(lx.pool, TokenType.NewLine, lx.lineno, lx.col) _emit(lx, tok) # Generate remaining remaining TokenType.Dedent while lx.indent_top > 0: lx.indent_top -= 1 - tok: rawptr[Token] = new_token(lx.pool, TokenType.Dedent, lx.lineno, 0) + tok: Token* = new_token(lx.pool, TokenType.Dedent, lx.lineno, 0) _emit(lx, tok) # TokenType.EndMarker - tok: rawptr[Token] = new_token(lx.pool, TokenType.EndMarker, lx.lineno, 0) + tok: Token* = new_token(lx.pool, TokenType.EndMarker, lx.lineno, 0) _emit(lx, tok) return lx.tokens_head diff --git a/ast/match.vp b/ast/match.vp index 02ef401..88f6f76 100644 --- a/ast/match.vp +++ b/ast/match.vp @@ -14,17 +14,17 @@ from .base import ( # ============================================================ class MatchCase(AST): """MatchCase(pattern: AST, guard: AST)""" - pattern: rawptr[AST] - guard: rawptr[AST] + pattern: AST* + guard: AST* - def __new__(self, pool: rawptr[memhub.MemManager], - pattern: rawptr[AST], guard: rawptr[AST]): - ptr: rawptr[MatchCase] = pool.alloc(MatchCase.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + pattern: AST*, guard: AST*): + ptr: MatchCase* = pool.alloc(MatchCase.__sizeof__()) if ptr: string.memset(ptr, 0, MatchCase.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - pattern: rawptr[AST], guard: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + pattern: AST*, guard: AST*): _init_ast(self, pool, 0, 0) self.pattern = pattern self.guard = guard @@ -53,14 +53,14 @@ class MatchCase(AST): # ============================================================ class MatchValue(AST): """MatchValue(value: AST)""" - value: rawptr[AST] + value: AST* - def __new__(self, pool: rawptr[memhub.MemManager], value: rawptr[AST]): - ptr: rawptr[MatchValue] = pool.alloc(MatchValue.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, value: AST*): + ptr: MatchValue* = pool.alloc(MatchValue.__sizeof__()) if ptr: string.memset(ptr, 0, MatchValue.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], value: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, value: AST*): _init_ast(self, pool, 0, 0) self.value = value @@ -83,14 +83,14 @@ class MatchValue(AST): # ============================================================ class MatchSingleton(AST): """MatchSingleton(value: AST)""" - value: rawptr[AST] + value: AST* - def __new__(self, pool: rawptr[memhub.MemManager], value: rawptr[AST]): - ptr: rawptr[MatchSingleton] = pool.alloc(MatchSingleton.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, value: AST*): + ptr: MatchSingleton* = pool.alloc(MatchSingleton.__sizeof__()) if ptr: string.memset(ptr, 0, MatchSingleton.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], value: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, value: AST*): _init_ast(self, pool, 0, 0) self.value = value @@ -113,16 +113,16 @@ class MatchSingleton(AST): # ============================================================ class MatchSequence(AST): """MatchSequence(patterns: list[rawptr[AST]])""" - patterns: rawptr[list[rawptr[AST]]] + patterns: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - patterns: rawptr[list[rawptr[AST]]]): - ptr: rawptr[MatchSequence] = pool.alloc(MatchSequence.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + patterns: list[AST*]*): + ptr: MatchSequence* = pool.alloc(MatchSequence.__sizeof__()) if ptr: string.memset(ptr, 0, MatchSequence.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - patterns: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + patterns: list[AST*]*): _init_ast(self, pool, 0, 0) self.patterns = patterns _set_parent_list(patterns, self) @@ -145,21 +145,21 @@ class MatchSequence(AST): # ============================================================ class MatchMapping(AST): """MatchMapping(keys: list[rawptr[AST]], patterns: list[rawptr[AST]], rest: str)""" - keys: rawptr[list[rawptr[AST]]] - patterns: rawptr[list[rawptr[AST]]] + keys: list[AST*]* + patterns: list[AST*]* rest: str - def __new__(self, pool: rawptr[memhub.MemManager], - keys: rawptr[list[rawptr[AST]]], - patterns: rawptr[list[rawptr[AST]]], + def __new__(self, pool: memhub.MemManager*, + keys: list[AST*]*, + patterns: list[AST*]*, rest: str): - ptr: rawptr[MatchMapping] = pool.alloc(MatchMapping.__sizeof__()) + ptr: MatchMapping* = pool.alloc(MatchMapping.__sizeof__()) if ptr: string.memset(ptr, 0, MatchMapping.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - keys: rawptr[list[rawptr[AST]]], - patterns: rawptr[list[rawptr[AST]]], + def __init__(self, pool: memhub.MemManager*, + keys: list[AST*]*, + patterns: list[AST*]*, rest: str): _init_ast(self, pool, 0, 0) self.keys = keys @@ -191,26 +191,26 @@ class MatchMapping(AST): class MatchClass(AST): """MatchClass(cls: AST, patterns: list[rawptr[AST]], - kwd_attrs: list[rawptr[AST]], kwd_patterns: list[rawptr[AST]])""" - cls: rawptr[AST] - patterns: rawptr[list[rawptr[AST]]] - kwd_attrs: rawptr[list[rawptr[AST]]] - kwd_patterns: rawptr[list[rawptr[AST]]] + kwd_attrs: list[AST*], kwd_patterns: list[AST*])""" + cls: AST* + patterns: list[AST*]* + kwd_attrs: list[AST*]* + kwd_patterns: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - cls: rawptr[AST], - patterns: rawptr[list[rawptr[AST]]], - kwd_attrs: rawptr[list[rawptr[AST]]], - kwd_patterns: rawptr[list[rawptr[AST]]]): - ptr: rawptr[MatchClass] = pool.alloc(MatchClass.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + cls: AST*, + patterns: list[AST*]*, + kwd_attrs: list[AST*]*, + kwd_patterns: list[AST*]*): + ptr: MatchClass* = pool.alloc(MatchClass.__sizeof__()) if ptr: string.memset(ptr, 0, MatchClass.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - cls: rawptr[AST], - patterns: rawptr[list[rawptr[AST]]], - kwd_attrs: rawptr[list[rawptr[AST]]], - kwd_patterns: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + cls: AST*, + patterns: list[AST*]*, + kwd_attrs: list[AST*]*, + kwd_patterns: list[AST*]*): _init_ast(self, pool, 0, 0) self.cls = cls self.patterns = patterns @@ -247,12 +247,12 @@ class MatchStar(AST): """MatchStar(name: str)""" name: str - def __new__(self, pool: rawptr[memhub.MemManager], name: str): - ptr: rawptr[MatchStar] = pool.alloc(MatchStar.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, name: str): + ptr: MatchStar* = pool.alloc(MatchStar.__sizeof__()) if ptr: string.memset(ptr, 0, MatchStar.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], name: str): + def __init__(self, pool: memhub.MemManager*, name: str): _init_ast(self, pool, 0, 0) self.name = _copy_str(pool, name) @@ -275,17 +275,17 @@ class MatchStar(AST): class MatchAs(AST): """MatchAs(pattern: AST, name: str)""" - pattern: rawptr[AST] + pattern: AST* name: str - def __new__(self, pool: rawptr[memhub.MemManager], - pattern: rawptr[AST], name: str): - ptr: rawptr[MatchAs] = pool.alloc(MatchAs.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + pattern: AST*, name: str): + ptr: MatchAs* = pool.alloc(MatchAs.__sizeof__()) if ptr: string.memset(ptr, 0, MatchAs.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - pattern: rawptr[AST], name: str): + def __init__(self, pool: memhub.MemManager*, + pattern: AST*, name: str): _init_ast(self, pool, 0, 0) self.pattern = pattern self.name = _copy_str(pool, name) @@ -311,16 +311,16 @@ class MatchAs(AST): class MatchOr(AST): """MatchOr(patterns: list[rawptr[AST]])""" - patterns: rawptr[list[rawptr[AST]]] + patterns: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - patterns: rawptr[list[rawptr[AST]]]): - ptr: rawptr[MatchOr] = pool.alloc(MatchOr.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + patterns: list[AST*]*): + ptr: MatchOr* = pool.alloc(MatchOr.__sizeof__()) if ptr: string.memset(ptr, 0, MatchOr.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - patterns: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + patterns: list[AST*]*): _init_ast(self, pool, 0, 0) self.patterns = patterns _set_parent_list(patterns, self) diff --git a/ast/parser.vp b/ast/parser.vp index 0f3d332..0cf8716 100644 --- a/ast/parser.vp +++ b/ast/parser.vp @@ -49,14 +49,14 @@ define PARSER_MAX_TOKENS = 8000000 class Parser: - tokens: rawptr[Token] # token linked list head - cur: rawptr[Token] # current token - prev: rawptr[Token] # previous consumed token (for the `T*(x)` adjacency test) - pool: rawptr[memhub.MemManager] # memory pool + tokens: Token* # token linked list head + cur: Token* # current token + prev: Token* # previous consumed token (for the `T*(x)` adjacency test) + pool: memhub.MemManager* # memory pool error_count: int # error count - pending_decorators: rawptr[list[rawptr[AST]]] # pending decorators list + pending_decorators: list[AST*]* # pending decorators list # Pending parsed left operand for a leading `*` in argument position (see _parse_call / _parse_power). - starred_seed: rawptr[AST] + starred_seed: AST* # `static` modifier (soft keyword) pending flag: set after consuming `static` before a `Name :` # declaration; the next _parse_type_ann prepends t.CStatic and clears it (see _ParseStaticModified). pending_static: int @@ -72,19 +72,19 @@ class Parser: tick_count: sizet aborted: int - def __new__(self, pool: rawptr[memhub.MemManager]): - ptr: rawptr[Parser] = pool.alloc(Parser.__sizeof__()) + def __new__(self, pool: memhub.MemManager*): + ptr: Parser* = pool.alloc(Parser.__sizeof__()) if ptr: string.memset(ptr, 0, Parser.__sizeof__()) return ptr -def new_parser(pool: rawptr[memhub.MemManager]) -> rawptr[Parser]: +def new_parser(pool: memhub.MemManager*) -> Parser*: """Allocate from the pool and return the Parser (cross-module safe wrapper)""" return Parser(pool) -def _parser_init(ps: rawptr[Parser], tokens: rawptr[Token], - pool: rawptr[memhub.MemManager]): +def _parser_init(ps: Parser*, tokens: Token*, + pool: memhub.MemManager*): if ps is None: return ps.tokens = tokens ps.cur = tokens @@ -114,7 +114,7 @@ def _parser_init(ps: rawptr[Parser], tokens: rawptr[Token], # file:line:col SyntaxError; there is no silent-hang path left. # ============================================================ -def _tick(ps: rawptr[Parser]): +def _tick(ps: Parser*): """Tick the watchdog; over budget sets aborted and records the first parse error (with position)""" if ps is None: return if ps.aborted != 0: return @@ -129,7 +129,7 @@ def _tick(ps: rawptr[Parser]): # Token Navigation Helpers # ============================================================ -def _advance(ps: rawptr[Parser]): +def _advance(ps: Parser*): """Advance to the next token""" _tick(ps) if ps.aborted != 0: @@ -142,45 +142,45 @@ def _advance(ps: rawptr[Parser]): ps.step_count += 1 -def _cur_type(ps: rawptr[Parser]) -> int: +def _cur_type(ps: Parser*) -> int: _tick(ps) if ps.aborted != 0: return TokenType.EndMarker if ps.cur is None: return TokenType.EndMarker return ps.cur.type -def _cur_op(ps: rawptr[Parser]) -> int: +def _cur_op(ps: Parser*) -> int: _tick(ps) if ps.aborted != 0: return 0 if ps.cur is None: return 0 return ps.cur.op_subtype -def _cur_kw(ps: rawptr[Parser]) -> int: +def _cur_kw(ps: Parser*) -> int: _tick(ps) if ps.aborted != 0: return 0 if ps.cur is None: return 0 return ps.cur.kw_subtype -def _is_funcdef_kw(ps: rawptr[Parser], kw: int) -> int: +def _is_funcdef_kw(ps: Parser*, kw: int) -> int: """Whether the current token is a function-definition keyword (def and its aliases fn/fun/func/function, plus extern/export). def is a hard keyword. fn/fun/func/function/extern/export are soft: they count only when the next token is a Name followed by '(' or a generic '['; extern/export also accept ` def A(...)`. - Otherwise they are ordinary identifiers (e.g. the AST `func` field or `func: rawptr[AST]`). + Otherwise they are ordinary identifiers (e.g. the AST `func` field or `func: AST*`). """ if kw == Keyword.Def: return 1 if kw == Keyword.Extern or kw == Keyword.Export: # extern/export def A(...) or extern/export A(...) # (after extern/export comes def or Name + '(' / '[') - nxt: rawptr[Token] = ps.cur.next + nxt: Token* = ps.cur.next if nxt is None: return 0 if nxt.kw_subtype == Keyword.Def: return 1 if nxt.type != TokenType.Name: return 0 - nxt2: rawptr[Token] = nxt.next + nxt2: Token* = nxt.next if nxt2 is None: return 0 if nxt2.type == TokenType.Op and (nxt2.op_subtype == TokOp.LPar or nxt2.op_subtype == TokOp.Lsqb): return 1 @@ -190,12 +190,12 @@ def _is_funcdef_kw(ps: rawptr[Parser], kw: int) -> int: or kw == Keyword.Define: # Soft-keyword lookahead: next is a Name, the one after is '(' or a generic '[T...]' (PEP 695) # (the define macro function matches def, with t.CDefine appended to the return annotation) - nxt: rawptr[Token] = ps.cur.next + nxt: Token* = ps.cur.next if nxt is None: return 0 if nxt.type != TokenType.Name: return 0 - nxt2: rawptr[Token] = nxt.next + nxt2: Token* = nxt.next if nxt2 is None: return 0 if nxt2.type == TokenType.Op \ @@ -205,7 +205,7 @@ def _is_funcdef_kw(ps: rawptr[Parser], kw: int) -> int: return 0 -def _is_define_const(ps: rawptr[Parser]) -> int: +def _is_define_const(ps: Parser*) -> int: """Soft-keyword lookahead for a define constant declaration (1 = yes, 0 = no). `define NAME[: T] = `: next is a Name, then '=' (no annotation) or ':' (annotated). @@ -213,15 +213,15 @@ def _is_define_const(ps: rawptr[Parser]) -> int: does match and then fails loudly in _parse_define_const's _expect_op(Equal). """ if _cur_kw(ps) != Keyword.Define: return 0 - nxt: rawptr[Token] = ps.cur.next + nxt: Token* = ps.cur.next if nxt is None or nxt.type != TokenType.Name: return 0 - nxt2: rawptr[Token] = nxt.next + nxt2: Token* = nxt.next if nxt2 is None or nxt2.type != TokenType.Op: return 0 if nxt2.op_subtype == TokOp.Equal or nxt2.op_subtype == TokOp.Colon: return 1 return 0 -def _is_typedef(ps: rawptr[Parser]) -> int: +def _is_typedef(ps: Parser*) -> int: """Soft-keyword test for a typedef alias declaration (1 = yes, 0 = no). `typedef T1 = T2` is fully equivalent to `T1: t.CTypedef = T2`. `typedef` is a statement-level @@ -232,7 +232,7 @@ def _is_typedef(ps: rawptr[Parser]) -> int: return 1 -def _is_export_extern_var(ps: rawptr[Parser]) -> int: +def _is_export_extern_var(ps: Parser*) -> int: """Soft-keyword test for `export NAME :` / `extern NAME :` variable declarations (1 = yes, 0 = no). export/extern also serve function declarations (see _is_funcdef_kw); the third token distinguishes @@ -241,7 +241,7 @@ def _is_export_extern_var(ps: rawptr[Parser]) -> int: kw: int = _cur_kw(ps) if kw != Keyword.Export and kw != Keyword.Extern: return 0 - nxt: rawptr[Token] = ps.cur.next + nxt: Token* = ps.cur.next if nxt is None: return 0 if nxt.type != TokenType.Name: @@ -249,7 +249,7 @@ def _is_export_extern_var(ps: rawptr[Parser]) -> int: # The name must be a non-keyword identifier (excludes forms like `export def f()`) if nxt.kw_subtype != Keyword.NotKeyword: return 0 - nxt2: rawptr[Token] = nxt.next + nxt2: Token* = nxt.next if nxt2 is None: return 0 if nxt2.type != TokenType.Op: @@ -265,7 +265,7 @@ _g_parse_err_col: int = 0 _g_parse_err_msg: str = None -def _record_parse_err(ps: rawptr[Parser]): +def _record_parse_err(ps: Parser*): """Record the position and message of the first parse error (later errors do not overwrite it)""" global _g_parse_err_line, _g_parse_err_col, _g_parse_err_msg if _g_parse_err_line != 0: @@ -284,7 +284,7 @@ def _record_parse_err(ps: rawptr[Parser]): _g_parse_err_msg = err_s -def _record_parse_err_ctx(ps: rawptr[Parser], tok_type: int, +def _record_parse_err_ctx(ps: Parser*, tok_type: int, pv_str: str, pv_line: int, pv_col: int, nx_str: str, nx_line: int, nx_col: int): """Record the first parse error with token type and prev/next tokens appended to the message. @@ -338,7 +338,7 @@ def _record_neg_literal_overflow(lit_text: str, lineno: int, col: int): # ============================================================ # Type descriptors const / volatile (soft keywords, annotation position only) # ============================================================ -def _IsDescriptorKeyword(ps: rawptr[Parser]) -> int: +def _IsDescriptorKeyword(ps: Parser*) -> int: """Whether the current token is a type-descriptor keyword (const / volatile), 1 = yes / 0 = no. Soft keywords consumed by _parse_type_ann only in annotation position; `t.attr.const()` as an @@ -351,7 +351,7 @@ def _IsDescriptorKeyword(ps: rawptr[Parser]) -> int: return 0 -def _IsMagicAttributeCall(ps: rawptr[Parser]) -> int: +def _IsMagicAttributeCall(ps: Parser*) -> int: """Test for an annotation-position `__attribute__(...)` prefix, 1 = yes / 0 = no. `__attribute__` is a soft keyword (not in the keyword table): consumed here only in annotation @@ -362,13 +362,13 @@ def _IsMagicAttributeCall(ps: rawptr[Parser]) -> int: s: str = _cur_str(ps) if s is None or string.strcmp(s, "__attribute__") != 0: return 0 - nxt: rawptr[Token] = ps.cur.next + nxt: Token* = ps.cur.next if nxt is None or nxt.type != TokenType.Op or nxt.op_subtype != TokOp.LPar: return 0 return 1 -def _MakeDescriptorMarker(ps: rawptr[Parser]) -> rawptr[AST]: +def _MakeDescriptorMarker(ps: Parser*) -> AST*: """Build the marker node Attribute(Name('t'), 'CConst'/'CVolatile') from the current descriptor keyword. Field-identical to TPC's _ExpandTypeDescriptors text expansion (t.CConst / t.CVolatile) so both @@ -377,31 +377,31 @@ def _MakeDescriptorMarker(ps: rawptr[Parser]) -> rawptr[AST]: attr_name: str = "CConst" if _cur_kw(ps) == Keyword.Volatile: attr_name = "CVolatile" - marker: rawptr[AST] = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), + marker: AST* = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), attr_name, ASTCtx.Load) _set_pos(marker, _cur_lineno(ps), _cur_col(ps), 0, 0) return marker -def _PrependDescriptorMarkers(ps: rawptr[Parser], - base: rawptr[AST], - mods: rawptr[list[rawptr[AST]]], - mod_count: int) -> rawptr[AST]: +def _PrependDescriptorMarkers(ps: Parser*, + base: AST*, + mods: list[AST*]*, + mod_count: int) -> AST*: """Prepend descriptor markers to the leftmost operand of the type union (same shape as TPC text). TPC expands `const volatile int | t.CPtr` to the left-associative `(((t.CConst | t.CVolatile) | int) | t.CPtr)`; this function produces the identical tree rather than a differently-shaped one. """ - slot_parent: rawptr[BinOp] = None # leftmost BitOr node: its left is the leftmost operand - slot_node: rawptr[AST] = base - cur: rawptr[AST] = base + slot_parent: BinOp* = None # leftmost BitOr node: its left is the leftmost operand + slot_node: AST* = base + cur: AST* = base while cur is not None and cur.kind() == ASTKind.BinOp: - b: rawptr[BinOp] = (rawptr[BinOp])(cur) + b: BinOp* = (BinOp*)(cur) if b.op != OpKind.BitOr or b.left is None: break - nxt: rawptr[AST] = b.left + nxt: AST* = b.left if nxt.kind() == ASTKind.BinOp: - nb: rawptr[BinOp] = (rawptr[BinOp])(nxt) + nb: BinOp* = (BinOp*)(nxt) if nb.op == OpKind.BitOr and nb.left is not None: cur = nxt continue @@ -409,12 +409,12 @@ def _PrependDescriptorMarkers(ps: rawptr[Parser], slot_node = nxt break # Descriptor chain left-associates in source order: `const volatile` -> (t.CConst | t.CVolatile) - chain: rawptr[AST] = mods.get(0) + chain: AST* = mods.get(0) i: int = 1 while i < mod_count: chain = BinOp(ps.pool, chain, OpKind.BitOr, mods.get(i)) i += 1 - newnode: rawptr[AST] = BinOp(ps.pool, chain, OpKind.BitOr, slot_node) + newnode: AST* = BinOp(ps.pool, chain, OpKind.BitOr, slot_node) if slot_parent is None: return newnode slot_parent.left = newnode @@ -449,7 +449,7 @@ def _RecordDescriptorErr(detail: str, lineno: int, col: int): # ============================================================ # virtual / novirtual modifier (soft keyword; statement start before class/def only), same # representation as @t.CVTable / @t.NoVTable. Invalid forms fail loudly; `x = d.virtual` unaffected. -def _IsVirtualModifier(ps: rawptr[Parser]) -> int: +def _IsVirtualModifier(ps: Parser*) -> int: """Whether the current token is a virtual / novirtual modifier (1 = yes / 0 = no). Called only at statement start; identifier positions never reach this test, so `x = d.virtual`, @@ -462,7 +462,7 @@ def _IsVirtualModifier(ps: rawptr[Parser]) -> int: return 0 -def _MakeVirtualMarker(ps: rawptr[Parser]) -> rawptr[AST]: +def _MakeVirtualMarker(ps: Parser*) -> AST*: """Build the marker node Attribute(Name('t'), 'CVTable'|'NoVTable') from the current virtual/novirtual token. Field-identical to hand-written @t.CVTable / @t.NoVTable, so ClassGenBase._has_decorator needs no new test. @@ -470,7 +470,7 @@ def _MakeVirtualMarker(ps: rawptr[Parser]) -> rawptr[AST]: attr_name: str = "CVTable" if _cur_kw(ps) == Keyword.Novirtual: attr_name = "NoVTable" - marker: rawptr[AST] = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), + marker: AST* = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), attr_name, ASTCtx.Load) _set_pos(marker, _cur_lineno(ps), _cur_col(ps), 0, 0) return marker @@ -504,7 +504,7 @@ def _RecordVirtualErr(detail: str, lineno: int, col: int, extra: str): _g_parse_err_msg = detail -def _ParseVirtualModified(ps: rawptr[Parser], parent: rawptr[AST]): +def _ParseVirtualModified(ps: Parser*, parent: AST*): """`virtual class` / `novirtual class` / `virtual def` / `novirtual def`. Synthesizes a @t.CVTable / @t.NoVTable decorator (merged with existing decorators, appended last; @@ -515,7 +515,7 @@ def _ParseVirtualModified(ps: rawptr[Parser], parent: rawptr[AST]): mod_name: str = "virtual" if _cur_kw(ps) == Keyword.Novirtual: mod_name = "novirtual" - marker: rawptr[AST] = _MakeVirtualMarker(ps) + marker: AST* = _MakeVirtualMarker(ps) _advance(ps) # consume the modifier # The modifier must be followed by class / def (the def aliases fn/fun/func/function are accepted too, # matching _is_funcdef_kw and TPC, whose fn->def expansion only hits a leading fn). @@ -554,7 +554,7 @@ def _ParseVirtualModified(ps: rawptr[Parser], parent: rawptr[AST]): f"模块级 / 函数体 / 分支体内没有可归属的类。") ps.error_count += 1 # Merge existing decorators (@deco + virtual class/def) then hand off to the existing class/def parser - merged: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + merged: list[AST*]* = list[AST*](ps.pool, 8) if merged is None: return if ps.pending_decorators is not None: @@ -563,7 +563,7 @@ def _ParseVirtualModified(ps: rawptr[Parser], parent: rawptr[AST]): merged.append(ps.pending_decorators.get(di)) merged.append(marker) ps.pending_decorators = merged - stmt: rawptr[AST] = None + stmt: AST* = None if is_class != 0: stmt = _parse_classdef(ps) else: @@ -576,17 +576,17 @@ def _ParseVirtualModified(ps: rawptr[Parser], parent: rawptr[AST]): # inline modifier (soft keyword): `inline def f(...)` -> synthesizes @t.attr.always_inline, same shape as # virtual/novirtual (statement start before a function definition only); kept out of the keyword table. # ============================================================ -def _IsInlineModifier(ps: rawptr[Parser]) -> int: +def _IsInlineModifier(ps: Parser*) -> int: """Whether the current token is `inline` (soft keyword followed by a function definition), 1 = yes / 0 = no""" if _cur_type(ps) != TokenType.Name: return 0 s: str = _cur_str(ps) if s is None or string.strcmp(s, "inline") != 0: return 0 - nxt: rawptr[Token] = ps.cur.next + nxt: Token* = ps.cur.next if nxt is None or nxt.type != TokenType.Name: return 0 - nxt2: rawptr[Token] = nxt.next + nxt2: Token* = nxt.next if nxt2 is None: return 0 # Followed by def (hard keyword): `inline def f(...)` @@ -602,7 +602,7 @@ def _IsInlineModifier(ps: rawptr[Parser]) -> int: return 0 -def _MakeInlineMarker(ps: rawptr[Parser]) -> rawptr[AST]: +def _MakeInlineMarker(ps: Parser*) -> AST*: """Build the marker Attribute(Attribute(Name('t'),'attr'), 'always_inline') from the current inline token. Field-identical to a hand-written @t.attr.always_inline. Deliberately not @c.Attribute(t.attr.x), @@ -610,22 +610,22 @@ def _MakeInlineMarker(ps: rawptr[Parser]) -> rawptr[AST]: """ lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) - t_name: rawptr[AST] = Name(ps.pool, "t", ASTCtx.Load) - attr_at: rawptr[AST] = Attribute(ps.pool, t_name, "attr", ASTCtx.Load) - marker: rawptr[AST] = Attribute(ps.pool, attr_at, "always_inline", ASTCtx.Load) + t_name: AST* = Name(ps.pool, "t", ASTCtx.Load) + attr_at: AST* = Attribute(ps.pool, t_name, "attr", ASTCtx.Load) + marker: AST* = Attribute(ps.pool, attr_at, "always_inline", ASTCtx.Load) _set_pos(marker, lineno, col, 0, 0) return marker -def _ParseInlineModified(ps: rawptr[Parser], parent: rawptr[AST]): +def _ParseInlineModified(ps: Parser*, parent: AST*): """`inline def f(...)`: consume inline, synthesize @t.attr.always_inline and hand off to _parse_funcdef""" - marker: rawptr[AST] = _MakeInlineMarker(ps) + marker: AST* = _MakeInlineMarker(ps) if marker is None: return _advance(ps) # consume the inline modifier # Merge existing decorators (@deco + inline def), appending the marker last; position-independent # (matched by name downstream). Same pending_decorators channel as _ParseVirtualModified. - merged: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + merged: list[AST*]* = list[AST*](ps.pool, 8) if merged is None: return if ps.pending_decorators is not None: @@ -634,12 +634,12 @@ def _ParseInlineModified(ps: rawptr[Parser], parent: rawptr[AST]): merged.append(ps.pending_decorators.get(di)) merged.append(marker) ps.pending_decorators = merged - stmt: rawptr[AST] = _parse_funcdef(ps, 0) + stmt: AST* = _parse_funcdef(ps, 0) if stmt is not None: parent.append(stmt) -def _IsStaticModifier(ps: rawptr[Parser]) -> int: +def _IsStaticModifier(ps: Parser*) -> int: """Whether the current token is a `static` modifier (soft keyword), 1 = yes / 0 = no. Called only at statement start; matches when followed by (1) a function definition (`def` or the @@ -651,13 +651,13 @@ def _IsStaticModifier(ps: rawptr[Parser]) -> int: s: str = _cur_str(ps) if s is None or string.strcmp(s, "static") != 0: return 0 - nxt: rawptr[Token] = ps.cur.next + nxt: Token* = ps.cur.next if nxt is None or nxt.type != TokenType.Name: return 0 # (1) followed by def (hard keyword): `static def f(...)` if nxt.kw_subtype == Keyword.Def: return 1 - nxt2: rawptr[Token] = nxt.next + nxt2: Token* = nxt.next # (1') followed by a function-definition alias: must be Name + '(' or '[T]', same rule as # _IsInlineModifier / _is_funcdef_kw, so `static func` is not misread. if nxt.kw_subtype == Keyword.Fn or nxt.kw_subtype == Keyword.Fun \ @@ -671,7 +671,7 @@ def _IsStaticModifier(ps: rawptr[Parser]) -> int: return 0 -def _IsStaticDescriptorKeyword(ps: rawptr[Parser]) -> int: +def _IsStaticDescriptorKeyword(ps: Parser*) -> int: """Whether the current token is an annotation-position `static` (soft keyword), 1 = yes / 0 = no. This position (`name: static T`) is no longer supported: _parse_type_ann only detects it as misuse @@ -687,33 +687,33 @@ def _IsStaticDescriptorKeyword(ps: rawptr[Parser]) -> int: return 1 -def _MakeStaticMarker(ps: rawptr[Parser]) -> rawptr[AST]: +def _MakeStaticMarker(ps: Parser*) -> AST*: """Build the marker node Attribute(Name('t'), 'CStatic'). Field-identical to the hand-written @t.CStatic decorator / `x: t.CStatic | T` marker, so downstream (FuncGenDef storage-class detection, TypeGenResolve qualifier resolution) needs no new test. """ - marker: rawptr[AST] = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), + marker: AST* = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), "CStatic", ASTCtx.Load) _set_pos(marker, _cur_lineno(ps), _cur_col(ps), 0, 0) return marker -def _ParseStaticModified(ps: rawptr[Parser], parent: rawptr[AST]) -> int: +def _ParseStaticModified(ps: Parser*, parent: AST*) -> int: """Dispatch the `static` modifier: 1 = fully handled (function definition), 0 = only flagged (variable declaration, caller continues with the generic statement dispatch). Function: consume static and synthesize an @t.CStatic decorator, handed to _parse_funcdef. Variable: set pending_static and consume static; the next _parse_type_ann prepends t.CStatic. """ - nxt: rawptr[Token] = ps.cur.next + nxt: Token* = ps.cur.next is_func: int = 0 if nxt is not None and nxt.type == TokenType.Name: if nxt.kw_subtype == Keyword.Def: is_func = 1 elif nxt.kw_subtype == Keyword.Fn or nxt.kw_subtype == Keyword.Fun \ or nxt.kw_subtype == Keyword.Func or nxt.kw_subtype == Keyword.Function: - nxt2: rawptr[Token] = nxt.next + nxt2: Token* = nxt.next if nxt2 is not None and nxt2.type == TokenType.Op \ and (nxt2.op_subtype == TokOp.LPar or nxt2.op_subtype == TokOp.Lsqb): is_func = 1 @@ -723,13 +723,13 @@ def _ParseStaticModified(ps: rawptr[Parser], parent: rawptr[AST]) -> int: ps.pending_static = 1 _advance(ps) return 0 - marker: rawptr[AST] = _MakeStaticMarker(ps) + marker: AST* = _MakeStaticMarker(ps) if marker is None: return 1 _advance(ps) # consume the static modifier # Merge existing decorators (@deco + static def), appending the marker last; position-independent # (matched by name downstream). Same pending_decorators channel as _ParseInlineModified. - merged: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + merged: list[AST*]* = list[AST*](ps.pool, 8) if merged is None: return 1 if ps.pending_decorators is not None: @@ -738,13 +738,13 @@ def _ParseStaticModified(ps: rawptr[Parser], parent: rawptr[AST]) -> int: merged.append(ps.pending_decorators.get(di)) merged.append(marker) ps.pending_decorators = merged - stmt: rawptr[AST] = _parse_funcdef(ps, 0) + stmt: AST* = _parse_funcdef(ps, 0) if stmt is not None: parent.append(stmt) return 1 -def _IsBareDescriptor(ps: rawptr[Parser]) -> int: +def _IsBareDescriptor(ps: Parser*) -> int: """Bare-descriptor test: the whole statement is a single descriptor run (const[: volatile]), 1 = yes / 0 = no. Matches only when the descriptor run is followed directly by newline / EOF / semicolon; identifiers @@ -752,7 +752,7 @@ def _IsBareDescriptor(ps: rawptr[Parser]) -> int: """ if _IsDescriptorKeyword(ps) == 0: return 0 - nxt: rawptr[Token] = ps.cur.next + nxt: Token* = ps.cur.next while nxt is not None and nxt.type == TokenType.Name \ and (nxt.kw_subtype == Keyword.Const or nxt.kw_subtype == Keyword.Volatile): nxt = nxt.next @@ -780,28 +780,28 @@ def get_parse_err_msg() -> str: return _g_parse_err_msg -def _cur_str(ps: rawptr[Parser]) -> str: +def _cur_str(ps: Parser*) -> str: if ps.cur is None: return None return ps.cur.str_val -def _cur_lineno(ps: rawptr[Parser]) -> int: +def _cur_lineno(ps: Parser*) -> int: if ps.cur is None: return 0 return ps.cur.lineno -def _cur_col(ps: rawptr[Parser]) -> int: +def _cur_col(ps: Parser*) -> int: if ps.cur is None: return 0 return ps.cur.col_offset -def _skip_nl(ps: rawptr[Parser]): +def _skip_nl(ps: Parser*): """Skip TokenType.Nl token""" while ps.cur is not None and ps.cur.type == TokenType.Nl: _advance(ps) -def _skip_nls_and_newlines(ps: rawptr[Parser]): +def _skip_nls_and_newlines(ps: Parser*): """Skip TokenType.Nl and TokenType.NewLine (used for line continuation)""" while ps.cur is not None: if ps.cur.type == TokenType.Nl or ps.cur.type == TokenType.NewLine: @@ -810,7 +810,7 @@ def _skip_nls_and_newlines(ps: rawptr[Parser]): break -def _expect_type(ps: rawptr[Parser], ttype: int) -> int: +def _expect_type(ps: Parser*, ttype: int) -> int: """Expect the current token to be of the specified type, advance and return 1, otherwise return 0""" if _cur_type(ps) == ttype: _advance(ps) @@ -820,7 +820,7 @@ def _expect_type(ps: rawptr[Parser], ttype: int) -> int: return 0 -def _expect_op(ps: rawptr[Parser], op_id: int) -> int: +def _expect_op(ps: Parser*, op_id: int) -> int: """Expecting the current one to be some operator""" if _cur_type(ps) == TokenType.Op and _cur_op(ps) == op_id: _advance(ps) @@ -830,7 +830,7 @@ def _expect_op(ps: rawptr[Parser], op_id: int) -> int: return 0 -def _match_op(ps: rawptr[Parser], op_id: int) -> int: +def _match_op(ps: Parser*, op_id: int) -> int: """Check but not consume the current token""" _tick(ps) if ps.aborted != 0: @@ -845,7 +845,7 @@ def _match_op(ps: rawptr[Parser], op_id: int) -> int: return 0 -def _accept_op(ps: rawptr[Parser], op_id: int) -> int: +def _accept_op(ps: Parser*, op_id: int) -> int: """If match, consume and return 1""" if _match_op(ps, op_id): _advance(ps) @@ -857,15 +857,15 @@ def _accept_op(ps: rawptr[Parser], op_id: int) -> int: # Constant Construction Helper (New API: Constant directly accepts lineno/col) # ============================================================ -def _new_const_int(pool: rawptr[memhub.MemManager], val: int64, - lineno: int, col: int) -> rawptr[AST]: +def _new_const_int(pool: memhub.MemManager*, val: int64, + lineno: int, col: int) -> AST*: return Constant(pool, CONST_INT, val, 0.0, None, lineno, col) -def _new_const_float(pool: rawptr[memhub.MemManager], val: double, - lineno: int, col: int) -> rawptr[AST]: +def _new_const_float(pool: memhub.MemManager*, val: double, + lineno: int, col: int) -> AST*: global _g_dbg_pts, _g_dbg_vals, _g_dbg_cnt - new_c: rawptr[Constant] = Constant(pool, CONST_FLOAT, 0, val, None, lineno, col) + new_c: Constant* = Constant(pool, CONST_FLOAT, 0, val, None, lineno, col) # Store the numeric text in str_val (stdlib allocation, bypassing the pool overwrite of float_val); # REG-SRC recovers the original value with string.atof(str_val). lit_txt: str = stdlib.malloc(64) @@ -888,8 +888,8 @@ def _new_const_float(pool: rawptr[memhub.MemManager], val: double, # Float-node construction-value table (stdlib allocated to avoid polluting the pool) -_g_dbg_pts: rawptr[uint64] = None -_g_dbg_vals: rawptr[double] = None +_g_dbg_pts: uint64* = None +_g_dbg_vals: double* = None _g_dbg_cnt: int = 0 # Whether the latest _dbg_lookup_lit_val hit _g_dbg_lit_found: int = 0 @@ -916,11 +916,11 @@ def _dbg_lit_found() -> int: return _g_dbg_lit_found -def _new_const_str(pool: rawptr[memhub.MemManager], val: str, +def _new_const_str(pool: memhub.MemManager*, val: str, lineno: int, col: int, is_dquote: int = 1, is_triple: int = 0, - is_char: int = 0) -> rawptr[AST]: + is_char: int = 0) -> AST*: """Create a string/character constant node is_dquote: 0 = single quote, non-0 = double quote (default double quote) @@ -944,13 +944,13 @@ def _new_const_str(pool: rawptr[memhub.MemManager], val: str, return Constant(pool, CONST_STR, 0, 0.0, val, lineno, col) -def _new_const_bool(pool: rawptr[memhub.MemManager], val: int, - lineno: int, col: int) -> rawptr[AST]: +def _new_const_bool(pool: memhub.MemManager*, val: int, + lineno: int, col: int) -> AST*: return Constant(pool, CONST_BOOL, val, 0.0, None, lineno, col) -def _new_const_none(pool: rawptr[memhub.MemManager], - lineno: int, col: int) -> rawptr[AST]: +def _new_const_none(pool: memhub.MemManager*, + lineno: int, col: int) -> AST*: return Constant(pool, CONST_NONE, 0, 0.0, None, lineno, col) @@ -958,50 +958,50 @@ def _new_const_none(pool: rawptr[memhub.MemManager], # ctx Helper (Recursive Fixing Store Context) # ============================================================ -def _set_ctx(node: rawptr[AST], ctx: int): +def _set_ctx(node: AST*, ctx: int): """Set ctx field of node (based on kind conversion)""" if node is None: return k: int = node.kind() if k == ASTKind.Name: - nm: rawptr[Name] = (rawptr[Name])(node) + nm: Name* = (Name*)(node) nm.ctx = ctx elif k == ASTKind.Attribute: - at: rawptr[Attribute] = (rawptr[Attribute])(node) + at: Attribute* = (Attribute*)(node) at.ctx = ctx elif k == ASTKind.Subscript: - sb: rawptr[Subscript] = (rawptr[Subscript])(node) + sb: Subscript* = (Subscript*)(node) sb.ctx = ctx elif k == ASTKind.Tuple: - tp: rawptr[Tuple] = (rawptr[Tuple])(node) + tp: Tuple* = (Tuple*)(node) tp.ctx = ctx elif k == ASTKind.List: - ls: rawptr[List] = (rawptr[List])(node) + ls: List* = (List*)(node) ls.ctx = ctx elif k == ASTKind.Starred: - st: rawptr[Starred] = (rawptr[Starred])(node) + st: Starred* = (Starred*)(node) st.ctx = ctx -def _fix_store_ctx(node: rawptr[AST]): +def _fix_store_ctx(node: AST*): """Fix ctx of store targets to be Store""" if node is None: return _set_ctx(node, ASTCtx.Store) k: int = node.kind() if k == ASTKind.Tuple or k == ASTKind.List: - tp_elts: rawptr[list[rawptr[AST]]] = None + tp_elts: list[AST*]* = None if k == ASTKind.Tuple: - tp: rawptr[Tuple] = (rawptr[Tuple])(node) + tp: Tuple* = (Tuple*)(node) tp_elts = tp.elts else: - ls: rawptr[List] = (rawptr[List])(node) + ls: List* = (List*)(node) tp_elts = ls.elts if tp_elts is not None: n: sizet = tp_elts.__len__() for i in range(n): - cur: rawptr[AST] = tp_elts.get(i) + cur: AST* = tp_elts.get(i) _fix_store_ctx(cur) elif k == ASTKind.Starred: - st2: rawptr[Starred] = (rawptr[Starred])(node) + st2: Starred* = (Starred*)(node) _fix_store_ctx(st2.value) @@ -1009,27 +1009,27 @@ def _fix_store_ctx(node: rawptr[AST]): # Expression Parser # ============================================================ -def _parse_expr(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_expr(ps: Parser*) -> AST*: """expr: yield_expr | namedexpr_test""" if _cur_kw(ps) == Keyword.Yield: return _parse_yield(ps) return _parse_namedexpr(ps) -def _parse_namedexpr(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_namedexpr(ps: Parser*) -> AST*: """namedexpr_test: test [':=' test]""" - left: rawptr[AST] = _parse_test(ps) + left: AST* = _parse_test(ps) if left is None: return None if _match_op(ps, TokOp.ColonEq): _advance(ps) - right: rawptr[AST] = _parse_test(ps) - node: rawptr[AST] = NamedExpr(ps.pool, left, right) + right: AST* = _parse_test(ps) + node: AST* = NamedExpr(ps.pool, left, right) _set_pos(node, left.lineno, left.col_offset, 0, 0) return node return left -def _IsVolatileCallPrefix(ps: rawptr[Parser]) -> int: +def _IsVolatileCallPrefix(ps: Parser*) -> int: """Test for a value-position `volatile f()` / `volatile S()` prefix, 1 = yes / 0 = no. `volatile` is a soft keyword consumed only in value position before a call (Name followed by '('); @@ -1037,16 +1037,16 @@ def _IsVolatileCallPrefix(ps: rawptr[Parser]) -> int: """ if _cur_kw(ps) != Keyword.Volatile: return 0 - nxt: rawptr[Token] = ps.cur.next + nxt: Token* = ps.cur.next if nxt is None or nxt.type != TokenType.Name: return 0 - nxt2: rawptr[Token] = nxt.next + nxt2: Token* = nxt.next if nxt2 is None or nxt2.type != TokenType.Op or nxt2.op_subtype != TokOp.LPar: return 0 return 1 -def _parse_test(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_test(ps: Parser*) -> AST*: """test: or_test ['if' or_test 'else' test] | lambdef""" if _cur_kw(ps) == Keyword.Lambda: return _parse_lambda(ps) @@ -1054,19 +1054,19 @@ def _parse_test(ps: rawptr[Parser]) -> rawptr[AST]: # mark the call node (result slot accessed volatile, struct writes too; LLVM call has no volatile qualifier). if _IsVolatileCallPrefix(ps) != 0: _advance(ps) # consume volatile - vinner: rawptr[AST] = _parse_test(ps) + vinner: AST* = _parse_test(ps) if vinner is not None and vinner.kind() == ASTKind.Call: (Call*(vinner)).IsVolatile = 1 return vinner - left: rawptr[AST] = _parse_or_test(ps) + left: AST* = _parse_or_test(ps) if left is None: return None if _cur_kw(ps) == Keyword.If: _advance(ps) - test: rawptr[AST] = _parse_or_test(ps) + test: AST* = _parse_or_test(ps) if _cur_kw(ps) == Keyword.Else: _advance(ps) - orelse: rawptr[AST] = _parse_test(ps) - node: rawptr[AST] = IfExp(ps.pool, test, left, orelse) + orelse: AST* = _parse_test(ps) + node: AST* = IfExp(ps.pool, test, left, orelse) _set_pos(node, left.lineno, left.col_offset, 0, 0) return node ps.error_count += 1 @@ -1074,27 +1074,27 @@ def _parse_test(ps: rawptr[Parser]) -> rawptr[AST]: return left -def _parse_lambda(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_lambda(ps: Parser*) -> AST*: """lambdef: 'lambda' [varargslist] ':' test""" lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # lambda - args: rawptr[AST] = None + args: AST* = None if not _match_op(ps, TokOp.Colon): args = _parse_varargslist(ps, 1) if not _expect_op(ps, TokOp.Colon): return None - body: rawptr[AST] = _parse_test(ps) - node: rawptr[AST] = Lambda(ps.pool, args, body) + body: AST* = _parse_test(ps) + node: AST* = Lambda(ps.pool, args, body) _set_pos(node, lineno, col, 0, 0) return node -def _parse_or_test(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_or_test(ps: Parser*) -> AST*: """or_test: and_test ('or' and_test)*""" - left: rawptr[AST] = _parse_and_test(ps) + left: AST* = _parse_and_test(ps) if left is None: return None - values: rawptr[list[rawptr[AST]]] = None + values: list[AST*]* = None while True: # Supports both leading `or` ((A\n or B)) and trailing `or` (A or\n B) inside parens: # each round skips Nl before checking, otherwise A or B\n or C stops on Nl after B. @@ -1102,25 +1102,25 @@ def _parse_or_test(ps: rawptr[Parser]) -> rawptr[AST]: if _cur_kw(ps) != Keyword.Or: break if values is None: - values = list[rawptr[AST]](ps.pool, 8) + values = list[AST*](ps.pool, 8) values.append(left) _advance(ps) _skip_nl(ps) # cross-line inside parens: a or\n b - right: rawptr[AST] = _parse_and_test(ps) + right: AST* = _parse_and_test(ps) if right is None: break values.append(right) if values is not None: - node: rawptr[AST] = BoolOp(ps.pool, OpKind.Or, values) + node: AST* = BoolOp(ps.pool, OpKind.Or, values) _set_pos(node, left.lineno, left.col_offset, 0, 0) return node return left -def _parse_and_test(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_and_test(ps: Parser*) -> AST*: """and_test: not_test ('and' not_test)*""" - left: rawptr[AST] = _parse_not_test(ps) + left: AST* = _parse_not_test(ps) if left is None: return None - values: rawptr[list[rawptr[AST]]] = None + values: list[AST*]* = None while True: # Supports both leading `and` ((A\n and B)) and trailing `and` (A and\n B) inside parens: # each round skips Nl before checking, otherwise A and B\n and C stops on Nl after B. @@ -1128,40 +1128,40 @@ def _parse_and_test(ps: rawptr[Parser]) -> rawptr[AST]: if _cur_kw(ps) != Keyword.And: break if values is None: - values = list[rawptr[AST]](ps.pool, 8) + values = list[AST*](ps.pool, 8) values.append(left) _advance(ps) _skip_nl(ps) # cross-line inside parens: a and\n b - right: rawptr[AST] = _parse_not_test(ps) + right: AST* = _parse_not_test(ps) if right is None: break values.append(right) if values is not None: - node: rawptr[AST] = BoolOp(ps.pool, OpKind.And, values) + node: AST* = BoolOp(ps.pool, OpKind.And, values) _set_pos(node, left.lineno, left.col_offset, 0, 0) return node return left -def _parse_not_test(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_not_test(ps: Parser*) -> AST*: """not_test: 'not' not_test | comparison""" if _cur_kw(ps) == Keyword.Not: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) - operand: rawptr[AST] = _parse_not_test(ps) - node: rawptr[AST] = UnaryOp(ps.pool, OpKind.Not, operand) + operand: AST* = _parse_not_test(ps) + node: AST* = UnaryOp(ps.pool, OpKind.Not, operand) _set_pos(node, lineno, col, 0, 0) return node return _parse_comparison(ps) -def _parse_comparison(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_comparison(ps: Parser*) -> AST*: """comparison: bitor_expr (comp_op bitor_expr)* Single comparison design: a < b → Compare(left=a, op=Lt, right=b) Chained comparison a < b < c → BoolOp(And, [Compare(a,<,b), Compare(b,<,c)]) """ - left: rawptr[AST] = _parse_bitor(ps) + left: AST* = _parse_bitor(ps) if left is None: return None _skip_nl(ps) # leading comparison operator inside parens: (a\n < b) @@ -1170,13 +1170,13 @@ def _parse_comparison(ps: rawptr[Parser]) -> rawptr[AST]: return left _advance_comp_op(ps) _skip_nl(ps) # cross-line inside parens: a ==\n b - right: rawptr[AST] = _parse_bitor(ps) + right: AST* = _parse_bitor(ps) # Single comparison: construct ops and comparators list - ops: rawptr[list[int]] = list[int](ps.pool, 8) + ops: list[int]* = list[int](ps.pool, 8) ops.append(op_id) - comparators: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + comparators: list[AST*]* = list[AST*](ps.pool, 8) comparators.append(right) - first_cmp: rawptr[AST] = Compare(ps.pool, left, ops, comparators) + first_cmp: AST* = Compare(ps.pool, left, ops, comparators) _set_pos(first_cmp, left.lineno, left.col_offset, 0, 0) # Check chained comparison @@ -1186,29 +1186,29 @@ def _parse_comparison(ps: rawptr[Parser]) -> rawptr[AST]: return first_cmp # Single comparison with chained conditions: a < b < c → BoolOp(And, [Compare(a,<,b), Compare(b,<,c), ...]) - values: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + values: list[AST*]* = list[AST*](ps.pool, 8) values.append(first_cmp) - cur_left: rawptr[AST] = right + cur_left: AST* = right while next_op != OpKind.NoneOp: _advance_comp_op(ps) _skip_nl(ps) # cross-line chained comparison inside parens - cur_right: rawptr[AST] = _parse_bitor(ps) - ops2: rawptr[list[int]] = list[int](ps.pool, 8) + cur_right: AST* = _parse_bitor(ps) + ops2: list[int]* = list[int](ps.pool, 8) ops2.append(next_op) - comparators2: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + comparators2: list[AST*]* = list[AST*](ps.pool, 8) comparators2.append(cur_right) - cmp: rawptr[AST] = Compare(ps.pool, cur_left, ops2, comparators2) + cmp: AST* = Compare(ps.pool, cur_left, ops2, comparators2) _set_pos(cmp, cur_left.lineno, cur_left.col_offset, 0, 0) values.append(cmp) cur_left = cur_right _skip_nl(ps) # leading chained comparison inside parens: (a < b\n < c) next_op = _match_comp_op(ps) - node: rawptr[AST] = BoolOp(ps.pool, OpKind.And, values) + node: AST* = BoolOp(ps.pool, OpKind.And, values) _set_pos(node, left.lineno, left.col_offset, 0, 0) return node -def _match_comp_op(ps: rawptr[Parser]) -> int: +def _match_comp_op(ps: Parser*) -> int: """Check if the current one is a comparison operator, return OP_* or OpKind.NoneOp""" if _cur_type(ps) == TokenType.Op: op_id: int = _cur_op(ps) @@ -1230,7 +1230,7 @@ def _match_comp_op(ps: rawptr[Parser]) -> int: return OpKind.NoneOp -def _advance_comp_op(ps: rawptr[Parser]): +def _advance_comp_op(ps: Parser*): """Consume comparison operator token""" if _cur_type(ps) == TokenType.Op: _advance(ps) @@ -1249,8 +1249,8 @@ def _advance_comp_op(ps: rawptr[Parser]): _advance(ps) -def _parse_bitor(ps: rawptr[Parser]) -> rawptr[AST]: - left: rawptr[AST] = _parse_bitxor(ps) +def _parse_bitor(ps: Parser*) -> AST*: + left: AST* = _parse_bitxor(ps) if left is None: return None while True: _skip_nl(ps) # leading '|' inside parens: (a\n | b) @@ -1258,15 +1258,15 @@ def _parse_bitor(ps: rawptr[Parser]) -> rawptr[AST]: break _advance(ps) _skip_nl(ps) # cross-line inside parens: a |\n b - right: rawptr[AST] = _parse_bitxor(ps) - node: rawptr[AST] = BinOp(ps.pool, left, OpKind.BitOr, right) + right: AST* = _parse_bitxor(ps) + node: AST* = BinOp(ps.pool, left, OpKind.BitOr, right) _set_pos(node, left.lineno, left.col_offset, 0, 0) left = node return left -def _parse_bitxor(ps: rawptr[Parser]) -> rawptr[AST]: - left: rawptr[AST] = _parse_bitand(ps) +def _parse_bitxor(ps: Parser*) -> AST*: + left: AST* = _parse_bitand(ps) if left is None: return None while True: _skip_nl(ps) # leading '^' inside parens: (a\n ^ b) @@ -1274,15 +1274,15 @@ def _parse_bitxor(ps: rawptr[Parser]) -> rawptr[AST]: break _advance(ps) _skip_nl(ps) # cross-line inside parens: a ^\n b - right: rawptr[AST] = _parse_bitand(ps) - node: rawptr[AST] = BinOp(ps.pool, left, OpKind.BitXor, right) + right: AST* = _parse_bitand(ps) + node: AST* = BinOp(ps.pool, left, OpKind.BitXor, right) _set_pos(node, left.lineno, left.col_offset, 0, 0) left = node return left -def _parse_bitand(ps: rawptr[Parser]) -> rawptr[AST]: - left: rawptr[AST] = _parse_shift(ps) +def _parse_bitand(ps: Parser*) -> AST*: + left: AST* = _parse_shift(ps) if left is None: return None while True: _skip_nl(ps) # leading '&' inside parens: (a\n & b) @@ -1290,15 +1290,15 @@ def _parse_bitand(ps: rawptr[Parser]) -> rawptr[AST]: break _advance(ps) _skip_nl(ps) # cross-line inside parens: a &\n b - right: rawptr[AST] = _parse_shift(ps) - node: rawptr[AST] = BinOp(ps.pool, left, OpKind.BitAnd, right) + right: AST* = _parse_shift(ps) + node: AST* = BinOp(ps.pool, left, OpKind.BitAnd, right) _set_pos(node, left.lineno, left.col_offset, 0, 0) left = node return left -def _parse_shift(ps: rawptr[Parser]) -> rawptr[AST]: - left: rawptr[AST] = _parse_arith(ps) +def _parse_shift(ps: Parser*) -> AST*: + left: AST* = _parse_arith(ps) if left is None: return None while True: _skip_nl(ps) # leading '<<'/'>>' inside parens: (a\n << b) @@ -1307,18 +1307,18 @@ def _parse_shift(ps: rawptr[Parser]) -> rawptr[AST]: op_token: int = _cur_op(ps) _advance(ps) _skip_nl(ps) # cross-line inside parens: a <<\n b - right: rawptr[AST] = _parse_arith(ps) + right: AST* = _parse_arith(ps) ast_op: int = OpKind.LShift if op_token == TokOp.GtGt: ast_op = OpKind.RShift - node: rawptr[AST] = BinOp(ps.pool, left, ast_op, right) + node: AST* = BinOp(ps.pool, left, ast_op, right) _set_pos(node, left.lineno, left.col_offset, 0, 0) left = node return left -def _parse_arith(ps: rawptr[Parser]) -> rawptr[AST]: - left: rawptr[AST] = _parse_term(ps) +def _parse_arith(ps: Parser*) -> AST*: + left: AST* = _parse_term(ps) if left is None: return None while True: _skip_nl(ps) # leading '+'/'-' inside parens: (a\n + b) @@ -1327,11 +1327,11 @@ def _parse_arith(ps: rawptr[Parser]) -> rawptr[AST]: op_token: int = _cur_op(ps) _advance(ps) _skip_nl(ps) # cross-line inside parens: a +\n b - right: rawptr[AST] = _parse_term(ps) + right: AST* = _parse_term(ps) ast_op: int = OpKind.Add if op_token == TokOp.Minus: ast_op = OpKind.Sub - node: rawptr[AST] = BinOp(ps.pool, left, ast_op, right) + node: AST* = BinOp(ps.pool, left, ast_op, right) _set_pos(node, left.lineno, left.col_offset, 0, 0) left = node return left @@ -1360,7 +1360,7 @@ def _ptr_suffix_end_op(op: int) -> int: return 0 -def _at_ptr_suffix(ps: rawptr[Parser], base: rawptr[AST]) -> int: +def _at_ptr_suffix(ps: Parser*, base: AST*) -> int: """Whether the current '*'/'**' run is a C-style pointer suffix applied to base. Rule (same as vast): base is a type atom (Name/Attribute/Subscript) and, skipping consecutive @@ -1371,7 +1371,7 @@ def _at_ptr_suffix(ps: rawptr[Parser], base: rawptr[AST]) -> int: k: int = base.kind() if k != ASTKind.Name and k != ASTKind.Attribute and k != ASTKind.Subscript: return 0 - nxt: rawptr[Token] = ps.cur + nxt: Token* = ps.cur stars: int = 0 while nxt is not None: if nxt.type == TokenType.Op \ @@ -1387,16 +1387,16 @@ def _at_ptr_suffix(ps: rawptr[Parser], base: rawptr[AST]) -> int: return _ptr_suffix_end_op(nxt.op_subtype) -def _make_ptr_type(ps: rawptr[Parser], base: rawptr[AST]) -> rawptr[AST]: +def _make_ptr_type(ps: Parser*, base: AST*) -> AST*: """Build one pointer wrapper layer: base | t.CPtr.""" - cptr: rawptr[AST] = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), + cptr: AST* = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), "CPtr", ASTCtx.Load) - node: rawptr[AST] = BinOp(ps.pool, base, OpKind.BitOr, cptr) + node: AST* = BinOp(ps.pool, base, OpKind.BitOr, cptr) _set_pos(node, base.lineno, base.col_offset, 0, 0) return node -def _consume_ptr_suffix(ps: rawptr[Parser], base: rawptr[AST]) -> rawptr[AST]: +def _consume_ptr_suffix(ps: Parser*, base: AST*) -> AST*: """Consume consecutive C-style pointer suffixes ('*' = 1 layer, '**' = 2), expanding into a base | t.CPtr chain.""" global _g_ptr_suffix_line, _g_ptr_suffix_col while True: @@ -1418,7 +1418,7 @@ def _consume_ptr_suffix(ps: rawptr[Parser], base: rawptr[AST]) -> rawptr[AST]: return base -def _at_cast_operand(ps: rawptr[Parser]) -> int: +def _at_cast_operand(ps: Parser*) -> int: """Whether the current token may start the operand of a paren-less cast `(T*)x`. '(' is deliberately absent: `(T*)(x)` is already handled by the trailer loop as a @@ -1437,7 +1437,7 @@ def _at_cast_operand(ps: rawptr[Parser]) -> int: return 0 -def _at_ptr_suffix_call(ps: rawptr[Parser], base: rawptr[AST]) -> int: +def _at_ptr_suffix_call(ps: Parser*, base: AST*) -> int: """Whether the current '*'/'**' run is a `T*(x)` pointer-suffix cast call. Rule (same as TPC lib/vast _AtPtrSuffixCall): (1) base is a type atom; (2) base and the star run are @@ -1449,8 +1449,8 @@ def _at_ptr_suffix_call(ps: rawptr[Parser], base: rawptr[AST]) -> int: k: int = base.kind() if k != ASTKind.Name and k != ASTKind.Attribute and k != ASTKind.Subscript: return 0 - nxt: rawptr[Token] = ps.cur - pv: rawptr[Token] = ps.prev + nxt: Token* = ps.cur + pv: Token* = ps.prev if pv is None or nxt is None: return 0 if pv.type == TokenType.Nl or pv.type == TokenType.NewLine: @@ -1458,8 +1458,8 @@ def _at_ptr_suffix_call(ps: rawptr[Parser], base: rawptr[AST]) -> int: if pv.end_lineno != nxt.lineno or pv.end_col_offset != nxt.col_offset: return 0 # whitespace/newline between base and '*': not a C-style cast stars: int = 0 - prev: rawptr[Token] = None - last: rawptr[Token] = None + prev: Token* = None + last: Token* = None while nxt is not None: if nxt.type == TokenType.Op \ and (nxt.op_subtype == TokOp.Star or nxt.op_subtype == TokOp.StarStar): @@ -1481,18 +1481,18 @@ def _at_ptr_suffix_call(ps: rawptr[Parser], base: rawptr[AST]) -> int: return 1 -def _consume_ptr_suffix_call(ps: rawptr[Parser], base: rawptr[AST]) -> rawptr[AST]: +def _consume_ptr_suffix_call(ps: Parser*, base: AST*) -> AST*: """Parse a recognized `T*(...)` pointer-suffix cast as a call. Identical to the existing cast form `(T | t.CPtr)(...)`: a Call (func = the expanded base | t.CPtr chain, args/keywords = the parenthesized arguments); no second cast representation is introduced. """ - func: rawptr[AST] = _consume_ptr_suffix(ps, base) + func: AST* = _consume_ptr_suffix(ps, base) return _parse_call(ps, func) -def _parse_term(ps: rawptr[Parser]) -> rawptr[AST]: - left: rawptr[AST] = _parse_factor(ps) +def _parse_term(ps: Parser*) -> AST*: + left: AST* = _parse_factor(ps) if left is None: return None while True: _skip_nl(ps) # leading '*'/'/'/'//'/'%'/'@' inside parens: (a\n * b) @@ -1508,20 +1508,20 @@ def _parse_term(ps: rawptr[Parser]) -> rawptr[AST]: if op_token == 0: break _advance(ps) _skip_nl(ps) # cross-line inside parens: a *\n b - right: rawptr[AST] = _parse_factor(ps) + right: AST* = _parse_factor(ps) ast_op: int = _binop_from_op(op_token) - node: rawptr[AST] = BinOp(ps.pool, left, ast_op, right) + node: AST* = BinOp(ps.pool, left, ast_op, right) _set_pos(node, left.lineno, left.col_offset, 0, 0) left = node return left -def _parse_factor(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_factor(ps: Parser*) -> AST*: """factor: '+' factor | '-' factor | '~' factor | '*' factor | '&' factor | power""" # A leading `*` in argument position was already parsed by _parse_call as a tightly bound Starred # operand; return it as this level's factor, before the unary test (so `*p + n` => `(*p) + n`). if ps.starred_seed is not None: - seed: rawptr[AST] = ps.starred_seed + seed: AST* = ps.starred_seed ps.starred_seed = None return seed if (_match_op(ps, TokOp.Plus) or _match_op(ps, TokOp.Minus) or _match_op(ps, TokOp.Tilde) @@ -1538,7 +1538,7 @@ def _parse_factor(ps: rawptr[Parser]) -> rawptr[AST]: _record_neg_literal_overflow(_cur_str(ps), lineno, col) ps.error_count += 1 return None - operand: rawptr[AST] = _parse_factor(ps) + operand: AST* = _parse_factor(ps) ast_op: int = OpKind.UAdd if op_token == TokOp.Minus: ast_op = OpKind.USub @@ -1548,38 +1548,38 @@ def _parse_factor(ps: rawptr[Parser]) -> rawptr[AST]: ast_op = OpKind.Deref elif op_token == TokOp.Amp: ast_op = OpKind.AddrOf - node: rawptr[AST] = UnaryOp(ps.pool, ast_op, operand) + node: AST* = UnaryOp(ps.pool, ast_op, operand) _set_pos(node, lineno, col, 0, 0) return node return _parse_power(ps) -def _parse_power(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_power(ps: Parser*) -> AST*: """power: await_expr ['**' factor] | atom_expr ['**' factor]""" - base: rawptr[AST] = _parse_atom_expr(ps) + base: AST* = _parse_atom_expr(ps) if base is None: return None if _match_op(ps, TokOp.StarStar) and _at_ptr_suffix(ps, base) != 0: return _consume_ptr_suffix(ps, base) # C-style pointer suffix ('**' counts as 2 layers) if _match_op(ps, TokOp.StarStar): _advance(ps) - exp: rawptr[AST] = _parse_factor(ps) - node: rawptr[AST] = BinOp(ps.pool, base, OpKind.Pow, exp) + exp: AST* = _parse_factor(ps) + node: AST* = BinOp(ps.pool, base, OpKind.Pow, exp) _set_pos(node, base.lineno, base.col_offset, 0, 0) return node return base -def _parse_atom_expr(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_atom_expr(ps: Parser*) -> AST*: """atom_expr: ['await'] atom trailer*""" if _cur_kw(ps) == Keyword.Await: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) - inner: rawptr[AST] = _parse_atom_expr(ps) - node: rawptr[AST] = Await(ps.pool, inner) + inner: AST* = _parse_atom_expr(ps) + node: AST* = Await(ps.pool, inner) _set_pos(node, lineno, col, 0, 0) return node - base: rawptr[AST] = _parse_atom(ps) + base: AST* = _parse_atom(ps) if base is None: return None # trailer loop while True: @@ -1614,14 +1614,14 @@ def _parse_atom_expr(ps: rawptr[Parser]) -> rawptr[AST]: return base -def _parse_call(ps: rawptr[Parser], func: rawptr[AST]) -> rawptr[AST]: +def _parse_call(ps: Parser*, func: AST*) -> AST*: """Parse function call trailer. Both args and keywords are lists.""" lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # ( _skip_nls_and_newlines(ps) # Skip the line break after '(' - args: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - keywords: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + args: list[AST*]* = list[AST*](ps.pool, 8) + keywords: list[AST*]* = list[AST*](ps.pool, 8) if not _match_op(ps, TokOp.RPar): while True: @@ -1629,8 +1629,8 @@ def _parse_call(ps: rawptr[Parser], func: rawptr[AST]) -> rawptr[AST]: if _match_op(ps, TokOp.StarStar): _advance(ps) _skip_nls_and_newlines(ps) - val: rawptr[AST] = _parse_expr(ps) - kw: rawptr[AST] = KwNode(ps.pool, None, val) + val: AST* = _parse_expr(ps) + kw: AST* = KwNode(ps.pool, None, val) _set_pos(kw, _cur_lineno(ps), _cur_col(ps), 0, 0) keywords.append(kw) # *expr @@ -1639,11 +1639,11 @@ def _parse_call(ps: rawptr[Parser], func: rawptr[AST]) -> rawptr[AST]: _skip_nls_and_newlines(ps) # Bind only a unary factor (preserving `*p[0]` = `*(p[0])`), put it on starred_seed and let # _parse_expr continue the binary ops: `*p + n` => `(*p) + n`, not `*(p + n)`. - seed: rawptr[AST] = _parse_factor(ps) + seed: AST* = _parse_factor(ps) if seed is None: ps.error_count += 1 break - star: rawptr[AST] = Starred(ps.pool, seed, ASTCtx.Load) + star: AST* = Starred(ps.pool, seed, ASTCtx.Load) _set_pos(star, seed.lineno, seed.col_offset, 0, 0) ps.starred_seed = star val = _parse_expr(ps) @@ -1673,30 +1673,30 @@ def _parse_call(ps: rawptr[Parser], func: rawptr[AST]) -> rawptr[AST]: _skip_nls_and_newlines(ps) # Skip the line break after the comma _skip_nls_and_newlines(ps) # Skip the line break before ')' _expect_op(ps, TokOp.RPar) - node: rawptr[AST] = Call(ps.pool, func, args, keywords) + node: AST* = Call(ps.pool, func, args, keywords) _set_pos(node, lineno, col, 0, 0) return node -def _parse_subscript(ps: rawptr[Parser], value: rawptr[AST]) -> rawptr[AST]: +def _parse_subscript(ps: Parser*, value: AST*) -> AST*: """Parse subscript trailer.""" lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # [ _skip_nl(ps) - slice_node: rawptr[AST] = _parse_slice(ps) + slice_node: AST* = _parse_slice(ps) _expect_op(ps, TokOp.Rsqb) ctx: int = ASTCtx.Load if _match_op(ps, TokOp.Equal): ctx = ASTCtx.Store - node: rawptr[AST] = Subscript(ps.pool, value, slice_node, ctx) + node: AST* = Subscript(ps.pool, value, slice_node, ctx) _set_pos(node, lineno, col, 0, 0) return node -def _parse_slice(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_slice(ps: Parser*) -> AST*: """Parse slice: [expr] ':' [expr] [':' [expr]] | expr | expr, expr, ...""" - lower: rawptr[AST] = None + lower: AST* = None # Empty subscript (`T[]`): `[` directly followed by `]` => slice is None (the type side treats it as # an empty param list); calling _parse_expr here would report an unexpected token ']'. if not _match_op(ps, TokOp.Colon) and not _match_op(ps, TokOp.Rsqb): @@ -1704,28 +1704,28 @@ def _parse_slice(ps: rawptr[Parser]) -> rawptr[AST]: # Check if there’s a comma (tuple syntax: a[x, y, ...]) if _match_op(ps, TokOp.Comma): - elts: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + elts: list[AST*]* = list[AST*](ps.pool, 8) if lower is not None: elts.append(lower) while _accept_op(ps, TokOp.Comma): if _match_op(ps, TokOp.Rsqb): break # Trailing comma - elem: rawptr[AST] = _parse_expr(ps) + elem: AST* = _parse_expr(ps) if elem is not None: elts.append(elem) lineno: int = 0 if lower is not None: lineno = lower.lineno - node: rawptr[AST] = Tuple(ps.pool, elts, ASTCtx.Load) + node: AST* = Tuple(ps.pool, elts, ASTCtx.Load) _set_pos(node, lineno, 0, 0, 0) return node if _match_op(ps, TokOp.Colon): _advance(ps) - upper: rawptr[AST] = None + upper: AST* = None if not _match_op(ps, TokOp.Colon) and not _match_op(ps, TokOp.Rsqb): upper = _parse_expr(ps) - step: rawptr[AST] = None + step: AST* = None if _accept_op(ps, TokOp.Colon): if not _match_op(ps, TokOp.Rsqb): step = _parse_expr(ps) @@ -1736,13 +1736,13 @@ def _parse_slice(ps: rawptr[Parser]) -> rawptr[AST]: lineno = upper.lineno else: lineno = _cur_lineno(ps) - node: rawptr[AST] = Slice(ps.pool, lower, upper, step) + node: AST* = Slice(ps.pool, lower, upper, step) _set_pos(node, lineno, 0, 0, 0) return node return lower -def _parse_atom(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_atom(ps: Parser*) -> AST*: """atom: the smallest unit of expression""" ttype: int = _cur_type(ps) lineno: int = _cur_lineno(ps) @@ -1761,12 +1761,12 @@ def _parse_atom(ps: rawptr[Parser]) -> rawptr[AST]: return _new_const_none(ps.pool, lineno, col) name_str: str = _cur_str(ps) _advance(ps) - node: rawptr[AST] = Name(ps.pool, name_str, ASTCtx.Load) + node: AST* = Name(ps.pool, name_str, ASTCtx.Load) _set_pos(node, lineno, col, 0, 0) return node if ttype == TokenType.Number: - tok: rawptr[Token] = ps.cur + tok: Token* = ps.cur _advance(ps) if tok.is_float: return _new_const_float(ps.pool, tok.float_val, lineno, col) @@ -1779,7 +1779,7 @@ def _parse_atom(ps: rawptr[Parser]) -> rawptr[AST]: is_dquote: int = ps.cur.kw_subtype & 16 is_char: int = ps.cur.kw_subtype & 32 _advance(ps) - node: rawptr[AST] + node: AST* if is_fstr: node = _parse_fstring(ps, sval, lineno, col) else: @@ -1796,7 +1796,7 @@ def _parse_atom(ps: rawptr[Parser]) -> rawptr[AST]: n_dquote: int = ps.cur.kw_subtype & 16 n_char: int = ps.cur.kw_subtype & 32 _advance(ps) - n_node: rawptr[AST] + n_node: AST* if n_fstr: n_node = _parse_fstring(ps, n_sval, lineno, col) else: @@ -1820,7 +1820,7 @@ def _parse_atom(ps: rawptr[Parser]) -> rawptr[AST]: return None -def _parse_paren(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_paren(ps: Parser*) -> AST*: """Parenthesis expressions: () | (expr) | (expr,) | (expr, ...) | (yield)""" lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) @@ -1829,25 +1829,25 @@ def _parse_paren(ps: rawptr[Parser]) -> rawptr[AST]: if _match_op(ps, TokOp.RPar): _advance(ps) # Empty tuple - empty: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - node: rawptr[AST] = Tuple(ps.pool, empty, ASTCtx.Load) + empty: list[AST*]* = list[AST*](ps.pool, 8) + node: AST* = Tuple(ps.pool, empty, ASTCtx.Load) _set_pos(node, lineno, col, 0, 0) return node # yield if _cur_kw(ps) == Keyword.Yield: - y: rawptr[AST] = _parse_yield(ps) + y: AST* = _parse_yield(ps) _expect_op(ps, TokOp.RPar) return y - first: rawptr[AST] = _parse_expr(ps) + first: AST* = _parse_expr(ps) if _match_op(ps, TokOp.Comma): # Tuple - elts: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + elts: list[AST*]* = list[AST*](ps.pool, 8) elts.append(first) while _accept_op(ps, TokOp.Comma): _skip_nl(ps) if _match_op(ps, TokOp.RPar): break - e: rawptr[AST] = _parse_expr(ps) + e: AST* = _parse_expr(ps) elts.append(e) _skip_nl(ps) # finish when the last element has no trailing comma (multi-line tuple) _expect_op(ps, TokOp.RPar) @@ -1866,17 +1866,17 @@ def _parse_paren(ps: rawptr[Parser]) -> rawptr[AST]: if _cur_kw(ps) == Keyword.For: return _parse_comprehension(ps, first, ASTKind.GeneratorExp, lineno, col) if is_ptr_cast != 0 and _at_cast_operand(ps) != 0: - operand: rawptr[AST] = _parse_factor(ps) - cast_args: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + operand: AST* = _parse_factor(ps) + cast_args: list[AST*]* = list[AST*](ps.pool, 8) cast_args.append(operand) - cast_kws: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - cast_node: rawptr[AST] = Call(ps.pool, first, cast_args, cast_kws) + cast_kws: list[AST*]* = list[AST*](ps.pool, 8) + cast_node: AST* = Call(ps.pool, first, cast_args, cast_kws) _set_pos(cast_node, first.lineno, first.col_offset, 0, 0) return cast_node return first -def _parse_list(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_list(ps: Parser*) -> AST*: """List expressions: [] | [expr_list] | [expr_list comp_for]""" lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) @@ -1884,22 +1884,22 @@ def _parse_list(ps: rawptr[Parser]) -> rawptr[AST]: _skip_nl(ps) # Skip the line break after '[' (multi-line list) if _match_op(ps, TokOp.Rsqb): _advance(ps) - empty: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - node: rawptr[AST] = List(ps.pool, empty, ASTCtx.Load) + empty: list[AST*]* = list[AST*](ps.pool, 8) + node: AST* = List(ps.pool, empty, ASTCtx.Load) _set_pos(node, lineno, col, 0, 0) return node - first: rawptr[AST] = _parse_expr(ps) + first: AST* = _parse_expr(ps) if _cur_kw(ps) == Keyword.For: node = _parse_comprehension(ps, first, ASTKind.ListComp, lineno, col) _expect_op(ps, TokOp.Rsqb) return node - elts: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + elts: list[AST*]* = list[AST*](ps.pool, 8) elts.append(first) while _accept_op(ps, TokOp.Comma): _skip_nl(ps) if _match_op(ps, TokOp.Rsqb): break - e: rawptr[AST] = _parse_expr(ps) + e: AST* = _parse_expr(ps) elts.append(e) _skip_nl(ps) # finish when the last element has no trailing comma (multi-line list) _expect_op(ps, TokOp.Rsqb) @@ -1908,7 +1908,7 @@ def _parse_list(ps: rawptr[Parser]) -> rawptr[AST]: return node -def _parse_brace(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_brace(ps: Parser*) -> AST*: """Brace expressions: {} | {set_items} | {dict_items} | {comp_for}""" lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) @@ -1916,34 +1916,34 @@ def _parse_brace(ps: rawptr[Parser]) -> rawptr[AST]: _skip_nl(ps) # Skip the line break after '{' (multi-line dict) if _match_op(ps, TokOp.RBrace): _advance(ps) - empty_k: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - empty_v: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - node: rawptr[AST] = Dict(ps.pool, empty_k, empty_v) + empty_k: list[AST*]* = list[AST*](ps.pool, 8) + empty_v: list[AST*]* = list[AST*](ps.pool, 8) + node: AST* = Dict(ps.pool, empty_k, empty_v) _set_pos(node, lineno, col, 0, 0) return node - first: rawptr[AST] = _parse_expr(ps) + first: AST* = _parse_expr(ps) # dict: key: value if _match_op(ps, TokOp.Colon): _advance(ps) - val: rawptr[AST] = _parse_expr(ps) + val: AST* = _parse_expr(ps) if _cur_kw(ps) == Keyword.For: # dict comprehension - gens: rawptr[list[rawptr[AST]]] = _parse_comp_for(ps) + gens: list[AST*]* = _parse_comp_for(ps) node = DictComp(ps.pool, first, val, gens) _set_pos(node, lineno, col, 0, 0) _expect_op(ps, TokOp.RBrace) return node - keys: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - values: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + keys: list[AST*]* = list[AST*](ps.pool, 8) + values: list[AST*]* = list[AST*](ps.pool, 8) keys.append(first) values.append(val) while _accept_op(ps, TokOp.Comma): _skip_nl(ps) if _match_op(ps, TokOp.RBrace): break - k: rawptr[AST] = _parse_expr(ps) + k: AST* = _parse_expr(ps) _expect_op(ps, TokOp.Colon) - v: rawptr[AST] = _parse_expr(ps) + v: AST* = _parse_expr(ps) keys.append(k) values.append(v) _skip_nl(ps) # finish when the last element has no trailing comma @@ -1956,13 +1956,13 @@ def _parse_brace(ps: rawptr[Parser]) -> rawptr[AST]: node = _parse_comprehension(ps, first, ASTKind.SetComp, lineno, col) _expect_op(ps, TokOp.RBrace) return node - elts: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + elts: list[AST*]* = list[AST*](ps.pool, 8) elts.append(first) while _accept_op(ps, TokOp.Comma): _skip_nl(ps) # cross-line set literal inside braces if _match_op(ps, TokOp.RBrace): break - e: rawptr[AST] = _parse_expr(ps) + e: AST* = _parse_expr(ps) elts.append(e) _skip_nl(ps) # finish when the last element has no trailing comma _expect_op(ps, TokOp.RBrace) @@ -1975,28 +1975,28 @@ def _parse_brace(ps: rawptr[Parser]) -> rawptr[AST]: # f-string parsing # ============================================================ -def _parse_sub_expr(ps: rawptr[Parser], src: str) -> rawptr[AST]: +def _parse_sub_expr(ps: Parser*, src: str) -> AST*: """Create a sub-lexer and parser to parse expressions (used for {expr} inside f-strings)""" - pool: rawptr[memhub.MemManager] = ps.pool - lx: rawptr[Lexer] = new_lexer(pool) + pool: memhub.MemManager* = ps.pool + lx: Lexer* = new_lexer(pool) if lx is None: return None _lexer_init(lx, src, pool) - tokens: rawptr[Token] = tokenize(lx) + tokens: Token* = tokenize(lx) if tokens is None: return None - sub_ps: rawptr[Parser] = new_parser(pool) + sub_ps: Parser* = new_parser(pool) if sub_ps is None: return None _parser_init(sub_ps, tokens, pool) return _parse_test(sub_ps) -def _append_str_value(pool: rawptr[memhub.MemManager], - values: rawptr[list[rawptr[AST]]], - node: rawptr[AST]): +def _append_str_value(pool: memhub.MemManager*, + values: list[AST*]*, + node: AST*): """Flatten a string node into values (JoinedStr expands its values, everything else is appended)""" if node is None: return if node.kind() == ASTKind.JoinedStr: - js_val: rawptr[JoinedStr] = (rawptr[JoinedStr])(node) + js_val: JoinedStr* = (JoinedStr*)(node) if js_val.values is not None: n_v: sizet = js_val.values.__len__() i_v: sizet @@ -2006,8 +2006,8 @@ def _append_str_value(pool: rawptr[memhub.MemManager], values.append(node) -def _concat_str_nodes(pool: rawptr[memhub.MemManager], - a: rawptr[AST], b: rawptr[AST]) -> rawptr[AST]: +def _concat_str_nodes(pool: memhub.MemManager*, + a: AST*, b: AST*) -> AST*: """Merge adjacent string literal nodes (Python implicit concatenation "a" "b" -> "ab"). Pure constant strings are concatenated as text; f-strings (JoinedStr/FormattedValue) are merged @@ -2019,8 +2019,8 @@ def _concat_str_nodes(pool: rawptr[memhub.MemManager], return a # Both are constant strings -> concatenate the text directly if a.kind() == ASTKind.Constant and b.kind() == ASTKind.Constant: - ca_c: rawptr[Constant] = (rawptr[Constant])(a) - cb_c: rawptr[Constant] = (rawptr[Constant])(b) + ca_c: Constant* = (Constant*)(a) + cb_c: Constant* = (Constant*)(b) if ca_c.const_kind == CONST_STR and cb_c.const_kind == CONST_STR \ and ca_c.str_val is not None and cb_c.str_val is not None: la_c: sizet = string.strlen(ca_c.str_val) @@ -2031,21 +2031,21 @@ def _concat_str_nodes(pool: rawptr[memhub.MemManager], string.memcpy(buf_c + la_c, cb_c.str_val, lb_c + 1) return _new_const_str(pool, buf_c, a.lineno, a.col_offset, 0, 0, 0) # Involves an f-string -> merge into a JoinedStr - values_c: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](pool, 8) + values_c: list[AST*]* = list[AST*](pool, 8) _append_str_value(pool, values_c, a) _append_str_value(pool, values_c, b) if values_c.__len__() == 1: return values_c.get(0) - node_c: rawptr[AST] = JoinedStr(pool, values_c) + node_c: AST* = JoinedStr(pool, values_c) _set_pos(node_c, a.lineno, a.col_offset, 0, 0) return node_c -def _parse_fstring(ps: rawptr[Parser], content: str, - lineno: int, col: int) -> rawptr[AST]: +def _parse_fstring(ps: Parser*, content: str, + lineno: int, col: int) -> AST*: """Parse f-string content, building JoinedStr or FormattedValue nodes""" - pool: rawptr[memhub.MemManager] = ps.pool - values: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](pool, 8) + pool: memhub.MemManager* = ps.pool + values: list[AST*]* = list[AST*](pool, 8) i: sizet = 0 content_len: sizet = string.strlen(content) # Literal text buffer for f-string content @@ -2065,7 +2065,7 @@ def _parse_fstring(ps: rawptr[Parser], content: str, # Refresh literal buffer if lit_pos > 0: lit_buf[lit_pos] = '\0' - lit_node: rawptr[AST] = _new_const_str(pool, lit_buf, lineno, col) + lit_node: AST* = _new_const_str(pool, lit_buf, lineno, col) values.append(lit_node) lit_buf = pool.alloc(content_len + 1) if lit_buf is None: break @@ -2133,7 +2133,7 @@ def _parse_fstring(ps: rawptr[Parser], content: str, string.memcpy(expr_buf, content + i + 1, expr_len) expr_buf[expr_len] = '\0' # Parse expression text - expr_node: rawptr[AST] = _parse_sub_expr(ps, expr_buf) + expr_node: AST* = _parse_sub_expr(ps, expr_buf) # Conversion specifier conversion: int = -1 if conv_pos > 0: @@ -2145,7 +2145,7 @@ def _parse_fstring(ps: rawptr[Parser], content: str, elif conv_char == 'a': conversion = 97 # Format specifier - format_spec: rawptr[AST] = None + format_spec: AST* = None if fmt_pos > 0: spec_len: sizet = j - fmt_pos - 1 if spec_len > 0: @@ -2154,7 +2154,7 @@ def _parse_fstring(ps: rawptr[Parser], content: str, string.memcpy(spec_buf, content + fmt_pos + 1, spec_len) spec_buf[spec_len] = '\0' format_spec = _new_const_str(pool, spec_buf, lineno, col) - fv: rawptr[AST] = FormattedValue(pool, expr_node, conversion, format_spec) + fv: AST* = FormattedValue(pool, expr_node, conversion, format_spec) _set_pos(fv, lineno, col, 0, 0) values.append(fv) i = j + 1 @@ -2175,7 +2175,7 @@ def _parse_fstring(ps: rawptr[Parser], content: str, # Refresh remaining literal buffer if lit_pos > 0: lit_buf[lit_pos] = '\0' - lit_node2: rawptr[AST] = _new_const_str(pool, lit_buf, lineno, col) + lit_node2: AST* = _new_const_str(pool, lit_buf, lineno, col) values.append(lit_node2) # If no content, return empty string @@ -2183,19 +2183,19 @@ def _parse_fstring(ps: rawptr[Parser], content: str, return _new_const_str(pool, "", lineno, col) # If only one FormattedValue and no literal, return FormattedValue if values.__len__() == 1: - first: rawptr[AST] = values.get(0) + first: AST* = values.get(0) if first.kind() == ASTKind.FormattedValue: return first - node: rawptr[AST] = JoinedStr(pool, values) + node: AST* = JoinedStr(pool, values) _set_pos(node, lineno, col, 0, 0) return node -def _parse_comprehension(ps: rawptr[Parser], elt: rawptr[AST], - vtype: int, lineno: int, col: int) -> rawptr[AST]: +def _parse_comprehension(ps: Parser*, elt: AST*, + vtype: int, lineno: int, col: int) -> AST*: """General comprehension: elt comp_for""" - gens: rawptr[list[rawptr[AST]]] = _parse_comp_for(ps) - node: rawptr[AST] = None + gens: list[AST*]* = _parse_comp_for(ps) + node: AST* = None if vtype == ASTKind.ListComp: node = ListComp(ps.pool, elt, gens) elif vtype == ASTKind.SetComp: @@ -2206,10 +2206,10 @@ def _parse_comprehension(ps: rawptr[Parser], elt: rawptr[AST], return node -def _parse_comp_for(ps: rawptr[Parser]) -> rawptr[list[rawptr[AST]]]: +def _parse_comp_for(ps: Parser*) -> list[AST*]*: """comp_for: ['async'] 'for' exprlist 'in' or_test [comp_if] (comp_for)* Returns generators list.""" - gens: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + gens: list[AST*]* = list[AST*](ps.pool, 8) while True: is_async: int = 0 if _cur_kw(ps) == Keyword.Async: @@ -2220,67 +2220,67 @@ def _parse_comp_for(ps: rawptr[Parser]) -> rawptr[list[rawptr[AST]]]: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) - target: rawptr[AST] = _parse_target_list(ps) + target: AST* = _parse_target_list(ps) if _cur_kw(ps) != Keyword.In: ps.error_count += 1 break _advance(ps) - iter_: rawptr[AST] = _parse_or_test(ps) + iter_: AST* = _parse_or_test(ps) # Collect ifs to list - ifs: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + ifs: list[AST*]* = list[AST*](ps.pool, 8) while _cur_kw(ps) == Keyword.If: _advance(ps) - cond: rawptr[AST] = _parse_or_test(ps) + cond: AST* = _parse_or_test(ps) ifs.append(cond) - comp: rawptr[AST] = Comprehension(ps.pool, target, iter_, ifs, is_async) + comp: AST* = Comprehension(ps.pool, target, iter_, ifs, is_async) _set_pos(comp, lineno, col, 0, 0) gens.append(comp) return gens -def _parse_target_list(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_target_list(ps: Parser*) -> AST*: """Parse assignment target list (comma-separated)""" - first: rawptr[AST] = _parse_target(ps) + first: AST* = _parse_target(ps) if _match_op(ps, TokOp.Comma): - elts: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + elts: list[AST*]* = list[AST*](ps.pool, 8) elts.append(first) while _accept_op(ps, TokOp.Comma): if _cur_kw(ps) == Keyword.In: break - e: rawptr[AST] = _parse_target(ps) + e: AST* = _parse_target(ps) elts.append(e) - node: rawptr[AST] = Tuple(ps.pool, elts, ASTCtx.Store) + node: AST* = Tuple(ps.pool, elts, ASTCtx.Store) _set_pos(node, first.lineno, first.col_offset, 0, 0) return node return first -def _parse_target(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_target(ps: Parser*) -> AST*: """Parse assignment target""" if _match_op(ps, TokOp.Star): _advance(ps) - inner: rawptr[AST] = _parse_atom_expr(ps) - node: rawptr[AST] = Starred(ps.pool, inner, ASTCtx.Store) + inner: AST* = _parse_atom_expr(ps) + node: AST* = Starred(ps.pool, inner, ASTCtx.Store) _set_pos(node, inner.lineno, inner.col_offset, 0, 0) return node if _match_op(ps, TokOp.LPar): _advance(ps) _skip_nl(ps) - t_: rawptr[AST] = _parse_target_list(ps) + t_: AST* = _parse_target_list(ps) _skip_nl(ps) _expect_op(ps, TokOp.RPar) return t_ if _match_op(ps, TokOp.Lsqb): _advance(ps) _skip_nl(ps) - first: rawptr[AST] = _parse_target(ps) - elts: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + first: AST* = _parse_target(ps) + elts: list[AST*]* = list[AST*](ps.pool, 8) elts.append(first) while _accept_op(ps, TokOp.Comma): _skip_nl(ps) if _match_op(ps, TokOp.Rsqb): break - e: rawptr[AST] = _parse_target(ps) + e: AST* = _parse_target(ps) elts.append(e) _expect_op(ps, TokOp.Rsqb) node = List(ps.pool, elts, ASTCtx.Store) @@ -2293,17 +2293,17 @@ def _parse_target(ps: rawptr[Parser]) -> rawptr[AST]: return node -def _parse_yield(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_yield(ps: Parser*) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # yield if _cur_kw(ps) == Keyword.From: _advance(ps) - val: rawptr[AST] = _parse_expr(ps) - node: rawptr[AST] = YieldFrom(ps.pool, val) + val: AST* = _parse_expr(ps) + node: AST* = YieldFrom(ps.pool, val) _set_pos(node, lineno, col, 0, 0) return node - val2: rawptr[AST] = None + val2: AST* = None if not _match_op(ps, TokOp.RPar) and _cur_type(ps) != TokenType.NewLine and _cur_type(ps) != TokenType.EndMarker: if _cur_type(ps) == TokenType.Op and (_cur_op(ps) == TokOp.Comma or _cur_op(ps) == TokOp.Rsqb): pass @@ -2314,14 +2314,14 @@ def _parse_yield(ps: rawptr[Parser]) -> rawptr[AST]: return node -def _parse_varargslist(ps: rawptr[Parser], is_lambda: int = 0) -> rawptr[AST]: +def _parse_varargslist(ps: Parser*, is_lambda: int = 0) -> AST*: """Parse function parameter list New API: args/defaults/kw_defaults are lists, vararg/kwarg are fields.""" - args: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - vararg: rawptr[AST] = None - kwarg: rawptr[AST] = None - defaults: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - kw_defaults: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + args: list[AST*]* = list[AST*](ps.pool, 8) + vararg: AST* = None + kwarg: AST* = None + defaults: list[AST*]* = list[AST*](ps.pool, 8) + kw_defaults: list[AST*]* = list[AST*](ps.pool, 8) while True: _skip_nl(ps) @@ -2354,12 +2354,12 @@ def _parse_varargslist(ps: rawptr[Parser], is_lambda: int = 0) -> rawptr[AST]: _skip_nl(ps) continue # Normal parameter - a: rawptr[AST] = _parse_arg_def(ps, is_lambda) + a: AST* = _parse_arg_def(ps, is_lambda) if a is None: break args.append(a) if _match_op(ps, TokOp.Equal): _advance(ps) - d: rawptr[AST] = _parse_test(ps) + d: AST* = _parse_test(ps) defaults.append(d) if not _accept_op(ps, TokOp.Comma): break @@ -2367,7 +2367,7 @@ def _parse_varargslist(ps: rawptr[Parser], is_lambda: int = 0) -> rawptr[AST]: return Arguments(ps.pool, args, vararg, kwarg, defaults, kw_defaults) -def _parse_array_prefix_declarator(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_array_prefix_declarator(ps: Parser*) -> AST*: """C-style leading array declarator `[N]T` / `[]T` -> `t.CArray[T, N]` / `t.CArray[T, None]`. Consumed only in annotation position (_parse_type_ann); returns None if the current token is not '['. @@ -2379,7 +2379,7 @@ def _parse_array_prefix_declarator(ps: rawptr[Parser]) -> rawptr[AST]: lb_lineno: int = _cur_lineno(ps) lb_col: int = _cur_col(ps) _advance(ps) # consume '[' - count_node: rawptr[AST] = None + count_node: AST* = None if _match_op(ps, TokOp.Rsqb) == 0: # Length expression (constant/constant expression; invalid lengths are rejected downstream) count_node = _parse_test(ps) @@ -2392,17 +2392,17 @@ def _parse_array_prefix_declarator(ps: rawptr[Parser]) -> rawptr[AST]: return None _advance(ps) # consume ']' # Element type: recurse into _parse_type_ann, so `[N]const int` / `[N]int*` share one rule source - elem: rawptr[AST] = _parse_type_ann(ps) + elem: AST* = _parse_type_ann(ps) if elem is None: return None if count_node is None: count_node = _new_const_none(ps.pool, lb_lineno, lb_col) # Element size must be explicitly 8 (list[T](pool, elem_size) addresses by byte stride; passing 2 # would write 8-byte pointers with a 2-byte stride -> heap overflow). Same arg as other list sites. - elts: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + elts: list[AST*]* = list[AST*](ps.pool, 8) elts.append(elem) elts.append(count_node) - carray: rawptr[AST] = Subscript(ps.pool, + carray: AST* = Subscript(ps.pool, Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), "CArray", ASTCtx.Load), Tuple(ps.pool, elts, ASTCtx.Load), @@ -2411,13 +2411,13 @@ def _parse_array_prefix_declarator(ps: rawptr[Parser]) -> rawptr[AST]: return carray -def _parse_type_ann(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_type_ann(ps: Parser*) -> AST*: """Parse a type annotation: descriptor prefixes (const / volatile / __attribute__) and C-style pointer suffixes (* / **), field-identical to TPC's expansion. `static` is invalid here; missing type / non-type follower / bare use fail loudly. Reclaims the Mult/Pow junk _parse_test leaves and rebuilds t.CPtr chains. """ # Descriptor prefix: collect const / volatile markers (soft keywords, consumed only here) - mods: rawptr[list[rawptr[AST]]] = None + mods: list[AST*]* = None mod_count: int = 0 mod_lineno: int = _cur_lineno(ps) mod_col: int = _cur_col(ps) @@ -2426,8 +2426,8 @@ def _parse_type_ann(ps: rawptr[Parser]) -> rawptr[AST]: if ps.pending_static != 0: ps.pending_static = 0 if mods is None: - mods = list[rawptr[AST]](ps.pool, 8) - st_mk: rawptr[AST] = _MakeStaticMarker(ps) + mods = list[AST*](ps.pool, 8) + st_mk: AST* = _MakeStaticMarker(ps) if st_mk is not None: mods.append(st_mk) mod_count += 1 @@ -2444,7 +2444,7 @@ def _parse_type_ann(ps: rawptr[Parser]) -> rawptr[AST]: if mods is None: # Element size is explicitly 8: list[T](pool, elem_size) addresses by byte stride, so passing 4 # would make the 2nd 8-byte pointer (e.g. for `const volatile`) write out of bounds. - mods = list[rawptr[AST]](ps.pool, 8) + mods = list[AST*](ps.pool, 8) if _IsMagicAttributeCall(ps) != 0: # C-style `a: __attribute__(section(".text.wo"), aligned(16)) const int = ...`: same position # and order-free mixing as const / volatile; each argument desugars to `t.attr.` and joins @@ -2454,10 +2454,10 @@ def _parse_type_ann(ps: rawptr[Parser]) -> rawptr[AST]: # annotation to a bare element type with zero errors reported. mka_lineno: int = _cur_lineno(ps) mka_col: int = _cur_col(ps) - mka_fn: rawptr[AST] = Name(ps.pool, "__attribute__", ASTCtx.Load) + mka_fn: AST* = Name(ps.pool, "__attribute__", ASTCtx.Load) _set_pos(mka_fn, mka_lineno, mka_col, 0, 0) _advance(ps) # consume `__attribute__` - ac_node: rawptr[AST] = _parse_call(ps, mka_fn) # parse only `( args )` + ac_node: AST* = _parse_call(ps, mka_fn) # parse only `( args )` if ac_node is None: break if ac_node.kind() != ASTKind.Call: @@ -2466,7 +2466,7 @@ def _parse_type_ann(ps: rawptr[Parser]) -> rawptr[AST]: if ac.args is not None: acn: sizet = len(ac.args) for aci in range(acn): - mk: rawptr[AST] = _MakeTAttrMarker(ps, ac.args.get(aci)) + mk: AST* = _MakeTAttrMarker(ps, ac.args.get(aci)) if mk is not None: mods.append(mk) mod_count += 1 @@ -2477,7 +2477,7 @@ def _parse_type_ann(ps: rawptr[Parser]) -> rawptr[AST]: # C-style leading array declarator `[N]T` / `[]T` (incl. `const [N]T`): desugar in place to # `t.CArray[T, N]` / `t.CArray[T, None]` and paste the already-collected descriptors onto it. if _match_op(ps, TokOp.Lsqb) != 0: - arr: rawptr[AST] = _parse_array_prefix_declarator(ps) + arr: AST* = _parse_array_prefix_declarator(ps) if arr is None: return None if mod_count > 0: @@ -2490,7 +2490,7 @@ def _parse_type_ann(ps: rawptr[Parser]) -> rawptr[AST]: ps.error_count += 1 return None before_ec: int = ps.error_count - base: rawptr[AST] = _parse_test(ps) + base: AST* = _parse_test(ps) if base is None: if mod_count > 0: # Descriptor consumed but type parsing failed (e.g. `a: const = 1`): fail loudly keeping the descriptor error. @@ -2506,7 +2506,7 @@ def _parse_type_ann(ps: rawptr[Parser]) -> rawptr[AST]: ptr_level: int = 0 # Reclaim the junk nodes left by _parse_test consuming the * / ** suffixes if base.kind() == ASTKind.BinOp: - gb: rawptr[BinOp] = (rawptr[BinOp])(base) + gb: BinOp* = (BinOp*)(base) if gb.op == OpKind.Mult and gb.right is None: ptr_level += 1 base = gb.left @@ -2515,7 +2515,7 @@ def _parse_type_ann(ps: rawptr[Parser]) -> rawptr[AST]: ptr_level += 2 base = gb.left elif gb.right.kind() == ASTKind.UnaryOp: - gu: rawptr[UnaryOp] = (rawptr[UnaryOp])(gb.right) + gu: UnaryOp* = (UnaryOp*)(gb.right) if gu.op == OpKind.Deref and gu.operand is None: ptr_level += 3 base = gb.left @@ -2530,7 +2530,7 @@ def _parse_type_ann(ps: rawptr[Parser]) -> rawptr[AST]: ptr_level += 1 # Build n nested base | t.CPtr layers for li_an in range(ptr_level): - cptr_an: rawptr[AST] = Attribute(ps.pool, + cptr_an: AST* = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), "CPtr", ASTCtx.Load) base = BinOp(ps.pool, base, OpKind.BitOr, cptr_an) @@ -2540,7 +2540,7 @@ def _parse_type_ann(ps: rawptr[Parser]) -> rawptr[AST]: return base -def _parse_arg_def(ps: rawptr[Parser], is_lambda: int = 0) -> rawptr[AST]: +def _parse_arg_def(ps: Parser*, is_lambda: int = 0) -> AST*: """arg: TokenType.Name [':' annotation]""" if _cur_type(ps) != TokenType.Name: ps.error_count += 1 @@ -2549,11 +2549,11 @@ def _parse_arg_def(ps: rawptr[Parser], is_lambda: int = 0) -> rawptr[AST]: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) - annotation: rawptr[AST] = None + annotation: AST* = None if is_lambda == 0: if _accept_op(ps, TokOp.Colon): annotation = _parse_type_ann(ps) - result: rawptr[AST] = Arg(ps.pool, name_str, annotation) + result: AST* = Arg(ps.pool, name_str, annotation) _set_pos(result, lineno, col, 0, 0) return result @@ -2562,7 +2562,7 @@ def _parse_arg_def(ps: rawptr[Parser], is_lambda: int = 0) -> rawptr[AST]: # Statement parsing (Design: directly append to parent, do not return a list) # ============================================================ -def _parse_suite_into_children(ps: rawptr[Parser], parent: rawptr[AST], +def _parse_suite_into_children(ps: Parser*, parent: AST*, owner_is_class: int = 0): """Parse statement suite, directly append to parent's children. suite: TokenType.NewLine TokenType.Indent stmt+ TokenType.Dedent | simple_stmt @@ -2592,7 +2592,7 @@ def _parse_suite_into_children(ps: rawptr[Parser], parent: rawptr[AST], # Decorator (class body methods can have decorators) if _match_op(ps, TokOp.At): ps.pending_decorators = _parse_decorators(ps) - before_cur: rawptr[Token] = ps.cur + before_cur: Token* = ps.cur _parse_statement_into(ps, parent) # Defensive: if parse did not advance token, force advance to avoid infinite loop if ps.cur is before_cur: @@ -2607,7 +2607,7 @@ def _parse_suite_into_children(ps: rawptr[Parser], parent: rawptr[AST], ps.in_class_body = prev_in_class -def _parse_statement_into(ps: rawptr[Parser], parent: rawptr[AST]): +def _parse_statement_into(ps: Parser*, parent: AST*): """Parse statement (compound or simple), append to the parent.""" ttype: int = _cur_type(ps) kw: int = _cur_kw(ps) @@ -2616,21 +2616,21 @@ def _parse_statement_into(ps: rawptr[Parser], parent: rawptr[AST]): # _parse_simple_stmt_into, otherwise `define` is parsed as an identifier expression and NAME is left # as a stray token. `define NAME(...)` (macro function) is excluded by _is_define_const's lookahead. if kw == Keyword.Define and _is_define_const(ps) != 0: - dc_stmt: rawptr[AST] = _parse_define_const(ps) + dc_stmt: AST* = _parse_define_const(ps) if dc_stmt is not None: parent.append(dc_stmt) return # typedef alias declaration: `typedef T1 = T2` (statement-level reserved word, no lookahead since # typedef is never an identifier in existing sources). Invalid forms fail loudly in _parse_typedef. if _is_typedef(ps) != 0: - td_stmt: rawptr[AST] = _parse_typedef(ps) + td_stmt: AST* = _parse_typedef(ps) if td_stmt is not None: parent.append(td_stmt) return # export / extern variable declaration (soft keyword): `export NAME: T [= v]` / `extern NAME: T` # -> a module-level AnnAssign with storage-class markers; function forms are excluded by lookahead. if _is_export_extern_var(ps) != 0: - ee_stmt: rawptr[AST] = _parse_export_extern_var(ps) + ee_stmt: AST* = _parse_export_extern_var(ps) if ee_stmt is not None: parent.append(ee_stmt) return @@ -2657,7 +2657,7 @@ def _parse_statement_into(ps: rawptr[Parser], parent: rawptr[AST]): _cur_lineno(ps), _cur_col(ps)) ps.error_count += 1 if kw == Keyword.If or kw == Keyword.While or kw == Keyword.For or kw == Keyword.Try: - stmt: rawptr[AST] = _parse_compound(ps) + stmt: AST* = _parse_compound(ps) if stmt is not None: parent.append(stmt) return @@ -2676,15 +2676,15 @@ def _parse_statement_into(ps: rawptr[Parser], parent: rawptr[AST]): _parse_simple_stmt_into(ps, parent) -def _parse_simple_stmt_into(ps: rawptr[Parser], parent: rawptr[AST]): +def _parse_simple_stmt_into(ps: Parser*, parent: AST*): """simple_stmt: small_stmt (';' small_stmt)* [';'] TokenType.NewLine""" - first: rawptr[AST] = _parse_small_stmt(ps) + first: AST* = _parse_small_stmt(ps) if first is not None: parent.append(first) while _accept_op(ps, TokOp.Semi): if _cur_type(ps) == TokenType.NewLine or _cur_type(ps) == TokenType.EndMarker: break - s: rawptr[AST] = _parse_small_stmt(ps) + s: AST* = _parse_small_stmt(ps) if s is None: break parent.append(s) # First skip Nl (in-paren newline, e.g. between multi-line call args; a legal token) @@ -2698,8 +2698,8 @@ def _parse_simple_stmt_into(ps: rawptr[Parser], parent: rawptr[AST]): # parse error channel with prev/next tokens appended, output Python-style by the caller's # dump_parse_traceback (Traceback + File/line + source line + caret + SyntaxError). # Locate: walk the list from the head to find cur, recording prev and next token context. - prev_tok: rawptr[Token] = None - walk_tok: rawptr[Token] = ps.tokens + prev_tok: Token* = None + walk_tok: Token* = ps.tokens while walk_tok is not None and walk_tok is not ps.cur: prev_tok = walk_tok walk_tok = walk_tok.next @@ -2710,7 +2710,7 @@ def _parse_simple_stmt_into(ps: rawptr[Parser], parent: rawptr[AST]): pv_str = prev_tok.str_val pv_line = prev_tok.lineno pv_col = prev_tok.col_offset - nxt_tok: rawptr[Token] = ps.cur.next + nxt_tok: Token* = ps.cur.next nxt_str: str = "(none)" nxt_line: int = 0 nxt_col: int = 0 @@ -2726,7 +2726,7 @@ def _parse_simple_stmt_into(ps: rawptr[Parser], parent: rawptr[AST]): _advance(ps) -def _parse_small_stmt(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_small_stmt(ps: Parser*) -> AST*: """small_stmt: various simple statements""" kw: int = _cur_kw(ps) # fallthrough keyword (hard): legal only inside a switch case body ("fall to the next case"). @@ -2735,14 +2735,14 @@ def _parse_small_stmt(ps: rawptr[Parser]) -> rawptr[AST]: ft_lineno: int = _cur_lineno(ps) ft_col: int = _cur_col(ps) _advance(ps) - ft_node: rawptr[AST] = FallThrough(ps.pool) + ft_node: AST* = FallThrough(ps.pool) _set_pos(ft_node, ft_lineno, ft_col, 0, 0) return ft_node if kw == Keyword.Pass: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) - node: rawptr[AST] = Pass(ps.pool) + node: AST* = Pass(ps.pool) _set_pos(node, lineno, col, 0, 0) return node if kw == Keyword.Break: @@ -2781,14 +2781,14 @@ def _parse_small_stmt(ps: rawptr[Parser]) -> rawptr[AST]: return _parse_expr_stmt(ps, None) -def _maybe_tuple(ps: rawptr[Parser], first: rawptr[AST]) -> rawptr[AST]: +def _maybe_tuple(ps: Parser*, first: AST*) -> AST*: """If there is a comma after first, collect the comma-separated expressions into a Tuple.""" if first is None: return None if not _match_op(ps, TokOp.Comma): return first lineno: int = first.lineno col: int = first.col_offset - elts: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + elts: list[AST*]* = list[AST*](ps.pool, 8) elts.append(first) _accept_op(ps, TokOp.Comma) while True: @@ -2799,23 +2799,23 @@ def _maybe_tuple(ps: rawptr[Parser], first: rawptr[AST]) -> rawptr[AST]: op: int = _cur_op(ps) if op == TokOp.Equal or op == TokOp.Semi: break - e: rawptr[AST] = _parse_expr(ps) + e: AST* = _parse_expr(ps) if e is None: break elts.append(e) if not _accept_op(ps, TokOp.Comma): break - node: rawptr[AST] = Tuple(ps.pool, elts, ASTCtx.Load) + node: AST* = Tuple(ps.pool, elts, ASTCtx.Load) _set_pos(node, lineno, col, 0, 0) return node -def _parse_testlist(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_testlist(ps: Parser*) -> AST*: """Parse a comma-separated list of expressions, if there’s more than one, form a tuple.""" - first: rawptr[AST] = _parse_expr(ps) + first: AST* = _parse_expr(ps) return _maybe_tuple(ps, first) -def _parse_expr_stmt(ps: rawptr[Parser], first: rawptr[AST]) -> rawptr[AST]: +def _parse_expr_stmt(ps: Parser*, first: AST*) -> AST*: """Expression statement, handle assignment/augassign/annassign""" if first is None: first = _parse_testlist(ps) @@ -2827,20 +2827,20 @@ def _parse_expr_stmt(ps: rawptr[Parser], first: rawptr[AST]) -> rawptr[AST]: col: int = first.col_offset # Assignment if _match_op(ps, TokOp.Equal): - targets: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + targets: list[AST*]* = list[AST*](ps.pool, 8) targets.append(first) _fix_store_ctx(first) - value: rawptr[AST] = None + value: AST* = None accept_result: int = _accept_op(ps, TokOp.Equal) while accept_result: - v: rawptr[AST] = _parse_testlist(ps) + v: AST* = _parse_testlist(ps) if v is None: break if value is not None: targets.append(value) _fix_store_ctx(value) value = v accept_result = _accept_op(ps, TokOp.Equal) - node: rawptr[AST] = Assign(ps.pool, targets, value) + node: AST* = Assign(ps.pool, targets, value) _set_pos(node, lineno, col, 0, 0) return node # augassign @@ -2849,16 +2849,16 @@ def _parse_expr_stmt(ps: rawptr[Parser], first: rawptr[AST]) -> rawptr[AST]: aug_op: int = _augop_from_op(op_id) if aug_op != OpKind.NoneOp: _advance(ps) - value2: rawptr[AST] = _parse_testlist(ps) + value2: AST* = _parse_testlist(ps) _fix_store_ctx(first) - node2: rawptr[AST] = AugAssign(ps.pool, first, aug_op, value2) + node2: AST* = AugAssign(ps.pool, first, aug_op, value2) _set_pos(node2, lineno, col, 0, 0) return node2 # annassign: target ':' annotation [= value] if _match_op(ps, TokOp.Colon): _advance(ps) - annotation: rawptr[AST] = _parse_type_ann(ps) - value3: rawptr[AST] = None + annotation: AST* = _parse_type_ann(ps) + value3: AST* = None if _accept_op(ps, TokOp.Equal): value3 = _parse_testlist(ps) if ps.pool is None: @@ -2866,52 +2866,52 @@ def _parse_expr_stmt(ps: rawptr[Parser], first: rawptr[AST]) -> rawptr[AST]: _fix_store_ctx(first) if ps.pool is None: return None - node3: rawptr[AST] = AnnAssign(ps.pool, first, annotation, value3, 1) + node3: AST* = AnnAssign(ps.pool, first, annotation, value3, 1) _set_pos(node3, lineno, col, 0, 0) return node3 # Expression statement - node4: rawptr[AST] = Expr(ps.pool, first) + node4: AST* = Expr(ps.pool, first) _set_pos(node4, lineno, col, 0, 0) return node4 -def _parse_return(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_return(ps: Parser*) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) - val: rawptr[AST] = None + val: AST* = None if _cur_type(ps) != TokenType.NewLine and _cur_type(ps) != TokenType.EndMarker and _cur_type(ps) != TokenType.Op: val = _parse_testlist(ps) elif _cur_type(ps) == TokenType.Op and _cur_op(ps) != TokOp.Semi: val = _parse_testlist(ps) - node: rawptr[AST] = Return(ps.pool, val) + node: AST* = Return(ps.pool, val) _set_pos(node, lineno, col, 0, 0) return node -def _parse_raise(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_raise(ps: Parser*) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) - exc: rawptr[AST] = None - cause: rawptr[AST] = None + exc: AST* = None + cause: AST* = None if _cur_type(ps) != TokenType.NewLine and _cur_type(ps) != TokenType.EndMarker: exc = _parse_test(ps) if _cur_kw(ps) == Keyword.From: _advance(ps) cause = _parse_test(ps) - node: rawptr[AST] = Raise(ps.pool, exc, cause) + node: AST* = Raise(ps.pool, exc, cause) _set_pos(node, lineno, col, 0, 0) return node -def _parse_global(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_global(ps: Parser*) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) - names: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + names: list[AST*]* = list[AST*](ps.pool, 8) if _cur_type(ps) == TokenType.Name: - n: rawptr[AST] = Name(ps.pool, _cur_str(ps), ASTCtx.Store) + n: AST* = Name(ps.pool, _cur_str(ps), ASTCtx.Store) _set_pos(n, _cur_lineno(ps), _cur_col(ps), 0, 0) names.append(n) _advance(ps) @@ -2921,18 +2921,18 @@ def _parse_global(ps: rawptr[Parser]) -> rawptr[AST]: _set_pos(n, _cur_lineno(ps), _cur_col(ps), 0, 0) names.append(n) _advance(ps) - node: rawptr[AST] = Global(ps.pool, names) + node: AST* = Global(ps.pool, names) _set_pos(node, lineno, col, 0, 0) return node -def _parse_nonlocal(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_nonlocal(ps: Parser*) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) - names: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + names: list[AST*]* = list[AST*](ps.pool, 8) if _cur_type(ps) == TokenType.Name: - n: rawptr[AST] = Name(ps.pool, _cur_str(ps), ASTCtx.Store) + n: AST* = Name(ps.pool, _cur_str(ps), ASTCtx.Store) _set_pos(n, _cur_lineno(ps), _cur_col(ps), 0, 0) names.append(n) _advance(ps) @@ -2942,22 +2942,22 @@ def _parse_nonlocal(ps: rawptr[Parser]) -> rawptr[AST]: _set_pos(n, _cur_lineno(ps), _cur_col(ps), 0, 0) names.append(n) _advance(ps) - node: rawptr[AST] = Nonlocal(ps.pool, names) + node: AST* = Nonlocal(ps.pool, names) _set_pos(node, lineno, col, 0, 0) return node -def _parse_import(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_import(ps: Parser*) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) - names: rawptr[list[rawptr[AST]]] = _parse_alias_list(ps) - node: rawptr[AST] = Import(ps.pool, names) + names: list[AST*]* = _parse_alias_list(ps) + node: AST* = Import(ps.pool, names) _set_pos(node, lineno, col, 0, 0) return node -def _parse_from_import(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_from_import(ps: Parser*) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) @@ -2999,30 +2999,30 @@ def _parse_from_import(ps: rawptr[Parser]) -> rawptr[AST]: # import * if _match_op(ps, TokOp.Star): _advance(ps) - star_alias: rawptr[AST] = Alias(ps.pool, "*", None) + star_alias: AST* = Alias(ps.pool, "*", None) _set_pos(star_alias, lineno, col, 0, 0) - star_names: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + star_names: list[AST*]* = list[AST*](ps.pool, 8) star_names.append(star_alias) - node: rawptr[AST] = ImportFrom(ps.pool, module_name, star_names, level) + node: AST* = ImportFrom(ps.pool, module_name, star_names, level) _set_pos(node, lineno, col, 0, 0) return node # ( names ) or names if _match_op(ps, TokOp.LPar): _advance(ps) _skip_nl(ps) - names: rawptr[list[rawptr[AST]]] = _parse_alias_list(ps) + names: list[AST*]* = _parse_alias_list(ps) _skip_nl(ps) _expect_op(ps, TokOp.RPar) else: names = _parse_alias_list(ps) - node: rawptr[AST] = ImportFrom(ps.pool, module_name, names, level) + node: AST* = ImportFrom(ps.pool, module_name, names, level) _set_pos(node, lineno, col, 0, 0) return node -def _parse_alias_list(ps: rawptr[Parser]) -> rawptr[list[rawptr[AST]]]: +def _parse_alias_list(ps: Parser*) -> list[AST*]*: """Parse alias list.""" - names: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + names: list[AST*]* = list[AST*](ps.pool, 8) while True: if _cur_type(ps) != TokenType.Name: break @@ -3050,7 +3050,7 @@ def _parse_alias_list(ps: rawptr[Parser]) -> rawptr[list[rawptr[AST]]]: if _cur_type(ps) == TokenType.Name: asname = _cur_str(ps) _advance(ps) - a: rawptr[AST] = Alias(ps.pool, name_str, asname) + a: AST* = Alias(ps.pool, name_str, asname) _set_pos(a, lineno, col, 0, 0) names.append(a) if not _accept_op(ps, TokOp.Comma): @@ -3059,32 +3059,32 @@ def _parse_alias_list(ps: rawptr[Parser]) -> rawptr[list[rawptr[AST]]]: return names -def _parse_del(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_del(ps: Parser*) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) - targets: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + targets: list[AST*]* = list[AST*](ps.pool, 8) while True: - t_: rawptr[AST] = _parse_atom_expr(ps) + t_: AST* = _parse_atom_expr(ps) if t_ is None: break _set_ctx(t_, ASTCtx.Del) targets.append(t_) if not _accept_op(ps, TokOp.Comma): break - node: rawptr[AST] = Delete(ps.pool, targets) + node: AST* = Delete(ps.pool, targets) _set_pos(node, lineno, col, 0, 0) return node -def _parse_assert(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_assert(ps: Parser*) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) - test: rawptr[AST] = _parse_test(ps) - msg: rawptr[AST] = None + test: AST* = _parse_test(ps) + msg: AST* = None if _accept_op(ps, TokOp.Comma): msg = _parse_test(ps) - node: rawptr[AST] = Assert(ps.pool, test, msg) + node: AST* = Assert(ps.pool, test, msg) _set_pos(node, lineno, col, 0, 0) return node @@ -3093,7 +3093,7 @@ def _parse_assert(ps: rawptr[Parser]) -> rawptr[AST]: # Compound statements # ============================================================ -def _parse_compound(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_compound(ps: Parser*) -> AST*: kw: int = _cur_kw(ps) if kw == Keyword.If: return _parse_if(ps) @@ -3135,23 +3135,23 @@ def _parse_compound(ps: rawptr[Parser]) -> rawptr[AST]: return None -def _parse_if(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_if(ps: Parser*) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # if - test: rawptr[AST] = _parse_test(ps) + test: AST* = _parse_test(ps) _expect_op(ps, TokOp.Colon) # First construct with empty orelse, then fill it in later - empty: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - node: rawptr[If] = If(ps.pool, test, empty) + empty: list[AST*]* = list[AST*](ps.pool, 8) + node: If* = If(ps.pool, test, empty) _parse_suite_into_children(ps, node) - orelse: rawptr[list[rawptr[AST]]] = _parse_if_tail(ps) + orelse: list[AST*]* = _parse_if_tail(ps) node.orelse = orelse _set_pos(node, lineno, col, 0, 0) return node -def _parse_if_tail(ps: rawptr[Parser]) -> rawptr[list[rawptr[AST]]]: +def _parse_if_tail(ps: Parser*) -> list[AST*]*: """Parse elif/else chain and return orelse list. elif: orelse = list containing single If node (nested) @@ -3161,86 +3161,86 @@ def _parse_if_tail(ps: rawptr[Parser]) -> rawptr[list[rawptr[AST]]]: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) - elif_test: rawptr[AST] = _parse_test(ps) + elif_test: AST* = _parse_test(ps) _expect_op(ps, TokOp.Colon) - empty: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - elif_node: rawptr[If] = If(ps.pool, elif_test, empty) + empty: list[AST*]* = list[AST*](ps.pool, 8) + elif_node: If* = If(ps.pool, elif_test, empty) _parse_suite_into_children(ps, elif_node) - elif_orelse: rawptr[list[rawptr[AST]]] = _parse_if_tail(ps) + elif_orelse: list[AST*]* = _parse_if_tail(ps) elif_node.orelse = elif_orelse _set_pos(elif_node, lineno, col, 0, 0) - orelse: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + orelse: list[AST*]* = list[AST*](ps.pool, 8) orelse.append(elif_node) return orelse if _cur_kw(ps) == Keyword.Else: _advance(ps) _expect_op(ps, TokOp.Colon) - scratch: rawptr[Module] = Module(ps.pool) + scratch: Module* = Module(ps.pool) _parse_suite_into_children(ps, scratch) return scratch.children - return list[rawptr[AST]](ps.pool, 8) # empty list + return list[AST*](ps.pool, 8) # empty list # ============================================================ # Parsing Compound Statements (Continued) # ============================================================ -def _parse_while(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_while(ps: Parser*) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # while - test: rawptr[AST] = _parse_test(ps) + test: AST* = _parse_test(ps) _expect_op(ps, TokOp.Colon) - empty: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - node: rawptr[While] = While(ps.pool, test, empty) + empty: list[AST*]* = list[AST*](ps.pool, 8) + node: While* = While(ps.pool, test, empty) _parse_suite_into_children(ps, node) if _cur_kw(ps) == Keyword.Else: _advance(ps) _expect_op(ps, TokOp.Colon) - scratch: rawptr[Module] = Module(ps.pool) + scratch: Module* = Module(ps.pool) _parse_suite_into_children(ps, scratch) node.orelse = scratch.children _set_pos(node, lineno, col, 0, 0) return node -def _parse_for(ps: rawptr[Parser], is_async: int) -> rawptr[AST]: +def _parse_for(ps: Parser*, is_async: int) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # for - target: rawptr[AST] = _parse_target_list(ps) + target: AST* = _parse_target_list(ps) if _cur_kw(ps) != Keyword.In: ps.error_count += 1 return None _advance(ps) - iter_: rawptr[AST] = _parse_or_test(ps) + iter_: AST* = _parse_or_test(ps) _expect_op(ps, TokOp.Colon) - empty: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - node: rawptr[For] = For(ps.pool, target, iter_, empty, is_async) + empty: list[AST*]* = list[AST*](ps.pool, 8) + node: For* = For(ps.pool, target, iter_, empty, is_async) _fix_store_ctx(target) _parse_suite_into_children(ps, node) if _cur_kw(ps) == Keyword.Else: _advance(ps) _expect_op(ps, TokOp.Colon) - scratch: rawptr[Module] = Module(ps.pool) + scratch: Module* = Module(ps.pool) _parse_suite_into_children(ps, scratch) node.orelse = scratch.children _set_pos(node, lineno, col, 0, 0) return node -def _parse_try(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_try(ps: Parser*) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # try _expect_op(ps, TokOp.Colon) - empty: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - node: rawptr[Try] = Try(ps.pool, empty, empty, empty) + empty: list[AST*]* = list[AST*](ps.pool, 8) + node: Try* = Try(ps.pool, empty, empty, empty) _parse_suite_into_children(ps, node) # handlers (except) - handlers: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + handlers: list[AST*]* = list[AST*](ps.pool, 8) while _cur_kw(ps) == Keyword.Except: - h: rawptr[AST] = _parse_except_handler(ps) + h: AST* = _parse_except_handler(ps) if h is not None: handlers.append(h) node.handlers = handlers @@ -3248,25 +3248,25 @@ def _parse_try(ps: rawptr[Parser]) -> rawptr[AST]: if _cur_kw(ps) == Keyword.Else: _advance(ps) _expect_op(ps, TokOp.Colon) - scratch: rawptr[Module] = Module(ps.pool) + scratch: Module* = Module(ps.pool) _parse_suite_into_children(ps, scratch) node.orelse = scratch.children # finally if _cur_kw(ps) == Keyword.Finally: _advance(ps) _expect_op(ps, TokOp.Colon) - scratch2: rawptr[Module] = Module(ps.pool) + scratch2: Module* = Module(ps.pool) _parse_suite_into_children(ps, scratch2) node.finalbody = scratch2.children _set_pos(node, lineno, col, 0, 0) return node -def _parse_except_handler(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_except_handler(ps: Parser*) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # except - type_: rawptr[AST] = None + type_: AST* = None name: str = None if _cur_op(ps) != TokOp.Colon: type_ = _parse_test(ps) @@ -3276,20 +3276,20 @@ def _parse_except_handler(ps: rawptr[Parser]) -> rawptr[AST]: name = _cur_str(ps) _advance(ps) _expect_op(ps, TokOp.Colon) - node: rawptr[AST] = ExceptHandler(ps.pool, type_, name) + node: AST* = ExceptHandler(ps.pool, type_, name) _parse_suite_into_children(ps, node) _set_pos(node, lineno, col, 0, 0) return node -def _parse_with(ps: rawptr[Parser], is_async: int) -> rawptr[AST]: +def _parse_with(ps: Parser*, is_async: int) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # with - items: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + items: list[AST*]* = list[AST*](ps.pool, 8) # items while True: - item: rawptr[AST] = _parse_with_item(ps) + item: AST* = _parse_with_item(ps) if item is None: break items.append(item) if not _accept_op(ps, TokOp.Comma): @@ -3298,29 +3298,29 @@ def _parse_with(ps: rawptr[Parser], is_async: int) -> rawptr[AST]: if _cur_type(ps) == TokenType.NewLine or _cur_type(ps) == TokenType.Nl: break _expect_op(ps, TokOp.Colon) - node: rawptr[With] = With(ps.pool, items, is_async) + node: With* = With(ps.pool, items, is_async) _parse_suite_into_children(ps, node) _set_pos(node, lineno, col, 0, 0) return node -def _parse_with_item(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_with_item(ps: Parser*) -> AST*: """with_item: test ['as' expr]""" lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) - context_expr: rawptr[AST] = _parse_or_test(ps) + context_expr: AST* = _parse_or_test(ps) if context_expr is None: return None - optional_vars: rawptr[AST] = None + optional_vars: AST* = None if _cur_kw(ps) == Keyword.As: _advance(ps) optional_vars = _parse_target(ps) _fix_store_ctx(optional_vars) - node: rawptr[AST] = WithItem(ps.pool, context_expr, optional_vars) + node: AST* = WithItem(ps.pool, context_expr, optional_vars) _set_pos(node, lineno, col, 0, 0) return node -def _parse_funcdef(ps: rawptr[Parser], is_async: int) -> rawptr[AST]: +def _parse_funcdef(ps: Parser*, is_async: int) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) is_extern_fd: int = 0 @@ -3352,7 +3352,7 @@ def _parse_funcdef(ps: rawptr[Parser], is_async: int) -> rawptr[AST]: _advance(ps) # PEP 695 generic function type parameters: def add[T](a: T, b: T) -- parsed and stored into # type_params, consistent with the class parser. type_params maps to int as a fallback during translation. - type_params_fd: rawptr[list[str]] = None + type_params_fd: list[str]* = None if _accept_op(ps, TokOp.Lsqb): type_params_fd = list[str](ps.pool, 8) while not _match_op(ps, TokOp.Rsqb): @@ -3369,17 +3369,17 @@ def _parse_funcdef(ps: rawptr[Parser], is_async: int) -> rawptr[AST]: if not _accept_op(ps, TokOp.Comma): break _expect_op(ps, TokOp.Rsqb) - args: rawptr[AST] = None + args: AST* = None if _accept_op(ps, TokOp.LPar): args = _parse_varargslist(ps, 0) _expect_op(ps, TokOp.RPar) - returns: rawptr[AST] = None + returns: AST* = None if _accept_op(ps, TokOp.RArrow): returns = _parse_type_ann(ps) if is_extern_fd: # extern declaration: rewrite the return annotation to | t.State, reusing the existing # State/external-C-function path (vpi annotation containing "State" -> bare name, no function body) - state_attr_fd: rawptr[AST] = Attribute(ps.pool, + state_attr_fd: AST* = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), "State", ASTCtx.Load) if returns != None: @@ -3389,7 +3389,7 @@ def _parse_funcdef(ps: rawptr[Parser], is_async: int) -> rawptr[AST]: elif is_export_fd: # export declaration: rewrite the return annotation to | t.CExport, reusing the existing # CExport path (vpi annotation containing "CExport" -> bare name, no module SHA1 header) - export_attr_fd: rawptr[AST] = Attribute(ps.pool, + export_attr_fd: AST* = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), "CExport", ASTCtx.Load) if returns != None: @@ -3399,16 +3399,16 @@ def _parse_funcdef(ps: rawptr[Parser], is_async: int) -> rawptr[AST]: elif is_define_fd: # define macro function: rewrite the return annotation to | t.CDefine, reusing the # existing CDefine path (StubGen keeps it as-is -> C #define / alwaysinline) - define_attr_fd: rawptr[AST] = Attribute(ps.pool, + define_attr_fd: AST* = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), "CDefine", ASTCtx.Load) if returns != None: returns = BinOp(ps.pool, returns, OpKind.BitOr, define_attr_fd) else: returns = define_attr_fd - dec_list: rawptr[list[rawptr[AST]]] = ps.pending_decorators + dec_list: list[AST*]* = ps.pending_decorators ps.pending_decorators = None - node: rawptr[FunctionDef] = FunctionDef(ps.pool, name, args, dec_list, returns, is_async, type_params_fd) + node: FunctionDef* = FunctionDef(ps.pool, name, args, dec_list, returns, is_async, type_params_fd) if is_extern_fd: node.flags = node.flags | FLAG_IS_EXTERN if is_export_fd: @@ -3428,7 +3428,7 @@ def _parse_funcdef(ps: rawptr[Parser], is_async: int) -> rawptr[AST]: return node -def _parse_classdef(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_classdef(ps: Parser*) -> AST*: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # class @@ -3438,7 +3438,7 @@ def _parse_classdef(ps: rawptr[Parser]) -> rawptr[AST]: name: str = _cur_str(ps) _advance(ps) # Parse type parameters [T] or [T, U] (PEP 695 generic class syntax) - type_params: rawptr[list[str]] = None + type_params: list[str]* = None if _accept_op(ps, TokOp.Lsqb): type_params = list[str](ps.pool, 8) while not _match_op(ps, TokOp.Rsqb): @@ -3454,8 +3454,8 @@ def _parse_classdef(ps: rawptr[Parser]) -> rawptr[AST]: if not _accept_op(ps, TokOp.Comma): break _expect_op(ps, TokOp.Rsqb) - bases: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - keywords: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + bases: list[AST*]* = list[AST*](ps.pool, 8) + keywords: list[AST*]* = list[AST*](ps.pool, 8) # bases / keywords if _accept_op(ps, TokOp.LPar): while not _match_op(ps, TokOp.RPar): @@ -3466,11 +3466,11 @@ def _parse_classdef(ps: rawptr[Parser]) -> rawptr[AST]: # base or keyword=value if _cur_type(ps) == TokenType.Name: # Parse as expression, if followed by '=', then as keyword=value - e: rawptr[AST] = _parse_or_test(ps) + e: AST* = _parse_or_test(ps) if _match_op(ps, TokOp.Equal): _advance(ps) - v: rawptr[AST] = _parse_test(ps) - kw_node: rawptr[AST] = KwNode(ps.pool, e, v) + v: AST* = _parse_test(ps) + kw_node: AST* = KwNode(ps.pool, e, v) keywords.append(kw_node) else: bases.append(e) @@ -3479,9 +3479,9 @@ def _parse_classdef(ps: rawptr[Parser]) -> rawptr[AST]: _skip_nl(ps) # finish the newline after the last base (class X(A,\n B):) _expect_op(ps, TokOp.RPar) _expect_op(ps, TokOp.Colon) - dec_list: rawptr[list[rawptr[AST]]] = ps.pending_decorators + dec_list: list[AST*]* = ps.pending_decorators ps.pending_decorators = None - node: rawptr[ClassDef] = ClassDef(ps.pool, name, bases, keywords, dec_list, type_params) + node: ClassDef* = ClassDef(ps.pool, name, bases, keywords, dec_list, type_params) # owner_is_class=1: ps.in_class_body=1 during the class body, so virtual/novirtual modifiers can tell # whether a method-level modifier is directly in the class body (see _ParseVirtualModified). _parse_suite_into_children(ps, node, 1) @@ -3495,65 +3495,65 @@ def _parse_classdef(ps: rawptr[Parser]) -> rawptr[AST]: # downstream (ClassGenEnum._translate_enum_def -> EnumTable) has a single implementation path. # ============================================================ -def _enum_member_annassign(ps: rawptr[Parser], owner: rawptr[AST], - name_node: rawptr[AST], +def _enum_member_annassign(ps: Parser*, owner: AST*, + name_node: AST*, lineno: int, col: int, - end_lineno: int, end_col: int) -> rawptr[AST]: + end_lineno: int, end_col: int) -> AST*: """Rewrite a single member-name node into a `Name: t.State` AnnAssign (the uniform enum member form). target=Name(id, Store), annotation=Attribute(Name('t'), 'State'), value=None, simple=1 -- field-identical to a hand-written `class X(t.CEnum): A: t.State`. """ - ann: rawptr[AST] = Attribute(ps.pool, + ann: AST* = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), "State", ASTCtx.Load) _set_pos(ann, lineno, col, end_lineno, end_col) - aa: rawptr[AST] = AnnAssign(ps.pool, name_node, ann, None, 1) + aa: AST* = AnnAssign(ps.pool, name_node, ann, None, 1) _fix_store_ctx(name_node) _set_pos(aa, lineno, col, end_lineno, end_col) aa.parent = owner # maintain the parent pointer like AST.append does return aa -def _convert_enum_bare_members(ps: rawptr[Parser], node: rawptr[ClassDef]): +def _convert_enum_bare_members(ps: Parser*, node: ClassDef*): """Rewrite bare-name / comma-grouped member lines in an enum body into `Name: t.State` AnnAssigns. Member collection only recognizes Assign / AnnAssign Name targets, so bare names and comma groups (`A, B, C`) were silently dropped; now `A` -> `A: t.State` and `A, B, C` -> three AnnAssigns. Valued or annotated groups are not rewritten here and are caught by the registration-site fail-fast. """ - children: rawptr[list[rawptr[AST]]] = node.children + children: list[AST*]* = node.children if children is None: return cn: sizet = len(children) # Rebuild the child list: one comma-group line -> several AnnAssigns. list has no insert, so rebuild # entirely; the assignment form matches AST.append in base.vp. - node.children = list[rawptr[AST]](ps.pool, 8) - out: rawptr[list[rawptr[AST]]] = node.children + node.children = list[AST*](ps.pool, 8) + out: list[AST*]* = node.children for i in range(cn): - stmt: rawptr[AST] = children.get(i) + stmt: AST* = children.get(i) handled: int = 0 if stmt is not None and stmt.kind() == ASTKind.Expr: - ex: rawptr[Expr] = (rawptr[Expr])(stmt) + ex: Expr* = (Expr*)(stmt) if ex.value is not None and ex.value.kind() == ASTKind.Name: out.append(_enum_member_annassign(ps, node, ex.value, ex.lineno, ex.col_offset, ex.end_lineno, ex.end_col_offset)) handled = 1 elif ex.value is not None and ex.value.kind() == ASTKind.Tuple: - tup: rawptr[Tuple] = (rawptr[Tuple])(ex.value) + tup: Tuple* = (Tuple*)(ex.value) if tup.elts is not None and len(tup.elts) >= 2: all_names: int = 1 k: sizet = 0 while k < len(tup.elts): - el: rawptr[AST] = tup.elts.get(k) + el: AST* = tup.elts.get(k) if el is None or el.kind() != ASTKind.Name: all_names = 0 break k += 1 if all_names == 1: for k in range(len(tup.elts)): - el2: rawptr[AST] = tup.elts.get(k) + el2: AST* = tup.elts.get(k) out.append(_enum_member_annassign(ps, node, el2, el2.lineno, el2.col_offset, el2.end_lineno, el2.end_col_offset)) @@ -3562,7 +3562,7 @@ def _convert_enum_bare_members(ps: rawptr[Parser], node: rawptr[ClassDef]): out.append(stmt) -def _parse_define_const(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_define_const(ps: Parser*) -> AST*: """`define NAME[: T] = ` -> an AnnAssign field-identical to `NAME: [T |] t.CDefine = `. Same CDefine registration path as hand-written `NAME: t.CDefine = value`. With a type, T goes before @@ -3577,27 +3577,27 @@ def _parse_define_const(ps: rawptr[Parser]) -> rawptr[AST]: return None name: str = _cur_str(ps) _advance(ps) - explicit_ann: rawptr[AST] = None + explicit_ann: AST* = None if _accept_op(ps, TokOp.Colon): explicit_ann = _parse_type_ann(ps) if explicit_ann is None: return None if _expect_op(ps, TokOp.Equal) == 0: return None - value: rawptr[AST] = _parse_test(ps) + value: AST* = _parse_test(ps) if value is None: ps.error_count += 1 _record_parse_err(ps) return None - cdefine_marker: rawptr[AST] = Attribute(ps.pool, + cdefine_marker: AST* = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), "CDefine", ASTCtx.Load) - annotation: rawptr[AST] = cdefine_marker + annotation: AST* = cdefine_marker if explicit_ann is not None: annotation = BinOp(ps.pool, explicit_ann, OpKind.BitOr, cdefine_marker) - target: rawptr[AST] = Name(ps.pool, name, ASTCtx.Store) + target: AST* = Name(ps.pool, name, ASTCtx.Store) _set_pos(target, lineno, col, 0, 0) - node: rawptr[AST] = AnnAssign(ps.pool, target, annotation, value, 1) + node: AST* = AnnAssign(ps.pool, target, annotation, value, 1) _set_pos(node, lineno, col, 0, 0) _skip_nl(ps) if _cur_type(ps) != TokenType.NewLine and _cur_type(ps) != TokenType.EndMarker: @@ -3609,7 +3609,7 @@ def _parse_define_const(ps: rawptr[Parser]) -> rawptr[AST]: return node -def _parse_typedef(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_typedef(ps: Parser*) -> AST*: """`typedef T1 = T2` -> an AnnAssign field-identical to `T1: t.CTypedef = T2`. Same typedef registration/lookup path as the hand-written form (CTypedef branch -> register_ctypedef); @@ -3628,18 +3628,18 @@ def _parse_typedef(ps: rawptr[Parser]) -> rawptr[AST]: if _expect_op(ps, TokOp.Equal) == 0: # Missing '=' (e.g. `typedef A`): fail loudly. return None - value: rawptr[AST] = _parse_test(ps) + value: AST* = _parse_test(ps) if value is None: # Missing RHS (e.g. `typedef A = `): fail loudly. ps.error_count += 1 _record_parse_err(ps) return None - ctypedef_marker: rawptr[AST] = Attribute(ps.pool, + ctypedef_marker: AST* = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), "CTypedef", ASTCtx.Load) - target: rawptr[AST] = Name(ps.pool, name, ASTCtx.Store) + target: AST* = Name(ps.pool, name, ASTCtx.Store) _set_pos(target, lineno, col, 0, 0) - node: rawptr[AST] = AnnAssign(ps.pool, target, ctypedef_marker, value, 1) + node: AST* = AnnAssign(ps.pool, target, ctypedef_marker, value, 1) _set_pos(node, lineno, col, 0, 0) _skip_nl(ps) if _cur_type(ps) != TokenType.NewLine and _cur_type(ps) != TokenType.EndMarker: @@ -3651,7 +3651,7 @@ def _parse_typedef(ps: rawptr[Parser]) -> rawptr[AST]: return node -def _parse_export_extern_var(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_export_extern_var(ps: Parser*) -> AST*: """`export NAME: T [= v]` / `extern NAME: T` -> a module-level AnnAssign with storage-class markers. export rewrites the annotation to `T | t.CExport` (same marker/path as `export def`: bare name, no @@ -3674,18 +3674,18 @@ def _parse_export_extern_var(ps: rawptr[Parser]) -> rawptr[AST]: if _expect_op(ps, TokOp.Colon) == 0: # Missing ':' (e.g. `export x`): fail loudly. return None - ann: rawptr[AST] = _parse_type_ann(ps) + ann: AST* = _parse_type_ann(ps) if ann is None: ps.error_count += 1 _record_parse_err(ps) return None # Storage-class marker: export -> t.CExport (bare-name export); extern -> t.State (declaration + bare name) - storage_attr: rawptr[AST] = Attribute(ps.pool, + storage_attr: AST* = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), "State" if is_extern != 0 else "CExport", ASTCtx.Load) - annotation: rawptr[AST] = BinOp(ps.pool, ann, OpKind.BitOr, storage_attr) - value: rawptr[AST] = None + annotation: AST* = BinOp(ps.pool, ann, OpKind.BitOr, storage_attr) + value: AST* = None if _match_op(ps, TokOp.Equal): if is_extern != 0: # An extern variable is externally defined: no initializer allowed in this module. @@ -3699,9 +3699,9 @@ def _parse_export_extern_var(ps: rawptr[Parser]) -> rawptr[AST]: ps.error_count += 1 _record_parse_err(ps) return None - target: rawptr[AST] = Name(ps.pool, name, ASTCtx.Store) + target: AST* = Name(ps.pool, name, ASTCtx.Store) _set_pos(target, lineno, col, 0, 0) - node: rawptr[AST] = AnnAssign(ps.pool, target, annotation, value, 1) + node: AST* = AnnAssign(ps.pool, target, annotation, value, 1) _set_pos(node, lineno, col, 0, 0) _skip_nl(ps) if _cur_type(ps) != TokenType.NewLine and _cur_type(ps) != TokenType.EndMarker: @@ -3713,7 +3713,7 @@ def _parse_export_extern_var(ps: rawptr[Parser]) -> rawptr[AST]: return node -def _parse_enumdef(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_enumdef(ps: Parser*) -> AST*: """enum NAME: sugar -> a ClassDef field-identical to `class NAME(t.CEnum):`. Member forms (same as TPC's _ExpandEnumBlocks): bare `A` -> `A: t.State` (auto-numbered, i32 width); @@ -3729,21 +3729,21 @@ def _parse_enumdef(ps: rawptr[Parser]) -> rawptr[AST]: return None name: str = _cur_str(ps) _advance(ps) - bases: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + bases: list[AST*]* = list[AST*](ps.pool, 8) bases.append(Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), "CEnum", ASTCtx.Load)) - keywords: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - dec_list: rawptr[list[rawptr[AST]]] = ps.pending_decorators + keywords: list[AST*]* = list[AST*](ps.pool, 8) + dec_list: list[AST*]* = ps.pending_decorators ps.pending_decorators = None _expect_op(ps, TokOp.Colon) - node: rawptr[ClassDef] = ClassDef(ps.pool, name, bases, keywords, dec_list, None) + node: ClassDef* = ClassDef(ps.pool, name, bases, keywords, dec_list, None) _parse_suite_into_children(ps, node) _convert_enum_bare_members(ps, node) _set_pos(node, lineno, col, 0, 0) return node -def _parse_uniondef(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_uniondef(ps: Parser*) -> AST*: """union NAME: sugar -> a ClassDef field-identical to `class NAME(t.CUnion):`. Members are parsed as a normal class body (AnnAssign). Base is always Attribute(Name('t'), 'CUnion'), @@ -3758,20 +3758,20 @@ def _parse_uniondef(ps: rawptr[Parser]) -> rawptr[AST]: return None name: str = _cur_str(ps) _advance(ps) - bases: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + bases: list[AST*]* = list[AST*](ps.pool, 8) bases.append(Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), "CUnion", ASTCtx.Load)) - keywords: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - dec_list: rawptr[list[rawptr[AST]]] = ps.pending_decorators + keywords: list[AST*]* = list[AST*](ps.pool, 8) + dec_list: list[AST*]* = ps.pending_decorators ps.pending_decorators = None _expect_op(ps, TokOp.Colon) - node: rawptr[ClassDef] = ClassDef(ps.pool, name, bases, keywords, dec_list, None) + node: ClassDef* = ClassDef(ps.pool, name, bases, keywords, dec_list, None) _parse_suite_into_children(ps, node) _set_pos(node, lineno, col, 0, 0) return node -def _parse_renumdef(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_renumdef(ps: Parser*) -> AST*: """renum NAME: sugar -> a ClassDef field-identical to `class NAME(t.REnum):`. Members are parsed as a normal class body: a variant is a nested ClassDef (`class Some:` + field @@ -3786,14 +3786,14 @@ def _parse_renumdef(ps: rawptr[Parser]) -> rawptr[AST]: return None name: str = _cur_str(ps) _advance(ps) - bases: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + bases: list[AST*]* = list[AST*](ps.pool, 8) bases.append(Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), "REnum", ASTCtx.Load)) - keywords: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - dec_list: rawptr[list[rawptr[AST]]] = ps.pending_decorators + keywords: list[AST*]* = list[AST*](ps.pool, 8) + dec_list: list[AST*]* = ps.pending_decorators ps.pending_decorators = None _expect_op(ps, TokOp.Colon) - node: rawptr[ClassDef] = ClassDef(ps.pool, name, bases, keywords, dec_list, None) + node: ClassDef* = ClassDef(ps.pool, name, bases, keywords, dec_list, None) _parse_suite_into_children(ps, node) _set_pos(node, lineno, col, 0, 0) return node @@ -3824,7 +3824,7 @@ def _RecordStructErr(detail: str, lineno: int, col: int, extra: str): _g_parse_err_msg = detail -def _parse_structdef(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_structdef(ps: Parser*) -> AST*: """struct NAME: / struct NAME(Base): sugar -> a ClassDef field-identical to `@t.NoVTable class NAME(t.CStruct):`. @@ -3843,7 +3843,7 @@ def _parse_structdef(ps: rawptr[Parser]) -> rawptr[AST]: name: str = _cur_str(ps) _advance(ps) # Type parameters [T] / [T, U] (same as class, PEP 695 generics) - type_params: rawptr[list[str]] = None + type_params: list[str]* = None if _accept_op(ps, TokOp.Lsqb): type_params = list[str](ps.pool, 8) while not _match_op(ps, TokOp.Rsqb): @@ -3858,19 +3858,19 @@ def _parse_structdef(ps: rawptr[Parser]) -> rawptr[AST]: if not _accept_op(ps, TokOp.Comma): break _expect_op(ps, TokOp.Rsqb) - bases: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - keywords: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + bases: list[AST*]* = list[AST*](ps.pool, 8) + keywords: list[AST*]* = list[AST*](ps.pool, 8) # bases / keywords (same parse path as _parse_classdef, including cross-line and keyword=value) if _accept_op(ps, TokOp.LPar): while not _match_op(ps, TokOp.RPar): _skip_nl(ps) if _cur_type(ps) == TokenType.EndMarker: break if _cur_type(ps) == TokenType.Name: - e: rawptr[AST] = _parse_or_test(ps) + e: AST* = _parse_or_test(ps) if _match_op(ps, TokOp.Equal): _advance(ps) - v: rawptr[AST] = _parse_test(ps) - kw_node: rawptr[AST] = KwNode(ps.pool, e, v) + v: AST* = _parse_test(ps) + kw_node: AST* = KwNode(ps.pool, e, v) keywords.append(kw_node) else: bases.append(e) @@ -3883,29 +3883,29 @@ def _parse_structdef(ps: rawptr[Parser]) -> rawptr[AST]: "CStruct", ASTCtx.Load)) _expect_op(ps, TokOp.Colon) # Pseudo decorator @t.NoVTable: appended after the user decorators (same merge as _ParseVirtualModified) - dec_list: rawptr[list[rawptr[AST]]] = ps.pending_decorators + dec_list: list[AST*]* = ps.pending_decorators ps.pending_decorators = None - marker: rawptr[AST] = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), + marker: AST* = Attribute(ps.pool, Name(ps.pool, "t", ASTCtx.Load), "NoVTable", ASTCtx.Load) _set_pos(marker, lineno, col, 0, 0) - merged: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + merged: list[AST*]* = list[AST*](ps.pool, 8) if merged is not None: if dec_list is not None: dn_s: sizet = len(dec_list) for di_s in range(dn_s): merged.append(dec_list.get(di_s)) merged.append(marker) - node: rawptr[ClassDef] = ClassDef(ps.pool, name, bases, keywords, merged, type_params) + node: ClassDef* = ClassDef(ps.pool, name, bases, keywords, merged, type_params) # owner_is_class=1: same as class (ps.in_class_body=1 during the class body) _parse_suite_into_children(ps, node, 1) # struct forbids def: check the direct children - chk: rawptr[list[rawptr[AST]]] = node.children + chk: list[AST*]* = node.children if chk is not None: cn_s: sizet = len(chk) for ci_s in range(cn_s): - it_s: rawptr[AST] = chk.get(ci_s) + it_s: AST* = chk.get(ci_s) if it_s is not None and it_s.kind() == ASTKind.FunctionDef: - fd_s: rawptr[FunctionDef] = (rawptr[FunctionDef])(it_s) + fd_s: FunctionDef* = (FunctionDef*)(it_s) fname_s: str = "(anonymous)" if fd_s is not None and fd_s.name is not None: fname_s = fd_s.name @@ -3919,15 +3919,15 @@ def _parse_structdef(ps: rawptr[Parser]) -> rawptr[AST]: return node -def _parse_match(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_match(ps: Parser*) -> AST*: """match statement: match subject ':' NewLine Indent case+ Dedent""" lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # match - subject: rawptr[AST] = _parse_test(ps) + subject: AST* = _parse_test(ps) _expect_op(ps, TokOp.Colon) - cases: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - node: rawptr[AST] = Match(ps.pool, subject, cases, 0) + cases: list[AST*]* = list[AST*](ps.pool, 8) + node: AST* = Match(ps.pool, subject, cases, 0) # Parsing body: Same NewLine/Indent/Dedent pattern as _parse_suite_into_children, # but parses case clauses into a cases list instead of normal statements into children _skip_nl(ps) @@ -3938,7 +3938,7 @@ def _parse_match(ps: rawptr[Parser]) -> rawptr[AST]: _advance(ps) while _cur_type(ps) != TokenType.Dedent and _cur_type(ps) != TokenType.EndMarker: if _cur_kw(ps) == Keyword.Case: - case_node: rawptr[AST] = _parse_match_case(ps) + case_node: AST* = _parse_match_case(ps) if case_node is not None: cases.append(case_node) else: @@ -3955,7 +3955,7 @@ def _parse_match(ps: rawptr[Parser]) -> rawptr[AST]: # multi-value `case 1 | 2:`, not structured patterns. # ============================================================ -def _is_switch_default_kw(ps: rawptr[Parser]) -> int: +def _is_switch_default_kw(ps: Parser*) -> int: """`default` is a context keyword inside a switch suite: matches `default:` or `default if :` (the latter supports a guard like `case _ if `).""" if _cur_type(ps) != TokenType.Name: @@ -3963,7 +3963,7 @@ def _is_switch_default_kw(ps: rawptr[Parser]) -> int: s: str = _cur_str(ps) if s is None or string.strcmp(s, "default") != 0: return 0 - nxt: rawptr[Token] = ps.cur.next + nxt: Token* = ps.cur.next if nxt is None: return 0 if nxt.type == TokenType.Op and nxt.op_subtype == TokOp.Colon: @@ -3991,7 +3991,7 @@ def _RecordSwitchCaseErr(detail: str, lineno: int, col: int): _g_parse_err_msg = "switch 的 case 标签非法" -def _CheckSwitchCasePattern(ps: rawptr[Parser], pat: rawptr[AST]) -> int: +def _CheckSwitchCasePattern(ps: Parser*, pat: AST*) -> int: """Validate a switch case label (only constants / enum variants / multi-value patterns allowed)""" if pat is None: return 0 @@ -4000,19 +4000,19 @@ def _CheckSwitchCasePattern(ps: rawptr[Parser], pat: rawptr[AST]) -> int: return 1 if k == ASTKind.MatchAs: # Only the wildcard (`case _`, equivalent to default) is legal; as-bindings with a subpattern are not - ma_w: rawptr[MatchAs] = rawptr[MatchAs](pat) + ma_w: MatchAs* = MatchAs*(pat) if ma_w.pattern is None: return 1 return 0 if k == ASTKind.MatchOr: - mo: rawptr[MatchOr] = rawptr[MatchOr](pat) - pats: rawptr[list[rawptr[AST]]] = mo.patterns + mo: MatchOr* = MatchOr*(pat) + pats: list[AST*]* = mo.patterns if pats is None or len(pats) == 0: return 0 i: sizet = 0 n: sizet = len(pats) while i < n: - sub: rawptr[AST] = pats.get(i) + sub: AST* = pats.get(i) if sub is None: return 0 sk: int = sub.kind() @@ -4024,7 +4024,7 @@ def _CheckSwitchCasePattern(ps: rawptr[Parser], pat: rawptr[AST]) -> int: return 0 -def _parse_switch_case(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_switch_case(ps: Parser*) -> AST*: """switch `case [if ] ':' suite` (guard supported). A bare name is a capture pattern (MatchAs) in match but a value reference in switch (like C's @@ -4034,31 +4034,31 @@ def _parse_switch_case(ps: rawptr[Parser]) -> rawptr[AST]: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # case - pattern: rawptr[AST] = _parse_pattern(ps) + pattern: AST* = _parse_pattern(ps) if pattern is not None and pattern.kind() == ASTKind.MatchAs: - ma: rawptr[MatchAs] = rawptr[MatchAs](pattern) + ma: MatchAs* = MatchAs*(pattern) if ma.pattern is None and ma.name is not None: - ref: rawptr[AST] = Name(ps.pool, ma.name, ASTCtx.Load) + ref: AST* = Name(ps.pool, ma.name, ASTCtx.Load) _set_pos(ref, pattern.lineno, pattern.col_offset, 0, 0) - mv: rawptr[AST] = MatchValue(ps.pool, ref) + mv: AST* = MatchValue(ps.pool, ref) _set_pos(mv, pattern.lineno, pattern.col_offset, 0, 0) pattern = mv if _CheckSwitchCasePattern(ps, pattern) == 0: _RecordSwitchCaseErr("case 标签不是常量/枚举变体", lineno, col) ps.error_count += 1 # guard: `case if ':'` (same form as _parse_match_case) - guard: rawptr[AST] = None + guard: AST* = None if _cur_kw(ps) == Keyword.If: _advance(ps) guard = _parse_or_test(ps) _expect_op(ps, TokOp.Colon) - node: rawptr[AST] = MatchCase(ps.pool, pattern, guard) + node: AST* = MatchCase(ps.pool, pattern, guard) _parse_suite_into_children(ps, node) _set_pos(node, lineno, col, 0, 0) return node -def _parse_switch_default(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_switch_default(ps: Parser*) -> AST*: """switch `default [if ] ':' suite` -- desugared to `case []` (MatchAs wildcard). `default` is switch's spelling of `case _`; it supports a guard like `case _ if `, passed @@ -4067,28 +4067,28 @@ def _parse_switch_default(ps: rawptr[Parser]) -> rawptr[AST]: lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # default - guard: rawptr[AST] = None + guard: AST* = None if _cur_kw(ps) == Keyword.If: _advance(ps) guard = _parse_or_test(ps) _expect_op(ps, TokOp.Colon) - wild: rawptr[AST] = MatchAs(ps.pool, None, None) + wild: AST* = MatchAs(ps.pool, None, None) _set_pos(wild, lineno, col, 0, 0) - node: rawptr[AST] = MatchCase(ps.pool, wild, guard) + node: AST* = MatchCase(ps.pool, wild, guard) _parse_suite_into_children(ps, node) _set_pos(node, lineno, col, 0, 0) return node -def _parse_switch(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_switch(ps: Parser*) -> AST*: """switch statement: switch subject ':' NewLine Indent (case|default)+ Dedent""" lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # switch - subject: rawptr[AST] = _parse_test(ps) + subject: AST* = _parse_test(ps) _expect_op(ps, TokOp.Colon) - cases: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - node: rawptr[AST] = Match(ps.pool, subject, cases, 1) + cases: list[AST*]* = list[AST*](ps.pool, 8) + node: AST* = Match(ps.pool, subject, cases, 1) _skip_nl(ps) if _cur_type(ps) == TokenType.NewLine: _advance(ps) @@ -4097,11 +4097,11 @@ def _parse_switch(ps: rawptr[Parser]) -> rawptr[AST]: _advance(ps) while _cur_type(ps) != TokenType.Dedent and _cur_type(ps) != TokenType.EndMarker: if _cur_kw(ps) == Keyword.Case: - case_node: rawptr[AST] = _parse_switch_case(ps) + case_node: AST* = _parse_switch_case(ps) if case_node is not None: cases.append(case_node) elif _is_switch_default_kw(ps) != 0: - def_node: rawptr[AST] = _parse_switch_default(ps) + def_node: AST* = _parse_switch_default(ps) if def_node is not None: cases.append(def_node) else: @@ -4115,25 +4115,25 @@ def _parse_switch(ps: rawptr[Parser]) -> rawptr[AST]: # Match pattern parsing # ============================================================ -def _make_name_ast(pool: rawptr[memhub.MemManager], node: rawptr[Name]) -> rawptr[AST]: +def _make_name_ast(pool: memhub.MemManager*, node: Name*) -> AST*: # Analysis: "Convert Name* to AST* (Solving the TransPyC Type Inference Problem)" return node -def _parse_pattern(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_pattern(ps: Parser*) -> AST*: """pattern: or_pattern ['as' NAME] or_pattern: closed_pattern ('|' closed_pattern)*""" - pat: rawptr[AST] = _parse_closed_pattern(ps) + pat: AST* = _parse_closed_pattern(ps) if pat is None: return None # OR pattern if _match_op(ps, TokOp.VBar): - patterns: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + patterns: list[AST*]* = list[AST*](ps.pool, 8) patterns.append(pat) while _accept_op(ps, TokOp.VBar): - p: rawptr[AST] = _parse_closed_pattern(ps) + p: AST* = _parse_closed_pattern(ps) if p is not None: patterns.append(p) - or_node: rawptr[AST] = MatchOr(ps.pool, patterns) + or_node: AST* = MatchOr(ps.pool, patterns) _set_pos(or_node, pat.lineno, pat.col_offset, 0, 0) pat = or_node # AS pattern @@ -4144,20 +4144,20 @@ def _parse_pattern(ps: rawptr[Parser]) -> rawptr[AST]: return pat name_str: str = _cur_str(ps) _advance(ps) - as_node: rawptr[AST] = MatchAs(ps.pool, pat, name_str) + as_node: AST* = MatchAs(ps.pool, pat, name_str) _set_pos(as_node, pat.lineno, pat.col_offset, 0, 0) return as_node return pat -def _parse_closed_pattern(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_closed_pattern(ps: Parser*) -> AST*: """closed_pattern: literal | capture | wildcard | value | group | sequence | mapping | class""" lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) ttype: int = _cur_type(ps) - val: rawptr[AST] - node: rawptr[AST] - tok: rawptr[Token] + val: AST* + node: AST* + tok: Token* sval: str # Number literal pattern @@ -4229,9 +4229,9 @@ def _parse_closed_pattern(ps: rawptr[Parser]) -> rawptr[AST]: _advance(ps) # Check dotted name (value pattern or class pattern) if _match_op(ps, TokOp.Dot): - name_node: rawptr[Name] = Name(ps.pool, name_str, ASTCtx.Load) + name_node: Name* = Name(ps.pool, name_str, ASTCtx.Load) _set_pos(name_node, lineno, col, 0, 0) - base: rawptr[AST] = _make_name_ast(ps.pool, name_node) + base: AST* = _make_name_ast(ps.pool, name_node) while _match_op(ps, TokOp.Dot): _advance(ps) if _cur_type(ps) != TokenType.Name: @@ -4252,9 +4252,9 @@ def _parse_closed_pattern(ps: rawptr[Parser]) -> rawptr[AST]: return node # class pattern: Name(...) if _match_op(ps, TokOp.LPar): - cls_node: rawptr[Name] = Name(ps.pool, name_str, ASTCtx.Load) + cls_node: Name* = Name(ps.pool, name_str, ASTCtx.Load) _set_pos(cls_node, lineno, col, 0, 0) - cls: rawptr[AST] = _make_name_ast(ps.pool, cls_node) + cls: AST* = _make_name_ast(ps.pool, cls_node) return _parse_class_pattern(ps, cls, lineno, col) # capture pattern: NAME node = MatchAs(ps.pool, None, name_str) @@ -4264,14 +4264,14 @@ def _parse_closed_pattern(ps: rawptr[Parser]) -> rawptr[AST]: # group pattern / sequence pattern (tuple): (...) if _match_op(ps, TokOp.LPar): _advance(ps) - inner: rawptr[AST] = _parse_pattern(ps) + inner: AST* = _parse_pattern(ps) if _accept_op(ps, TokOp.Comma): # sequence pattern (tuple) - patterns: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + patterns: list[AST*]* = list[AST*](ps.pool, 8) if inner is not None: patterns.append(inner) while not _match_op(ps, TokOp.RPar) and _cur_type(ps) != TokenType.EndMarker: - p: rawptr[AST] = _parse_pattern(ps) + p: AST* = _parse_pattern(ps) if p is not None: patterns.append(p) if not _accept_op(ps, TokOp.Comma): @@ -4295,10 +4295,10 @@ def _parse_closed_pattern(ps: rawptr[Parser]) -> rawptr[AST]: return None -def _parse_sequence_pattern(ps: rawptr[Parser], close_op: int, - lineno: int, col: int) -> rawptr[AST]: +def _parse_sequence_pattern(ps: Parser*, close_op: int, + lineno: int, col: int) -> AST*: """sequence_pattern: '[' [pattern_list] ']'""" - patterns: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + patterns: list[AST*]* = list[AST*](ps.pool, 8) _advance(ps) # [ while not _match_op(ps, close_op) and _cur_type(ps) != TokenType.EndMarker: # *name (star pattern) @@ -4307,7 +4307,7 @@ def _parse_sequence_pattern(ps: rawptr[Parser], close_op: int, if _cur_type(ps) == TokenType.Name: star_name: str = _cur_str(ps) _advance(ps) - star_node: rawptr[AST] + star_node: AST* if string.strcmp(star_name, "_") == 0: star_node = MatchStar(ps.pool, None) else: @@ -4315,27 +4315,27 @@ def _parse_sequence_pattern(ps: rawptr[Parser], close_op: int, _set_pos(star_node, lineno, col, 0, 0) patterns.append(star_node) else: - p: rawptr[AST] = _parse_pattern(ps) + p: AST* = _parse_pattern(ps) if p is not None: patterns.append(p) if not _accept_op(ps, TokOp.Comma): break _expect_op(ps, close_op) - node: rawptr[AST] = MatchSequence(ps.pool, patterns) + node: AST* = MatchSequence(ps.pool, patterns) _set_pos(node, lineno, col, 0, 0) return node -def _parse_mapping_pattern(ps: rawptr[Parser], - lineno: int, col: int) -> rawptr[AST]: +def _parse_mapping_pattern(ps: Parser*, + lineno: int, col: int) -> AST*: """mapping_pattern: '{' [items] '}' items: key ':' pattern (',' key ':' pattern)* [',' '**' NAME] | '**' NAME""" - keys: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - patterns: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + keys: list[AST*]* = list[AST*](ps.pool, 8) + patterns: list[AST*]* = list[AST*](ps.pool, 8) rest: str = None - node: rawptr[AST] - key: rawptr[AST] - val_pat: rawptr[AST] + node: AST* + key: AST* + val_pat: AST* _advance(ps) # { if _match_op(ps, TokOp.RBrace): _advance(ps) @@ -4364,30 +4364,30 @@ def _parse_mapping_pattern(ps: rawptr[Parser], return node -def _parse_class_pattern(ps: rawptr[Parser], cls: rawptr[AST], - lineno: int, col: int) -> rawptr[AST]: +def _parse_class_pattern(ps: Parser*, cls: AST*, + lineno: int, col: int) -> AST*: """class_pattern: cls '(' [pattern_list] ')' pattern_list: positional_pattern (',' positional_pattern)* [',' keyword_pattern]* | keyword_pattern (',' keyword_pattern)* keyword_pattern: NAME '=' pattern""" - patterns: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - kwd_attrs: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - kwd_patterns: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) - p: rawptr[AST] + patterns: list[AST*]* = list[AST*](ps.pool, 8) + kwd_attrs: list[AST*]* = list[AST*](ps.pool, 8) + kwd_patterns: list[AST*]* = list[AST*](ps.pool, 8) + p: AST* _advance(ps) # ( if not _match_op(ps, TokOp.RPar): while _cur_type(ps) != TokenType.EndMarker: # keyword pattern: NAME '=' pattern if _cur_type(ps) == TokenType.Name and ps.cur is not None: - nxt: rawptr[Token] = ps.cur.next + nxt: Token* = ps.cur.next if nxt is not None and nxt.type == TokenType.Op and nxt.op_subtype == TokOp.Equal: attr_name: str = _cur_str(ps) _advance(ps) # NAME _advance(ps) # = - kwd_pat: rawptr[AST] = _parse_pattern(ps) - attr_n: rawptr[Name] = Name(ps.pool, attr_name, ASTCtx.Load) + kwd_pat: AST* = _parse_pattern(ps) + attr_n: Name* = Name(ps.pool, attr_name, ASTCtx.Load) _set_pos(attr_n, lineno, col, 0, 0) - attr_node: rawptr[AST] = _make_name_ast(ps.pool, attr_n) + attr_node: AST* = _make_name_ast(ps.pool, attr_n) kwd_attrs.append(attr_node) if kwd_pat is not None: kwd_patterns.append(kwd_pat) @@ -4402,23 +4402,23 @@ def _parse_class_pattern(ps: rawptr[Parser], cls: rawptr[AST], if not _accept_op(ps, TokOp.Comma): break _expect_op(ps, TokOp.RPar) - node: rawptr[AST] = MatchClass(ps.pool, cls, patterns, kwd_attrs, kwd_patterns) + node: AST* = MatchClass(ps.pool, cls, patterns, kwd_attrs, kwd_patterns) _set_pos(node, lineno, col, 0, 0) return node -def _parse_match_case(ps: rawptr[Parser]) -> rawptr[AST]: +def _parse_match_case(ps: Parser*) -> AST*: """case pattern [if guard] ':' suite""" lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # case - guard: rawptr[AST] = None - pattern: rawptr[AST] = _parse_pattern(ps) + guard: AST* = None + pattern: AST* = _parse_pattern(ps) if _cur_kw(ps) == Keyword.If: _advance(ps) guard = _parse_or_test(ps) _expect_op(ps, TokOp.Colon) - node: rawptr[AST] = MatchCase(ps.pool, pattern, guard) + node: AST* = MatchCase(ps.pool, pattern, guard) _parse_suite_into_children(ps, node) _set_pos(node, lineno, col, 0, 0) return node @@ -4448,7 +4448,7 @@ def _IsMagicAttributeCallee(node: AST*) -> int: return 0 -def _MakeTAttrMarker(ps: rawptr[Parser], arg: AST*) -> AST*: +def _MakeTAttrMarker(ps: Parser*, arg: AST*) -> AST*: """Desugar one __attribute__ argument into `t.attr.` (calls keep their arguments). `always_inline` (Name) -> `t.attr.always_inline`; `section(".text.wo")` (Call) -> `t.attr.section(...)`; @@ -4486,7 +4486,7 @@ def _MakeTAttrMarker(ps: rawptr[Parser], arg: AST*) -> AST*: return arg -def _DesugarMagicAttribute(ps: rawptr[Parser], expr: AST*) -> AST*: +def _DesugarMagicAttribute(ps: Parser*, expr: AST*) -> AST*: """`@__attribute__(...)` -> `@c.Attribute(t.attr.x, ...)`; other decorators are returned as-is""" if expr is None or expr.kind() != ASTKind.Call: return expr @@ -4495,7 +4495,7 @@ def _DesugarMagicAttribute(ps: rawptr[Parser], expr: AST*) -> AST*: return expr c_func: AST* = Attribute(ps.pool, Name(ps.pool, "c", ASTCtx.Load), "Attribute", ASTCtx.Load) - new_args: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + new_args: list[AST*]* = list[AST*](ps.pool, 8) if new_args is None: return expr if cl.args is not None: @@ -4509,14 +4509,14 @@ def _DesugarMagicAttribute(ps: rawptr[Parser], expr: AST*) -> AST*: return new_call -def _parse_decorators(ps: rawptr[Parser]) -> rawptr[list[rawptr[AST]]]: +def _parse_decorators(ps: Parser*) -> list[AST*]*: """Parse a decorator chain, returning a list.""" - decs: rawptr[list[rawptr[AST]]] = list[rawptr[AST]](ps.pool, 8) + decs: list[AST*]* = list[AST*](ps.pool, 8) while _match_op(ps, TokOp.At): lineno: int = _cur_lineno(ps) col: int = _cur_col(ps) _advance(ps) # @ - expr: rawptr[AST] = _parse_namedexpr(ps) + expr: AST* = _parse_namedexpr(ps) # C-style `@__attribute__(...)` desugars into the existing `@c.Attribute(t.attr....)` expr = _DesugarMagicAttribute(ps, expr) _skip_nl(ps) @@ -4530,7 +4530,7 @@ def _parse_decorators(ps: rawptr[Parser]) -> rawptr[list[rawptr[AST]]]: # Module entry # ============================================================ -def _parse_module_body(ps: rawptr[Parser], module_node: rawptr[AST]): +def _parse_module_body(ps: Parser*, module_node: AST*): """Parse the module body, appending to module_node.""" _skip_nl(ps) stmt_idx: int = 0 @@ -4544,7 +4544,7 @@ def _parse_module_body(ps: rawptr[Parser], module_node: rawptr[AST]): if _match_op(ps, TokOp.At): ps.pending_decorators = _parse_decorators(ps) # Record current token pointer to check for infinite loop - before_cur: rawptr[Token] = ps.cur + before_cur: Token* = ps.cur _parse_statement_into(ps, module_node) # Defense: If parsing doesn't advance the token (like when _parse_atom encounters an unrecognized token and returns None), # force it to move forward to avoid an infinite loop in the main loop; accumulate error_count for the caller to diagnose @@ -4554,8 +4554,8 @@ def _parse_module_body(ps: rawptr[Parser], module_node: rawptr[AST]): _skip_nl(ps) -def parse_tokens(pool: rawptr[memhub.MemManager], - tokens: rawptr[Token]) -> rawptr[AST]: +def parse_tokens(pool: memhub.MemManager*, + tokens: Token*) -> AST*: """Parse an AST Module from a token list.""" if pool is None or tokens is None: return None @@ -4571,13 +4571,13 @@ def parse_tokens(pool: rawptr[memhub.MemManager], _g_parse_err_col = get_lex_err_col() _g_parse_err_msg = get_lex_err_msg() return None - ps: rawptr[Parser] = new_parser(pool) + ps: Parser* = new_parser(pool) if ps is None: return None _parser_init(ps, tokens, pool) # fail-fast anti-hang: count the token list first, detecting a cycle. A cyclic list (Token appended # twice or aliased) would hang the statement loop; exceeding the cap before the tail means a cycle. tok_count: sizet = 0 - walk_t: rawptr[Token] = tokens + walk_t: Token* = tokens while walk_t is not None: walk_t = walk_t.next tok_count += 1 @@ -4589,7 +4589,7 @@ def parse_tokens(pool: rawptr[memhub.MemManager], # Budget: the watchdog counts "query current token" calls (well below 256 per token in valid parses, # so it cannot trip falsely) while catching cycles/spins; it also bounds _advance and statement loops. ps.step_limit = tok_count * 256 + 262144 - module_node: rawptr[Module] = Module(pool) + module_node: Module* = Module(pool) _parse_module_body(ps, module_node) # fail-fast: on a parse error (error_count > 0) return None so the caller aborts, avoiding silently # compiling broken code (e.g. a function definition left without its def keyword). diff --git a/ast/stmts.vp b/ast/stmts.vp index e368e81..005896e 100644 --- a/ast/stmts.vp +++ b/ast/stmts.vp @@ -16,12 +16,12 @@ from .base import ( virtual class Module(AST): """Module(children: list[rawptr[AST]])""" - def __new__(self, pool: rawptr[memhub.MemManager]): - ptr: rawptr[Module] = pool.alloc(Module.__sizeof__()) + def __new__(self, pool: memhub.MemManager*): + ptr: Module* = pool.alloc(Module.__sizeof__()) if ptr: string.memset(ptr, 0, Module.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager]): + def __init__(self, pool: memhub.MemManager*): _init_ast(self, pool, 0, 0) def kind(self) -> int: @@ -43,17 +43,17 @@ virtual class Module(AST): class Assign(Stmt): """Assign(targets: list[rawptr[AST]], value: AST)""" - targets: rawptr[list[rawptr[AST]]] - value: rawptr[AST] + targets: list[AST*]* + value: AST* - def __new__(self, pool: rawptr[memhub.MemManager], - targets: rawptr[list[rawptr[AST]]], value: rawptr[AST]): - ptr: rawptr[Assign] = pool.alloc(Assign.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + targets: list[AST*]*, value: AST*): + ptr: Assign* = pool.alloc(Assign.__sizeof__()) if ptr: string.memset(ptr, 0, Assign.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - targets: rawptr[list[rawptr[AST]]], value: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + targets: list[AST*]*, value: AST*): _init_ast(self, pool, 0, 0) self.targets = targets self.value = value @@ -83,19 +83,19 @@ class Assign(Stmt): class If(Stmt): """If(test: AST, orelse: list[rawptr[AST]])""" - test: rawptr[AST] - orelse: rawptr[list[rawptr[AST]]] + test: AST* + orelse: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - test: rawptr[AST], - orelse: rawptr[list[rawptr[AST]]]): - ptr: rawptr[If] = pool.alloc(If.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + test: AST*, + orelse: list[AST*]*): + ptr: If* = pool.alloc(If.__sizeof__()) if ptr: string.memset(ptr, 0, If.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - test: rawptr[AST], - orelse: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + test: AST*, + orelse: list[AST*]*): _init_ast(self, pool, 0, 0) self.test = test self.orelse = orelse @@ -127,22 +127,22 @@ class If(Stmt): class For(Stmt): """For(target: AST, iter: AST, orelse: list[rawptr[AST]], is_async: CInt)""" - target: rawptr[AST] - iter: rawptr[AST] - orelse: rawptr[list[rawptr[AST]]] + target: AST* + iter: AST* + orelse: list[AST*]* flags: int - def __new__(self, pool: rawptr[memhub.MemManager], - target: rawptr[AST], iter: rawptr[AST], - orelse: rawptr[list[rawptr[AST]]], + def __new__(self, pool: memhub.MemManager*, + target: AST*, iter: AST*, + orelse: list[AST*]*, is_async: int): - ptr: rawptr[For] = pool.alloc(For.__sizeof__()) + ptr: For* = pool.alloc(For.__sizeof__()) if ptr: string.memset(ptr, 0, For.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - target: rawptr[AST], iter: rawptr[AST], - orelse: rawptr[list[rawptr[AST]]], + def __init__(self, pool: memhub.MemManager*, + target: AST*, iter: AST*, + orelse: list[AST*]*, is_async: int): _init_ast(self, pool, 0, 0) self.target = target @@ -183,19 +183,19 @@ class For(Stmt): class While(Stmt): """While(test: AST, orelse: list[rawptr[AST]])""" - test: rawptr[AST] - orelse: rawptr[list[rawptr[AST]]] + test: AST* + orelse: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - test: rawptr[AST], - orelse: rawptr[list[rawptr[AST]]]): - ptr: rawptr[While] = pool.alloc(While.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + test: AST*, + orelse: list[AST*]*): + ptr: While* = pool.alloc(While.__sizeof__()) if ptr: string.memset(ptr, 0, While.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - test: rawptr[AST], - orelse: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + test: AST*, + orelse: list[AST*]*): _init_ast(self, pool, 0, 0) self.test = test self.orelse = orelse @@ -225,14 +225,14 @@ class While(Stmt): class Return(Stmt): """Return(value: AST | None)""" - value: rawptr[AST] + value: AST* - def __new__(self, pool: rawptr[memhub.MemManager], value: rawptr[AST]): - ptr: rawptr[Return] = pool.alloc(Return.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, value: AST*): + ptr: Return* = pool.alloc(Return.__sizeof__()) if ptr: string.memset(ptr, 0, Return.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], value: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, value: AST*): _init_ast(self, pool, 0, 0) self.value = value @@ -258,14 +258,14 @@ class Return(Stmt): class Expr(Stmt): """Expr(value: AST)""" - value: rawptr[AST] + value: AST* - def __new__(self, pool: rawptr[memhub.MemManager], value: rawptr[AST]): - ptr: rawptr[Expr] = pool.alloc(Expr.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, value: AST*): + ptr: Expr* = pool.alloc(Expr.__sizeof__()) if ptr: string.memset(ptr, 0, Expr.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], value: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, value: AST*): _init_ast(self, pool, 0, 0) self.value = value @@ -291,31 +291,31 @@ class Expr(Stmt): class FunctionDef(Stmt): """FunctionDef(name: str, args: AST, - decorator_list: list[rawptr[AST]], returns: AST, flags: CInt, - type_params: rawptr[list[str]] = None) + decorator_list: list[AST*], returns: AST, flags: CInt, + type_params: list[str]* = None) type_params: generic function type-parameter name list (the [T] in PEP 695 def f[T](...)), None means a non-generic function.""" name: str - args: rawptr[AST] - decorator_list: rawptr[list[rawptr[AST]]] - returns: rawptr[AST] + args: AST* + decorator_list: list[AST*]* + returns: AST* flags: int - type_params: rawptr[list[str]] + type_params: list[str]* - def __new__(self, pool: rawptr[memhub.MemManager], - name: str, args: rawptr[AST], - decorator_list: rawptr[list[rawptr[AST]]], - returns: rawptr[AST], is_async: int): - ptr: rawptr[FunctionDef] = pool.alloc(FunctionDef.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + name: str, args: AST*, + decorator_list: list[AST*]*, + returns: AST*, is_async: int): + ptr: FunctionDef* = pool.alloc(FunctionDef.__sizeof__()) if ptr: string.memset(ptr, 0, FunctionDef.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - name: str, args: rawptr[AST], - decorator_list: rawptr[list[rawptr[AST]]], - returns: rawptr[AST], is_async: int, - type_params: rawptr[list[str]] = None): + def __init__(self, pool: memhub.MemManager*, + name: str, args: AST*, + decorator_list: list[AST*]*, + returns: AST*, is_async: int, + type_params: list[str]* = None): _init_ast(self, pool, 0, 0) self.name = _copy_str(pool, name) self.args = args @@ -361,16 +361,16 @@ class FunctionDef(Stmt): class Expression(AST): """Expression(body: AST)""" - body: rawptr[AST] + body: AST* - def __new__(self, pool: rawptr[memhub.MemManager], - body: rawptr[AST]): - ptr: rawptr[Expression] = pool.alloc(Expression.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + body: AST*): + ptr: Expression* = pool.alloc(Expression.__sizeof__()) if ptr: string.memset(ptr, 0, Expression.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - body: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + body: AST*): _init_ast(self, pool, 0, 0) self.body = body @@ -396,16 +396,16 @@ class Expression(AST): class Interactive(AST): """Interactive(body: AST)""" - body: rawptr[AST] + body: AST* - def __new__(self, pool: rawptr[memhub.MemManager], - body: rawptr[AST]): - ptr: rawptr[Interactive] = pool.alloc(Interactive.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + body: AST*): + ptr: Interactive* = pool.alloc(Interactive.__sizeof__()) if ptr: string.memset(ptr, 0, Interactive.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - body: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + body: AST*): _init_ast(self, pool, 0, 0) self.body = body @@ -431,19 +431,19 @@ class Interactive(AST): class FunctionType(AST): """FunctionType(argtypes: list[rawptr[AST]], returns: AST)""" - argtypes: rawptr[list[rawptr[AST]]] - returns: rawptr[AST] + argtypes: list[AST*]* + returns: AST* - def __new__(self, pool: rawptr[memhub.MemManager], - argtypes: rawptr[list[rawptr[AST]]], - returns: rawptr[AST]): - ptr: rawptr[FunctionType] = pool.alloc(FunctionType.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + argtypes: list[AST*]*, + returns: AST*): + ptr: FunctionType* = pool.alloc(FunctionType.__sizeof__()) if ptr: string.memset(ptr, 0, FunctionType.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - argtypes: rawptr[list[rawptr[AST]]], - returns: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + argtypes: list[AST*]*, + returns: AST*): _init_ast(self, pool, 0, 0) self.argtypes = argtypes self.returns = returns @@ -472,32 +472,32 @@ class FunctionType(AST): class ClassDef(Stmt): """ClassDef(name: str, bases: list[rawptr[AST]], keywords: list[rawptr[AST]], - decorator_list: list[rawptr[AST]], type_params: rawptr[list[str]]) + decorator_list: list[AST*], type_params: list[str]*) type_params: generic type-parameter name list (the [T] in PEP 695 class list[T]:), None means a non-generic class.""" name: str - bases: rawptr[list[rawptr[AST]]] - keywords: rawptr[list[rawptr[AST]]] - decorator_list: rawptr[list[rawptr[AST]]] - type_params: rawptr[list[str]] + bases: list[AST*]* + keywords: list[AST*]* + decorator_list: list[AST*]* + type_params: list[str]* - def __new__(self, pool: rawptr[memhub.MemManager], + def __new__(self, pool: memhub.MemManager*, name: str, - bases: rawptr[list[rawptr[AST]]], - keywords: rawptr[list[rawptr[AST]]], - decorator_list: rawptr[list[rawptr[AST]]], - type_params: rawptr[list[str]] = None): - ptr: rawptr[ClassDef] = pool.alloc(ClassDef.__sizeof__()) + bases: list[AST*]*, + keywords: list[AST*]*, + decorator_list: list[AST*]*, + type_params: list[str]* = None): + ptr: ClassDef* = pool.alloc(ClassDef.__sizeof__()) if ptr: string.memset(ptr, 0, ClassDef.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], + def __init__(self, pool: memhub.MemManager*, name: str, - bases: rawptr[list[rawptr[AST]]], - keywords: rawptr[list[rawptr[AST]]], - decorator_list: rawptr[list[rawptr[AST]]], - type_params: rawptr[list[str]] = None): + bases: list[AST*]*, + keywords: list[AST*]*, + decorator_list: list[AST*]*, + type_params: list[str]* = None): _init_ast(self, pool, 0, 0) self.name = _copy_str(pool, name) self.bases = bases @@ -533,16 +533,16 @@ class ClassDef(Stmt): class Delete(Stmt): """Delete(targets: list[rawptr[AST]])""" - targets: rawptr[list[rawptr[AST]]] + targets: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - targets: rawptr[list[rawptr[AST]]]): - ptr: rawptr[Delete] = pool.alloc(Delete.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + targets: list[AST*]*): + ptr: Delete* = pool.alloc(Delete.__sizeof__()) if ptr: string.memset(ptr, 0, Delete.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - targets: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + targets: list[AST*]*): _init_ast(self, pool, 0, 0) self.targets = targets _set_parent_list(targets, self) @@ -566,18 +566,18 @@ class Delete(Stmt): class AugAssign(Stmt): """AugAssign(target: AST, op: CInt, value: AST)""" - target: rawptr[AST] + target: AST* op: int - value: rawptr[AST] + value: AST* - def __new__(self, pool: rawptr[memhub.MemManager], - target: rawptr[AST], op: int, value: rawptr[AST]): - ptr: rawptr[AugAssign] = pool.alloc(AugAssign.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + target: AST*, op: int, value: AST*): + ptr: AugAssign* = pool.alloc(AugAssign.__sizeof__()) if ptr: string.memset(ptr, 0, AugAssign.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - target: rawptr[AST], op: int, value: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + target: AST*, op: int, value: AST*): _init_ast(self, pool, 0, 0) self.target = target self.op = op @@ -612,21 +612,21 @@ class AugAssign(Stmt): class AnnAssign(Stmt): """AnnAssign(target: AST, annotation: AST, value: AST, simple: CInt)""" - target: rawptr[AST] - annotation: rawptr[AST] - value: rawptr[AST] + target: AST* + annotation: AST* + value: AST* simple: int - def __new__(self, pool: rawptr[memhub.MemManager], - target: rawptr[AST], annotation: rawptr[AST], - value: rawptr[AST], simple: int): - ptr: rawptr[AnnAssign] = pool.alloc(AnnAssign.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + target: AST*, annotation: AST*, + value: AST*, simple: int): + ptr: AnnAssign* = pool.alloc(AnnAssign.__sizeof__()) if ptr: string.memset(ptr, 0, AnnAssign.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - target: rawptr[AST], annotation: rawptr[AST], - value: rawptr[AST], simple: int): + def __init__(self, pool: memhub.MemManager*, + target: AST*, annotation: AST*, + value: AST*, simple: int): _init_ast(self, pool, 0, 0) self.target = target self.annotation = annotation @@ -667,18 +667,18 @@ class AnnAssign(Stmt): class With(Stmt): """With(items: list[rawptr[AST]], is_async: CInt)""" - items: rawptr[list[rawptr[AST]]] + items: list[AST*]* flags: int - def __new__(self, pool: rawptr[memhub.MemManager], - items: rawptr[list[rawptr[AST]]], + def __new__(self, pool: memhub.MemManager*, + items: list[AST*]*, is_async: int): - ptr: rawptr[With] = pool.alloc(With.__sizeof__()) + ptr: With* = pool.alloc(With.__sizeof__()) if ptr: string.memset(ptr, 0, With.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - items: rawptr[list[rawptr[AST]]], + def __init__(self, pool: memhub.MemManager*, + items: list[AST*]*, is_async: int): _init_ast(self, pool, 0, 0) self.items = items @@ -709,17 +709,17 @@ class With(Stmt): class Raise(Stmt): """Raise(exc: AST, cause: AST)""" - exc: rawptr[AST] - cause: rawptr[AST] + exc: AST* + cause: AST* - def __new__(self, pool: rawptr[memhub.MemManager], - exc: rawptr[AST], cause: rawptr[AST]): - ptr: rawptr[Raise] = pool.alloc(Raise.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + exc: AST*, cause: AST*): + ptr: Raise* = pool.alloc(Raise.__sizeof__()) if ptr: string.memset(ptr, 0, Raise.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - exc: rawptr[AST], cause: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + exc: AST*, cause: AST*): _init_ast(self, pool, 0, 0) self.exc = exc self.cause = cause @@ -751,23 +751,23 @@ class Raise(Stmt): class Try(Stmt): """Try(handlers: list[rawptr[AST]], - orelse: list[rawptr[AST]], finalbody: list[rawptr[AST]])""" - handlers: rawptr[list[rawptr[AST]]] - orelse: rawptr[list[rawptr[AST]]] - finalbody: rawptr[list[rawptr[AST]]] + orelse: list[AST*], finalbody: list[AST*])""" + handlers: list[AST*]* + orelse: list[AST*]* + finalbody: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - handlers: rawptr[list[rawptr[AST]]], - orelse: rawptr[list[rawptr[AST]]], - finalbody: rawptr[list[rawptr[AST]]]): - ptr: rawptr[Try] = pool.alloc(Try.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + handlers: list[AST*]*, + orelse: list[AST*]*, + finalbody: list[AST*]*): + ptr: Try* = pool.alloc(Try.__sizeof__()) if ptr: string.memset(ptr, 0, Try.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - handlers: rawptr[list[rawptr[AST]]], - orelse: rawptr[list[rawptr[AST]]], - finalbody: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + handlers: list[AST*]*, + orelse: list[AST*]*, + finalbody: list[AST*]*): _init_ast(self, pool, 0, 0) self.handlers = handlers self.orelse = orelse @@ -801,17 +801,17 @@ class Try(Stmt): class Assert(Stmt): """Assert(test: AST, msg: AST)""" - test: rawptr[AST] - msg: rawptr[AST] + test: AST* + msg: AST* - def __new__(self, pool: rawptr[memhub.MemManager], - test: rawptr[AST], msg: rawptr[AST]): - ptr: rawptr[Assert] = pool.alloc(Assert.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + test: AST*, msg: AST*): + ptr: Assert* = pool.alloc(Assert.__sizeof__()) if ptr: string.memset(ptr, 0, Assert.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - test: rawptr[AST], msg: rawptr[AST]): + def __init__(self, pool: memhub.MemManager*, + test: AST*, msg: AST*): _init_ast(self, pool, 0, 0) self.test = test self.msg = msg @@ -843,16 +843,16 @@ class Assert(Stmt): class Global(Stmt): """Global(names: list[rawptr[AST]])""" - names: rawptr[list[rawptr[AST]]] + names: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - names: rawptr[list[rawptr[AST]]]): - ptr: rawptr[Global] = pool.alloc(Global.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + names: list[AST*]*): + ptr: Global* = pool.alloc(Global.__sizeof__()) if ptr: string.memset(ptr, 0, Global.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - names: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + names: list[AST*]*): _init_ast(self, pool, 0, 0) self.names = names _set_parent_list(names, self) @@ -876,16 +876,16 @@ class Global(Stmt): class Nonlocal(Stmt): """Nonlocal(names: list[rawptr[AST]])""" - names: rawptr[list[rawptr[AST]]] + names: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - names: rawptr[list[rawptr[AST]]]): - ptr: rawptr[Nonlocal] = pool.alloc(Nonlocal.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + names: list[AST*]*): + ptr: Nonlocal* = pool.alloc(Nonlocal.__sizeof__()) if ptr: string.memset(ptr, 0, Nonlocal.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - names: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + names: list[AST*]*): _init_ast(self, pool, 0, 0) self.names = names _set_parent_list(names, self) @@ -910,12 +910,12 @@ class Nonlocal(Stmt): class Pass(Stmt): """Pass()""" - def __new__(self, pool: rawptr[memhub.MemManager]): - ptr: rawptr[Pass] = pool.alloc(Pass.__sizeof__()) + def __new__(self, pool: memhub.MemManager*): + ptr: Pass* = pool.alloc(Pass.__sizeof__()) if ptr: string.memset(ptr, 0, Pass.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager]): + def __init__(self, pool: memhub.MemManager*): _init_ast(self, pool, 0, 0) def kind(self) -> int: @@ -936,12 +936,12 @@ class Pass(Stmt): class Break(Stmt): """Break()""" - def __new__(self, pool: rawptr[memhub.MemManager]): - ptr: rawptr[Break] = pool.alloc(Break.__sizeof__()) + def __new__(self, pool: memhub.MemManager*): + ptr: Break* = pool.alloc(Break.__sizeof__()) if ptr: string.memset(ptr, 0, Break.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager]): + def __init__(self, pool: memhub.MemManager*): _init_ast(self, pool, 0, 0) def kind(self) -> int: @@ -962,12 +962,12 @@ class Break(Stmt): class Continue(Stmt): """Continue()""" - def __new__(self, pool: rawptr[memhub.MemManager]): - ptr: rawptr[Continue] = pool.alloc(Continue.__sizeof__()) + def __new__(self, pool: memhub.MemManager*): + ptr: Continue* = pool.alloc(Continue.__sizeof__()) if ptr: string.memset(ptr, 0, Continue.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager]): + def __init__(self, pool: memhub.MemManager*): _init_ast(self, pool, 0, 0) def kind(self) -> int: @@ -988,12 +988,12 @@ class Continue(Stmt): class FallThrough(Stmt): """FallThrough() - a switch case body does not auto-break, so it falls through to the next case""" - def __new__(self, pool: rawptr[memhub.MemManager]): - ptr: rawptr[FallThrough] = pool.alloc(FallThrough.__sizeof__()) + def __new__(self, pool: memhub.MemManager*): + ptr: FallThrough* = pool.alloc(FallThrough.__sizeof__()) if ptr: string.memset(ptr, 0, FallThrough.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager]): + def __init__(self, pool: memhub.MemManager*): _init_ast(self, pool, 0, 0) def kind(self) -> int: @@ -1013,16 +1013,16 @@ class FallThrough(Stmt): class Import(Stmt): """Import(names: list[rawptr[AST]])""" - names: rawptr[list[rawptr[AST]]] + names: list[AST*]* - def __new__(self, pool: rawptr[memhub.MemManager], - names: rawptr[list[rawptr[AST]]]): - ptr: rawptr[Import] = pool.alloc(Import.__sizeof__()) + def __new__(self, pool: memhub.MemManager*, + names: list[AST*]*): + ptr: Import* = pool.alloc(Import.__sizeof__()) if ptr: string.memset(ptr, 0, Import.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - names: rawptr[list[rawptr[AST]]]): + def __init__(self, pool: memhub.MemManager*, + names: list[AST*]*): _init_ast(self, pool, 0, 0) self.names = names _set_parent_list(names, self) @@ -1047,20 +1047,20 @@ class Import(Stmt): class ImportFrom(Stmt): """ImportFrom(module: str, names: list[rawptr[AST]], level: CInt)""" module: str - names: rawptr[list[rawptr[AST]]] + names: list[AST*]* level: int - def __new__(self, pool: rawptr[memhub.MemManager], + def __new__(self, pool: memhub.MemManager*, module: str, - names: rawptr[list[rawptr[AST]]], + names: list[AST*]*, level: int): - ptr: rawptr[ImportFrom] = pool.alloc(ImportFrom.__sizeof__()) + ptr: ImportFrom* = pool.alloc(ImportFrom.__sizeof__()) if ptr: string.memset(ptr, 0, ImportFrom.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], + def __init__(self, pool: memhub.MemManager*, module: str, - names: rawptr[list[rawptr[AST]]], + names: list[AST*]*, level: int): _init_ast(self, pool, 0, 0) self.module = _copy_str(pool, module) @@ -1095,21 +1095,21 @@ class Match(Stmt): is_switch=1: from `switch :` sugar (see _parse_switch), C semantics (no fall-through without `fallthrough`). is_switch=0: real `match`, fallthrough is completely forbidden (fail-fast). """ - subject: rawptr[AST] - cases: rawptr[list[rawptr[AST]]] + subject: AST* + cases: list[AST*]* is_switch: int - def __new__(self, pool: rawptr[memhub.MemManager], - subject: rawptr[AST], - cases: rawptr[list[rawptr[AST]]], + def __new__(self, pool: memhub.MemManager*, + subject: AST*, + cases: list[AST*]*, is_switch: int): - ptr: rawptr[Match] = pool.alloc(Match.__sizeof__()) + ptr: Match* = pool.alloc(Match.__sizeof__()) if ptr: string.memset(ptr, 0, Match.__sizeof__()) return ptr - def __init__(self, pool: rawptr[memhub.MemManager], - subject: rawptr[AST], - cases: rawptr[list[rawptr[AST]]], + def __init__(self, pool: memhub.MemManager*, + subject: AST*, + cases: list[AST*]*, is_switch: int): _init_ast(self, pool, 0, 0) self.subject = subject diff --git a/ast/tokens.vp b/ast/tokens.vp index c691e21..e9f33da 100644 --- a/ast/tokens.vp +++ b/ast/tokens.vp @@ -200,11 +200,11 @@ class Token: col_offset: int # Starting column offset end_lineno: int # Ending line number end_col_offset: int # Ending column offset - next: rawptr[Token] # Next token in linked list + next: Token* # Next token in linked list - def __new__(self, pool: rawptr[memhub.MemManager]): + def __new__(self, pool: memhub.MemManager*): """Allocate zero‑initialized Token struct memory from mpool""" - ptr: rawptr[Token] = pool.alloc(Token.__sizeof__()) + ptr: Token* = pool.alloc(Token.__sizeof__()) if ptr == None: _ast_pool_fatal("Token", sizet(Token.__sizeof__())) string.memset(ptr, 0, Token.__sizeof__()) @@ -218,10 +218,10 @@ class Token: class KwEntry: name: str kw_id: int - next: rawptr[KwEntry] + next: KwEntry* - def __new__(self, pool: rawptr[memhub.MemManager]): - ptr: rawptr[KwEntry] = pool.alloc(KwEntry.__sizeof__()) + def __new__(self, pool: memhub.MemManager*): + ptr: KwEntry* = pool.alloc(KwEntry.__sizeof__()) if ptr == None: _ast_pool_fatal("KwEntry", sizet(KwEntry.__sizeof__())) string.memset(ptr, 0, KwEntry.__sizeof__()) @@ -229,8 +229,8 @@ class KwEntry: # Global keyword linked list head (lazy initialization) -_kw_head: rawptr[KwEntry] = None -_kw_pool: rawptr[memhub.MemManager] = None +_kw_head: KwEntry* = None +_kw_pool: memhub.MemManager* = None # Keyword hash index (open addressing, linear probing): slot u64, 0 = empty else KwEntry address; # expected O(1) lookups, falling back to the list only when not built (alloc failure). Miss returns 0. @@ -253,7 +253,7 @@ def _kw_hash_str(key: str) -> uint64: return uint64(h) -def _kw_index_put(entry: rawptr[KwEntry]): +def _kw_index_put(entry: KwEntry*): """Write a keyword entry into the hash index (silently skipped if not built); a duplicate key keeps the first registrant, and collisions are separated by strcmp (hash alone could return a wrong kw_id).""" if _kw_index == None: return @@ -272,10 +272,10 @@ def _kw_index_put(entry: rawptr[KwEntry]): idx = (idx + 1) & mask -def _kw_intern(pool: rawptr[memhub.MemManager], name: str, kw_id: int): +def _kw_intern(pool: memhub.MemManager*, name: str, kw_id: int): """Register keyword name in the linked list""" global _kw_head - entry: rawptr[KwEntry] = KwEntry(pool) + entry: KwEntry* = KwEntry(pool) if entry == None: return slen: sizet = string.strlen(name) buf: str = pool.alloc(slen + 1) @@ -313,7 +313,7 @@ def _kw_lookup(name: str) -> int: return cur.kw_id idx = (idx + 1) & mask return 0 - cur2: rawptr[KwEntry] = _kw_head + cur2: KwEntry* = _kw_head while cur2 != None: if string.strcmp(cur2.name, name) == 0: return cur2.kw_id @@ -321,7 +321,7 @@ def _kw_lookup(name: str) -> int: return 0 -def _init_keywords(pool: rawptr[memhub.MemManager]): +def _init_keywords(pool: memhub.MemManager*): """Initialize keyword linked list (only once)""" global _kw_head, _kw_pool, _kw_index if _kw_head != None: return @@ -406,21 +406,21 @@ class OpEntry: name: str # Operator text (e.g. "==", "+=") op_id: int length: int - next: rawptr[OpEntry] + next: OpEntry* - def __new__(self, pool: rawptr[memhub.MemManager]): - ptr: rawptr[OpEntry] = pool.alloc(OpEntry.__sizeof__()) + def __new__(self, pool: memhub.MemManager*): + ptr: OpEntry* = pool.alloc(OpEntry.__sizeof__()) if ptr: string.memset(ptr, 0, OpEntry.__sizeof__()) return ptr -_op_head: rawptr[OpEntry] = None +_op_head: OpEntry* = None -def _op_intern(pool: rawptr[memhub.MemManager], name: str, op_id: int): +def _op_intern(pool: memhub.MemManager*, name: str, op_id: int): global _op_head slen: sizet = string.strlen(name) - entry: rawptr[OpEntry] = OpEntry(pool) + entry: OpEntry* = OpEntry(pool) if entry == None: return buf: str = pool.alloc(slen + 1) if buf == None: return @@ -432,7 +432,7 @@ def _op_intern(pool: rawptr[memhub.MemManager], name: str, op_id: int): _op_head = entry -def _init_operators(pool: rawptr[memhub.MemManager]): +def _init_operators(pool: memhub.MemManager*): """Initialize the operator table (register in descending length order for easy greedy matching)""" global _op_head if _op_head != None: return @@ -488,7 +488,7 @@ def _init_operators(pool: rawptr[memhub.MemManager]): _op_intern(pool, "~", TokOp.Tilde) -def _init_tables(pool: rawptr[memhub.MemManager]): +def _init_tables(pool: memhub.MemManager*): """Initialize all lookup tables (idempotent)""" _init_keywords(pool) _init_operators(pool) @@ -498,10 +498,10 @@ def _init_tables(pool: rawptr[memhub.MemManager]): # Token creation helper functions # ============================================================ -def new_token(pool: rawptr[memhub.MemManager], ttype: int, lineno: int, - col_offset: int) -> rawptr[Token]: +def new_token(pool: memhub.MemManager*, ttype: int, lineno: int, + col_offset: int) -> Token*: """Create a new empty Token and fill in fields later""" - tok: rawptr[Token] = Token(pool) + tok: Token* = Token(pool) if tok == None: return None tok.type = ttype tok.lineno = lineno @@ -511,7 +511,7 @@ def new_token(pool: rawptr[memhub.MemManager], ttype: int, lineno: int, return tok -def token_set_str(pool: rawptr[memhub.MemManager], tok: rawptr[Token], +def token_set_str(pool: memhub.MemManager*, tok: Token*, src: str, start: sizet, length: sizet): """Copy text from src[start:start + length] to token.str_val @@ -527,7 +527,7 @@ def token_set_str(pool: rawptr[memhub.MemManager], tok: rawptr[Token], tok.str_val = buf -def token_set_str_literal(pool: rawptr[memhub.MemManager], tok: rawptr[Token], +def token_set_str_literal(pool: memhub.MemManager*, tok: Token*, text: str): """Copy a C string to token.str_val""" if tok == None or text == None: return diff --git a/hashlib/__md5.vp b/hashlib/__md5.vp index 4cef426..8e7bba9 100644 --- a/hashlib/__md5.vp +++ b/hashlib/__md5.vp @@ -48,7 +48,7 @@ class md5: def __init__(self): string.memset(self.buf, 0, MD5_BLOCK_LEN) # MD5 single-group compression transform - def transform(self, block: rawptr[uint8]): + def transform(self, block: uint8*): a: uint32 = self.state[0] b: uint32 = self.state[1] c: uint32 = self.state[2] diff --git a/hashlib/__sha1.vp b/hashlib/__sha1.vp index 5a5ee37..e2d0919 100644 --- a/hashlib/__sha1.vp +++ b/hashlib/__sha1.vp @@ -27,9 +27,9 @@ class sha1: def __init__(self): string.memset(self.buf, 0, SHA1_BLOCK_LEN) # Single-group compression transform - def transform(self, block: rawptr[uint8]): + def transform(self, block: uint8*): w: [80]uint32 - data: rawptr[uint8] = block + data: uint8* = block # First 16 words for i in range(16): w[i] = (((uint32(data[i * 4 + 0])) << 24) | diff --git a/hashlib/__sha256.vp b/hashlib/__sha256.vp index 8ca3d3d..7b1f8e2 100644 --- a/hashlib/__sha256.vp +++ b/hashlib/__sha256.vp @@ -42,7 +42,7 @@ class sha256: string.memset(self, 0, sha256.__sizeof__()) # string.memset(self.buf, 0, SHA256_BLOCK_LEN) # SHA256 single-group compression transform - def transform(self, block: rawptr[uint8]): + def transform(self, block: uint8*): w: [64]uint32 for i in range(16): w[i] = ((uint32(block[i * 4 + 0]) << 24) | diff --git a/json/__init__.vp b/json/__init__.vp index 1c6f205..b4db1ca 100644 --- a/json/__init__.vp +++ b/json/__init__.vp @@ -31,7 +31,7 @@ class JsonValue: child: 'JsonValue' | t.CPtr child_count: sizet - def __new__(self, pool: rawptr[memhub.MemManager]): + def __new__(self, pool: memhub.MemManager*): """Allocate and zero-initialize a JsonValue struct from mpool.""" ptr: JsonValue* = pool.alloc(JsonValue.__sizeof__()) if ptr: @@ -148,34 +148,34 @@ class JsonValue: # Constructors: create each kind of JsonValue (allocated from mpool) # ============================================================ -def null(pool: rawptr[memhub.MemManager]) -> JsonValue*: +def null(pool: memhub.MemManager*) -> JsonValue*: v: JsonValue* = JsonValue(pool) if v == None: return None v.vtype = JSON_NULL return v -def bool_val(pool: rawptr[memhub.MemManager], val: bool) -> JsonValue*: +def bool_val(pool: memhub.MemManager*, val: bool) -> JsonValue*: v: JsonValue* = JsonValue(pool) if v == None: return None v.vtype = JSON_BOOL v.bool_val = 1 if val else 0 return v -def int_val(pool: rawptr[memhub.MemManager], val: int64) -> JsonValue*: +def int_val(pool: memhub.MemManager*, val: int64) -> JsonValue*: v: JsonValue* = JsonValue(pool) if v == None: return None v.vtype = JSON_INT v.int_val = val return v -def float_val(pool: rawptr[memhub.MemManager], val: double) -> JsonValue*: +def float_val(pool: memhub.MemManager*, val: double) -> JsonValue*: v: JsonValue* = JsonValue(pool) if v == None: return None v.vtype = JSON_FLOAT v.float_val = val return v -def string_val(pool: rawptr[memhub.MemManager], val: str) -> JsonValue*: +def string_val(pool: memhub.MemManager*, val: str) -> JsonValue*: v: JsonValue* = JsonValue(pool) if v == None: return None v.vtype = JSON_STRING @@ -187,26 +187,26 @@ def string_val(pool: rawptr[memhub.MemManager], val: str) -> JsonValue*: v.str_val = buf return v -def array(pool: rawptr[memhub.MemManager]) -> JsonValue*: +def array(pool: memhub.MemManager*) -> JsonValue*: v: JsonValue* = JsonValue(pool) if v == None: return None v.vtype = JSON_ARRAY return v -def object(pool: rawptr[memhub.MemManager]) -> JsonValue*: +def object(pool: memhub.MemManager*) -> JsonValue*: v: JsonValue* = JsonValue(pool) if v == None: return None v.vtype = JSON_OBJECT return v # Append an element to an array -def array_append(pool: rawptr[memhub.MemManager], arr: JsonValue*, item: JsonValue*): +def array_append(pool: memhub.MemManager*, arr: JsonValue*, item: JsonValue*): if arr == None or item == None: return if arr.vtype != JSON_ARRAY: return arr._append_child(item) # Set a key/value pair on an object -def object_set(pool: rawptr[memhub.MemManager], obj: JsonValue*, key: str, val: JsonValue*): +def object_set(pool: memhub.MemManager*, obj: JsonValue*, key: str, val: JsonValue*): if obj == None or key == None or val == None: return if obj.vtype != JSON_OBJECT: return cur: JsonValue* = obj.child diff --git a/json/__parser.vp b/json/__parser.vp index e63a870..f6dd804 100644 --- a/json/__parser.vp +++ b/json/__parser.vp @@ -13,25 +13,25 @@ class ParseState: src: str pos: sizet = 0 len: sizet = 0 - pool: rawptr[memhub.MemManager] + pool: memhub.MemManager* - def __init__(self, src: str, pool: rawptr[memhub.MemManager]): + def __init__(self, src: str, pool: memhub.MemManager*): self.src = src self.len = string.strlen(src) if src != None else 0 self.pool = pool -def _peek(s: rawptr[ParseState]) -> char: +def _peek(s: ParseState*) -> char: if s.pos >= s.len: return '\0' return s.src[s.pos] -def _advance(s: rawptr[ParseState]) -> char: +def _advance(s: ParseState*) -> char: if s.pos >= s.len: return '\0' ch: char = s.src[s.pos] s.pos += 1 return ch -def _skip_whitespace(s: rawptr[ParseState]): +def _skip_whitespace(s: ParseState*): while s.pos < s.len: ch: char = s.src[s.pos] if ch == ' ' or ch == '\t' or ch == '\n' or ch == '\r': @@ -39,7 +39,7 @@ def _skip_whitespace(s: rawptr[ParseState]): else: break -def _expect(s: rawptr[ParseState], ch: char) -> bool: +def _expect(s: ParseState*, ch: char) -> bool: _skip_whitespace(s) if s.pos >= s.len: return False if s.src[s.pos] != ch: return False @@ -47,7 +47,7 @@ def _expect(s: rawptr[ParseState], ch: char) -> bool: return True -def _parse_string(s: rawptr[ParseState]) -> str: +def _parse_string(s: ParseState*) -> str: if _peek(s) != '"': return None _advance(s) @@ -103,7 +103,7 @@ def _parse_string(s: rawptr[ParseState]) -> str: return buf -def _parse_number(s: rawptr[ParseState]) -> rawptr[JsonValue]: +def _parse_number(s: ParseState*) -> JsonValue*: _skip_whitespace(s) is_float: bool = False start: sizet = s.pos @@ -157,7 +157,7 @@ def _parse_number(s: rawptr[ParseState]) -> rawptr[JsonValue]: return int_val(s.pool, ival) -def _parse_value(s: rawptr[ParseState]) -> rawptr[JsonValue]: +def _parse_value(s: ParseState*) -> JsonValue*: _skip_whitespace(s) if s.pos >= s.len: return null(s.pool) @@ -201,11 +201,11 @@ def _parse_value(s: rawptr[ParseState]) -> rawptr[JsonValue]: return null(s.pool) -def _parse_array(s: rawptr[ParseState]) -> rawptr[JsonValue]: +def _parse_array(s: ParseState*) -> JsonValue*: if not _expect(s, '['): return null(s.pool) - arr: rawptr[JsonValue] = array(s.pool) + arr: JsonValue* = array(s.pool) # Pool exhausted => array() returns None; continuing to arr._append_child(...) would deref # a null pointer, so return None here (json.parse may return None; callers must check). if arr == None: @@ -216,7 +216,7 @@ def _parse_array(s: rawptr[ParseState]) -> rawptr[JsonValue]: _advance(s) return arr - item: rawptr[JsonValue] = _parse_value(s) + item: JsonValue* = _parse_value(s) # item == None iff allocation failed somewhere inside _parse_value (syntax errors yield # a valid JSON_NULL node; only pool exhaustion yields None) => return None, append nothing. if item == None: @@ -239,11 +239,11 @@ def _parse_array(s: rawptr[ParseState]) -> rawptr[JsonValue]: return arr -def _parse_object(s: rawptr[ParseState]) -> rawptr[JsonValue]: +def _parse_object(s: ParseState*) -> JsonValue*: if not _expect(s, '{'): return null(s.pool) - obj: rawptr[JsonValue] = object(s.pool) + obj: JsonValue* = object(s.pool) # Same as _parse_array: obj is None on pool exhaustion; do not call _append_child on None. if obj == None: return null(s.pool) @@ -256,7 +256,7 @@ def _parse_object(s: rawptr[ParseState]) -> rawptr[JsonValue]: _skip_whitespace(s) key: str = _parse_string(s) _expect(s, ':') - val: rawptr[JsonValue] = _parse_value(s) + val: JsonValue* = _parse_value(s) if key != None and val != None: klen: sizet = string.strlen(key) kbuf: str = s.pool.alloc(klen + 1) @@ -288,9 +288,9 @@ def _parse_object(s: rawptr[ParseState]) -> rawptr[JsonValue]: return obj -def parse(pool: rawptr[memhub.MemManager], src: str) -> rawptr[JsonValue]: +def parse(pool: memhub.MemManager*, src: str) -> JsonValue*: """Parse a JSON string, returning a JsonValue tree.""" if src == None: return null(pool) - s: rawptr[ParseState] = ParseState(src, pool) + s: ParseState* = ParseState(src, pool) return _parse_value(s) diff --git a/json/__writer.vp b/json/__writer.vp index 9a29718..efa6fbb 100644 --- a/json/__writer.vp +++ b/json/__writer.vp @@ -71,8 +71,8 @@ def _write_string_escaped(buf: str, pos: sizet, cap: sizet, s: str) -> sizet: return pos -def _write_value(buf: str, pos: sizet, cap: sizet, val: rawptr[JsonValue], - pool: rawptr[memhub.MemManager]) -> sizet: +def _write_value(buf: str, pos: sizet, cap: sizet, val: JsonValue*, + pool: memhub.MemManager*) -> sizet: if pos >= cap: return pos # already overflowed: stop writing (recursion converges here) if val == None: @@ -108,7 +108,7 @@ def _write_value(buf: str, pos: sizet, cap: sizet, val: rawptr[JsonValue], pos = _write_str(buf, pos, cap, "[]") return pos pos = _write_char(buf, pos, cap, '[') - cur: rawptr[JsonValue] = val.child + cur: JsonValue* = val.child first: bool = True while cur != None: if pos >= cap: @@ -125,7 +125,7 @@ def _write_value(buf: str, pos: sizet, cap: sizet, val: rawptr[JsonValue], pos = _write_str(buf, pos, cap, "{}") return pos pos = _write_char(buf, pos, cap, '{') - cur2: rawptr[JsonValue] = val.child + cur2: JsonValue* = val.child first2: bool = True while cur2 != None: if pos >= cap: @@ -144,7 +144,7 @@ def _write_value(buf: str, pos: sizet, cap: sizet, val: rawptr[JsonValue], # Serialize to a JSON string. cap = output buffer size (bytes, incl trailing NUL), default 4096. # Returns None when content does not fit (never writes past the buffer). -def write(pool: rawptr[memhub.MemManager], val: rawptr[JsonValue], pretty: bool, +def write(pool: memhub.MemManager*, val: JsonValue*, pretty: bool, cap: sizet = 4096) -> str: """Serialize a JsonValue into a JSON string.""" if cap < 2: diff --git a/memhub.vp b/memhub.vp index 5be2014..82d28af 100644 --- a/memhub.vp +++ b/memhub.vp @@ -453,7 +453,7 @@ def NewMemPool(base: rawptr, size: sizet) -> MemPool*: # detection) and then calls the existing virtual alloc => no new virtual function, no vtable change, # no contract change; for a MemBuddy pool its alloc_tagged is also available (that one additionally # records a record-table tag for [FREEFRAME] reports). -def MemAllocTagged(pool: rawptr[MemManager], size: sizet, tag: sizet) -> rawptr: +def MemAllocTagged(pool: MemManager*, size: sizet, tag: sizet) -> rawptr: if pool is None: return None prev: uint64 = _alloc_site_enter(uint64(tag)) diff --git a/mlirlite/__builder.vp b/mlirlite/__builder.vp index c0f2167..fa05dad 100644 --- a/mlirlite/__builder.vp +++ b/mlirlite/__builder.vp @@ -48,8 +48,8 @@ _LINE_CAP: sizet = 2560 novirtual class IRBuilder: Pool: memhub.MemBuddy* # Memory pool - Func: rawptr[Function] # Owning function - CurBlock: rawptr[BasicBlock] # Current insertion point + Func: Function* # Owning function + CurBlock: BasicBlock* # Current insertion point Counter: int # SSA name counter DbgLoc: str # current DILocation ref (kept same-shaped; MLIR printing ignores it, no !dbg suffix) @@ -66,7 +66,7 @@ novirtual class IRBuilder: return buf - def _type_str(self, ty: rawptr[LLVMType]) -> str: + def _type_str(self, ty: LLVMType*) -> str: """Get the MLIR text of a type (allocates a _TY_TEXT_CAP-byte buffer from pool). MLIR type text inlines full struct bodies; overflow makes TypePrint fail-fast loudly. """ @@ -114,7 +114,7 @@ novirtual class IRBuilder: def _build_binop(self, op: str, - lhs: rawptr[Value], rhs: rawptr[Value]) -> rawptr[Value]: + lhs: Value*, rhs: Value*) -> Value*: """Shared implementation of binary operations""" if self is None or lhs is None or rhs is None: return None pool: memhub.MemBuddy* = self.Pool @@ -130,7 +130,7 @@ novirtual class IRBuilder: # ============================================================ # Block positioning # ============================================================ - def position_at_end(self, block: rawptr[BasicBlock]): + def position_at_end(self, block: BasicBlock*): """Set the insertion point to the end of block and move block to the end of the function's block list, keeping text order consistent with control-flow order (else non-monotonic SSA names break llc).""" @@ -151,7 +151,7 @@ novirtual class IRBuilder: # ============================================================ # Memory instructions # ============================================================ - def build_alloca(self, ty: rawptr[LLVMType]) -> rawptr[Value]: + def build_alloca(self, ty: LLVMType*) -> Value*: """%N = alloca Returns an SSA value of type ty* (default alignment, backend-decided). @@ -168,16 +168,16 @@ novirtual class IRBuilder: self._emit(line) # result type is ty* - result_ty: rawptr[LLVMType] = LLVMType.Ptr(ty) - result_ty_ptr: rawptr[LLVMType] = pool.alloc(LLVMType.__sizeof__()) + result_ty: LLVMType* = LLVMType.Ptr(ty) + result_ty_ptr: LLVMType* = pool.alloc(LLVMType.__sizeof__()) if result_ty_ptr is not None: string.memset(result_ty_ptr, 0, LLVMType.__sizeof__()) c.DerefAs(result_ty_ptr, result_ty) return SSAValue(pool, result_ty_ptr, name) - def build_alloca_aligned(self, ty: rawptr[LLVMType], - align: int) -> rawptr[Value]: + def build_alloca_aligned(self, ty: LLVMType*, + align: int) -> Value*: """%N = alloca , align N. Returns an SSA value of type ty* with explicit alignment (e.g. va_list 24-byte buffer needs 16). align has no default; callers must pass it.""" if self is None: return None @@ -190,24 +190,24 @@ novirtual class IRBuilder: self._emit(line) # result type is ty* - result_ty: rawptr[LLVMType] = LLVMType.Ptr(ty) - result_ty_ptr: rawptr[LLVMType] = pool.alloc(LLVMType.__sizeof__()) + result_ty: LLVMType* = LLVMType.Ptr(ty) + result_ty_ptr: LLVMType* = pool.alloc(LLVMType.__sizeof__()) if result_ty_ptr is not None: string.memset(result_ty_ptr, 0, LLVMType.__sizeof__()) c.DerefAs(result_ty_ptr, result_ty) return SSAValue(pool, result_ty_ptr, name) - def build_alloca_at_entry(self, ty: rawptr[LLVMType]) -> rawptr[Value]: + def build_alloca_at_entry(self, ty: LLVMType*) -> Value*: """%N = alloca , emitted in the function entry block to ensure dominance. Inserts before the entry terminator; alloca inside a conditional branch violates dominance.""" if self is None: return None pool: memhub.MemBuddy* = self.Pool - func: rawptr[Function] = self.Func + func: Function* = self.Func if func is None or func.Blocks is None: return self.build_alloca(ty) - blocks: rawptr[GSList[BasicBlock]] = func.Blocks - entry_blk: rawptr[BasicBlock] = blocks.Head + blocks: GSList[BasicBlock]* = func.Blocks + entry_blk: BasicBlock* = blocks.Head if entry_blk is None: return self.build_alloca(ty) name: str = self._alloc_ssa_name() @@ -219,17 +219,17 @@ novirtual class IRBuilder: # would put alloca after the terminator (invalid IR); insert-before-terminator handles both. block_insert_text_before_terminator(pool, entry_blk, line_text) # result type is ty* - result_ty: rawptr[LLVMType] = LLVMType.Ptr(ty) - result_ty_ptr: rawptr[LLVMType] = pool.alloc(LLVMType.__sizeof__()) + result_ty: LLVMType* = LLVMType.Ptr(ty) + result_ty_ptr: LLVMType* = pool.alloc(LLVMType.__sizeof__()) if result_ty_ptr is not None: string.memset(result_ty_ptr, 0, LLVMType.__sizeof__()) c.DerefAs(result_ty_ptr, result_ty) return SSAValue(pool, result_ty_ptr, name) - def build_load(self, ty: rawptr[LLVMType], - ptr: rawptr[Value], - is_volatile: int = 0) -> rawptr[Value]: + def build_load(self, ty: LLVMType*, + ptr: Value*, + is_volatile: int = 0) -> Value*: """%N = load [volatile ], is_volatile=0 (default) emits the plain form; =1 adds the volatile qualifier so the optimizer cannot hoist/merge the access (e.g. spinlocks).""" @@ -248,7 +248,7 @@ novirtual class IRBuilder: return SSAValue(pool, ty, name) - def build_store(self, val: rawptr[Value], ptr: rawptr[Value], + def build_store(self, val: Value*, ptr: Value*, is_volatile: int = 0): """store [volatile ] , is_volatile=0 (default) emits the plain form; =1 adds the volatile qualifier @@ -269,80 +269,80 @@ novirtual class IRBuilder: # ============================================================ # Binary operation instructions # ============================================================ - def build_add(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_add(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = add , """ return self._build_binop("add", lhs, rhs) - def build_sub(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_sub(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = sub , """ return self._build_binop("sub", lhs, rhs) - def build_mul(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_mul(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = mul , """ return self._build_binop("mul", lhs, rhs) - def build_sdiv(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_sdiv(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = sdiv , """ return self._build_binop("sdiv", lhs, rhs) - def build_udiv(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_udiv(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = udiv , """ return self._build_binop("udiv", lhs, rhs) - def build_srem(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_srem(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = srem , """ return self._build_binop("srem", lhs, rhs) - def build_urem(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_urem(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = urem , """ return self._build_binop("urem", lhs, rhs) - def build_and(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_and(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = and , """ return self._build_binop("and", lhs, rhs) - def build_or(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_or(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = or , """ return self._build_binop("or", lhs, rhs) - def build_xor(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_xor(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = xor , """ return self._build_binop("xor", lhs, rhs) - def build_shl(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_shl(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = shl , """ return self._build_binop("shl", lhs, rhs) - def build_lshr(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_lshr(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = lshr , """ return self._build_binop("lshr", lhs, rhs) - def build_ashr(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_ashr(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = ashr , """ return self._build_binop("ashr", lhs, rhs) @@ -350,37 +350,37 @@ novirtual class IRBuilder: # ============================================================ # Float binary operation instructions # ============================================================ - def build_fadd(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_fadd(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = fadd , """ return self._build_binop("fadd", lhs, rhs) - def build_fsub(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_fsub(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = fsub , """ return self._build_binop("fsub", lhs, rhs) - def build_fmul(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_fmul(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = fmul , """ return self._build_binop("fmul", lhs, rhs) - def build_fdiv(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_fdiv(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = fdiv , """ return self._build_binop("fdiv", lhs, rhs) - def build_frem(self, lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: + def build_frem(self, lhs: Value*, + rhs: Value*) -> Value*: """%N = frem , """ return self._build_binop("frem", lhs, rhs) - def build_fneg(self, val: rawptr[Value]) -> rawptr[Value]: + def build_fneg(self, val: Value*) -> Value*: """%N = fneg """ if self is None or val is None: return None pool: memhub.MemBuddy* = self.Pool @@ -397,7 +397,7 @@ novirtual class IRBuilder: # Comparison instructions # ============================================================ def build_icmp(self, pred: int, - lhs: rawptr[Value], rhs: rawptr[Value]) -> rawptr[Value]: + lhs: Value*, rhs: Value*) -> Value*: """%N = icmp , Returns an SSA value of type i1.""" if self is None or lhs is None or rhs is None: return None @@ -411,7 +411,7 @@ novirtual class IRBuilder: self._emit(line) # result type is i1 - i1_ty: rawptr[LLVMType] = pool.alloc(LLVMType.__sizeof__()) + i1_ty: LLVMType* = pool.alloc(LLVMType.__sizeof__()) if i1_ty is not None: string.memset(i1_ty, 0, LLVMType.__sizeof__()) c.DerefAs(i1_ty, LLVMType.Int(1)) @@ -419,7 +419,7 @@ novirtual class IRBuilder: def build_fcmp(self, pred: int, - lhs: rawptr[Value], rhs: rawptr[Value]) -> rawptr[Value]: + lhs: Value*, rhs: Value*) -> Value*: """%N = fcmp , Returns an SSA value of type i1.""" if self is None or lhs is None or rhs is None: return None @@ -433,7 +433,7 @@ novirtual class IRBuilder: self._emit(line) # result type is i1 - i1_ty: rawptr[LLVMType] = pool.alloc(LLVMType.__sizeof__()) + i1_ty: LLVMType* = pool.alloc(LLVMType.__sizeof__()) if i1_ty is not None: string.memset(i1_ty, 0, LLVMType.__sizeof__()) c.DerefAs(i1_ty, LLVMType.Int(1)) @@ -443,7 +443,7 @@ novirtual class IRBuilder: # ============================================================ # Terminator instructions # ============================================================ - def build_br(self, target: rawptr[BasicBlock]): + def build_br(self, target: BasicBlock*): """br label %""" if self is None or target is None: return pool: memhub.MemBuddy* = self.Pool @@ -454,8 +454,8 @@ novirtual class IRBuilder: self._mark_terminated() - def build_cond_br(self, cond: rawptr[Value], - then_blk: rawptr[BasicBlock], else_blk: rawptr[BasicBlock]): + def build_cond_br(self, cond: Value*, + then_blk: BasicBlock*, else_blk: BasicBlock*): """br i1 , label %, label %""" if self is None or cond is None or then_blk is None or else_blk is None: return pool: memhub.MemBuddy* = self.Pool @@ -467,7 +467,7 @@ novirtual class IRBuilder: self._mark_terminated() - def build_ret(self, val: rawptr[Value]): + def build_ret(self, val: Value*): """ret """ if self is None or val is None: return pool: memhub.MemBuddy* = self.Pool @@ -494,9 +494,9 @@ novirtual class IRBuilder: # Call instructions # ============================================================ def build_call(self, callee: str, - args: rawptr[Value], arg_count: int, - ret_ty: rawptr[LLVMType], - is_variadic: int = 0) -> rawptr[Value]: + args: Value*, arg_count: int, + ret_ty: LLVMType*, + is_variadic: int = 0) -> Value*: """%N = call @() args is the Value list head, arg_count the argument count. If ret_ty is void no SSA name is allocated (plain call); is_variadic=1 emits the function type signature (e.g. i32 (i8*, ...)).""" @@ -530,7 +530,7 @@ novirtual class IRBuilder: func_ty_buf: str = pool.alloc(arg_cap) if func_ty_buf is None: return None func_ty_buf[0] = '\0' - cur: rawptr[Value] = args + cur: Value* = args first: int = 1 while cur is not None: if first == 0: @@ -586,9 +586,9 @@ novirtual class IRBuilder: # # callee_val is a function-pointer SSA value (must already be a pointer type, e.g. i32(i8*)*) # ============================================================ - def build_call_indirect(self, callee_val: rawptr[Value], - args: rawptr[Value], arg_count: int, - ret_ty: rawptr[LLVMType]) -> rawptr[Value]: + def build_call_indirect(self, callee_val: Value*, + args: Value*, arg_count: int, + ret_ty: LLVMType*) -> Value*: """%N = call %callee() Indirect call: callee_val is a function-pointer SSA value.""" if self is None or callee_val is None: return None @@ -612,7 +612,7 @@ novirtual class IRBuilder: args_buf: str = pool.alloc(arg_cap2) if args_buf is None: return None args_buf[0] = '\0' - cur: rawptr[Value] = args + cur: Value* = args first: int = 1 while cur is not None: if first == 0: @@ -643,8 +643,8 @@ novirtual class IRBuilder: # ============================================================ # Type conversion instructions # ============================================================ - def build_bitcast(self, val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: + def build_bitcast(self, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = bitcast to """ if self is None or val is None: return None @@ -658,12 +658,12 @@ novirtual class IRBuilder: return None viperlib.snprintf(line, _LINE_CAP, "%s = bitcast %s %s to %s", name, from_ty_s, val.Name, to_ty_s) self._emit(line) - ret: rawptr[Value] = SSAValue(pool, to_ty, name) + ret: Value* = SSAValue(pool, to_ty, name) return ret - def build_sext(self, val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: + def build_sext(self, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = sext to """ if self is None or val is None: return None pool: memhub.MemBuddy* = self.Pool @@ -677,8 +677,8 @@ novirtual class IRBuilder: return SSAValue(pool, to_ty, name) - def build_trunc(self, val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: + def build_trunc(self, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = trunc to """ if self is None or val is None: return None pool: memhub.MemBuddy* = self.Pool @@ -692,8 +692,8 @@ novirtual class IRBuilder: return SSAValue(pool, to_ty, name) - def build_zext(self, val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: + def build_zext(self, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = zext to """ if self is None or val is None: return None pool: memhub.MemBuddy* = self.Pool @@ -707,8 +707,8 @@ novirtual class IRBuilder: return SSAValue(pool, to_ty, name) - def build_ptrtoint(self, val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: + def build_ptrtoint(self, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = ptrtoint to """ if self is None or val is None: return None pool: memhub.MemBuddy* = self.Pool @@ -722,8 +722,8 @@ novirtual class IRBuilder: return SSAValue(pool, to_ty, name) - def build_inttoptr(self, val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: + def build_inttoptr(self, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = inttoptr to """ if self is None or val is None: return None pool: memhub.MemBuddy* = self.Pool @@ -740,8 +740,8 @@ novirtual class IRBuilder: # ============================================================ # Float conversion instructions # ============================================================ - def build_fpext(self, val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: + def build_fpext(self, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = fpext to """ if self is None or val is None: return None pool: memhub.MemBuddy* = self.Pool @@ -755,8 +755,8 @@ novirtual class IRBuilder: return SSAValue(pool, to_ty, name) - def build_fptrunc(self, val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: + def build_fptrunc(self, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = fptrunc to """ if self is None or val is None: return None pool: memhub.MemBuddy* = self.Pool @@ -770,8 +770,8 @@ novirtual class IRBuilder: return SSAValue(pool, to_ty, name) - def build_fp2si(self, val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: + def build_fp2si(self, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = fptosi to """ if self is None or val is None: return None pool: memhub.MemBuddy* = self.Pool @@ -785,8 +785,8 @@ novirtual class IRBuilder: return SSAValue(pool, to_ty, name) - def build_si2fp(self, val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: + def build_si2fp(self, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = sitofp to """ if self is None or val is None: return None pool: memhub.MemBuddy* = self.Pool @@ -800,8 +800,8 @@ novirtual class IRBuilder: return SSAValue(pool, to_ty, name) - def build_fp2ui(self, val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: + def build_fp2ui(self, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = fptoui to """ if self is None or val is None: return None pool: memhub.MemBuddy* = self.Pool @@ -815,8 +815,8 @@ novirtual class IRBuilder: return SSAValue(pool, to_ty, name) - def build_ui2fp(self, val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: + def build_ui2fp(self, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = uitofp to """ if self is None or val is None: return None pool: memhub.MemBuddy* = self.Pool @@ -836,7 +836,7 @@ novirtual class IRBuilder: # LLVM sign-extends narrow GEP indices (i8 0xE2 = -30); Viper indices are non-negative, so all # <32-bit indices are zext'd to i32. build_gep/build_gep_array handle this internally. # ============================================================ - def _gep_index_zext(self, idx: rawptr[Value]) -> rawptr[Value]: + def _gep_index_zext(self, idx: Value*) -> Value*: """Zero-extend a <32-bit integer index to i32; other types are returned unchanged""" if self is None or idx is None or idx.Ty is None: return idx @@ -848,20 +848,20 @@ novirtual class IRBuilder: bits = 0 if bits == 0 or bits >= 32: return idx - i32_ty: rawptr[LLVMType] = self.Pool.alloc(LLVMType.__sizeof__()) + i32_ty: LLVMType* = self.Pool.alloc(LLVMType.__sizeof__()) if i32_ty is None: return idx string.memset(i32_ty, 0, LLVMType.__sizeof__()) c.DerefAs(i32_ty, LLVMType.Int(32)) - z: rawptr[Value] = self.build_zext(idx, i32_ty) + z: Value* = self.build_zext(idx, i32_ty) return z if z is not None else idx # ============================================================ # GEP instructions # ============================================================ - def build_gep(self, elem_ty: rawptr[LLVMType], - ptr: rawptr[Value], idx: rawptr[Value]) -> rawptr[Value]: + def build_gep(self, elem_ty: LLVMType*, + ptr: Value*, idx: Value*) -> Value*: """%N = getelementptr , , """ if self is None or ptr is None or idx is None: return None # Defensive check: ptr.Ty must be a pointer type, else llc errors ("base of getelementptr @@ -881,7 +881,7 @@ novirtual class IRBuilder: self._emit(line) # GEP result type is elem_ty* - result_ty: rawptr[LLVMType] = pool.alloc(LLVMType.__sizeof__()) + result_ty: LLVMType* = pool.alloc(LLVMType.__sizeof__()) if result_ty is not None: string.memset(result_ty, 0, LLVMType.__sizeof__()) c.DerefAs(result_ty, LLVMType.Ptr(elem_ty)) @@ -891,9 +891,9 @@ novirtual class IRBuilder: # ============================================================ # build_gep_array - two-index array GEP: getelementptr [N x ty], [N x ty]* %ptr, i32 0, i32 %idx # ============================================================ - def build_gep_array(self, array_ty: rawptr[LLVMType], - elem_ty: rawptr[LLVMType], - ptr: rawptr[Value], idx: rawptr[Value]) -> rawptr[Value]: + def build_gep_array(self, array_ty: LLVMType*, + elem_ty: LLVMType*, + ptr: Value*, idx: Value*) -> Value*: """%N = getelementptr [N x elem_ty], [N x elem_ty]* %ptr, i32 0, i32 %idx Result type is elem_ty*.""" if self is None or ptr is None or idx is None: return None @@ -910,7 +910,7 @@ novirtual class IRBuilder: self._emit(line) # GEP result type is elem_ty* - result_ty: rawptr[LLVMType] = pool.alloc(LLVMType.__sizeof__()) + result_ty: LLVMType* = pool.alloc(LLVMType.__sizeof__()) if result_ty is not None: string.memset(result_ty, 0, LLVMType.__sizeof__()) c.DerefAs(result_ty, LLVMType.Ptr(elem_ty)) @@ -920,9 +920,9 @@ novirtual class IRBuilder: # ============================================================ # build_gep_struct - struct-field GEP: getelementptr struct_ty, struct_ty* %ptr, i32 0, i32 %field_idx # ============================================================ - def build_gep_struct(self, struct_ty: rawptr[LLVMType], - field_ty: rawptr[LLVMType], - ptr: rawptr[Value], field_idx: int) -> rawptr[Value]: + def build_gep_struct(self, struct_ty: LLVMType*, + field_ty: LLVMType*, + ptr: Value*, field_idx: int) -> Value*: """%N = getelementptr struct_ty, struct_ty* %ptr, i32 0, i32 %field_idx Result type is field_ty*.""" if self is None or ptr is None: return None @@ -939,13 +939,13 @@ novirtual class IRBuilder: self._emit(line) # GEP result type is field_ty* - result_ty: rawptr[LLVMType] = pool.alloc(LLVMType.__sizeof__()) + result_ty: LLVMType* = pool.alloc(LLVMType.__sizeof__()) if result_ty is None: stdio.printf("[BGS] result_ty alloc None\n") else: string.memset(result_ty, 0, LLVMType.__sizeof__()) c.DerefAs(result_ty, LLVMType.Ptr(field_ty)) - rv: rawptr[Value] = SSAValue(pool, result_ty, name) + rv: Value* = SSAValue(pool, result_ty, name) if rv is None: stdio.printf("[BGS] SSAValue None\n") return rv @@ -954,8 +954,8 @@ novirtual class IRBuilder: # ============================================================ # Phi instruction # ============================================================ - def build_phi(self, ty: rawptr[LLVMType], - incoming_head: rawptr[PhiIncoming], count: int) -> rawptr[Value]: + def build_phi(self, ty: LLVMType*, + incoming_head: PhiIncoming*, count: int) -> Value*: """%N = phi [val1, %blk1], [val2, %blk2], ... incoming_head is the PhiIncoming list head; count is the incoming-edge count.""" if self is None: return None @@ -968,20 +968,20 @@ novirtual class IRBuilder: parts: str = pool.alloc(4096) if parts is None: return None parts[0] = '\0' - cur: rawptr[PhiIncoming] = incoming_head + cur: PhiIncoming* = incoming_head first: int = 1 while cur is not None: if first == 0: _append_cstr(parts, 4096, ", ") _append_cstr(parts, 4096, "[") # use an intermediate var; chained struct member access would be dropped by the compiler - inc_val: rawptr[Value] = cur.Val + inc_val: Value* = cur.Val if inc_val is not None: inc_val_name: str = inc_val.Name if inc_val_name is not None: _append_cstr(parts, 4096, inc_val_name) _append_cstr(parts, 4096, ", %") - inc_blk: rawptr[BasicBlock] = cur.Block + inc_blk: BasicBlock* = cur.Block if inc_blk is not None: inc_blk_name: str = inc_blk.Name if inc_blk_name is not None: @@ -1000,9 +1000,9 @@ novirtual class IRBuilder: # ============================================================ # Switch instruction # ============================================================ - def build_switch(self, val: rawptr[Value], - default_blk: rawptr[BasicBlock], - cases_head: rawptr[SwitchCase], case_count: int): + def build_switch(self, val: Value*, + default_blk: BasicBlock*, + cases_head: SwitchCase*, case_count: int): """switch , label % [, label % ...]""" if self is None or val is None or default_blk is None: return pool: memhub.MemBuddy* = self.Pool @@ -1017,14 +1017,14 @@ novirtual class IRBuilder: _append_cstr(line, _LINE_CAP, "\n") # iterate the case list - cur: rawptr[SwitchCase] = cases_head + cur: SwitchCase* = cases_head case_ty_s: str = self._type_str(val.Ty) while cur is not None: case_line: str = pool.alloc(_LINE_CAP) if case_line is not None: # use an intermediate var; chained struct member access would be dropped by the compiler - cv: rawptr[Value] = cur.CaseVal - cb: rawptr[BasicBlock] = cur.Block + cv: Value* = cur.CaseVal + cb: BasicBlock* = cur.Block if cv is not None and cb is not None: cv_name: str = cv.Name cb_name: str = cb.Name @@ -1042,8 +1042,8 @@ novirtual class IRBuilder: # ============================================================ # Select instruction # ============================================================ - def build_select(self, cond: rawptr[Value], - true_val: rawptr[Value], false_val: rawptr[Value]) -> rawptr[Value]: + def build_select(self, cond: Value*, + true_val: Value*, false_val: Value*) -> Value*: """%N = select i1 , , """ if self is None or cond is None or true_val is None or false_val is None: return None pool: memhub.MemBuddy* = self.Pool @@ -1075,8 +1075,8 @@ novirtual class IRBuilder: # Atomic instructions (Phase 3) # ============================================================ def build_atomicrmw(self, op: int, - ptr: rawptr[Value], val: rawptr[Value], - order: int) -> rawptr[Value]: + ptr: Value*, val: Value*, + order: int) -> Value*: """%N = atomicrmw , """ if self is None or ptr is None or val is None: return None pool: memhub.MemBuddy* = self.Pool @@ -1093,9 +1093,9 @@ novirtual class IRBuilder: return SSAValue(pool, val.Ty, name) - def build_cmpxchg(self, ptr: rawptr[Value], - cmp_val: rawptr[Value], new_val: rawptr[Value], - succ_order: int, fail_order: int) -> rawptr[Value]: + def build_cmpxchg(self, ptr: Value*, + cmp_val: Value*, new_val: Value*, + succ_order: int, fail_order: int) -> Value*: """%N = cmpxchg , , Returns a {, i1} SSA value (simplified to an i64 representing the pair).""" if self is None or ptr is None or cmp_val is None or new_val is None: return None @@ -1120,8 +1120,8 @@ novirtual class IRBuilder: # va_arg instruction: read the next variadic argument from va_list # ============================================================ def build_va_arg(self, - va_list_ptr: rawptr[Value], - arg_ty: rawptr[LLVMType]) -> rawptr[Value]: + va_list_ptr: Value*, + arg_ty: LLVMType*) -> Value*: """%N = va_arg , """ if self is None or va_list_ptr is None or arg_ty is None: return None @@ -1142,9 +1142,9 @@ novirtual class IRBuilder: # ============================================================ # Inline assembly (Phase 3) # ============================================================ - def build_inline_asm(self, ret_ty: rawptr[LLVMType], + def build_inline_asm(self, ret_ty: LLVMType*, asm_text: str, constraints: str, - has_side_effects: int) -> rawptr[Value]: + has_side_effects: int) -> Value*: """%N = call asm [sideeffect] "" ""() Simplified inline-assembly call, no-argument version.""" if self is None: return None @@ -1193,9 +1193,9 @@ novirtual class IRBuilder: # IRBuilder hardcoded size: Pool(8) + Func(8) + CurBlock(8) + Counter(4) + DbgLoc(8) = 40 bytes (same layout as llvmlite) define BUILDER_SIZE = 40 -def new_builder(pool: memhub.MemBuddy*, func: rawptr[Function]) -> rawptr[IRBuilder]: +def new_builder(pool: memhub.MemBuddy*, func: Function*) -> IRBuilder*: """Create an IRBuilder associated with function func.""" - ptr: rawptr[IRBuilder] = pool.alloc(BUILDER_SIZE) + ptr: IRBuilder* = pool.alloc(BUILDER_SIZE) if ptr is None: return None string.memset(ptr, 0, BUILDER_SIZE) ptr.Pool = pool @@ -1209,7 +1209,7 @@ def new_builder(pool: memhub.MemBuddy*, func: rawptr[Function]) -> rawptr[IRBuil # ============================================================ # Block positioning # ============================================================ -def position_at_end(builder: rawptr[IRBuilder], block: rawptr[BasicBlock]): +def position_at_end(builder: IRBuilder*, block: BasicBlock*): """Set the insertion point to the end of block and move block to the end of the function's block list, keeping text order consistent with control-flow order (else non-monotonic SSA names break llc).""" @@ -1219,28 +1219,28 @@ def position_at_end(builder: rawptr[IRBuilder], block: rawptr[BasicBlock]): # ============================================================ # Internal helpers # ============================================================ -def _alloc_ssa_name(builder: rawptr[IRBuilder]) -> str: +def _alloc_ssa_name(builder: IRBuilder*) -> str: """Allocate an SSA name string "%N" and increment the counter""" return builder._alloc_ssa_name() -def _type_str(builder: rawptr[IRBuilder], ty: rawptr[LLVMType]) -> str: +def _type_str(builder: IRBuilder*, ty: LLVMType*) -> str: """Get the IR text of a type (allocates a buffer from pool). Complex struct types (e.g. a 13-method vtable) can exceed 64 bytes; too small a buffer truncates '}' and breaks the IR.""" return builder._type_str(ty) -def _emit(builder: rawptr[IRBuilder], text: str): +def _emit(builder: IRBuilder*, text: str): """Append instruction text to the current block.""" builder._emit(text) -def _mark_terminated(builder: rawptr[IRBuilder]): +def _mark_terminated(builder: IRBuilder*): """Mark the current block as terminated""" builder._mark_terminated() -def builder_cur_block_is_terminated(builder: rawptr[IRBuilder]) -> int: +def builder_cur_block_is_terminated(builder: IRBuilder*) -> int: """Check the current block's IsTerminated flag via block_get_terminated instead of the chained builder.CurBlock.IsTerminated, which silently skips the GEP when BasicBlock is opaque.""" return builder.builder_cur_block_is_terminated() @@ -1249,12 +1249,12 @@ def builder_cur_block_is_terminated(builder: rawptr[IRBuilder]) -> int: # ============================================================ # Debug location (kept same-shaped; ignored by MLIR printing) # ============================================================ -def builder_set_debug_location(builder: rawptr[IRBuilder], ref: str): +def builder_set_debug_location(builder: IRBuilder*, ref: str): """Set the current DILocation ref (kept same-shaped; MLIR only records it, no output effect)""" builder.set_debug_location(ref) -def builder_clear_debug_location(builder: rawptr[IRBuilder]): +def builder_clear_debug_location(builder: IRBuilder*): """Clear the current DILocation ref (kept same-shaped; MLIR only records it)""" builder.clear_debug_location() @@ -1262,7 +1262,7 @@ def builder_clear_debug_location(builder: rawptr[IRBuilder]): # ============================================================ # Memory instructions # ============================================================ -def build_alloca(builder: rawptr[IRBuilder], ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_alloca(builder: IRBuilder*, ty: LLVMType*) -> Value*: """%N = alloca Returns an SSA value of type ty* (default alignment, backend-decided). @@ -1272,27 +1272,27 @@ def build_alloca(builder: rawptr[IRBuilder], ty: rawptr[LLVMType]) -> rawptr[Val return builder.build_alloca(ty) -def build_alloca_aligned(builder: rawptr[IRBuilder], ty: rawptr[LLVMType], - align: int) -> rawptr[Value]: +def build_alloca_aligned(builder: IRBuilder*, ty: LLVMType*, + align: int) -> Value*: """%N = alloca , align N. Returns an SSA value of type ty* with explicit alignment (e.g. va_list 24-byte buffer needs 16). align has no default; callers must pass it.""" return builder.build_alloca_aligned(ty, align) -def build_alloca_at_entry(builder: rawptr[IRBuilder], ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_alloca_at_entry(builder: IRBuilder*, ty: LLVMType*) -> Value*: """%N = alloca , emitted in the function entry block to ensure dominance. Inserts before the entry terminator; alloca inside a conditional branch violates dominance.""" return builder.build_alloca_at_entry(ty) -def build_load(builder: rawptr[IRBuilder], ty: rawptr[LLVMType], - ptr: rawptr[Value], - is_volatile: int = 0) -> rawptr[Value]: +def build_load(builder: IRBuilder*, ty: LLVMType*, + ptr: Value*, + is_volatile: int = 0) -> Value*: """%N = load [volatile ], """ return builder.build_load(ty, ptr, is_volatile) -def build_store(builder: rawptr[IRBuilder], val: rawptr[Value], ptr: rawptr[Value], +def build_store(builder: IRBuilder*, val: Value*, ptr: Value*, is_volatile: int = 0): """store [volatile ] , """ builder.build_store(val, ptr, is_volatile) @@ -1301,80 +1301,80 @@ def build_store(builder: rawptr[IRBuilder], val: rawptr[Value], ptr: rawptr[Valu # ============================================================ # Binary operation instructions # ============================================================ -def build_add(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_add(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = add , """ return builder.build_add(lhs, rhs) -def build_sub(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_sub(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = sub , """ return builder.build_sub(lhs, rhs) -def build_mul(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_mul(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = mul , """ return builder.build_mul(lhs, rhs) -def build_sdiv(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_sdiv(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = sdiv , """ return builder.build_sdiv(lhs, rhs) -def build_udiv(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_udiv(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = udiv , """ return builder.build_udiv(lhs, rhs) -def build_srem(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_srem(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = srem , """ return builder.build_srem(lhs, rhs) -def build_urem(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_urem(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = urem , """ return builder.build_urem(lhs, rhs) -def build_and(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_and(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = and , """ return builder.build_and(lhs, rhs) -def build_or(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_or(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = or , """ return builder.build_or(lhs, rhs) -def build_xor(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_xor(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = xor , """ return builder.build_xor(lhs, rhs) -def build_shl(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_shl(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = shl , """ return builder.build_shl(lhs, rhs) -def build_lshr(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_lshr(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = lshr , """ return builder.build_lshr(lhs, rhs) -def build_ashr(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_ashr(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = ashr , """ return builder.build_ashr(lhs, rhs) @@ -1382,43 +1382,43 @@ def build_ashr(builder: rawptr[IRBuilder], lhs: rawptr[Value], # ============================================================ # Float binary operation instructions # ============================================================ -def build_fadd(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_fadd(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = fadd , """ return builder.build_fadd(lhs, rhs) -def build_fsub(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_fsub(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = fsub , """ return builder.build_fsub(lhs, rhs) -def build_fmul(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_fmul(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = fmul , """ return builder.build_fmul(lhs, rhs) -def build_fdiv(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_fdiv(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = fdiv , """ return builder.build_fdiv(lhs, rhs) -def build_frem(builder: rawptr[IRBuilder], lhs: rawptr[Value], - rhs: rawptr[Value]) -> rawptr[Value]: +def build_frem(builder: IRBuilder*, lhs: Value*, + rhs: Value*) -> Value*: """%N = frem , """ return builder.build_frem(lhs, rhs) -def build_fneg(builder: rawptr[IRBuilder], val: rawptr[Value]) -> rawptr[Value]: +def build_fneg(builder: IRBuilder*, val: Value*) -> Value*: """%N = fneg """ return builder.build_fneg(val) -def _build_binop(builder: rawptr[IRBuilder], op: str, - lhs: rawptr[Value], rhs: rawptr[Value]) -> rawptr[Value]: +def _build_binop(builder: IRBuilder*, op: str, + lhs: Value*, rhs: Value*) -> Value*: """Shared implementation of binary operations""" return builder._build_binop(op, lhs, rhs) @@ -1491,15 +1491,15 @@ def _fcmp_pred_str(pred: int) -> str: return "oeq" -def build_icmp(builder: rawptr[IRBuilder], pred: int, - lhs: rawptr[Value], rhs: rawptr[Value]) -> rawptr[Value]: +def build_icmp(builder: IRBuilder*, pred: int, + lhs: Value*, rhs: Value*) -> Value*: """%N = icmp , Returns an SSA value of type i1.""" return builder.build_icmp(pred, lhs, rhs) -def build_fcmp(builder: rawptr[IRBuilder], pred: int, - lhs: rawptr[Value], rhs: rawptr[Value]) -> rawptr[Value]: +def build_fcmp(builder: IRBuilder*, pred: int, + lhs: Value*, rhs: Value*) -> Value*: """%N = fcmp , Returns an SSA value of type i1.""" return builder.build_fcmp(pred, lhs, rhs) @@ -1508,23 +1508,23 @@ def build_fcmp(builder: rawptr[IRBuilder], pred: int, # ============================================================ # Terminator instructions # ============================================================ -def build_br(builder: rawptr[IRBuilder], target: rawptr[BasicBlock]): +def build_br(builder: IRBuilder*, target: BasicBlock*): """br label %""" builder.build_br(target) -def build_cond_br(builder: rawptr[IRBuilder], cond: rawptr[Value], - then_blk: rawptr[BasicBlock], else_blk: rawptr[BasicBlock]): +def build_cond_br(builder: IRBuilder*, cond: Value*, + then_blk: BasicBlock*, else_blk: BasicBlock*): """br i1 , label %, label %""" builder.build_cond_br(cond, then_blk, else_blk) -def build_ret(builder: rawptr[IRBuilder], val: rawptr[Value]): +def build_ret(builder: IRBuilder*, val: Value*): """ret """ builder.build_ret(val) -def build_ret_void(builder: rawptr[IRBuilder]): +def build_ret_void(builder: IRBuilder*): """ret void""" builder.build_ret_void() @@ -1532,10 +1532,10 @@ def build_ret_void(builder: rawptr[IRBuilder]): # ============================================================ # Call instructions # ============================================================ -def build_call(builder: rawptr[IRBuilder], callee: str, - args: rawptr[Value], arg_count: int, - ret_ty: rawptr[LLVMType], - is_variadic: int = 0) -> rawptr[Value]: +def build_call(builder: IRBuilder*, callee: str, + args: Value*, arg_count: int, + ret_ty: LLVMType*, + is_variadic: int = 0) -> Value*: """%N = call @() args is the Value list head, arg_count the argument count. If ret_ty is void no SSA name is allocated (plain call); is_variadic=1 emits the function type signature (e.g. i32 (i8*, ...)).""" @@ -1547,9 +1547,9 @@ def build_call(builder: rawptr[IRBuilder], callee: str, # # callee_val is a function-pointer SSA value (must already be a pointer type, e.g. i32(i8*)*) # ============================================================ -def build_call_indirect(builder: rawptr[IRBuilder], callee_val: rawptr[Value], - args: rawptr[Value], arg_count: int, - ret_ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_call_indirect(builder: IRBuilder*, callee_val: Value*, + args: Value*, arg_count: int, + ret_ty: LLVMType*) -> Value*: """%N = call %callee() Indirect call: callee_val is a function-pointer SSA value.""" return builder.build_call_indirect(callee_val, args, arg_count, ret_ty) @@ -1558,38 +1558,38 @@ def build_call_indirect(builder: rawptr[IRBuilder], callee_val: rawptr[Value], # ============================================================ # Type conversion instructions # ============================================================ -def build_bitcast(builder: rawptr[IRBuilder], val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_bitcast(builder: IRBuilder*, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = bitcast to """ return builder.build_bitcast(val, to_ty) -def build_sext(builder: rawptr[IRBuilder], val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_sext(builder: IRBuilder*, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = sext to """ return builder.build_sext(val, to_ty) -def build_trunc(builder: rawptr[IRBuilder], val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_trunc(builder: IRBuilder*, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = trunc to """ return builder.build_trunc(val, to_ty) -def build_zext(builder: rawptr[IRBuilder], val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_zext(builder: IRBuilder*, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = zext to """ return builder.build_zext(val, to_ty) -def build_ptrtoint(builder: rawptr[IRBuilder], val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_ptrtoint(builder: IRBuilder*, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = ptrtoint to """ return builder.build_ptrtoint(val, to_ty) -def build_inttoptr(builder: rawptr[IRBuilder], val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_inttoptr(builder: IRBuilder*, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = inttoptr to """ return builder.build_inttoptr(val, to_ty) @@ -1597,38 +1597,38 @@ def build_inttoptr(builder: rawptr[IRBuilder], val: rawptr[Value], # ============================================================ # Float conversion instructions # ============================================================ -def build_fpext(builder: rawptr[IRBuilder], val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_fpext(builder: IRBuilder*, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = fpext to """ return builder.build_fpext(val, to_ty) -def build_fptrunc(builder: rawptr[IRBuilder], val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_fptrunc(builder: IRBuilder*, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = fptrunc to """ return builder.build_fptrunc(val, to_ty) -def build_fp2si(builder: rawptr[IRBuilder], val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_fp2si(builder: IRBuilder*, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = fptosi to """ return builder.build_fp2si(val, to_ty) -def build_si2fp(builder: rawptr[IRBuilder], val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_si2fp(builder: IRBuilder*, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = sitofp to """ return builder.build_si2fp(val, to_ty) -def build_fp2ui(builder: rawptr[IRBuilder], val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_fp2ui(builder: IRBuilder*, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = fptoui to """ return builder.build_fp2ui(val, to_ty) -def build_ui2fp(builder: rawptr[IRBuilder], val: rawptr[Value], - to_ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_ui2fp(builder: IRBuilder*, val: Value*, + to_ty: LLVMType*) -> Value*: """%N = uitofp to """ return builder.build_ui2fp(val, to_ty) @@ -1636,7 +1636,7 @@ def build_ui2fp(builder: rawptr[IRBuilder], val: rawptr[Value], # ============================================================ # GEP instructions # ============================================================ -def _is_ptr_type(ty: rawptr[LLVMType]) -> int: +def _is_ptr_type(ty: LLVMType*) -> int: """Check whether ty is a Ptr type (standalone function to avoid the nested-match compiler bug)""" if ty is None: return 0 @@ -1647,8 +1647,8 @@ def _is_ptr_type(ty: rawptr[LLVMType]) -> int: return 0 -def build_gep(builder: rawptr[IRBuilder], elem_ty: rawptr[LLVMType], - ptr: rawptr[Value], idx: rawptr[Value]) -> rawptr[Value]: +def build_gep(builder: IRBuilder*, elem_ty: LLVMType*, + ptr: Value*, idx: Value*) -> Value*: """%N = getelementptr , , """ return builder.build_gep(elem_ty, ptr, idx) @@ -1656,9 +1656,9 @@ def build_gep(builder: rawptr[IRBuilder], elem_ty: rawptr[LLVMType], # ============================================================ # build_gep_array - two-index array GEP: getelementptr [N x ty], [N x ty]* %ptr, i32 0, i32 %idx # ============================================================ -def build_gep_array(builder: rawptr[IRBuilder], array_ty: rawptr[LLVMType], - elem_ty: rawptr[LLVMType], - ptr: rawptr[Value], idx: rawptr[Value]) -> rawptr[Value]: +def build_gep_array(builder: IRBuilder*, array_ty: LLVMType*, + elem_ty: LLVMType*, + ptr: Value*, idx: Value*) -> Value*: """%N = getelementptr [N x elem_ty], [N x elem_ty]* %ptr, i32 0, i32 %idx Result type is elem_ty*.""" return builder.build_gep_array(array_ty, elem_ty, ptr, idx) @@ -1667,9 +1667,9 @@ def build_gep_array(builder: rawptr[IRBuilder], array_ty: rawptr[LLVMType], # ============================================================ # build_gep_struct - struct-field GEP: getelementptr struct_ty, struct_ty* %ptr, i32 0, i32 %field_idx # ============================================================ -def build_gep_struct(builder: rawptr[IRBuilder], struct_ty: rawptr[LLVMType], - field_ty: rawptr[LLVMType], - ptr: rawptr[Value], field_idx: int) -> rawptr[Value]: +def build_gep_struct(builder: IRBuilder*, struct_ty: LLVMType*, + field_ty: LLVMType*, + ptr: Value*, field_idx: int) -> Value*: """%N = getelementptr struct_ty, struct_ty* %ptr, i32 0, i32 %field_idx Result type is field_ty*.""" return builder.build_gep_struct(struct_ty, field_ty, ptr, field_idx) @@ -1682,16 +1682,16 @@ def build_gep_struct(builder: rawptr[IRBuilder], struct_ty: rawptr[LLVMType], # Note: @t.NoVTable is required (rationale in the Line comment in __function.py). # ============================================================ novirtual class PhiIncoming(GSListNode[PhiIncoming]): - Val: rawptr[Value] - Block: rawptr[BasicBlock] + Val: Value* + Block: BasicBlock* # PhiIncoming hardcoded size: Next(8) + Val(8) + Block(8) = 24 bytes define PHIINC_SIZE = 24 def new_phi_incoming(pool: memhub.MemBuddy*, - val: rawptr[Value], block: rawptr[BasicBlock]) -> rawptr[PhiIncoming]: - ptr: rawptr[PhiIncoming] = pool.alloc(PHIINC_SIZE) + val: Value*, block: BasicBlock*) -> PhiIncoming*: + ptr: PhiIncoming* = pool.alloc(PHIINC_SIZE) if ptr is None: return None string.memset(ptr, 0, PHIINC_SIZE) ptr.Val = val @@ -1702,8 +1702,8 @@ def new_phi_incoming(pool: memhub.MemBuddy*, # ============================================================ # Phi instruction # ============================================================ -def build_phi(builder: rawptr[IRBuilder], ty: rawptr[LLVMType], - incoming_head: rawptr[PhiIncoming], count: int) -> rawptr[Value]: +def build_phi(builder: IRBuilder*, ty: LLVMType*, + incoming_head: PhiIncoming*, count: int) -> Value*: """%N = phi [val1, %blk1], [val2, %blk2], ... incoming_head is the PhiIncoming list head; count is the incoming-edge count.""" return builder.build_phi(ty, incoming_head, count) @@ -1715,16 +1715,16 @@ def build_phi(builder: rawptr[IRBuilder], ty: rawptr[LLVMType], # Note: @t.NoVTable is required (rationale in the Line comment in __function.py). # ============================================================ novirtual class SwitchCase(GSListNode[SwitchCase]): - CaseVal: rawptr[Value] - Block: rawptr[BasicBlock] + CaseVal: Value* + Block: BasicBlock* # SwitchCase hardcoded size: Next(8) + CaseVal(8) + Block(8) = 24 bytes define SWCASE_SIZE = 24 def new_switch_case(pool: memhub.MemBuddy*, - case_val: rawptr[Value], block: rawptr[BasicBlock]) -> rawptr[SwitchCase]: - ptr: rawptr[SwitchCase] = pool.alloc(SWCASE_SIZE) + case_val: Value*, block: BasicBlock*) -> SwitchCase*: + ptr: SwitchCase* = pool.alloc(SWCASE_SIZE) if ptr is None: return None string.memset(ptr, 0, SWCASE_SIZE) ptr.CaseVal = case_val @@ -1735,9 +1735,9 @@ def new_switch_case(pool: memhub.MemBuddy*, # ============================================================ # Switch instruction # ============================================================ -def build_switch(builder: rawptr[IRBuilder], val: rawptr[Value], - default_blk: rawptr[BasicBlock], - cases_head: rawptr[SwitchCase], case_count: int): +def build_switch(builder: IRBuilder*, val: Value*, + default_blk: BasicBlock*, + cases_head: SwitchCase*, case_count: int): """switch , label % [, label % ...]""" builder.build_switch(val, default_blk, cases_head, case_count) @@ -1745,8 +1745,8 @@ def build_switch(builder: rawptr[IRBuilder], val: rawptr[Value], # ============================================================ # Select instruction # ============================================================ -def build_select(builder: rawptr[IRBuilder], cond: rawptr[Value], - true_val: rawptr[Value], false_val: rawptr[Value]) -> rawptr[Value]: +def build_select(builder: IRBuilder*, cond: Value*, + true_val: Value*, false_val: Value*) -> Value*: """%N = select i1 , , """ return builder.build_select(cond, true_val, false_val) @@ -1754,7 +1754,7 @@ def build_select(builder: rawptr[IRBuilder], cond: rawptr[Value], # ============================================================ # Unreachable instruction # ============================================================ -def build_unreachable(builder: rawptr[IRBuilder]): +def build_unreachable(builder: IRBuilder*): """unreachable""" builder.build_unreachable() @@ -1810,16 +1810,16 @@ def _atomic_order_str(ord: int) -> str: return "monotonic" -def build_atomicrmw(builder: rawptr[IRBuilder], op: int, - ptr: rawptr[Value], val: rawptr[Value], - order: int) -> rawptr[Value]: +def build_atomicrmw(builder: IRBuilder*, op: int, + ptr: Value*, val: Value*, + order: int) -> Value*: """%N = atomicrmw , """ return builder.build_atomicrmw(op, ptr, val, order) -def build_cmpxchg(builder: rawptr[IRBuilder], ptr: rawptr[Value], - cmp_val: rawptr[Value], new_val: rawptr[Value], - succ_order: int, fail_order: int) -> rawptr[Value]: +def build_cmpxchg(builder: IRBuilder*, ptr: Value*, + cmp_val: Value*, new_val: Value*, + succ_order: int, fail_order: int) -> Value*: """%N = cmpxchg , , Returns a {, i1} SSA value (simplified to an i64 representing the pair).""" return builder.build_cmpxchg(ptr, cmp_val, new_val, succ_order, fail_order) @@ -1828,9 +1828,9 @@ def build_cmpxchg(builder: rawptr[IRBuilder], ptr: rawptr[Value], # ============================================================ # va_arg instruction: read the next variadic argument from va_list # ============================================================ -def build_va_arg(builder: rawptr[IRBuilder], - va_list_ptr: rawptr[Value], - arg_ty: rawptr[LLVMType]) -> rawptr[Value]: +def build_va_arg(builder: IRBuilder*, + va_list_ptr: Value*, + arg_ty: LLVMType*) -> Value*: """%N = va_arg , """ return builder.build_va_arg(va_list_ptr, arg_ty) @@ -1838,9 +1838,9 @@ def build_va_arg(builder: rawptr[IRBuilder], # ============================================================ # Inline assembly (Phase 3) # ============================================================ -def build_inline_asm(builder: rawptr[IRBuilder], ret_ty: rawptr[LLVMType], +def build_inline_asm(builder: IRBuilder*, ret_ty: LLVMType*, asm_text: str, constraints: str, - has_side_effects: int) -> rawptr[Value]: + has_side_effects: int) -> Value*: """%N = call asm [sideeffect] "" ""() Simplified inline-assembly call, no-argument version.""" return builder.build_inline_asm(ret_ty, asm_text, constraints, has_side_effects) diff --git a/mlirlite/__function.vp b/mlirlite/__function.vp index 35c8204..67903ec 100644 --- a/mlirlite/__function.vp +++ b/mlirlite/__function.vp @@ -50,7 +50,7 @@ novirtual class Line(GSListNode[Line]): # ============================================================ novirtual class BasicBlock(GSListNode[BasicBlock]): Name: str # block name (e.g. "entry"/"if.then") - Lines: rawptr[GSList[Line]] # instruction-line list container (Head/Tail/Count) + Lines: GSList[Line]* # instruction-line list container (Head/Tail/Count) IsTerminated: int # 1=terminator present (br/ret) @@ -63,7 +63,7 @@ novirtual class BasicBlock(GSListNode[BasicBlock]): # NOTE: must carry @t.NoVTable (same reason as Line). # ============================================================ novirtual class Param(GSListNode[Param]): - Ty: rawptr[LLVMType] # parameter type + Ty: LLVMType* # parameter type Name: str # parameter name (e.g. "%0"/"%a") Attrs: str # parameter attribute text (None=none) @@ -80,9 +80,9 @@ novirtual class Param(GSListNode[Param]): # ============================================================ novirtual class Function(GSListNode[Function]): Name: str # function name - RetTy: rawptr[LLVMType] # return type - Params: rawptr[GSList[Param]] # parameter list container - Blocks: rawptr[GSList[BasicBlock]] # basic-block list container + RetTy: LLVMType* # return type + Params: GSList[Param]* # parameter list container + Blocks: GSList[BasicBlock]* # basic-block list container IsDeclared: int # 1=declaration only (declare), 0=definition (define) IsVarArg: int # 1=variadic function (...) Attrs: str # function attribute text (None=none) @@ -98,9 +98,9 @@ novirtual class Function(GSListNode[Function]): # Line hardcoded size: Next(8) + Buf(8) + Len(8) = 24 bytes define LINE_SIZE = 24 -def new_line(pool: memhub.MemBuddy*, text: str) -> rawptr[Line]: +def new_line(pool: memhub.MemBuddy*, text: str) -> Line*: """Create an instruction line, copying text into a newly allocated buffer""" - ptr: rawptr[Line] = pool.alloc(LINE_SIZE) + ptr: Line* = pool.alloc(LINE_SIZE) if ptr is None: return None string.memset(ptr, 0, LINE_SIZE) if text is not None: @@ -124,9 +124,9 @@ def _new_gslist(pool: memhub.MemBuddy*, list_size: sizet) -> t.CPtr: # BasicBlock hardcoded size: Next(8) + Name(8) + Lines(8) + IsTerminated(4) = 32 bytes define BLOCK_SIZE = 32 -def new_basic_block(pool: memhub.MemBuddy*, name: str) -> rawptr[BasicBlock]: +def new_basic_block(pool: memhub.MemBuddy*, name: str) -> BasicBlock*: """Create a basic block""" - ptr: rawptr[BasicBlock] = pool.alloc(BLOCK_SIZE) + ptr: BasicBlock* = pool.alloc(BLOCK_SIZE) if ptr is None: return None string.memset(ptr, 0, BLOCK_SIZE) ptr.Name = name @@ -138,10 +138,10 @@ def new_basic_block(pool: memhub.MemBuddy*, name: str) -> rawptr[BasicBlock]: # Param hardcoded size: Next(8) + Ty(8) + Name(8) + Attrs(8) = 32 bytes define PARAM_SIZE = 32 -def new_param(pool: memhub.MemBuddy*, ty: rawptr[LLVMType], - name: str) -> rawptr[Param]: +def new_param(pool: memhub.MemBuddy*, ty: LLVMType*, + name: str) -> Param*: """Create a function parameter""" - ptr: rawptr[Param] = pool.alloc(PARAM_SIZE) + ptr: Param* = pool.alloc(PARAM_SIZE) if ptr is None: return None string.memset(ptr, 0, PARAM_SIZE) ptr.Ty = ty @@ -154,9 +154,9 @@ def new_param(pool: memhub.MemBuddy*, ty: rawptr[LLVMType], define FUNC_SIZE = 88 def new_function(pool: memhub.MemBuddy*, name: str, - ret_ty: rawptr[LLVMType]) -> rawptr[Function]: + ret_ty: LLVMType*) -> Function*: """Create a function""" - ptr: rawptr[Function] = pool.alloc(FUNC_SIZE) + ptr: Function* = pool.alloc(FUNC_SIZE) if ptr is None: return None string.memset(ptr, 0, FUNC_SIZE) ptr.Name = name @@ -179,25 +179,25 @@ def new_function(pool: memhub.MemBuddy*, name: str, # ============================================================ # List operations (delegating to GSList.append) # ============================================================ -def function_add_param(func: rawptr[Function], param: rawptr[Param]): +def function_add_param(func: Function*, param: Param*): """Append a parameter to the function's parameter list""" if func is None or param is None: return # NOTE: use a local variable + type parameter (see function_move_block_to_end): chaining # func.Params.append() mis-resolves to LinkedNode.append and corrupts memory 48 bytes before the container. - params: rawptr[GSList[Param]] = func.Params + params: GSList[Param]* = func.Params if params is None: return params.append(param) -def function_add_block(func: rawptr[Function], block: rawptr[BasicBlock]): +def function_add_block(func: Function*, block: BasicBlock*): """Append a basic block to the function's block list""" if func is None or block is None: return - blocks: rawptr[GSList[BasicBlock]] = func.Blocks + blocks: GSList[BasicBlock]* = func.Blocks if blocks is None: return blocks.append(block) -def function_move_block_to_end(func: rawptr[Function], block: rawptr[BasicBlock]): +def function_move_block_to_end(func: Function*, block: BasicBlock*): """Move block to the end of the function's block list (BB text order == control-flow order). Fixes non-monotonic SSA numbering (BBs are created in order but instructions are emitted in @@ -206,7 +206,7 @@ def function_move_block_to_end(func: rawptr[Function], block: rawptr[BasicBlock] type and blocks.Head/Tail/Count field reads return garbage. """ if func is None or block is None: return - blocks: rawptr[GSList[BasicBlock]] = func.Blocks + blocks: GSList[BasicBlock]* = func.Blocks if blocks is None: return # Already Tail; nothing to move @@ -219,7 +219,7 @@ def function_move_block_to_end(func: rawptr[Function], block: rawptr[BasicBlock] blocks.Head = block.Next else: # Walk to find the predecessor - prev: rawptr[BasicBlock] = blocks.Head + prev: BasicBlock* = blocks.Head while prev is not None and prev.Next is not block: prev = prev.Next if prev is None: @@ -237,38 +237,38 @@ def function_move_block_to_end(func: rawptr[Function], block: rawptr[BasicBlock] blocks.Tail = block -def block_append_line(block: rawptr[BasicBlock], line: rawptr[Line]): +def block_append_line(block: BasicBlock*, line: Line*): """Append an instruction line to the basic block""" if block is None or line is None: return - lines: rawptr[GSList[Line]] = block.Lines + lines: GSList[Line]* = block.Lines if lines is None: return lines.append(line) -def block_set_terminated(block: rawptr[BasicBlock], val: int): +def block_set_terminated(block: BasicBlock*, val: int): """Set the block terminator flag (cross-module call to avoid opaque chained field access)""" if block is None: return block.IsTerminated = val -def block_get_terminated(block: rawptr[BasicBlock]) -> int: +def block_get_terminated(block: BasicBlock*) -> int: """Get the block terminator flag (cross-module call to avoid opaque chained field access)""" if block is None: return 1 return block.IsTerminated -def block_append_text(pool: memhub.MemBuddy*, block: rawptr[BasicBlock], +def block_append_text(pool: memhub.MemBuddy*, block: BasicBlock*, text: str): """Create an instruction line and append it to the basic block""" if block is None or text is None: return - line: rawptr[Line] = new_line(pool, text) + line: Line* = new_line(pool, text) if line is not None: block_append_line(block, line) def block_insert_text_before_terminator(pool: memhub.MemBuddy*, - block: rawptr[BasicBlock], + block: BasicBlock*, text: str): """Create an instruction line and insert it before the block terminator. @@ -277,14 +277,14 @@ def block_insert_text_before_terminator(pool: memhub.MemBuddy*, """ if block is None or text is None: return if block.Lines is None: return - line: rawptr[Line] = new_line(pool, text) + line: Line* = new_line(pool, text) if line is None: return # Block not terminated: append directly if block.IsTerminated == 0: block_append_line(block, line) return # Block terminated: insert before Tail (the terminator) - lines: rawptr[GSList[Line]] = block.Lines + lines: GSList[Line]* = block.Lines if lines.Head is None: block_append_line(block, line) return @@ -295,7 +295,7 @@ def block_insert_text_before_terminator(pool: memhub.MemBuddy*, lines.Count += 1 return # Find the predecessor of Tail - prev: rawptr[Line] = lines.Head + prev: Line* = lines.Head while prev is not None and prev.Next is not lines.Tail: prev = prev.Next if prev is None: @@ -311,7 +311,7 @@ def block_insert_text_before_terminator(pool: memhub.MemBuddy*, # ============================================================ # Attribute setters # ============================================================ -def function_set_attrs(func: rawptr[Function], attrs: str): +def function_set_attrs(func: Function*, attrs: str): """Set function-level attribute text (e.g. "nounwind"/"noinline")""" if func is None: return func.Attrs = attrs @@ -319,7 +319,7 @@ def function_set_attrs(func: rawptr[Function], attrs: str): _g_attr_group_counter: int = 0 -def function_set_attr_group(func: rawptr[Function], group: str): +def function_set_attr_group(func: Function*, group: str): """Set function string attribute group (e.g. '"section"=".text.startup"') and assign #N. LLVM string attributes (with a value, e.g. section) cannot be inlined on the signature @@ -333,13 +333,13 @@ def function_set_attr_group(func: rawptr[Function], group: str): func.AttrGroupId = _g_attr_group_counter -def param_set_attrs(param: rawptr[Param], attrs: str): +def param_set_attrs(param: Param*, attrs: str): """Set parameter attribute text (e.g. "noundef"/"nocapture"/"readonly")""" if param is None: return param.Attrs = attrs -def function_set_dbg(func: rawptr[Function], ref: str): +def function_set_dbg(func: Function*, ref: str): """Set the function-level debug ref (DISubprogram node ref, e.g. "!3"). Kept as-is: MLIR printing ignores it (FunctionPrint emits no !dbg), so this only @@ -451,26 +451,26 @@ def _is_digit_ch(ch: char) -> int: def _map_get_i32(map_arr: str, idx: int) -> int: """Read i32 array map_arr[idx] (explicit byte offset idx*4). - Casts the byte offset to i32* via (rawptr[int])(uint64), then dereferences with c.Deref. + Casts the byte offset to i32* via (int*)(uint64), then dereferences with c.Deref. TPC has fixed type-union casts (_HandleTypeUnionCastLlvm fallback), so this form works. """ if map_arr is None: return -1 byte_off: uint64 = uint64(map_arr) + idx * 4 - elem_ptr: rawptr[int] = (rawptr[int])(byte_off) + elem_ptr: int* = (int*)(byte_off) return *elem_ptr def _map_set_i32(map_arr: str, idx: int, val: int): """Write map_arr[idx] = val (i32 array, explicit byte offset idx*4). - Casts via (rawptr[int])(uint64) and assigns through c.DerefAs. + Casts via (int*)(uint64) and assigns through c.DerefAs. TPC has fixed type-union casts, so this form works. """ if map_arr is None: return byte_off: uint64 = uint64(map_arr) + idx * 4 - elem_ptr: rawptr[int] = (rawptr[int])(byte_off) + elem_ptr: int* = (int*)(byte_off) c.DerefAs(elem_ptr, val) @@ -492,13 +492,13 @@ def _scan_max_ssa_in_text(text: str, cur_max: int) -> int: return result -def _find_max_ssa_number(func: rawptr[Function]) -> int: +def _find_max_ssa_number(func: Function*) -> int: """Walk all BB instruction lines for the largest %N; returns -1 if no numeric SSA names""" max_n: int = -1 if func is None or func.Blocks is None: return max_n - blocks: rawptr[GSList[BasicBlock]] = func.Blocks - blk: rawptr[BasicBlock] = blocks.Head + blocks: GSList[BasicBlock]* = func.Blocks + blk: BasicBlock* = blocks.Head blk_steps: sizet = 0 while blk is not None: blk_steps += 1 @@ -506,8 +506,8 @@ def _find_max_ssa_number(func: rawptr[Function]) -> int: stdio.printf("[IR-DUMP] 链表成环: func blocks(函数名=%s,ssa 扫描终止)\n", func.Name) stdlib.exit(1) if blk.Lines is not None: - lines: rawptr[GSList[Line]] = blk.Lines - line: rawptr[Line] = lines.Head + lines: GSList[Line]* = blk.Lines + line: Line* = lines.Head line_steps: sizet = 0 while line is not None: line_steps += 1 @@ -605,7 +605,7 @@ def _replace_ssa_numbers(text: str, return new_buf -def RenumberSSA(func: rawptr[Function], pool: memhub.MemBuddy*): +def RenumberSSA(func: Function*, pool: memhub.MemBuddy*): """Renumber all numeric SSA names in the function so text-output order is monotonic. Called before FunctionPrint serializes the body; only applies to define (IsDeclared==0) @@ -633,8 +633,8 @@ def RenumberSSA(func: rawptr[Function], pool: memhub.MemBuddy*): # 3. Second pass: assign new numbers in text order next_new: int = 0 - blocks: rawptr[GSList[BasicBlock]] = func.Blocks - blk: rawptr[BasicBlock] = blocks.Head + blocks: GSList[BasicBlock]* = func.Blocks + blk: BasicBlock* = blocks.Head blk_steps: sizet = 0 while blk is not None: blk_steps += 1 @@ -642,8 +642,8 @@ def RenumberSSA(func: rawptr[Function], pool: memhub.MemBuddy*): stdio.printf("[IR-DUMP] 链表成环: func blocks(函数名=%s,ssa 重编号终止)\n", func.Name) stdlib.exit(1) if blk.Lines is not None: - lines: rawptr[GSList[Line]] = blk.Lines - line: rawptr[Line] = lines.Head + lines: GSList[Line]* = blk.Lines + line: Line* = lines.Head line_steps: sizet = 0 while line is not None: line_steps += 1 @@ -677,8 +677,8 @@ def RenumberSSA(func: rawptr[Function], pool: memhub.MemBuddy*): stdio.printf("[IR-DUMP] 链表成环: func blocks(函数名=%s,ssa 替换终止)\n", func.Name) stdlib.exit(1) if blk.Lines is not None: - lines: rawptr[GSList[Line]] = blk.Lines - line: rawptr[Line] = lines.Head + lines: GSList[Line]* = blk.Lines + line: Line* = lines.Head line_steps = 0 while line is not None: line_steps += 1 @@ -846,24 +846,24 @@ def _peep_is_alloc_of(eb: str, a_name: str, nl: sizet) -> int: return 0 -def _peephole_opt(func: rawptr[Function], pool: memhub.MemBuddy*): +def _peephole_opt(func: Function*, pool: memhub.MemBuddy*): """Text-layer local peephole: T1 ret zeroinitializer; T2 entry-slot store->load forwarding""" if func is None or func.Blocks is None or pool is None: return # NOTE: TPC silently drops assignments for a two-level "var = ptr.field.member" auto-deref # chain (the IR reads an uninitialized stack var -> random stack errors). Split into one level: # fetch the field into a local rawptr, then null-check before .Head (same pattern as FunctionPrint). - func_blocks: rawptr[GSList[BasicBlock]] = func.Blocks - blk: rawptr[BasicBlock] = None + func_blocks: GSList[BasicBlock]* = func.Blocks + blk: BasicBlock* = None if func_blocks is not None: blk = func_blocks.Head # ---------- T1: ret zeroinitializer ---------- blk_t1 = blk while blk_t1 is not None: - line1: rawptr[Line] = None + line1: Line* = None if blk_t1.Lines is not None: - t1_lines: rawptr[GSList[Line]] = blk_t1.Lines + t1_lines: GSList[Line]* = blk_t1.Lines line1 = t1_lines.Head while line1 is not None: if line1.Buf is not None: @@ -893,13 +893,13 @@ def _peephole_opt(func: rawptr[Function], pool: memhub.MemBuddy*): blk_t1 = blk_t1.Next # ---------- T2: entry alloca slot forwarding ---------- - entry_blk: rawptr[BasicBlock] = blk + entry_blk: BasicBlock* = blk if entry_blk is None: return - entry_lines: rawptr[GSList[Line]] = entry_blk.Lines + entry_lines: GSList[Line]* = entry_blk.Lines if entry_lines is None: return - e_line: rawptr[Line] = entry_lines.Head + e_line: Line* = entry_lines.Head while e_line is not None: eb: str = e_line.Buf if eb is not None: @@ -920,9 +920,9 @@ def _peephole_opt(func: rawptr[Function], pool: memhub.MemBuddy*): # First pass: count this alloca's store/load/other refs and line order blk_s = blk while blk_s is not None: - l_s: rawptr[Line] = None + l_s: Line* = None if blk_s.Lines is not None: - scan_lines: rawptr[GSList[Line]] = blk_s.Lines + scan_lines: GSList[Line]* = blk_s.Lines l_s = scan_lines.Head while l_s is not None: sb: str = l_s.Buf @@ -1008,9 +1008,9 @@ def _peephole_opt(func: rawptr[Function], pool: memhub.MemBuddy*): ltok_len: sizet = string.strlen(ltok) blk_r = blk while blk_r is not None: - lr: rawptr[Line] = None + lr: Line* = None if blk_r.Lines is not None: - repl_lines: rawptr[GSList[Line]] = blk_r.Lines + repl_lines: GSList[Line]* = blk_r.Lines lr = repl_lines.Head while lr is not None: if lr.Buf is not None: @@ -1023,9 +1023,9 @@ def _peephole_opt(func: rawptr[Function], pool: memhub.MemBuddy*): # Delete: alloca def / the single store / all load lines blk_d = blk while blk_d is not None: - ld: rawptr[Line] = None + ld: Line* = None if blk_d.Lines is not None: - kill_lines: rawptr[GSList[Line]] = blk_d.Lines + kill_lines: GSList[Line]* = blk_d.Lines ld = kill_lines.Head while ld is not None: db: str = ld.Buf @@ -1048,7 +1048,7 @@ def _peephole_opt(func: rawptr[Function], pool: memhub.MemBuddy*): _peep_noop_bitcast(func, pool) -def _peep_noop_bitcast(func: rawptr[Function], pool: memhub.MemBuddy*): +def _peep_noop_bitcast(func: Function*, pool: memhub.MemBuddy*): """T3: remove no-op bitcast (bitcast %x to , same type on both sides). The emitter (virtual calls / union width casts) produces same-type identity bitcasts @@ -1062,13 +1062,13 @@ def _peep_noop_bitcast(func: rawptr[Function], pool: memhub.MemBuddy*): # resuming from the next line; stop at the first non-matching bitcast. Equivalent deletion # result to the old rescan-from-block-head approach (replacement only touches operand tokens), # but removes the O(K*C) quadratic rescan. - blk: rawptr[BasicBlock] = func.Blocks.Head + blk: BasicBlock* = func.Blocks.Head while blk is not None: - ln: rawptr[Line] = None + ln: Line* = None if blk.Lines is not None: ln = blk.Lines.Head while ln is not None: - nxt: rawptr[Line] = ln.Next + nxt: Line* = ln.Next if ln.Buf is not None: eqpos: str = string.strstr(ln.Buf, " = bitcast ") if eqpos is not None: @@ -1105,10 +1105,10 @@ def _peep_noop_bitcast(func: rawptr[Function], pool: memhub.MemBuddy*): # nm_buf/src_buf are constant across the scan; strlen computed once (not per line) nm_buf_len: sizet = string.strlen(nm_buf) src_buf_len: sizet = string.strlen(src_buf) - blk_r: rawptr[BasicBlock] = func.Blocks.Head + blk_r: BasicBlock* = func.Blocks.Head while blk_r is not None: if blk_r.Lines is not None: - ln2: rawptr[Line] = blk_r.Lines.Head + ln2: Line* = blk_r.Lines.Head while ln2 is not None: if ln2.Buf is not None: rb: str = _peep_replace_token(pool, ln2.Buf, nm_buf, src_buf, @@ -1147,8 +1147,8 @@ define MLIR_ALIAS_CAP = 512 # Render pass: 1=scan(register) 2=emit(write text) _MLIR_Pass: int = 0 _MLIR_Pool: memhub.MemBuddy* = None -_MLIR_Func: rawptr[Function] = None -_MLIR_SrcBlk: rawptr[BasicBlock] = None +_MLIR_Func: Function* = None +_MLIR_SrcBlk: BasicBlock* = None # Constant table: (MLIR type text, constant text) -> materialized SSA name _MLIR_ConstTy: t.CPtr = None @@ -1609,12 +1609,12 @@ def _MlirBlkRef(t: str) -> str: return t -def _MlirFindBlock(func: rawptr[Function], name: str) -> rawptr[BasicBlock]: +def _MlirFindBlock(func: Function*, name: str) -> BasicBlock*: """Find a basic block by name (without %) within the function""" if func is None or func.Blocks is None or name is None: return None - blocks: rawptr[GSList[BasicBlock]] = func.Blocks - blk: rawptr[BasicBlock] = blocks.Head + blocks: GSList[BasicBlock]* = func.Blocks + blk: BasicBlock* = blocks.Head steps: int = 0 while blk is not None: steps += 1 @@ -1719,7 +1719,7 @@ def _MlirPhiParam(text: str) -> int: return 1 -def _MlirPhiFindIncoming(text: str, src: rawptr[BasicBlock]) -> int: +def _MlirPhiFindIncoming(text: str, src: BasicBlock*) -> int: """Find the phi incoming edge matching the source block; on success writes _SC_B1(value)/_SC_B2(type) and returns 1""" p: str = _mlir_ws(text) tb: str = _SC_Buf @@ -1772,12 +1772,12 @@ def _MlirPhiFindIncoming(text: str, src: rawptr[BasicBlock]) -> int: # ============================================================ # Block parameters / block arguments # ============================================================ -def _MlirBlockHasPhi(blk: rawptr[BasicBlock]) -> int: +def _MlirBlockHasPhi(blk: BasicBlock*) -> int: """Whether the block head has a phi (i.e. the block carries block params)""" if blk is None or blk.Lines is None: return 0 - lines: rawptr[GSList[Line]] = blk.Lines - ln: rawptr[Line] = lines.Head + lines: GSList[Line]* = blk.Lines + ln: Line* = lines.Head while ln is not None: if ln.Buf is not None: if _MlirIsPhiLine(ln.Buf) != 0: @@ -1788,7 +1788,7 @@ def _MlirBlockHasPhi(blk: rawptr[BasicBlock]) -> int: def _MlirBlockOperands(out: str, outsz: sizet, - target: rawptr[BasicBlock], src: rawptr[BasicBlock]): + target: BasicBlock*, src: BasicBlock*): """Emit target's block arguments when branching to it: (%v : ty, ...). Incoming edges are matched to phis by source block; no match -> loud error (never silently drop args). @@ -1799,8 +1799,8 @@ def _MlirBlockOperands(out: str, outsz: sizet, return tmp: str = _SC_Tmp tmp[0] = '\0' - lines: rawptr[GSList[Line]] = target.Lines - ln: rawptr[Line] = lines.Head + lines: GSList[Line]* = target.Lines + ln: Line* = lines.Head cnt: int = 0 while ln is not None: if ln.Buf is None: @@ -1827,7 +1827,7 @@ def _MlirBlockOperands(out: str, outsz: sizet, _append_cstr(out, outsz, ")") -def _MlirEmitBlockHeader(out: str, outsz: sizet, blk: rawptr[BasicBlock]): +def _MlirEmitBlockHeader(out: str, outsz: sizet, blk: BasicBlock*): """Emit a non-entry block header: ^name(%p: ty, ...):""" _append_cstr(out, outsz, "^") if blk.Name is not None: @@ -1835,8 +1835,8 @@ def _MlirEmitBlockHeader(out: str, outsz: sizet, blk: rawptr[BasicBlock]): if _MlirBlockHasPhi(blk) != 0: tmp: str = _SC_Tmp tmp[0] = '\0' - lines: rawptr[GSList[Line]] = blk.Lines - ln: rawptr[Line] = lines.Head + lines: GSList[Line]* = blk.Lines + ln: Line* = lines.Head cnt: int = 0 while ln is not None: if ln.Buf is None: @@ -1863,12 +1863,12 @@ def _MlirEmitBlockHeader(out: str, outsz: sizet, blk: rawptr[BasicBlock]): _append_cstr(out, outsz, ":\n") -def _MlirEmitBlockLines(out: str, outsz: sizet, blk: rawptr[BasicBlock]): +def _MlirEmitBlockLines(out: str, outsz: sizet, blk: BasicBlock*): """Emit in-block instructions (skip leading phis, which became block params)""" if blk is None or blk.Lines is None: return - lines: rawptr[GSList[Line]] = blk.Lines - ln: rawptr[Line] = lines.Head + lines: GSList[Line]* = blk.Lines + ln: Line* = lines.Head skipping: int = 1 steps: int = 0 while ln is not None: @@ -1884,7 +1884,7 @@ def _MlirEmitBlockLines(out: str, outsz: sizet, blk: rawptr[BasicBlock]): ln = ln.Next -def _MlirCheckEntryNoPhi(blk: rawptr[BasicBlock]): +def _MlirCheckEntryNoPhi(blk: BasicBlock*): """entry block must not have phis (no predecessor, cannot become block params)""" if _MlirBlockHasPhi(blk) != 0: MlirFail("MLIR 渲染: entry 块不允许 phi(MLIR entry 块不接受块参数)") @@ -3136,7 +3136,7 @@ def _MlirRenderLine(text: str, out: str, outsz: sizet): # Function signature and body # ============================================================ def _MlirFuncSig(buf: str, size: sizet, - func: rawptr[Function], pool: memhub.MemBuddy*): + func: Function*, pool: memhub.MemBuddy*): """llvm.func @name(%a: i32, %b: i32) -> i32 (void return omits -> ty)""" _append_cstr(buf, size, "llvm.func @") if func.Name is not None: @@ -3147,8 +3147,8 @@ def _MlirFuncSig(buf: str, size: sizet, else: _append_cstr(buf, size, func.Name) _append_cstr(buf, size, "(") - params: rawptr[GSList[Param]] = func.Params - cur: rawptr[Param] = None + params: GSList[Param]* = func.Params + cur: Param* = None if params is not None: cur = params.Head first: int = 1 @@ -3194,7 +3194,7 @@ def _MlirFuncSig(buf: str, size: sizet, def FunctionPrint(buf: str, size: sizet, - func: rawptr[Function], pool: memhub.MemBuddy*): + func: Function*, pool: memhub.MemBuddy*): """Serialize function func as MLIR (llvm dialect) text APPENDED to buf. NOTE: like the llvmlite version, this appends (so the module printer can concatenate @@ -3235,7 +3235,7 @@ def FunctionPrint(buf: str, size: sizet, _MlirOutTruncFail() return - blocks: rawptr[GSList[BasicBlock]] = func.Blocks + blocks: GSList[BasicBlock]* = func.Blocks if blocks is None: _MlirFuncSig(buf, size, func, pool) _append_cstr(buf, size, "\n") @@ -3244,7 +3244,7 @@ def FunctionPrint(buf: str, size: sizet, # ---- pass1: scan (register constants/aliases + shape checks) ---- _MLIR_Pass = 1 - blk: rawptr[BasicBlock] = blocks.Head + blk: BasicBlock* = blocks.Head blk_steps: int = 0 while blk is not None: blk_steps += 1 @@ -3252,8 +3252,8 @@ def FunctionPrint(buf: str, size: sizet, MlirFail("MLIR 渲染: 函数块链疑似成环") _MLIR_SrcBlk = blk if blk.Lines is not None: - lines: rawptr[GSList[Line]] = blk.Lines - ln: rawptr[Line] = lines.Head + lines: GSList[Line]* = blk.Lines + ln: Line* = lines.Head ln_steps: int = 0 while ln is not None: ln_steps += 1 @@ -3570,14 +3570,14 @@ def DebugTakeText() -> str: # These accessors run inside this module where the full type definitions exist, so they can access # all fields correctly; other modules get field values via function calls, bypassing the stub limits. # ============================================================ -def function_get_name(func: rawptr[Function]) -> str: +def function_get_name(func: Function*) -> str: """Get the function name""" if func is None: return None return func.Name -def function_get_name_len(func: rawptr[Function]) -> sizet: +def function_get_name_len(func: Function*) -> sizet: """Get the function name length (computed once at creation, always == strlen(Name)). Mirrors function_get_name's cross-module stub-bypass pattern: the user module only has a stub @@ -3590,59 +3590,59 @@ def function_get_name_len(func: rawptr[Function]) -> sizet: return func.NameLen -def function_get_ret_ty(func: rawptr[Function]) -> rawptr[LLVMType]: +def function_get_ret_ty(func: Function*) -> LLVMType*: """Get the function return type""" if func is None: return None return func.RetTy -def function_get_params(func: rawptr[Function]) -> rawptr[GSList[Param]]: +def function_get_params(func: Function*) -> GSList[Param]*: """Get the function parameter list container""" if func is None: return None return func.Params -def function_get_param_head(func: rawptr[Function]) -> rawptr[Param]: +def function_get_param_head(func: Function*) -> Param*: """Get the function parameter list head (one step, avoiding GSList.Head access by callers)""" if func is None: return None - params: rawptr[GSList[Param]] = func.Params + params: GSList[Param]* = func.Params if params is None: return None return params.Head -def function_get_next(func: rawptr[Function]) -> rawptr[Function]: +def function_get_next(func: Function*) -> Function*: """Get the next function in the list""" if func is None: return None return func.Next -def function_is_declared(func: rawptr[Function]) -> int: +def function_is_declared(func: Function*) -> int: """Get whether the function is a declaration (1=declare, 0=define)""" if func is None: return 0 return func.IsDeclared -def param_get_name(param: rawptr[Param]) -> str: +def param_get_name(param: Param*) -> str: """Get the parameter name""" if param is None: return None return param.Name -def param_get_ty(param: rawptr[Param]) -> rawptr[LLVMType]: +def param_get_ty(param: Param*) -> LLVMType*: """Get the parameter type""" if param is None: return None return param.Ty -def param_get_next(param: rawptr[Param]) -> rawptr[Param]: +def param_get_next(param: Param*) -> Param*: """Get the next parameter in the list""" if param is None: return None diff --git a/mlirlite/__init__.vp b/mlirlite/__init__.vp index a18817f..8ca8ba7 100644 --- a/mlirlite/__init__.vp +++ b/mlirlite/__init__.vp @@ -110,8 +110,8 @@ def _str_dup(pool: memhub.MemBuddy*, src: str) -> str: # ============================================================ # Convenience factory: create a named basic block # ============================================================ -def create_block(pool: memhub.MemBuddy*, func: rawptr[Function], - name: str) -> rawptr[BasicBlock]: +def create_block(pool: memhub.MemBuddy*, func: Function*, + name: str) -> BasicBlock*: """Create a basic block and add it to the function.""" # Block-name/param conflict guard: block label "entry:" is value %entry, so a param %entry # collides; on collision append .1/.2/... (strip a leading % from Param.Name before comparing). @@ -125,7 +125,7 @@ def create_block(pool: memhub.MemBuddy*, func: rawptr[Function], cb_collide: int = 1 while cb_collide != 0: cb_collide = 0 - cb_p: rawptr[Param] = function_get_param_head(func) + cb_p: Param* = function_get_param_head(func) while cb_p is not None: cb_pnm: str = param_get_name(cb_p) if cb_pnm is not None: @@ -141,7 +141,7 @@ def create_block(pool: memhub.MemBuddy*, func: rawptr[Function], use_name = cb_buf cb_k += 1 name_dup: str = _str_dup(pool, use_name) - blk: rawptr[BasicBlock] = new_basic_block(pool, name_dup) + blk: BasicBlock* = new_basic_block(pool, name_dup) if blk is not None: function_add_block(func, blk) return blk @@ -151,12 +151,12 @@ def create_block(pool: memhub.MemBuddy*, func: rawptr[Function], # Convenience factory: create an integer constant value # ============================================================ def const_int(pool: memhub.MemBuddy*, bits: int, - val: int64) -> rawptr[Value]: + val: int64) -> Value*: """Create an integer constant value (auto-creates type + name text). bits: bit width (1/8/16/32/64); val: integer value. """ # create type - ty: rawptr[LLVMType] = pool.alloc(LLVMType.__sizeof__()) + ty: LLVMType* = pool.alloc(LLVMType.__sizeof__()) if ty is None: return None string.memset(ty, 0, LLVMType.__sizeof__()) c.DerefAs(ty, LLVMType.Int(bits)) @@ -174,12 +174,12 @@ def const_int(pool: memhub.MemBuddy*, bits: int, return ConstInt(pool, ty, val, name) -def const_int32(pool: memhub.MemBuddy*, val: int64) -> rawptr[Value]: +def const_int32(pool: memhub.MemBuddy*, val: int64) -> Value*: """Convenience: create an i32 integer constant.""" return const_int(pool, 32, val) -def const_int64(pool: memhub.MemBuddy*, val: int64) -> rawptr[Value]: +def const_int64(pool: memhub.MemBuddy*, val: int64) -> Value*: """Convenience: create an i64 integer constant.""" return const_int(pool, 64, val) @@ -187,21 +187,21 @@ def const_int64(pool: memhub.MemBuddy*, val: int64) -> rawptr[Value]: # ============================================================ # Convenience factory: create a function and add it to the module # ============================================================ -def create_function(pool: memhub.MemBuddy*, mod: rawptr[LLVMModule], - name: str, ret_ty: rawptr[LLVMType]) -> rawptr[Function]: +def create_function(pool: memhub.MemBuddy*, mod: LLVMModule*, + name: str, ret_ty: LLVMType*) -> Function*: """Create a function and add it to the module.""" name_dup: str = _str_dup(pool, name) - func: rawptr[Function] = new_function(pool, name_dup, ret_ty) + func: Function* = new_function(pool, name_dup, ret_ty) if func is not None: module_add_function(mod, func) return func -def add_param(pool: memhub.MemBuddy*, func: rawptr[Function], - ty: rawptr[LLVMType], name: str) -> rawptr[Param]: +def add_param(pool: memhub.MemBuddy*, func: Function*, + ty: LLVMType*, name: str) -> Param*: """Create a parameter and add it to the function.""" name_dup: str = _str_dup(pool, name) - param: rawptr[Param] = new_param(pool, ty, name_dup) + param: Param* = new_param(pool, ty, name_dup) if param is not None: function_add_param(func, param) return param @@ -210,13 +210,13 @@ def add_param(pool: memhub.MemBuddy*, func: rawptr[Function], # ============================================================ # Convenience factory: create a function declaration (declare) # ============================================================ -def create_declare(pool: memhub.MemBuddy*, mod: rawptr[LLVMModule], - name: str, ret_ty: rawptr[LLVMType]) -> rawptr[Function]: +def create_declare(pool: memhub.MemBuddy*, mod: LLVMModule*, + name: str, ret_ty: LLVMType*) -> Function*: """Create a function declaration (declare, no body) and add it to the module. Unlike create_function, it emits only: declare @() """ name_dup: str = _str_dup(pool, name) - func: rawptr[Function] = new_function(pool, name_dup, ret_ty) + func: Function* = new_function(pool, name_dup, ret_ty) if func is not None: func.IsDeclared = 1 module_add_function(mod, func) @@ -229,8 +229,8 @@ def create_declare(pool: memhub.MemBuddy*, mod: rawptr[LLVMModule], # The initializer is stored in gv.Initializer as llvmlite-shaped LLVM syntax text (c"contents\00"); # the MLIR render stage (__module.vp/_MlirGlobalInit) converts it to the attribute form "contents". # ============================================================ -def create_global_string(pool: memhub.MemBuddy*, mod: rawptr[LLVMModule], - name: str, text: str) -> rawptr[GlobalVariable]: +def create_global_string(pool: memhub.MemBuddy*, mod: LLVMModule*, + name: str, text: str) -> GlobalVariable*: """Create a string-constant global variable and add it to the module. name: global name (e.g. ".str"); text: C string without trailing NUL (added automatically). Returns: GlobalVariable pointer of type [len+1 x i8]. @@ -240,20 +240,20 @@ def create_global_string(pool: memhub.MemBuddy*, mod: rawptr[LLVMModule], count: int = slen + 1 # includes the trailing NUL # create i8 type - i8_ty: rawptr[LLVMType] = pool.alloc(LLVMType.__sizeof__()) + i8_ty: LLVMType* = pool.alloc(LLVMType.__sizeof__()) if i8_ty is None: return None string.memset(i8_ty, 0, LLVMType.__sizeof__()) c.DerefAs(i8_ty, LLVMType.Int(8)) # create [count x i8] array type - arr_ty: rawptr[LLVMType] = pool.alloc(LLVMType.__sizeof__()) + arr_ty: LLVMType* = pool.alloc(LLVMType.__sizeof__()) if arr_ty is None: return None string.memset(arr_ty, 0, LLVMType.__sizeof__()) c.DerefAs(arr_ty, LLVMType.Array(i8_ty, count)) # create global variable name_dup: str = _str_dup(pool, name) - gv: rawptr[GlobalVariable] = new_global_variable(pool, name_dup, arr_ty) + gv: GlobalVariable* = new_global_variable(pool, name_dup, arr_ty) if gv is None: return None # set attributes: private + unnamed_addr + constant @@ -310,19 +310,19 @@ def create_global_string(pool: memhub.MemBuddy*, mod: rawptr[LLVMModule], # ============================================================ # Convenience factory: create an integer global with an initializer # ============================================================ -def create_global_int(pool: memhub.MemBuddy*, mod: rawptr[LLVMModule], - name: str, bits: int, val: int64) -> rawptr[GlobalVariable]: +def create_global_int(pool: memhub.MemBuddy*, mod: LLVMModule*, + name: str, bits: int, val: int64) -> GlobalVariable*: """Create an integer global variable and add it to the module. MLIR output: llvm.mlir.global @( : i) : i """ # create integer type - ty: rawptr[LLVMType] = pool.alloc(LLVMType.__sizeof__()) + ty: LLVMType* = pool.alloc(LLVMType.__sizeof__()) if ty is None: return None string.memset(ty, 0, LLVMType.__sizeof__()) c.DerefAs(ty, LLVMType.Int(bits)) name_dup: str = _str_dup(pool, name) - gv: rawptr[GlobalVariable] = new_global_variable(pool, name_dup, ty) + gv: GlobalVariable* = new_global_variable(pool, name_dup, ty) if gv is None: return None # build initializer text "42" (the type is printed separately by the global render stage) @@ -353,109 +353,109 @@ class LLVMModuleCore: self.Pool = pool # ---- module operations ---- - def NewModule(self, name: str) -> rawptr[LLVMModule]: + def NewModule(self, name: str) -> LLVMModule*: return new_module(self.Pool, name) - def CreateFunction(self, mod: rawptr[LLVMModule], name: str, - ret_ty: rawptr[LLVMType]) -> rawptr[Function]: + def CreateFunction(self, mod: LLVMModule*, name: str, + ret_ty: LLVMType*) -> Function*: return create_function(self.Pool, mod, name, ret_ty) - def CreateDeclare(self, mod: rawptr[LLVMModule], name: str, - ret_ty: rawptr[LLVMType]) -> rawptr[Function]: + def CreateDeclare(self, mod: LLVMModule*, name: str, + ret_ty: LLVMType*) -> Function*: """Create a function declaration (declare, no body).""" return create_declare(self.Pool, mod, name, ret_ty) - def AddParam(self, func: rawptr[Function], ty: rawptr[LLVMType], - name: str) -> rawptr[Param]: + def AddParam(self, func: Function*, ty: LLVMType*, + name: str) -> Param*: return add_param(self.Pool, func, ty, name) - def FunctionSetAttrs(self, func: rawptr[Function], attrs: str): + def FunctionSetAttrs(self, func: Function*, attrs: str): """Set the function-level attribute text.""" function_set_attrs(func, attrs) - def ParamSetAttrs(self, param: rawptr[Param], attrs: str): + def ParamSetAttrs(self, param: Param*, attrs: str): """Set the parameter attribute text.""" param_set_attrs(param, attrs) - def CreateBlock(self, func: rawptr[Function], - name: str) -> rawptr[BasicBlock]: + def CreateBlock(self, func: Function*, + name: str) -> BasicBlock*: return create_block(self.Pool, func, name) - def NewBuilder(self, func: rawptr[Function]) -> rawptr[IRBuilder]: + def NewBuilder(self, func: Function*) -> IRBuilder*: return new_builder(self.Pool, func) # ---- globals ---- - def NewGlobal(self, mod: rawptr[LLVMModule], name: str, - ty: rawptr[LLVMType]) -> rawptr[GlobalVariable]: + def NewGlobal(self, mod: LLVMModule*, name: str, + ty: LLVMType*) -> GlobalVariable*: """Create a global variable and add it to the module.""" name_dup: str = _str_dup(self.Pool, name) - gv: rawptr[GlobalVariable] = new_global_variable(self.Pool, name_dup, ty) + gv: GlobalVariable* = new_global_variable(self.Pool, name_dup, ty) if gv is not None: module_add_global(mod, gv) return gv - def CreateGlobalString(self, mod: rawptr[LLVMModule], name: str, - text: str) -> rawptr[GlobalVariable]: + def CreateGlobalString(self, mod: LLVMModule*, name: str, + text: str) -> GlobalVariable*: """Create a string-constant global variable.""" return create_global_string(self.Pool, mod, name, text) - def CreateGlobalInt(self, mod: rawptr[LLVMModule], name: str, - bits: int, val: int64) -> rawptr[GlobalVariable]: + def CreateGlobalInt(self, mod: LLVMModule*, name: str, + bits: int, val: int64) -> GlobalVariable*: """Create an integer global with an initializer.""" return create_global_int(self.Pool, mod, name, bits, val) - def GlobalSetConstant(self, gv: rawptr[GlobalVariable], is_const: int): + def GlobalSetConstant(self, gv: GlobalVariable*, is_const: int): global_set_constant(gv, is_const) - def GlobalSetLinkage(self, gv: rawptr[GlobalVariable], linkage: str): + def GlobalSetLinkage(self, gv: GlobalVariable*, linkage: str): global_set_linkage(gv, linkage) - def GlobalSetUnnamedAddr(self, gv: rawptr[GlobalVariable], level: int): + def GlobalSetUnnamedAddr(self, gv: GlobalVariable*, level: int): global_set_unnamed_addr(gv, level) - def GlobalSetSection(self, gv: rawptr[GlobalVariable], section: str): + def GlobalSetSection(self, gv: GlobalVariable*, section: str): global_set_section(gv, section) # ---- value creation ---- - def ConstInt(self, bits: int, val: int64) -> rawptr[Value]: + def ConstInt(self, bits: int, val: int64) -> Value*: return const_int(self.Pool, bits, val) - def ConstInt32(self, val: int64) -> rawptr[Value]: + def ConstInt32(self, val: int64) -> Value*: return const_int32(self.Pool, val) - def ConstInt64(self, val: int64) -> rawptr[Value]: + def ConstInt64(self, val: int64) -> Value*: return const_int64(self.Pool, val) - def ConstFloat(self, ty: rawptr[LLVMType], val: double) -> rawptr[Value]: + def ConstFloat(self, ty: LLVMType*, val: double) -> Value*: return ConstFloat(self.Pool, ty, val) - def SSAValue(self, ty: rawptr[LLVMType], name: str) -> rawptr[Value]: + def SSAValue(self, ty: LLVMType*, name: str) -> Value*: return SSAValue(self.Pool, ty, name) - def ConstNull(self, ty: rawptr[LLVMType], name: str) -> rawptr[Value]: + def ConstNull(self, ty: LLVMType*, name: str) -> Value*: return ConstNull(self.Pool, ty, name) # ---- printing ---- - def PrintValue(self, buf: str, size: sizet, val: rawptr[Value]): + def PrintValue(self, buf: str, size: sizet, val: Value*): ValuePrint(buf, size, val, self.Pool) - def PrintFunction(self, buf: str, size: sizet, func: rawptr[Function]): + def PrintFunction(self, buf: str, size: sizet, func: Function*): FunctionPrint(buf, size, func, self.Pool) - def PrintModule(self, buf: str, size: sizet, mod: rawptr[LLVMModule]): + def PrintModule(self, buf: str, size: sizet, mod: LLVMModule*): LLVMModulePrint(buf, size, mod, self.Pool, OUTPUT_FULL) # ---- SSA verification ---- - def NewVerifyResult(self, buf_size: sizet) -> rawptr[VerifyResult]: + def NewVerifyResult(self, buf_size: sizet) -> VerifyResult*: """Create a verify-result object (buf_size = error message buffer size).""" return _new_verify_result(self.Pool, buf_size) - def VerifyFunction(self, func: rawptr[Function], - result: rawptr[VerifyResult]) -> int: + def VerifyFunction(self, func: Function*, + result: VerifyResult*) -> int: """Verify SSA correctness of one function; returns error count (0 = pass).""" return verify_function(self.Pool, func, result) - def VerifyModule(self, mod: rawptr[LLVMModule], - result: rawptr[VerifyResult]) -> int: + def VerifyModule(self, mod: LLVMModule*, + result: VerifyResult*) -> int: """Verify SSA correctness of all functions in the module; returns error count (0 = pass).""" return verify_module(self.Pool, mod, result) diff --git a/mlirlite/__module.vp b/mlirlite/__module.vp index 85f1a65..60fe7d3 100644 --- a/mlirlite/__module.vp +++ b/mlirlite/__module.vp @@ -23,7 +23,7 @@ from .__function import ( # and linkage; strong-typed Next via GSListNode[GlobalVariable]. novirtual class GlobalVariable(GSListNode[GlobalVariable]): Name: str # Global name (e.g. ".str" / "my_global") - Ty: rawptr[LLVMType] # Variable type + Ty: LLVMType* # Variable type Initializer: rawptr # Initializer Value* (None = no initializer) IsConstant: int # 1=constant, 0=variable Linkage: str # Linkage ("private"/"internal"/"external"/...) @@ -36,7 +36,7 @@ novirtual class GlobalVariable(GSListNode[GlobalVariable]): # strong-typed Next via GSListNode[NamedTypeNode]. @t.NoVTable class NamedTypeNode(GSListNode[NamedTypeNode]): - Ty: rawptr[LLVMType] # Named-struct type pointer + Ty: LLVMType* # Named-struct type pointer IsPacked: int # 1 = packed struct (MLIR !llvm.struct<"name", packed (…)>; no field padding) @@ -61,22 +61,22 @@ class DINamedMeta(GSListNode[DINamedMeta]): @t.NoVTable class LLVMModule: Name: str # Module name - FuncHead: rawptr[Function] # Function list head - FuncTail: rawptr[Function] # Function list tail + FuncHead: Function* # Function list head + FuncTail: Function* # Function list tail FuncCount: sizet # Function count - GlobalHead: rawptr[GlobalVariable] # Global list head - GlobalTail: rawptr[GlobalVariable] # Global list tail + GlobalHead: GlobalVariable* # Global list head + GlobalTail: GlobalVariable* # Global list tail GlobalCount: sizet # Global count TargetTriple: str # Target triple (e.g. "x86_64-pc-linux-gnu") DataLayout: str # Data layout (e.g. "e-m:e-p270:32:32-...") - NamedTypeHead: rawptr[NamedTypeNode] # Named-struct type list head - NamedTypeTail: rawptr[NamedTypeNode] # Named-struct type list tail + NamedTypeHead: NamedTypeNode* # Named-struct type list head + NamedTypeTail: NamedTypeNode* # Named-struct type list tail NamedTypeCount: sizet # Named-struct type count - DIMetaHead: rawptr[DINode] # DI metadata node list head (kept in sync; not printed by MLIR) - DIMetaTail: rawptr[DINode] # DI metadata node list tail + DIMetaHead: DINode* # DI metadata node list head (kept in sync; not printed by MLIR) + DIMetaTail: DINode* # DI metadata node list tail DIMetaCount: sizet # DI node count (= next !N id) - DINamedHead: rawptr[DINamedMeta] # named metadata list head - DINamedTail: rawptr[DINamedMeta] # named metadata list tail + DINamedHead: DINamedMeta* # named metadata list head + DINamedTail: DINamedMeta* # named metadata list tail DINamedCount: sizet # named metadata count # Total: 18 fields * 8 = 144 bytes (no vtable; same layout as includes/llvmlite) @@ -84,7 +84,7 @@ class LLVMModule: # kept as one-line delegates). # ---- List operations ---- - def add_function(self, func: rawptr[Function]): + def add_function(self, func: Function*): """Append a function to the module's function list (O(1)).""" if self is None or func is None: return func.Next = None @@ -95,7 +95,7 @@ class LLVMModule: self.FuncTail = func self.FuncCount += 1 - def add_global(self, gv: rawptr[GlobalVariable]): + def add_global(self, gv: GlobalVariable*): """Append a global to the module's global list (O(1)).""" if self is None or gv is None: return gv.Next = None @@ -127,7 +127,7 @@ class LLVMModule: """ if self is None or pool is None or text is None: return -1 - node: rawptr[DINode] = pool.alloc(DI_NODE_SIZE) + node: DINode* = pool.alloc(DI_NODE_SIZE) if node is None: return -1 string.memset(node, 0, DI_NODE_SIZE) @@ -155,7 +155,7 @@ class LLVMModule: """ if self is None or pool is None or name is None: return - cur: rawptr[DINamedMeta] = self.DINamedHead + cur: DINamedMeta* = self.DINamedHead cur_steps: sizet = 0 while cur is not None: cur_steps += 1 @@ -178,7 +178,7 @@ class LLVMModule: cur.Refs = merged return cur = cur.Next - entry: rawptr[DINamedMeta] = pool.alloc(DI_NAMED_SIZE) + entry: DINamedMeta* = pool.alloc(DI_NAMED_SIZE) if entry is None: return string.memset(entry, 0, DI_NAMED_SIZE) @@ -201,7 +201,7 @@ class LLVMModule: self.DINamedCount += 1 # ---- Named-struct type management ---- - def add_named_type(self, pool: memhub.MemBuddy*, ty: rawptr[LLVMType]): + def add_named_type(self, pool: memhub.MemBuddy*, ty: LLVMType*): """Register a named struct type in the module (MLIR keeps the model only, no output). Non-named structs (None Name or non-Struct) are ignored. Dedup by Name; a full definition @@ -215,7 +215,7 @@ class LLVMModule: if name is None: return # Dedup check (a full definition may replace an opaque declaration) - cur: rawptr[NamedTypeNode] = self.NamedTypeHead + cur: NamedTypeNode* = self.NamedTypeHead cnt_dedup: int = 0 while cur is not None: # Step guard: a cyclic NamedTypeHead list (corruption/insert bug) would hang the @@ -241,7 +241,7 @@ class LLVMModule: return cur = cur.Next # Create a new node - node: rawptr[NamedTypeNode] = pool.alloc(NAMED_TYPE_NODE_SIZE) + node: NamedTypeNode* = pool.alloc(NAMED_TYPE_NODE_SIZE) if node is None: return string.memset(node, 0, NAMED_TYPE_NODE_SIZE) @@ -268,7 +268,7 @@ class LLVMModule: """Return 1 if the module already defines a struct with this name, else 0.""" if self is None or name is None: return 0 - cur: rawptr[NamedTypeNode] = self.NamedTypeHead + cur: NamedTypeNode* = self.NamedTypeHead cnt_tdm: int = 0 while cur is not None: # Step guard: as above, prevent infinite traversal of a cyclic NamedTypeHead @@ -287,7 +287,7 @@ class LLVMModule: return 0 def ensure_opaque_for_type(self, pool: memhub.MemBuddy*, - ty: rawptr[LLVMType]): + ty: LLVMType*): """Add opaque declarations for cross-module struct references in a type. When the type references Ptr(Struct(name)) with a '.' in name (SHA1-qualified) and the @@ -343,7 +343,7 @@ class LLVMModule: # Globals (MLIR has no standalone type-definition line: named structs are inlined at the # use site, so NamedTypeHead definitions are not emitted here, only registered for lookup). - gv: rawptr[GlobalVariable] = self.GlobalHead + gv: GlobalVariable* = self.GlobalHead gv_steps: sizet = 0 while gv is not None: gv_steps += 1 @@ -365,7 +365,7 @@ class LLVMModule: gv = gv.Next # Walk functions (filter declare/define by mode) - func: rawptr[Function] = self.FuncHead + func: Function* = self.FuncHead func_steps: sizet = 0 while func is not None: func_steps += 1 @@ -397,7 +397,7 @@ class LLVMModule: # Name-only type text (%"sha1.Cls") must expand to the inline named body, so this publishes a # name → full-definition lookup (opaque entries too, so they report "still opaque", not # "unregistered") plus each node's packed flag (NamedTypeNode.IsPacked) for the render side. -def _MlirPublishNamedTypes(mod: rawptr[LLVMModule], pool: memhub.MemBuddy*): +def _MlirPublishNamedTypes(mod: LLVMModule*, pool: memhub.MemBuddy*): """Rebuild the named-struct registry from NamedTypeHead (print-time lookup, incl. packed). Count the real list length first (not trusting NamedTypeCount), then allocate exactly that @@ -407,7 +407,7 @@ def _MlirPublishNamedTypes(mod: rawptr[LLVMModule], pool: memhub.MemBuddy*): if mod is None or pool is None: return cnt: sizet = 0 - nt: rawptr[NamedTypeNode] = mod.NamedTypeHead + nt: NamedTypeNode* = mod.NamedTypeHead nt_steps: sizet = 0 while nt is not None: nt_steps += 1 @@ -434,11 +434,11 @@ def _MlirPublishNamedTypes(mod: rawptr[LLVMModule], pool: memhub.MemBuddy*): # Factory functions -def new_module(pool: memhub.MemBuddy*, name: str) -> rawptr[LLVMModule]: +def new_module(pool: memhub.MemBuddy*, name: str) -> LLVMModule*: """Create a module.""" # Hardcoded 144 bytes: 18 fields * 8 bytes (no vtable, @t.NoVTable), incl. the DI fields # (DIMetaHead/Tail/Count, DINamedHead/Tail/Count), same layout as llvmlite. - ptr: rawptr[LLVMModule] = pool.alloc(144) + ptr: LLVMModule* = pool.alloc(144) if ptr is None: return None string.memset(ptr, 0, 144) ptr.Name = name @@ -475,9 +475,9 @@ define DI_NODE_SIZE = 16 define DI_NAMED_SIZE = 24 def new_global_variable(pool: memhub.MemBuddy*, - name: str, ty: rawptr[LLVMType]) -> rawptr[GlobalVariable]: + name: str, ty: LLVMType*) -> GlobalVariable*: """Create a global variable.""" - ptr: rawptr[GlobalVariable] = pool.alloc(GV_SIZE) + ptr: GlobalVariable* = pool.alloc(GV_SIZE) if ptr is None: return None string.memset(ptr, 0, GV_SIZE) ptr.Name = name @@ -492,37 +492,37 @@ def new_global_variable(pool: memhub.MemBuddy*, # List operations (embedded Head/Tail/Count, O(1) append) -def module_add_function(mod: rawptr[LLVMModule], func: rawptr[Function]): +def module_add_function(mod: LLVMModule*, func: Function*): mod.add_function(func) -def module_get_func_head(mod: rawptr[LLVMModule]) -> rawptr[Function]: +def module_get_func_head(mod: LLVMModule*) -> Function*: """Return the module's function list head (cross-module accessor bypassing the stub-field trap).""" if mod is None: return None return mod.FuncHead -def module_add_global(mod: rawptr[LLVMModule], gv: rawptr[GlobalVariable]): +def module_add_global(mod: LLVMModule*, gv: GlobalVariable*): mod.add_global(gv) -def module_set_target(mod: rawptr[LLVMModule], triple: str): +def module_set_target(mod: LLVMModule*, triple: str): mod.set_target(triple) -def module_set_datalayout(mod: rawptr[LLVMModule], layout: str): +def module_set_datalayout(mod: LLVMModule*, layout: str): mod.set_datalayout(layout) # DI debug metadata (kept in sync; ignored at MLIR print time, model only) -def module_add_di_node(mod: rawptr[LLVMModule], pool: memhub.MemBuddy*, +def module_add_di_node(mod: LLVMModule*, pool: memhub.MemBuddy*, text: str) -> int: """Append a DI metadata node; return its !N id (-1 on failure).""" return mod.add_di_node(pool, text) -def module_add_named_metadata(mod: rawptr[LLVMModule], pool: memhub.MemBuddy*, +def module_add_named_metadata(mod: LLVMModule*, pool: memhub.MemBuddy*, name: str, refs: str): """Register named metadata "! = !{ }".""" mod.add_named_metadata(pool, name, refs) @@ -535,7 +535,7 @@ def module_add_named_metadata(mod: rawptr[LLVMModule], pool: memhub.MemBuddy*, # name only), created by Struct(pool, None, -1, name). Must be distinguished from an empty struct # (fcount==0, fields==None), which is a valid full definition ({} type, allocatable). # Returns: 1 = opaque / 0 = not. -def _is_opaque_struct(ty: rawptr[LLVMType]) -> int: +def _is_opaque_struct(ty: LLVMType*) -> int: """Return 1 if the type is an opaque struct, else 0. opaque is a cross-module forward declaration (name only) created by @@ -555,13 +555,13 @@ def _is_opaque_struct(ty: rawptr[LLVMType]) -> int: return 0 -def module_add_named_type(mod: rawptr[LLVMModule], pool: memhub.MemBuddy*, - ty: rawptr[LLVMType]): +def module_add_named_type(mod: LLVMModule*, pool: memhub.MemBuddy*, + ty: LLVMType*): mod.add_named_type(pool, ty) -def module_set_named_type_packed(mod: rawptr[LLVMModule], pool: memhub.MemBuddy*, - ty: rawptr[LLVMType], is_packed: int): +def module_set_named_type_packed(mod: LLVMModule*, pool: memhub.MemBuddy*, + ty: LLVMType*, is_packed: int): """Set a named struct's packed flag by name (MLIR emits !llvm.struct<"name", packed (…)>). Called after parsing @c.Attribute(t.attr.packed) so llc computes field offsets/GEP with the @@ -575,7 +575,7 @@ def module_set_named_type_packed(mod: rawptr[LLVMModule], pool: memhub.MemBuddy* name: str = get_struct_name(ty) if name is None: return - cur: rawptr[NamedTypeNode] = mod.NamedTypeHead + cur: NamedTypeNode* = mod.NamedTypeHead cnt_p: int = 0 while cur is not None: cnt_p += 1 @@ -592,13 +592,13 @@ def module_set_named_type_packed(mod: rawptr[LLVMModule], pool: memhub.MemBuddy* # module_ensure_opaque_for_type - add opaque declarations for cross-module struct references. # Recursively scans the LLVMType tree; for a Ptr(Struct(name)) whose '.'-containing (SHA1-qualified) # name is undefined in the module, adds an opaque declaration, fixing llc "use of undefined type". -def _is_type_defined_in_module(mod: rawptr[LLVMModule], name: str) -> int: +def _is_type_defined_in_module(mod: LLVMModule*, name: str) -> int: return mod._is_type_defined_in_module(name) def _scan_type_for_cross_module_refs(pool: memhub.MemBuddy*, - mod: rawptr[LLVMModule], - ty: rawptr[LLVMType], + mod: LLVMModule*, + ty: LLVMType*, depth: int = 0): """Recursively scan the type tree and add opaque declarations for cross-module struct refs.""" if ty is None or mod is None or pool is None: @@ -620,13 +620,13 @@ def _scan_type_for_cross_module_refs(pool: memhub.MemBuddy*, # Create an opaque type and add it to the module; fcount=-1 marks # opaque (vs. empty {} struct, whose fcount==0 is a valid # full definition and can be alloc'd). - opaque_ty: rawptr[LLVMType] = Struct(pool, None, -1, sname) + opaque_ty: LLVMType* = Struct(pool, None, -1, sname) if opaque_ty is not None: module_add_named_type(mod, pool, opaque_ty) # Recurse into struct fields for cross-module refs # (e.g. HashTable in TypeRegistry{HashTable*, MemManager*}). if sfields is not None: - fld: rawptr[ParamNode] = sfields + fld: ParamNode* = sfields fld_steps: sizet = 0 while fld is not None: fld_steps += 1 @@ -642,7 +642,7 @@ def _scan_type_for_cross_module_refs(pool: memhub.MemBuddy*, case LLVMType.Struct(sfields2, sfcount2, sname2): # Top-level struct (non-pointer): recurse into fields if sfields2 is not None: - fld2: rawptr[ParamNode] = sfields2 + fld2: ParamNode* = sfields2 fld2_steps: sizet = 0 while fld2 is not None: fld2_steps += 1 @@ -660,32 +660,32 @@ def _scan_type_for_cross_module_refs(pool: memhub.MemBuddy*, pass -def module_ensure_opaque_for_type(mod: rawptr[LLVMModule], +def module_ensure_opaque_for_type(mod: LLVMModule*, pool: memhub.MemBuddy*, - ty: rawptr[LLVMType]): + ty: LLVMType*): mod.ensure_opaque_for_type(pool, ty) # Global variable attribute setters -def global_set_constant(gv: rawptr[GlobalVariable], is_const: int): +def global_set_constant(gv: GlobalVariable*, is_const: int): """Set whether the global is a constant.""" if gv is None: return gv.IsConstant = is_const -def global_set_linkage(gv: rawptr[GlobalVariable], linkage: str): +def global_set_linkage(gv: GlobalVariable*, linkage: str): """Set the linkage (private/internal/external/...).""" if gv is None: return gv.Linkage = linkage -def global_set_unnamed_addr(gv: rawptr[GlobalVariable], level: int): +def global_set_unnamed_addr(gv: GlobalVariable*, level: int): """Set the unnamed_addr attribute (0=none, 1=unnamed_addr, 2=local_unnamed_addr).""" if gv is None: return gv.UnnamedAddr = level -def global_set_section(gv: rawptr[GlobalVariable], section: str): +def global_set_section(gv: GlobalVariable*, section: str): """Set the section name.""" if gv is None: return gv.Section = section @@ -704,7 +704,7 @@ _MlirModOutTrunc: int = 0 # LLVMModulePrint: serialize the module to .ll text; mode: OUTPUT_FULL / OUTPUT_STUB / OUTPUT_TEXT. def LLVMModulePrint(buf: str, size: sizet, - mod: rawptr[LLVMModule], pool: memhub.MemBuddy*, + mod: LLVMModule*, pool: memhub.MemBuddy*, mode: int): global _MlirModOutTrunc _MlirModOutTrunc = 0 @@ -720,7 +720,7 @@ def LLVMModulePrint(buf: str, size: sizet, # zeroinitializer, struct/vtable, symbol-referencing aggregates, pointer initializers → empty value # parens + initializer region). Any form neither path covers fails loud via MlirFail. def _MlirGlobalLine(buf: str, size: sizet, - pool: memhub.MemBuddy*, gv: rawptr[GlobalVariable], + pool: memhub.MemBuddy*, gv: GlobalVariable*, stub: int): """Render one llvm.mlir.global (stub=1 emits the external declaration form).""" if gv is None: @@ -803,7 +803,7 @@ def _MlirGlobalLine(buf: str, size: sizet, def _MlirGlobalInit(buf: str, size: sizet, - pool: memhub.MemBuddy*, gv: rawptr[GlobalVariable]): + pool: memhub.MemBuddy*, gv: GlobalVariable*): """Render a global initializer (MLIR attribute text).""" x: str = gv.Initializer if x is None: @@ -1057,7 +1057,7 @@ def _MlirGvArrayNeedsRegion(x: str) -> int: def _MlirGlobalInitRegion(buf: str, size: sizet, - pool: memhub.MemBuddy*, gv: rawptr[GlobalVariable]): + pool: memhub.MemBuddy*, gv: GlobalVariable*): """Render the initializer region body (lines indented 2 spaces, without the outer braces). Each line ends with '\\n'; the caller appends '}' and the module layer re-indents by 2. @@ -1116,7 +1116,7 @@ def _MlirGlobalInitRegion(buf: str, size: sizet, _append_cstr(buf, size, "\n") -def _MlirGvWalk(p: str, ty: rawptr[LLVMType], path: str, depth: int) -> str: +def _MlirGvWalk(p: str, ty: LLVMType*, path: str, depth: int) -> str: """Walk one node of the initializer-tree × type-tree in parallel; returns the new cursor. The result SSA name goes to _MlirGvLast (leaf = materialized name; aggregate = last @@ -1230,15 +1230,15 @@ def _MlirGvPathChild(path: str, idx: int, depth: int) -> str: return nb -def _MlirGvWalkStruct(p: str, ty: rawptr[LLVMType], path: str, depth: int) -> str: +def _MlirGvWalkStruct(p: str, ty: LLVMType*, path: str, depth: int) -> str: """Struct initializer { elem, elem, … }: field types come from the type tree's Struct field chain.""" - fields: rawptr[ParamNode] = None + fields: ParamNode* = None match ty: case LLVMType.Struct(sf, sfc, sn): fields = sf case _: MlirFail("MLIR 渲染: 初值为结构体,但全局类型不是结构体") - cur: rawptr[ParamNode] = fields + cur: ParamNode* = fields p = p + 1 idx: int = 0 done: int = 0 @@ -1256,7 +1256,7 @@ def _MlirGvWalkStruct(p: str, ty: rawptr[LLVMType], path: str, depth: int) -> st elif p[0] == ',': p = p + 1 else: - fty: rawptr[LLVMType] = None + fty: LLVMType* = None if cur is not None: fty = paramnode_get_ty(cur) p = _MlirGvWalk(p, fty, _MlirGvPathChild(path, idx, depth), depth + 1) @@ -1268,9 +1268,9 @@ def _MlirGvWalkStruct(p: str, ty: rawptr[LLVMType], path: str, depth: int) -> st return p -def _MlirGvWalkArray(p: str, ty: rawptr[LLVMType], path: str, depth: int) -> str: +def _MlirGvWalkArray(p: str, ty: LLVMType*, path: str, depth: int) -> str: """Array initializer [ elem, elem, … ]: element type comes from the type tree's Array element type.""" - elem_ty: rawptr[LLVMType] = None + elem_ty: LLVMType* = None match ty: case LLVMType.Array(ae, ac): elem_ty = ae @@ -1326,7 +1326,7 @@ def _MlirGvIsBareValue(p: str) -> int: return 0 -def _MlirGvWalkLeaf(p: str, ty: rawptr[LLVMType], path: str, depth: int) -> str: +def _MlirGvWalkLeaf(p: str, ty: LLVMType*, path: str, depth: int) -> str: """Leaf element ` `: the value parses to a symbol ref / null / scalar literal. The element MLIR type comes from the type tree (ty), not the text's type token. A top-level @@ -1465,7 +1465,7 @@ def _MlirGvEmitAddressOf(name: str): string.strcpy(_MlirGvLast, ln) -def _MlirGvEmitZero(ty: rawptr[LLVMType]): +def _MlirGvEmitZero(ty: LLVMType*): """Emit a leaf op: %vN = llvm.mlir.zero : .""" mt: str = _MlirGvTyBuf mt[0] = '\0' @@ -1479,7 +1479,7 @@ def _MlirGvEmitZero(ty: rawptr[LLVMType]): string.strcpy(_MlirGvLast, ln) -def _MlirGvEmitConst(val: str, ty: rawptr[LLVMType]): +def _MlirGvEmitConst(val: str, ty: LLVMType*): """Emit a leaf op: %vN = llvm.mlir.constant( : ) : .""" mt: str = _MlirGvTyBuf mt[0] = '\0' diff --git a/mlirlite/__types.vp b/mlirlite/__types.vp index b426815..4fd6116 100644 --- a/mlirlite/__types.vp +++ b/mlirlite/__types.vp @@ -24,23 +24,23 @@ class LLVMType(t.REnum): # Pointer type: pointee* class Ptr: - Pointee: rawptr[LLVMType] + Pointee: LLVMType* # Function type: ret (params) class Func: - Ret: rawptr[LLVMType] - Params: rawptr[ParamNode] + Ret: LLVMType* + Params: ParamNode* PCount: int # Array type: [N x elem_ty] class Array: - ElemTy: rawptr[LLVMType] + ElemTy: LLVMType* Count: int # Struct type {ty1, ty2, ...} or %"name" = type {...}; Fields reuse the ParamNode list # (ParamNode.Ty is the field type); a non-None Name makes it named (%"name" output). class Struct: - Fields: rawptr[ParamNode] + Fields: ParamNode* FCount: int Name: str @@ -73,52 +73,52 @@ def _TypeSizeGuard() -> sizet: return sz -def _new_type(pool: memhub.MemBuddy*) -> rawptr[LLVMType]: +def _new_type(pool: memhub.MemBuddy*) -> LLVMType*: """Allocate a zero-initialized LLVMType from the pool.""" sz_nt: sizet = _TypeSizeGuard() - ptr: rawptr[LLVMType] = pool.alloc(sz_nt) + ptr: LLVMType* = pool.alloc(sz_nt) if ptr: string.memset(ptr, 0, sz_nt) return ptr # Type factory functions -def Int1(pool: memhub.MemBuddy*) -> rawptr[LLVMType]: - ptr: rawptr[LLVMType] = _new_type(pool) +def Int1(pool: memhub.MemBuddy*) -> LLVMType*: + ptr: LLVMType* = _new_type(pool) if ptr is None: return None c.DerefAs(ptr, LLVMType.Int(1)) return ptr -def Int8(pool: memhub.MemBuddy*) -> rawptr[LLVMType]: - ptr: rawptr[LLVMType] = _new_type(pool) +def Int8(pool: memhub.MemBuddy*) -> LLVMType*: + ptr: LLVMType* = _new_type(pool) if ptr is None: return None c.DerefAs(ptr, LLVMType.Int(8)) return ptr -def Int16(pool: memhub.MemBuddy*) -> rawptr[LLVMType]: - ptr: rawptr[LLVMType] = _new_type(pool) +def Int16(pool: memhub.MemBuddy*) -> LLVMType*: + ptr: LLVMType* = _new_type(pool) if ptr is None: return None c.DerefAs(ptr, LLVMType.Int(16)) return ptr -def Int32(pool: memhub.MemBuddy*) -> rawptr[LLVMType]: - ptr: rawptr[LLVMType] = _new_type(pool) +def Int32(pool: memhub.MemBuddy*) -> LLVMType*: + ptr: LLVMType* = _new_type(pool) if ptr is None: return None c.DerefAs(ptr, LLVMType.Int(32)) return ptr -def Int64(pool: memhub.MemBuddy*) -> rawptr[LLVMType]: - ptr: rawptr[LLVMType] = _new_type(pool) +def Int64(pool: memhub.MemBuddy*) -> LLVMType*: + ptr: LLVMType* = _new_type(pool) if ptr is None: return None c.DerefAs(ptr, LLVMType.Int(64)) return ptr -def Ptr(pool: memhub.MemBuddy*, pointee: rawptr[LLVMType]) -> rawptr[LLVMType]: +def Ptr(pool: memhub.MemBuddy*, pointee: LLVMType*) -> LLVMType*: """Create pointer type Ptr(pointee). LLVM IR forbids void* pointers ("pointers to void are invalid"): None or @@ -126,7 +126,7 @@ def Ptr(pool: memhub.MemBuddy*, pointee: rawptr[LLVMType]) -> rawptr[LLVMType]: all other types build Ptr(pointee) normally. """ # Pre-check: reject Void / None pointee (void* is illegal). - safe_pointee: rawptr[LLVMType] = pointee + safe_pointee: LLVMType* = pointee if safe_pointee is None: safe_pointee = Int8(pool) else: @@ -135,84 +135,84 @@ def Ptr(pool: memhub.MemBuddy*, pointee: rawptr[LLVMType]) -> rawptr[LLVMType]: safe_pointee = Int8(pool) case _: pass - ptr: rawptr[LLVMType] = _new_type(pool) + ptr: LLVMType* = _new_type(pool) if ptr is None: return None c.DerefAs(ptr, LLVMType.Ptr(safe_pointee)) return ptr -def Func(pool: memhub.MemBuddy*, ret: rawptr[LLVMType], - params: rawptr[ParamNode], count: int) -> rawptr[LLVMType]: - ptr: rawptr[LLVMType] = _new_type(pool) +def Func(pool: memhub.MemBuddy*, ret: LLVMType*, + params: ParamNode*, count: int) -> LLVMType*: + ptr: LLVMType* = _new_type(pool) if ptr is None: return None c.DerefAs(ptr, LLVMType.Func(ret, params, count)) return ptr -def Void(pool: memhub.MemBuddy*) -> rawptr[LLVMType]: - ptr: rawptr[LLVMType] = _new_type(pool) +def Void(pool: memhub.MemBuddy*) -> LLVMType*: + ptr: LLVMType* = _new_type(pool) if ptr is None: return None c.DerefAs(ptr, LLVMType.Void()) return ptr -def Array(pool: memhub.MemBuddy*, elem_ty: rawptr[LLVMType], - count: int) -> rawptr[LLVMType]: +def Array(pool: memhub.MemBuddy*, elem_ty: LLVMType*, + count: int) -> LLVMType*: """Create array type [count x elem_ty].""" - ptr: rawptr[LLVMType] = _new_type(pool) + ptr: LLVMType* = _new_type(pool) if ptr is None: return None c.DerefAs(ptr, LLVMType.Array(elem_ty, count)) return ptr -def Struct(pool: memhub.MemBuddy*, fields: rawptr[ParamNode], - fcount: int, name: str) -> rawptr[LLVMType]: +def Struct(pool: memhub.MemBuddy*, fields: ParamNode*, + fcount: int, name: str) -> LLVMType*: """Create struct type {ty1, ty2, ...}. fields is the ParamNode list head and fcount the field count; a non-None name (e.g. "sha1.ClassName") yields a named struct printed as %"name", else anonymous. """ - ptr: rawptr[LLVMType] = _new_type(pool) + ptr: LLVMType* = _new_type(pool) if ptr is None: return None c.DerefAs(ptr, LLVMType.Struct(fields, fcount, name)) return ptr -def Half(pool: memhub.MemBuddy*) -> rawptr[LLVMType]: +def Half(pool: memhub.MemBuddy*) -> LLVMType*: """Create half-precision float type half (16-bit).""" - ptr: rawptr[LLVMType] = _new_type(pool) + ptr: LLVMType* = _new_type(pool) if ptr is None: return None c.DerefAs(ptr, LLVMType.Float(16)) return ptr -def Float(pool: memhub.MemBuddy*) -> rawptr[LLVMType]: +def Float(pool: memhub.MemBuddy*) -> LLVMType*: """Create single-precision float type float (32-bit).""" - ptr: rawptr[LLVMType] = _new_type(pool) + ptr: LLVMType* = _new_type(pool) if ptr is None: return None c.DerefAs(ptr, LLVMType.Float(32)) return ptr -def Double(pool: memhub.MemBuddy*) -> rawptr[LLVMType]: +def Double(pool: memhub.MemBuddy*) -> LLVMType*: """Create double-precision float type double (64-bit).""" - ptr: rawptr[LLVMType] = _new_type(pool) + ptr: LLVMType* = _new_type(pool) if ptr is None: return None c.DerefAs(ptr, LLVMType.Float(64)) return ptr -def FP128(pool: memhub.MemBuddy*) -> rawptr[LLVMType]: +def FP128(pool: memhub.MemBuddy*) -> LLVMType*: """Create quad-precision float type fp128 (128-bit).""" - ptr: rawptr[LLVMType] = _new_type(pool) + ptr: LLVMType* = _new_type(pool) if ptr is None: return None c.DerefAs(ptr, LLVMType.Float(128)) return ptr -def Label(pool: memhub.MemBuddy*) -> rawptr[LLVMType]: +def Label(pool: memhub.MemBuddy*) -> LLVMType*: """Create label type label.""" - ptr: rawptr[LLVMType] = _new_type(pool) + ptr: LLVMType* = _new_type(pool) if ptr is None: return None c.DerefAs(ptr, LLVMType.Label()) return ptr @@ -222,9 +222,9 @@ def Label(pool: memhub.MemBuddy*) -> rawptr[LLVMType]: # ParamNode hardcoded size: Next(8) + Ty(8) = 16 bytes define PNODE_SIZE = 16 -def new_param_node(pool: memhub.MemBuddy*, ty: rawptr[LLVMType]) -> rawptr[ParamNode]: +def new_param_node(pool: memhub.MemBuddy*, ty: LLVMType*) -> ParamNode*: """Create a parameter node with Ty set to the given type pointer.""" - ptr: rawptr[ParamNode] = pool.alloc(PNODE_SIZE) + ptr: ParamNode* = pool.alloc(PNODE_SIZE) if ptr is None: return None string.memset(ptr, 0, PNODE_SIZE) ptr.Ty = ty @@ -232,8 +232,8 @@ def new_param_node(pool: memhub.MemBuddy*, ty: rawptr[LLVMType]) -> rawptr[Param return ptr -def param_list_append(head: rawptr[ParamNode], tail: rawptr[ParamNode], - node: rawptr[ParamNode]) -> rawptr[ParamNode]: +def param_list_append(head: ParamNode*, tail: ParamNode*, + node: ParamNode*) -> ParamNode*: """Append node to the parameter list tail, returning head and updated tail.""" if node is None: return head node.Next = None @@ -246,28 +246,28 @@ def param_list_append(head: rawptr[ParamNode], tail: rawptr[ParamNode], # ParamNode field accessors (bypass the stub-type limitation): cross-module consumers # only have the stub type, so field access is skipped; these run where the type is full. -def paramnode_get_ty(node: rawptr[ParamNode]) -> rawptr[LLVMType]: +def paramnode_get_ty(node: ParamNode*) -> LLVMType*: """Return the parameter node's type.""" if node is None: return None - return (rawptr[LLVMType])(node.Ty) + return (LLVMType*)(node.Ty) -def paramnode_get_next(node: rawptr[ParamNode]) -> rawptr[ParamNode]: +def paramnode_get_next(node: ParamNode*) -> ParamNode*: """Return the next parameter node in the list.""" if node is None: return None return node.Next -def paramnode_set_ty(node: rawptr[ParamNode], ty: rawptr[LLVMType]): +def paramnode_set_ty(node: ParamNode*, ty: LLVMType*): """Set the parameter node's type.""" if node is None: return node.Ty = ty -def paramnode_set_next(node: rawptr[ParamNode], nxt: rawptr[ParamNode]): +def paramnode_set_next(node: ParamNode*, nxt: ParamNode*): """Set the next parameter node in the list.""" if node is None: return @@ -284,64 +284,64 @@ class LLVMTypeCore: def __init__(self, pool: memhub.MemBuddy*): self.Pool = pool - def Int1(self) -> rawptr[LLVMType]: + def Int1(self) -> LLVMType*: return Int1(self.Pool) - def Int8(self) -> rawptr[LLVMType]: + def Int8(self) -> LLVMType*: return Int8(self.Pool) - def Int16(self) -> rawptr[LLVMType]: + def Int16(self) -> LLVMType*: return Int16(self.Pool) - def Int32(self) -> rawptr[LLVMType]: + def Int32(self) -> LLVMType*: return Int32(self.Pool) - def Int64(self) -> rawptr[LLVMType]: + def Int64(self) -> LLVMType*: return Int64(self.Pool) - def Ptr(self, pointee: rawptr[LLVMType]) -> rawptr[LLVMType]: + def Ptr(self, pointee: LLVMType*) -> LLVMType*: return Ptr(self.Pool, pointee) - def Func(self, ret: rawptr[LLVMType], params: rawptr[ParamNode], - count: int) -> rawptr[LLVMType]: + def Func(self, ret: LLVMType*, params: ParamNode*, + count: int) -> LLVMType*: return Func(self.Pool, ret, params, count) - def Array(self, elem_ty: rawptr[LLVMType], count: int) -> rawptr[LLVMType]: + def Array(self, elem_ty: LLVMType*, count: int) -> LLVMType*: return Array(self.Pool, elem_ty, count) - def Struct(self, fields: rawptr[ParamNode], fcount: int, - name: str = None) -> rawptr[LLVMType]: + def Struct(self, fields: ParamNode*, fcount: int, + name: str = None) -> LLVMType*: return Struct(self.Pool, fields, fcount, name) - def Void(self) -> rawptr[LLVMType]: + def Void(self) -> LLVMType*: return Void(self.Pool) - def Half(self) -> rawptr[LLVMType]: + def Half(self) -> LLVMType*: return Half(self.Pool) - def Float(self) -> rawptr[LLVMType]: + def Float(self) -> LLVMType*: return Float(self.Pool) - def Double(self) -> rawptr[LLVMType]: + def Double(self) -> LLVMType*: return Double(self.Pool) - def FP128(self) -> rawptr[LLVMType]: + def FP128(self) -> LLVMType*: return FP128(self.Pool) - def Label(self) -> rawptr[LLVMType]: + def Label(self) -> LLVMType*: return Label(self.Pool) - def NewParamNode(self, ty: rawptr[LLVMType]) -> rawptr[ParamNode]: + def NewParamNode(self, ty: LLVMType*) -> ParamNode*: return new_param_node(self.Pool, ty) # ---- List helpers ---- - def ParamListAppend(self, head: rawptr[ParamNode], tail: rawptr[ParamNode], - node: rawptr[ParamNode]) -> rawptr[ParamNode]: + def ParamListAppend(self, head: ParamNode*, tail: ParamNode*, + node: ParamNode*) -> ParamNode*: """Append node to the parameter/field list, returning the new tail.""" return param_list_append(head, tail, node) # ---- Printing ---- - def PrintType(self, buf: str, size: sizet, ty: rawptr[LLVMType]): + def PrintType(self, buf: str, size: sizet, ty: LLVMType*): TypePrint(buf, size, ty, self.Pool) @@ -418,7 +418,7 @@ def MlirNamedTypesClear(): _MlirNamedCap = 0 -def MlirNamedTypeRegister(ty: rawptr[LLVMType], is_packed: int): +def MlirNamedTypeRegister(ty: LLVMType*, is_packed: int): """Register a named struct type and its packed flag (same name: full def replaces opaque). Dedup matches module_add_named_type; non-named structs are ignored; overflow stops @@ -434,7 +434,7 @@ def MlirNamedTypeRegister(ty: rawptr[LLVMType], is_packed: int): fcount: int = get_struct_fcount(ty) for i in range(_MlirNamedCount): slot: sizet* = _MlirNamedSlot(i) - ex: rawptr[LLVMType] = (rawptr[LLVMType])(slot[0]) + ex: LLVMType* = (LLVMType*)(slot[0]) ex_name: str = get_struct_name(ex) if ex_name is not None and string.strcmp(ex_name, name) == 0: if fcount < 0 and get_struct_fcount(ex) >= 0: @@ -456,7 +456,7 @@ def _MlirNamedFindSlot(name: str) -> int: return -1 for i in range(_MlirNamedCount): slot: sizet* = _MlirNamedSlot(i) - ty: rawptr[LLVMType] = (rawptr[LLVMType])(slot[0]) + ty: LLVMType* = (LLVMType*)(slot[0]) nm: str = get_struct_name(ty) if nm is not None and string.strcmp(nm, name) == 0: return i @@ -517,7 +517,7 @@ def _MlirNamedCheckName(pool: memhub.MemBuddy*, name: str): def _MlirNamedStructAppend(dst: str, dstsz: sizet, name: str, - fields: rawptr[ParamNode], fcount: int, packed: int, + fields: ParamNode*, fcount: int, packed: int, pool: memhub.MemBuddy*, depth: int): """Append MLIR named-struct type text to dst. @@ -542,7 +542,7 @@ def _MlirNamedStructAppend(dst: str, dstsz: sizet, name: str, if packed != 0: _strappend(dst, dstsz, "packed ") _strappend(dst, dstsz, "(") - cur: rawptr[ParamNode] = fields + cur: ParamNode* = fields first: int = 1 fidx: int = 0 tmp: str = pool.alloc(4096) @@ -578,7 +578,7 @@ def _MlirNamedBodyFromTable(dst: str, dstsz: sizet, name: str, if si < 0: return 0 slot: sizet* = _MlirNamedSlot(si) - sty: rawptr[LLVMType] = (rawptr[LLVMType])(slot[0]) + sty: LLVMType* = (LLVMType*)(slot[0]) spk: int = int(slot[1]) match sty: case LLVMType.Struct(sf, sc, _): @@ -593,7 +593,7 @@ def _MlirNamedBodyFromTable(dst: str, dstsz: sizet, name: str, # Func→!llvm.func, Void→none (omitted at return position); Label/Metadata fail loud. # Embedded types already arrive as MLIR text; pool allocates temp buffers for subtypes. def TypePrint(buf: str, size: sizet, - ty: rawptr[LLVMType], pool: memhub.MemBuddy*): + ty: LLVMType*, pool: memhub.MemBuddy*): """Serialize type ty as MLIR type text into buf (capacity size). pool allocates temp buffers for subtypes; overflow (text exceeds size) fails loud, since @@ -919,7 +919,7 @@ def _MlirNamedStructText(dst: str, dstsz: sizet, p: str, lt: sizet, "MLIR 渲染: 命名结构体类型文本未在模块中登记完整定义(MLIR 不允许无体前向声明,须以 !llvm.struct<\"name\", (…)> 内联形态使用)", nm) slot: sizet* = _MlirNamedSlot(si) - ty: rawptr[LLVMType] = (rawptr[LLVMType])(slot[0]) + ty: LLVMType* = (LLVMType*)(slot[0]) packed: int = int(slot[1]) match ty: case LLVMType.Struct(fields, fcount, _): @@ -1008,7 +1008,7 @@ def _MlirFuncText(dst: str, dstsz: sizet, p: str, lt: sizet, fp: sizet, define TYPEPRINT_MAX_DEPTH = 100 def _MlirTypePrintDepth(buf: str, size: sizet, - ty: rawptr[LLVMType], pool: memhub.MemBuddy*, + ty: LLVMType*, pool: memhub.MemBuddy*, depth: int): """Internal MLIR type printer with a recursion depth cap (overwrite-writes buf).""" if ty is None or buf is None or size == 0: @@ -1070,7 +1070,7 @@ def _MlirTypePrintDepth(buf: str, size: sizet, _MlirTypePrintDepth(rfb, 4096, ret, pool, depth + 1) _strappend(buf, size, rfb) _strappend(buf, size, " (") - cur2: rawptr[ParamNode] = params + cur2: ParamNode* = params first2: int = 1 _pc2: int = 0 tmp3: str = pool.alloc(4096) @@ -1100,12 +1100,12 @@ def _MlirTypePrintDepth(buf: str, size: sizet, def _MlirStructFields(buf: str, size: sizet, - fields: rawptr[ParamNode], pool: memhub.MemBuddy*, + fields: ParamNode*, pool: memhub.MemBuddy*, depth: int): """Render !llvm.struct<(f0, f1, …)> (overwrite-writes buf).""" buf[0] = '\0' _strappend(buf, size, "!llvm.struct<(") - cur: rawptr[ParamNode] = fields + cur: ParamNode* = fields first: int = 1 fidx: int = 0 tmp: str = pool.alloc(4096) @@ -1154,7 +1154,7 @@ def _strappend(dst: str, dst_size: sizet, src: str): # MLIR has no standalone type definition; struct types are inlined at the use site, so this # writes an empty string. The same-name/same-signature API is kept to match llvmlite. def PrintStructDefinition(buf: str, size: sizet, - ty: rawptr[LLVMType], pool: memhub.MemBuddy*, + ty: LLVMType*, pool: memhub.MemBuddy*, packed: int = 0): """No type definition line on the MLIR side: write an empty string (API kept in sync).""" if buf is None or size == 0: @@ -1164,7 +1164,7 @@ def PrintStructDefinition(buf: str, size: sizet, # get_struct_name - returns the named struct's Name (e.g. "sha1.ClassName"), or None for a # non-Struct / anonymous Struct; used by module_add_named_type to detect named structs and dedup. -def get_struct_name(ty: rawptr[LLVMType]) -> str: +def get_struct_name(ty: LLVMType*) -> str: """Return the named struct's name, or None if not a named struct.""" if ty is None: return None @@ -1175,7 +1175,7 @@ def get_struct_name(ty: rawptr[LLVMType]) -> str: return None -def get_struct_fields(ty: rawptr[LLVMType]) -> rawptr[ParamNode]: +def get_struct_fields(ty: LLVMType*) -> ParamNode*: """Return the struct's field list (used to rebuild Struct types across modules).""" if ty is None: return None @@ -1186,7 +1186,7 @@ def get_struct_fields(ty: rawptr[LLVMType]) -> rawptr[ParamNode]: return None -def get_struct_fcount(ty: rawptr[LLVMType]) -> int: +def get_struct_fcount(ty: LLVMType*) -> int: """Return the struct's field count (used to rebuild Struct types across modules).""" if ty is None: return 0 @@ -1204,13 +1204,13 @@ def get_struct_fcount(ty: rawptr[LLVMType]) -> int: define DEEPCOPY_MAX_DEPTH = 64 def DeepCopyType(pool: memhub.MemBuddy*, - ty: rawptr[LLVMType]) -> rawptr[LLVMType]: + ty: LLVMType*) -> LLVMType*: """Deep-copy LLVMType to the permanent pool (depth-limited against self-recursion); None on failure.""" return _DeepCopyDepth(pool, ty, 0) def _DeepCopyDepth(pool: memhub.MemBuddy*, - ty: rawptr[LLVMType], depth: int) -> rawptr[LLVMType]: + ty: LLVMType*, depth: int) -> LLVMType*: """Deep-copy implementation with a depth cap. The passed pool decides the lifetime: the main pool gives a transient copy (reclaimed by @@ -1219,7 +1219,7 @@ def _DeepCopyDepth(pool: memhub.MemBuddy*, if ty is None: return None sz_dc: sizet = _TypeSizeGuard() - new_ty: rawptr[LLVMType] = (rawptr[LLVMType])(pool.alloc(sz_dc)) + new_ty: LLVMType* = (LLVMType*)(pool.alloc(sz_dc)) if new_ty is None: return None string.memset(new_ty, 0, sz_dc) @@ -1271,19 +1271,19 @@ def _DeepCopyDepth(pool: memhub.MemBuddy*, def _DeepCopyParamChain(pool: memhub.MemBuddy*, - head: rawptr[ParamNode], depth: int) -> rawptr[ParamNode]: + head: ParamNode*, depth: int) -> ParamNode*: """Deep-copy the ParamNode chain to the permanent pool.""" if head is None: return None - first: rawptr[ParamNode] = None - prev: rawptr[ParamNode] = None - cur: rawptr[ParamNode] = head + first: ParamNode* = None + prev: ParamNode* = None + cur: ParamNode* = head guard: int = 0 while cur is not None: guard += 1 if guard > 512: break - node: rawptr[ParamNode] = (rawptr[ParamNode])(pool.alloc(PNODE_SIZE)) + node: ParamNode* = (ParamNode*)(pool.alloc(PNODE_SIZE)) if node is None: break string.memset(node, 0, PNODE_SIZE) diff --git a/mlirlite/__values.vp b/mlirlite/__values.vp index e005d3f..ed040b7 100644 --- a/mlirlite/__values.vp +++ b/mlirlite/__values.vp @@ -19,7 +19,7 @@ from .__types import LLVMType, TypePrint # ============================================================ @t.NoVTable class Value(GSListNode[Value]): - Ty: rawptr[LLVMType] # value type + Ty: LLVMType* # value type Name: str # SSA name ("%0"/"%result") or constant text ("42"/"1.5e+00") IsConst: int # 1 = constant literal, 0 = SSA temporary IntVal: int64 # integer constant value (used when IsConst=1) @@ -32,20 +32,20 @@ class Value(GSListNode[Value]): # Value hardcoded size: Next(8) + Ty(8) + Name(8) + IsConst(4) + IntVal(8) + FloatVal(8) = 48 bytes define VALUE_SIZE = 48 -def new_value(pool: memhub.MemBuddy*) -> rawptr[Value]: +def new_value(pool: memhub.MemBuddy*) -> Value*: """Allocate a zero-initialized Value from mpool.""" - ptr: rawptr[Value] = pool.alloc(VALUE_SIZE) + ptr: Value* = pool.alloc(VALUE_SIZE) if ptr: string.memset(ptr, 0, VALUE_SIZE) return ptr -def ConstInt(pool: memhub.MemBuddy*, ty: rawptr[LLVMType], - val: int64, name: str) -> rawptr[Value]: +def ConstInt(pool: memhub.MemBuddy*, ty: LLVMType*, + val: int64, name: str) -> Value*: """Create an integer constant value. ty: integer type (Int1/Int8/Int32/Int64); val: integer value; name: caller-provided constant text (e.g. "42"). """ - v: rawptr[Value] = new_value(pool) + v: Value* = new_value(pool) if v is None: return None v.Ty = ty v.Name = name @@ -54,10 +54,10 @@ def ConstInt(pool: memhub.MemBuddy*, ty: rawptr[LLVMType], return v -def ConstNull(pool: memhub.MemBuddy*, ty: rawptr[LLVMType], - name: str) -> rawptr[Value]: +def ConstNull(pool: memhub.MemBuddy*, ty: LLVMType*, + name: str) -> Value*: """Create a null pointer constant.""" - v: rawptr[Value] = new_value(pool) + v: Value* = new_value(pool) if v is None: return None v.Ty = ty v.Name = name @@ -66,9 +66,9 @@ def ConstNull(pool: memhub.MemBuddy*, ty: rawptr[LLVMType], return v -def ConstZero(pool: memhub.MemBuddy*, ty: rawptr[LLVMType]) -> rawptr[Value]: +def ConstZero(pool: memhub.MemBuddy*, ty: LLVMType*) -> Value*: """Create a zeroinitializer constant (zero-initialized aggregate: struct/array).""" - v: rawptr[Value] = new_value(pool) + v: Value* = new_value(pool) if v is None: return None v.Ty = ty v.Name = "zeroinitializer" @@ -77,14 +77,14 @@ def ConstZero(pool: memhub.MemBuddy*, ty: rawptr[LLVMType]) -> rawptr[Value]: return v -def ConstFloat(pool: memhub.MemBuddy*, ty: rawptr[LLVMType], - val: double) -> rawptr[Value]: +def ConstFloat(pool: memhub.MemBuddy*, ty: LLVMType*, + val: double) -> Value*: """Create a float constant value. ty: float type; val: float value. Name is the raw bit pattern (f16 0x%04x, f32 0x%08x, f64 0x%016llx, f128 0x%032x hi+lo) so MLIR FloatAttr is lossless; use CRT stdio.snprintf (%g in viperlib is buggy). """ - v: rawptr[Value] = new_value(pool) + v: Value* = new_value(pool) if v is None: return None v.Ty = ty v.IsConst = 1 @@ -113,11 +113,11 @@ def ConstFloat(pool: memhub.MemBuddy*, ty: rawptr[LLVMType], # quad: double -> fp128 is lossless (fpext); little-endian low 64 first, print big-endian # (hi first). c.Load width follows the source pointee, so cast the source to u64* to avoid overflow. q128: t.CFloat128T = t.CFloat128T(val) - q8: rawptr[uint8] = (rawptr[uint8])(&q128) + q8: uint8* = (uint8*)(&q128) q_lo: uint64 = 0 q_hi: uint64 = 0 - *&q_lo = *(rawptr[uint64])(q8) - *&q_hi = *(rawptr[uint64])(q8 + 8) + *&q_lo = *(uint64*)(q8) + *&q_hi = *(uint64*)(q8 + 8) stdio.snprintf(name_buf, 64, "0x%016llx%016llx", q_hi, q_lo) else: fv_bits: uint64 = 0 @@ -127,12 +127,12 @@ def ConstFloat(pool: memhub.MemBuddy*, ty: rawptr[LLVMType], return v -def SSAValue(pool: memhub.MemBuddy*, ty: rawptr[LLVMType], - name: str) -> rawptr[Value]: +def SSAValue(pool: memhub.MemBuddy*, ty: LLVMType*, + name: str) -> Value*: """Create an SSA temporary value. ty: value type; name: caller-provided SSA name (e.g. "%0"/"%result"). """ - v: rawptr[Value] = new_value(pool) + v: Value* = new_value(pool) if v is None: return None v.Ty = ty v.Name = name @@ -149,7 +149,7 @@ def SSAValue(pool: memhub.MemBuddy*, ty: rawptr[LLVMType], # must first be materialized as llvm.mlir.constant/zero/addressof ops). # ============================================================ def ValuePrint(buf: str, size: sizet, - val: rawptr[Value], pool: memhub.MemBuddy*): + val: Value*, pool: memhub.MemBuddy*): """Serialize val into buf as MLIR text; pool is used to allocate scratch buffers for recursive complex types (Array/Struct/Func). """ @@ -177,42 +177,42 @@ def ValuePrint(buf: str, size: sizet, # Cross-module callers only see a stub Value (missing/wrong fields), so TransPyC silently skips # field access; these accessors run inside this module with the full type definition. # ============================================================ -def value_get_ty(val: rawptr[Value]) -> rawptr[LLVMType]: +def value_get_ty(val: Value*) -> LLVMType*: """Get the value's type.""" if val is None: return None return val.Ty -def value_get_next(val: rawptr[Value]) -> rawptr[Value]: +def value_get_next(val: Value*) -> Value*: """Get the next value in the list.""" if val is None: return None return val.Next -def value_set_ty(val: rawptr[Value], ty: rawptr[LLVMType]): +def value_set_ty(val: Value*, ty: LLVMType*): """Set the value's type.""" if val is None: return val.Ty = ty -def value_set_next(val: rawptr[Value], nxt: rawptr[Value]): +def value_set_next(val: Value*, nxt: Value*): """Set the next value in the list.""" if val is None: return val.Next = nxt -def value_set_name(val: rawptr[Value], name: str): +def value_set_name(val: Value*, name: str): """Set the value's name.""" if val is None: return val.Name = name -def value_set_isconst(val: rawptr[Value], is_const: int): +def value_set_isconst(val: Value*, is_const: int): """Set whether the value is a constant.""" if val is None: return diff --git a/mlirlite/__verify.vp b/mlirlite/__verify.vp index 5e6858a..dd349b7 100644 --- a/mlirlite/__verify.vp +++ b/mlirlite/__verify.vp @@ -55,9 +55,9 @@ class VerifyResult: # Helper functions # ============================================================ def _new_verify_result(pool: memhub.MemBuddy*, - buf_size: sizet) -> rawptr[VerifyResult]: + buf_size: sizet) -> VerifyResult*: """Create a VerifyResult object""" - ptr: rawptr[VerifyResult] = pool.alloc(VerifyResult.__sizeof__()) + ptr: VerifyResult* = pool.alloc(VerifyResult.__sizeof__()) if ptr is None: return None string.memset(ptr, 0, VerifyResult.__sizeof__()) ptr.ErrorCount = 0 @@ -71,7 +71,7 @@ def _new_verify_result(pool: memhub.MemBuddy*, return ptr -def _report_error(result: rawptr[VerifyResult], code: int, msg: str): +def _report_error(result: VerifyResult*, code: int, msg: str): """Record one error""" if result is None: return result.ErrorCount += 1 @@ -125,9 +125,9 @@ def _append_cstr(dst: str, dst_size: sizet, src: str): # ============================================================ # SSA name-table operations # ============================================================ -def _new_name_table(pool: memhub.MemBuddy*) -> rawptr[GSList[NameEntry]]: +def _new_name_table(pool: memhub.MemBuddy*) -> GSList[NameEntry]*: """Create an empty name table""" - gsl: rawptr[GSList[NameEntry]] = pool.alloc(24) # GSList: Head+Tail+Count + gsl: GSList[NameEntry]* = pool.alloc(24) # GSList: Head+Tail+Count if gsl is None: return None string.memset(gsl, 0, 24) return gsl @@ -136,19 +136,19 @@ def _new_name_table(pool: memhub.MemBuddy*) -> rawptr[GSList[NameEntry]]: # NameEntry hardcoded size: Next(8) + Name(8) = 16 bytes define NENTRY_SIZE = 16 -def _name_table_add(table: rawptr[GSList[NameEntry]], +def _name_table_add(table: GSList[NameEntry]*, pool: memhub.MemBuddy*, name: str) -> int: """Add a name to the table. Returns 1=duplicate, 0=added""" if table is None or name is None: return 0 # Check for duplicates - cur: rawptr[NameEntry] = table.Head + cur: NameEntry* = table.Head while cur is not None: if string.strcmp(cur.Name, name) == 0: return 1 cur = cur.Next # Add new entry - entry: rawptr[NameEntry] = pool.alloc(NENTRY_SIZE) + entry: NameEntry* = pool.alloc(NENTRY_SIZE) if entry is None: return 0 string.memset(entry, 0, NENTRY_SIZE) entry.Name = name @@ -156,11 +156,11 @@ def _name_table_add(table: rawptr[GSList[NameEntry]], return 0 -def _name_table_contains(table: rawptr[GSList[NameEntry]], +def _name_table_contains(table: GSList[NameEntry]*, name: str) -> int: """Return 1 if name is in the table, else 0""" if table is None or name is None: return 0 - cur: rawptr[NameEntry] = table.Head + cur: NameEntry* = table.Head while cur is not None: if string.strcmp(cur.Name, name) == 0: return 1 @@ -222,7 +222,7 @@ def _is_phi(text: str) -> int: return 0 -def _check_uses_in_line(table: rawptr[GSList[NameEntry]], +def _check_uses_in_line(table: GSList[NameEntry]*, text: str, def_name: str) -> int: """Check that all SSA name uses in the line are defined. @@ -254,10 +254,10 @@ def _check_uses_in_line(table: rawptr[GSList[NameEntry]], def _name_matches_at(text: str, start: int, length: int, - table: rawptr[GSList[NameEntry]]) -> int: + table: GSList[NameEntry]*) -> int: """Return 1 if text[start:start+length] matches an entry in the name table, else 0.""" if table is None: return 0 - cur: rawptr[NameEntry] = table.Head + cur: NameEntry* = table.Head while cur is not None: if cur.Name is not None: if _str_matches_at(text, start, length, cur.Name) == 1: @@ -282,20 +282,20 @@ def _str_matches_at(text: str, start: int, length: int, # Main verification functions # ============================================================ def verify_function(pool: memhub.MemBuddy*, - func: rawptr[Function], - result: rawptr[VerifyResult]) -> int: + func: Function*, + result: VerifyResult*) -> int: """Verify a function's SSA correctness; result must be created via _new_verify_result. Returns the error count (0 = pass). """ if func is None or result is None: return 1 # Create name table - name_table: rawptr[GSList[NameEntry]] = _new_name_table(pool) + name_table: GSList[NameEntry]* = _new_name_table(pool) if name_table is None: return 1 # 1. Add function params to the name table (params are defined) - params: rawptr[GSList[Param]] = func.Params - param: rawptr[Param] = None + params: GSList[Param]* = func.Params + param: Param* = None if params is not None: param = params.Head while param is not None: @@ -304,8 +304,8 @@ def verify_function(pool: memhub.MemBuddy*, param = param.Next # 1b. Add block names to the table (block labels like %then are valid br/phi targets) - blocks: rawptr[GSList[BasicBlock]] = func.Blocks - blk_iter: rawptr[BasicBlock] = None + blocks: GSList[BasicBlock]* = func.Blocks + blk_iter: BasicBlock* = None if blocks is not None: blk_iter = blocks.Head while blk_iter is not None: @@ -322,7 +322,7 @@ def verify_function(pool: memhub.MemBuddy*, blk_iter = blk_iter.Next # 2. Walk all blocks - blk: rawptr[BasicBlock] = None + blk: BasicBlock* = None if blocks is not None: blk = blocks.Head while blk is not None: @@ -330,9 +330,9 @@ def verify_function(pool: memhub.MemBuddy*, if blk.IsTerminated == 0: # Also check whether the last line is a terminator has_term: int = 0 - line_check: rawptr[Line] = None + line_check: Line* = None if blk.Lines is not None: - lines_check: rawptr[GSList[Line]] = blk.Lines + lines_check: GSList[Line]* = blk.Lines line_check = lines_check.Head while line_check is not None: if line_check.Buf is not None: @@ -350,9 +350,9 @@ def verify_function(pool: memhub.MemBuddy*, # Walk instruction lines in the block seen_non_phi: int = 0 - line: rawptr[Line] = None + line: Line* = None if blk.Lines is not None: - lines: rawptr[GSList[Line]] = blk.Lines + lines: GSList[Line]* = blk.Lines line = lines.Head while line is not None: if line.Buf is not None: @@ -396,12 +396,12 @@ def verify_function(pool: memhub.MemBuddy*, return result.ErrorCount -def verify_module(pool: memhub.MemBuddy*, mod: rawptr[LLVMModule], result: rawptr[VerifyResult]) -> int: +def verify_module(pool: memhub.MemBuddy*, mod: LLVMModule*, result: VerifyResult*) -> int: """Verify SSA correctness of all functions in the module. Returns the total error count. """ if mod is None or result is None: return 1 - func: rawptr[Function] = mod.FuncHead + func: Function* = mod.FuncHead while func is not None: if func.IsDeclared == 0: # Verify only definitions with a body; skip declarations diff --git a/numpy/__init__.vp b/numpy/__init__.vp index b804538..c0ff936 100644 --- a/numpy/__init__.vp +++ b/numpy/__init__.vp @@ -34,9 +34,9 @@ class ndarray[T]: ndim: int size: sizet owns_data: int - pool: rawptr[memhub.MemManager] + pool: memhub.MemManager* - def __new__(self, pool: rawptr[memhub.MemManager], n: sizet): + def __new__(self, pool: memhub.MemManager*, n: sizet): self.pool = pool self.data = pool.alloc(n * T.__sizeof__()) if self.data: @@ -261,7 +261,7 @@ Uint8Array: t.CTypedef = ndarray[uchar] # Internal helpers (specialized for float64 by default) # Use _alloc_ndarray_t[T] / _empty_like_t[T] for other types # ============================================================ -def _alloc_ndarray(pool: rawptr[memhub.MemManager]) -> ndarray[double]*: +def _alloc_ndarray(pool: memhub.MemManager*) -> ndarray[double]*: a: ndarray[double]* = pool.alloc(ndarray[double].__sizeof__()) if a: string.memset(a, 0, ndarray[double].__sizeof__()) @@ -296,7 +296,7 @@ def _empty_like(a: ndarray[double]*) -> ndarray[double]*: # ============================================================ # Array creation functions (float64 default) # ============================================================ -def array(pool: rawptr[memhub.MemManager], data: double*, n: sizet) -> ndarray[double]*: +def array(pool: memhub.MemManager*, data: double*, n: sizet) -> ndarray[double]*: a: ndarray[double]* = _alloc_ndarray(pool) if not a: return None a.data = pool.alloc(n * double.__sizeof__()) @@ -312,7 +312,7 @@ def array(pool: rawptr[memhub.MemManager], data: double*, n: sizet) -> ndarray[d a.owns_data = 1 return a -def zeros(pool: rawptr[memhub.MemManager], n: sizet) -> ndarray[double]*: +def zeros(pool: memhub.MemManager*, n: sizet) -> ndarray[double]*: a: ndarray[double]* = _alloc_ndarray(pool) if not a: return None a.data = pool.alloc(n * double.__sizeof__()) @@ -328,19 +328,19 @@ def zeros(pool: rawptr[memhub.MemManager], n: sizet) -> ndarray[double]*: a.owns_data = 1 return a -def ones(pool: rawptr[memhub.MemManager], n: sizet) -> ndarray[double]*: +def ones(pool: memhub.MemManager*, n: sizet) -> ndarray[double]*: a: ndarray[double]* = zeros(pool, n) if not a: return None a.fill(double(1.0)) return a -def full(pool: rawptr[memhub.MemManager], n: sizet, val: double) -> ndarray[double]*: +def full(pool: memhub.MemManager*, n: sizet, val: double) -> ndarray[double]*: a: ndarray[double]* = zeros(pool, n) if not a: return None a.fill(val) return a -def arange(pool: rawptr[memhub.MemManager], start: double, stop: double, step: double) -> ndarray[double]*: +def arange(pool: memhub.MemManager*, start: double, stop: double, step: double) -> ndarray[double]*: if step == double(0.0): return None n: sizet = 0 if step > double(0.0): @@ -362,7 +362,7 @@ def arange(pool: rawptr[memhub.MemManager], start: double, stop: double, step: d v += step return a -def linspace(pool: rawptr[memhub.MemManager], start: double, stop: double, num: sizet) -> ndarray[double]*: +def linspace(pool: memhub.MemManager*, start: double, stop: double, num: sizet) -> ndarray[double]*: if num == 0: return None a: ndarray[double]* = zeros(pool, num) if not a: return None @@ -374,7 +374,7 @@ def linspace(pool: rawptr[memhub.MemManager], start: double, stop: double, num: a.data[i] = start + double(i) * step return a -def empty2d(pool: rawptr[memhub.MemManager], rows: sizet, cols: sizet) -> ndarray[double]*: +def empty2d(pool: memhub.MemManager*, rows: sizet, cols: sizet) -> ndarray[double]*: a: ndarray[double]* = _alloc_ndarray(pool) if not a: return None total: sizet = rows * cols @@ -392,23 +392,23 @@ def empty2d(pool: rawptr[memhub.MemManager], rows: sizet, cols: sizet) -> ndarra _compute_strides(a) return a -def zeros2d(pool: rawptr[memhub.MemManager], rows: sizet, cols: sizet) -> ndarray[double]*: +def zeros2d(pool: memhub.MemManager*, rows: sizet, cols: sizet) -> ndarray[double]*: return empty2d(pool, rows, cols) -def ones2d(pool: rawptr[memhub.MemManager], rows: sizet, cols: sizet) -> ndarray[double]*: +def ones2d(pool: memhub.MemManager*, rows: sizet, cols: sizet) -> ndarray[double]*: a: ndarray[double]* = empty2d(pool, rows, cols) if not a: return None a.fill(double(1.0)) return a -def eye(pool: rawptr[memhub.MemManager], n: sizet) -> ndarray[double]*: +def eye(pool: memhub.MemManager*, n: sizet) -> ndarray[double]*: a: ndarray[double]* = empty2d(pool, n, n) if not a: return None for i in range(n): a.data[i * n + i] = double(1.0) return a -def diag(pool: rawptr[memhub.MemManager], vals: ndarray[double]*) -> ndarray[double]*: +def diag(pool: memhub.MemManager*, vals: ndarray[double]*) -> ndarray[double]*: n: sizet = vals.size a: ndarray[double]* = empty2d(pool, n, n) if not a: return None @@ -887,10 +887,10 @@ def np_greater_equal(a: ndarray[double]*, b: ndarray[double]*) -> ndarray[double # ============================================================ # Additional creation functions (float64 default) # ============================================================ -def empty(pool: rawptr[memhub.MemManager], n: sizet) -> ndarray[double]*: +def empty(pool: memhub.MemManager*, n: sizet) -> ndarray[double]*: return zeros(pool, n) -def full2d(pool: rawptr[memhub.MemManager], rows: sizet, cols: sizet, val: double) -> ndarray[double]*: +def full2d(pool: memhub.MemManager*, rows: sizet, cols: sizet, val: double) -> ndarray[double]*: a: ndarray[double]* = empty2d(pool, rows, cols) if not a: return None a.fill(val) @@ -920,10 +920,10 @@ def ones_like(a: ndarray[double]*) -> ndarray[double]*: result.fill(double(1.0)) return result -def arange1(pool: rawptr[memhub.MemManager], stop: double) -> ndarray[double]*: +def arange1(pool: memhub.MemManager*, stop: double) -> ndarray[double]*: return arange(pool, double(0.0), stop, double(1.0)) -def linspace2(pool: rawptr[memhub.MemManager], start: double, stop: double) -> ndarray[double]*: +def linspace2(pool: memhub.MemManager*, start: double, stop: double) -> ndarray[double]*: return linspace(pool, start, stop, 50) def meshgrid(x: ndarray[double]*, y: ndarray[double]*) -> ndarray[double]*: diff --git a/os/_posix.vp b/os/_posix.vp index 21c4bd5..8e9b041 100644 --- a/os/_posix.vp +++ b/os/_posix.vp @@ -16,7 +16,7 @@ _mbuddy: memhub.MemBuddy* # File/Directory Attribute Query # ============================================================================= -def _stat(path: str) -> rawptr[posix.Stat]: +def _stat(path: str) -> posix.Stat*: """Call stat and return a Stat struct pointer. Return None on failure. Note: the Stat struct is allocated via _mbuddy; the caller must free it.""" st: posix.Stat = posix.Stat() @@ -146,7 +146,7 @@ def listdir(path: str, out_names: str*, max_count: ULONG) -> ULONG: count: ULONG = 0 while count < max_count: - entry: rawptr[posix.Dirent] = posix.readdir(dirp) + entry: posix.Dirent* = posix.readdir(dirp) if entry == None: break diff --git a/posix.vp b/posix.vp index 1343c1c..8f24a5c 100644 --- a/posix.vp +++ b/posix.vp @@ -162,42 +162,42 @@ class Dirent(): # ============================================================================= # File operations (10) # ============================================================================= -extern def open(path: t.CConst | str, oflag: INT, *args) -> INT +extern def open(path: const str, oflag: INT, *args) -> INT extern def close(fd: INT) -> INT extern def read(fd: INT, buf: bytes, count: sizet) -> ssize_t -extern def write(fd: INT, buf: t.CConst | bytes, count: sizet) -> ssize_t +extern def write(fd: INT, buf: const bytes, count: sizet) -> ssize_t extern def lseek(fd: INT, offset: off_t, whence: INT) -> off_t -extern def unlink(path: t.CConst | str) -> INT -extern def access(path: t.CConst | str, amode: INT) -> INT -extern def realpath(path: t.CConst | str, resolved: CHARPTR) -> CHARPTR -extern def rename(oldpath: t.CConst | str, newpath: t.CConst | str) -> INT -extern def chmod(path: t.CConst | str, mode: mode_t) -> INT +extern def unlink(path: const str) -> INT +extern def access(path: const str, amode: INT) -> INT +extern def realpath(path: const str, resolved: CHARPTR) -> CHARPTR +extern def rename(oldpath: const str, newpath: const str) -> INT +extern def chmod(path: const str, mode: mode_t) -> INT # ============================================================================= # stat series (2) # ============================================================================= -extern def stat(path: t.CConst | str, buf: Stat*) -> INT +extern def stat(path: const str, buf: Stat*) -> INT extern def fstat(fd: INT, buf: Stat*) -> INT # ============================================================================= # Directory operations (6) # ============================================================================= -extern def opendir(name: t.CConst | str) -> DIR +extern def opendir(name: const str) -> DIR extern def readdir(dirp: DIR) -> Dirent* extern def closedir(dirp: DIR) -> INT -extern def mkdir(path: t.CConst | str, mode: mode_t) -> INT -extern def rmdir(path: t.CConst | str) -> INT +extern def mkdir(path: const str, mode: mode_t) -> INT +extern def rmdir(path: const str) -> INT extern def getcwd(buf: CHARPTR, size: sizet) -> CHARPTR -extern def chdir(path: t.CConst | str) -> INT +extern def chdir(path: const str) -> INT # ============================================================================= # Process operations (8) # ============================================================================= extern def fork() -> pid_t -extern def execvp(file: t.CConst | str, argv: CHARPTR*) -> INT -extern def execv(path: t.CConst | str, argv: CHARPTR*) -> INT +extern def execvp(file: const str, argv: CHARPTR*) -> INT +extern def execv(path: const str, argv: CHARPTR*) -> INT extern def waitpid(pid: pid_t, status: INT*, options: INT) -> pid_t extern def pipe(fds: INT*) -> INT extern def dup2(oldfd: INT, newfd: INT) -> INT @@ -208,8 +208,8 @@ extern def getpid() -> pid_t # ============================================================================= # Environment operations (4) # ============================================================================= -extern def getenv(name: t.CConst | str) -> CHARPTR -extern def setenv(name: t.CConst | str, value: t.CConst | str, overwrite: INT) -> INT +extern def getenv(name: const str) -> CHARPTR +extern def setenv(name: const str, value: const str, overwrite: INT) -> INT extern def sysconf(name: INT) -> LONG extern def isatty(fd: INT) -> INT diff --git a/random.vp b/random.vp index 6125aeb..62a6529 100644 --- a/random.vp +++ b/random.vp @@ -63,7 +63,7 @@ def rdseed64() -> uint64: # Step version (with success flag, matching GCC builtin interface) # Returns success flag: 1 on success, 0 on failure; random value written to *p # ============================================================ -def rdrand16_step(p: rawptr[uint16]) -> int: +def rdrand16_step(p: uint16*) -> int: val: uint32 = 0 ok: uint32 = 0 c.Asm(f"""rdrand {c.AsmOut(val, t.ASM_DESCR.OUTPUT_REG)} @@ -74,7 +74,7 @@ def rdrand16_step(p: rawptr[uint16]) -> int: p[0] = uint16(val) return int(ok) -def rdrand32_step(p: rawptr[uint32]) -> int: +def rdrand32_step(p: uint32*) -> int: val: uint32 = 0 ok: uint32 = 0 c.Asm(f"""rdrand {c.AsmOut(val, t.ASM_DESCR.OUTPUT_REG)} @@ -85,7 +85,7 @@ def rdrand32_step(p: rawptr[uint32]) -> int: p[0] = val return int(ok) -def rdrand64_step(p: rawptr[uint64]) -> int: +def rdrand64_step(p: uint64*) -> int: val: uint64 = 0 ok: uint32 = 0 c.Asm(f"""rdrand {c.AsmOut(val, t.ASM_DESCR.OUTPUT_REG)} @@ -96,7 +96,7 @@ def rdrand64_step(p: rawptr[uint64]) -> int: p[0] = val return int(ok) -def rdseed16_step(p: rawptr[uint16]) -> int: +def rdseed16_step(p: uint16*) -> int: val: uint32 = 0 ok: uint32 = 0 c.Asm(f"""rdseed {c.AsmOut(val, t.ASM_DESCR.OUTPUT_REG)} @@ -107,7 +107,7 @@ def rdseed16_step(p: rawptr[uint16]) -> int: p[0] = uint16(val) return int(ok) -def rdseed32_step(p: rawptr[uint32]) -> int: +def rdseed32_step(p: uint32*) -> int: val: uint32 = 0 ok: uint32 = 0 c.Asm(f"""rdseed {c.AsmOut(val, t.ASM_DESCR.OUTPUT_REG)} @@ -118,7 +118,7 @@ def rdseed32_step(p: rawptr[uint32]) -> int: p[0] = val return int(ok) -def rdseed64_step(p: rawptr[uint64]) -> int: +def rdseed64_step(p: uint64*) -> int: val: uint64 = 0 ok: uint32 = 0 c.Asm(f"""rdseed {c.AsmOut(val, t.ASM_DESCR.OUTPUT_REG)} diff --git a/requests/download.vp b/requests/download.vp index 5991941..917f4d8 100644 --- a/requests/download.vp +++ b/requests/download.vp @@ -374,7 +374,7 @@ def download(url: str, path: str, threads: INT = 1, job.status = 0 ctxs[i] = t.CPtr(uint64(job)) - th: rawptr[vt.Thread] = vt.Thread(_dl_worker, ctxs[i]) + th: vt.Thread* = vt.Thread(_dl_worker, ctxs[i]) if th is None: stdlib.free(job.buf) stdlib.free(job.path) diff --git a/requests/https.vp b/requests/https.vp index bd6a670..fba95f7 100644 --- a/requests/https.vp +++ b/requests/https.vp @@ -219,7 +219,7 @@ def _TlsErrText(): # Core request # ============================================================ -def _HttpsRequest(method: str, url: str, verify: bool, ca_file: str, data: str, content_type: str, auth: str = None) -> rawptr[requests.Response]: +def _HttpsRequest(method: str, url: str, verify: bool, ca_file: str, data: str, content_type: str, auth: str = None) -> requests.Response*: """HTTPS GET/POST core. verify=False skips cert chain/hostname checks (not recommended); verify=True uses ca_file PEM bundle (else system default); auth adds Authorization header on POST only. """ @@ -228,7 +228,7 @@ def _HttpsRequest(method: str, url: str, verify: bool, ca_file: str, data: str, _last_verify_flag = 1 if verify else 0 - resp: rawptr[requests.Response] = requests.create_response() + resp: requests.Response* = requests.create_response() if resp is None: return None if _EnsureReady() != 0: @@ -478,7 +478,7 @@ def _HttpsRequest(method: str, url: str, verify: bool, ca_file: str, data: str, # Public API # ============================================================ -def _HttpsRedirectLoop(method: str, url: str, verify: bool, ca_file: str, data: str, content_type: str, auth: str = None) -> rawptr[requests.Response]: +def _HttpsRedirectLoop(method: str, url: str, verify: bool, ca_file: str, data: str, content_type: str, auth: str = None) -> requests.Response*: """HTTPS GET/POST with redirect following (cross http/https, max 5 hops). auth is passed through to _HttpsRequest; note Authorization also follows cross-host redirects. """ @@ -493,7 +493,7 @@ def _HttpsRedirectLoop(method: str, url: str, verify: bool, ca_file: str, data: string.strcpy(cur, url) for hop in range(5): - resp: rawptr[requests.Response] = _HttpsRequest(method, cur, verify, ca_file, data, content_type, auth) + resp: requests.Response* = _HttpsRequest(method, cur, verify, ca_file, data, content_type, auth) if resp is None: requests._mbuddy.free(cur) return None @@ -530,7 +530,7 @@ def _HttpsRedirectLoop(method: str, url: str, verify: bool, ca_file: str, data: if string.strncmp(nxt, "https://", 8) != 0: requests._mbuddy.free(loc) requests._mbuddy.free(cur) - http_resp: rawptr[requests.Response] = requests.get(nxt) + http_resp: requests.Response* = requests.get(nxt) requests._mbuddy.free(nxt) return http_resp @@ -543,7 +543,7 @@ def _HttpsRedirectLoop(method: str, url: str, verify: bool, ca_file: str, data: return None -def get(url: str, verify: bool = True, ca_file: str = None) -> rawptr[requests.Response]: +def get(url: str, verify: bool = True, ca_file: str = None) -> requests.Response*: """HTTPS GET (follows 3xx redirects, max 5 hops). verify checks cert chain + hostname; ca_file is a PEM CA bundle path, None uses system default. Returns Response* or None. """ @@ -551,7 +551,7 @@ def get(url: str, verify: bool = True, ca_file: str = None) -> rawptr[requests.R def post(url: str, data: str = None, content_type: str = "application/x-www-form-urlencoded", - verify: bool = True, ca_file: str = None, auth: str = None) -> rawptr[requests.Response]: + verify: bool = True, ca_file: str = None, auth: str = None) -> requests.Response*: """HTTPS POST (follows 3xx redirects, max 5 hops). verify checks cert chain + hostname; ca_file PEM CA bundle (None = system default); auth optional "Bearer ", sent when non-empty. """ @@ -563,20 +563,20 @@ def post(url: str, data: str = None, content_type: str = "application/x-www-form # choices[0].delta.content from data:{json} lines into _st_buf; blocking, returns HTTP status or -1/-2. # ============================================================ -def _SseDeltaContent(root: rawptr[json.JsonValue]) -> str: +def _SseDeltaContent(root: json.JsonValue*) -> str: """Extract choices[0].delta.content from a stream data event; None if absent.""" if root is None or not root.is_object(): return None - cv: rawptr[json.JsonValue] = root["choices"] + cv: json.JsonValue* = root["choices"] if cv is None or not cv.is_array(): return None - m0: rawptr[json.JsonValue] = cv.get_item(0) + m0: json.JsonValue* = cv.get_item(0) if m0 is None or not m0.is_object(): return None - dv: rawptr[json.JsonValue] = m0["delta"] + dv: json.JsonValue* = m0["delta"] if dv is None or not dv.is_object(): return None - content_v: rawptr[json.JsonValue] = dv["content"] + content_v: json.JsonValue* = dv["content"] if content_v is None or not content_v.is_string(): return None return content_v.as_string() @@ -782,7 +782,7 @@ def post_stream(url: str, data: str, content_type: str = "application/json", sock.close() requests._mbuddy.free(errmsg) return -1 - jpool: rawptr[memhub.MemPool] = memhub.MemPool(pmem, 524288) + jpool: memhub.MemPool* = memhub.MemPool(pmem, 524288) leftover: t.CArray[char, 16384] llen: INT = 0 @@ -840,7 +840,7 @@ def post_stream(url: str, data: str, content_type: str = "application/json", if pl[0] != 0: if string.strncmp(pl, "[DONE]", 6) != 0 or pl[6] != 0: jpool.reset() - ev: rawptr[json.JsonValue] = json.parse(jpool, pl) + ev: json.JsonValue* = json.parse(jpool, pl) dtx: str = _SseDeltaContent(ev) if dtx is not None: _StreamAppendContent(dtx) diff --git a/shutil.vp b/shutil.vp index 53539a9..7b5f60b 100644 --- a/shutil.vp +++ b/shutil.vp @@ -193,7 +193,7 @@ def _rmtree_posix(path: str) -> int: path_len: sizet = len(path) result: int = 0 - entry: rawptr[posix.Dirent] = posix.readdir(dirp) + entry: posix.Dirent* = posix.readdir(dirp) while entry != None: name: str = entry.d_name # Skip . and .. diff --git a/socket.vp b/socket.vp index af05390..9559079 100644 --- a/socket.vp +++ b/socket.vp @@ -90,7 +90,7 @@ extern def bind(fd: u64, addr: SocketAddr*, addrlen: INT) -> INT extern def listen(fd: u64, backlog: INT) -> INT extern def accept(fd: u64, addr: SocketAddr*, addrlen: INT*) -> u64 extern def setsockopt(fd: u64, level: INT, optname: INT, optval: t.CPtr, optlen: INT) -> INT -extern def gethostbyname(name: t.CConst | str) -> HostEnt* +extern def gethostbyname(name: const str) -> HostEnt* extern def ntohs(netshort: u16) -> u16 extern def htons(hostshort: u16) -> u16 extern def close(fd: u64) -> INT @@ -123,7 +123,7 @@ def _MakeAddr(host: str, port: INT) -> SocketAddr: # DNS resolution — gethostbyname returns struct hostent* # h_addr_list is char** → h_addr_list[0] is char* → *(uint32_t*)h_addr_list[0] is IP if platmacro.IS_WINDOWS: - he_raw: rawptr[w32.winsock2.WSAHostEnt] = w32.winsock2.gethostbyname(host) + he_raw: w32.winsock2.WSAHostEnt* = w32.winsock2.gethostbyname(host) if he_raw is not None: # he_raw.h_addr_list → he_raw->h_addr_list (char**) # c.Deref(uint64(he_raw.h_addr_list, t.CPtr)) → *(uint64_t*)(he_raw->h_addr_list) → h_addr_list[0] diff --git a/stdio.vp b/stdio.vp index 873fd3a..97b47b5 100644 --- a/stdio.vp +++ b/stdio.vp @@ -1,11 +1,11 @@ import t, c -extern def printf(fmt: t.CConst | str, *args) -> int -extern def fprintf(stream: bytes, fmt: t.CConst | str, *args) -> int -extern def sprintf(buf: bytes, fmt: t.CConst | str, *args) -> int -extern def snprintf(buf: bytes, size: sizet, fmt: t.CConst | str, *args) -> int -extern def puts(s: t.CConst | str) -> int -extern def fputs(s: t.CConst | str, stream: bytes) -> int +extern def printf(fmt: const str, *args) -> int +extern def fprintf(stream: bytes, fmt: const str, *args) -> int +extern def sprintf(buf: bytes, fmt: const str, *args) -> int +extern def snprintf(buf: bytes, size: sizet, fmt: const str, *args) -> int +extern def puts(s: const str) -> int +extern def fputs(s: const str, stream: bytes) -> int extern def fgets(buf: bytes, size: int, stream: bytes) -> bytes extern def fflush(stream: bytes) -> int diff --git a/stdlib.vp b/stdlib.vp index 68b6959..2a90d73 100644 --- a/stdlib.vp +++ b/stdlib.vp @@ -6,5 +6,5 @@ extern def malloc(size: sizet) -> t.CPtr extern def calloc(nmemb: sizet, size: sizet) -> t.CPtr extern def realloc(p: t.CPtr, size: sizet) -> t.CPtr extern def free(p: t.CPtr) -extern def system(cmd: t.CConst | str) -> int +extern def system(cmd: const str) -> int extern def exit(status: int) diff --git a/torch/__init__.vp b/torch/__init__.vp index 302619d..8108352 100644 --- a/torch/__init__.vp +++ b/torch/__init__.vp @@ -52,7 +52,7 @@ def zeros(pool: memhub.MemBuddy*, rows: sizet, """torch.zeros: create a rows x cols all-zero Tensor, optionally allocating a Grad buffer""" if pool is None: return None - t0: rawptr[Tensor] = pool.alloc(TENSOR_SIZE) + t0: Tensor* = pool.alloc(TENSOR_SIZE) if t0 is None: return None string.memset(t0, 0, TENSOR_SIZE) @@ -73,7 +73,7 @@ def from_raw(pool: memhub.MemBuddy*, data: t.CPtr, """torch.from_raw: wrap existing memory as a Tensor (no copy, not owned)""" if pool is None: return None - t0: rawptr[Tensor] = pool.alloc(TENSOR_SIZE) + t0: Tensor* = pool.alloc(TENSOR_SIZE) if t0 is None: return None string.memset(t0, 0, TENSOR_SIZE) diff --git a/traceback.vp b/traceback.vp index a043d89..2ac5590 100644 --- a/traceback.vp +++ b/traceback.vp @@ -533,7 +533,7 @@ class TracebackState(): # Sole global state: None = not installed (zero side effects while the sidecar is absent). # Pointer + lazy allocation instead of a module-level object constant, which would emit a # constructor that may run after Install and wipe the state it wrote. -_State: rawptr[TracebackState] = None +_State: TracebackState* = None # ---- Dump atomic lock / locked output handle ---- @@ -827,7 +827,7 @@ def EntryRva(Index: int) -> uint64: """RVA of record Index (record area starts at MapBase + 20). The bare `_State` null-check below is REQUIRED: the attribute layer registers `_State` per - function before it can resolve this module-level `rawptr[TracebackState]`; without it + function before it can resolve this module-level `TracebackState*`; without it `_State.MapBase` is silently folded to null (see header section 11 A). It also guards against an uninstalled state (returns 0). """ @@ -1131,7 +1131,7 @@ def ReadMemCb(hProcess: HANDLE, Addr: ULONGLONG, Buf: VOIDPTR, Size: DWORD, Read: sizet = 0 R: BOOL = wm.ReadProcessMemory(hProcess, t.CPtr(Addr), Buf, sizet(Size), &Read) if pRead != None: - Rd: rawptr[uint32] = (rawptr[uint32])(pRead) + Rd: uint32* = (uint32*)(pRead) Rd[0] = uint32(Read) if R == 0 and _State != None and _State.ReadMemFailed == 0: # Record only the first failure (address/size/error); WalkViaDbgHelp prints it next to the @@ -1153,7 +1153,7 @@ def WalkViaDbgHelp(hProcess: HANDLE, hThread: HANDLE, CtxPtr: VOIDPTR, never enters. It is the only path that can cross a frameless system frame (RBP=0 in the Ctrl+C context) via the PE unwind tables (.pdata) and reach the real .vp stack. - STACKFRAME64 fields are accessed through explicit sub-struct pointers (rawptr[dbg.ADDRESS64]): + STACKFRAME64 fields are accessed through explicit sub-struct pointers (dbg.ADDRESS64*): the ADDRESS64 structures sit at offsets 0 / 16 / 32 / 48 (= AddrPC / AddrReturn / AddrFrame / AddrStack, see includes/w32/win32dbghelp.vp). After zeroing, AddrPC/AddrFrame/AddrStack are pre-filled with the context's Rip/Rbp/Rsp and Mode = AddrModeFlat(3); MachineType is passed on @@ -1200,10 +1200,10 @@ def WalkViaDbgHelp(hProcess: HANDLE, hThread: HANDLE, CtxPtr: VOIDPTR, Reason: str = "frame_limit" if TRACEBACK_USE_DBGHELP != 0: string.memset(FBuf, 0, dbg.STACKFRAME64.__sizeof__()) - ctx: rawptr[wp.CONTEXT] = (rawptr[wp.CONTEXT])(CtxPtr) - Pc: rawptr[dbg.ADDRESS64] = (rawptr[dbg.ADDRESS64])(FBuf) - Fm: rawptr[dbg.ADDRESS64] = (rawptr[dbg.ADDRESS64])(FBuf + 32) - St: rawptr[dbg.ADDRESS64] = (rawptr[dbg.ADDRESS64])(FBuf + 48) + ctx: wp.CONTEXT* = (wp.CONTEXT*)(CtxPtr) + Pc: dbg.ADDRESS64* = (dbg.ADDRESS64*)(FBuf) + Fm: dbg.ADDRESS64* = (dbg.ADDRESS64*)(FBuf + 32) + St: dbg.ADDRESS64* = (dbg.ADDRESS64*)(FBuf + 48) Pc.Offset = ctx.Rip Pc.Mode = uint32(dbg.ADDR_MODE_FLAT) Fm.Offset = ctx.Rbp @@ -1628,7 +1628,7 @@ def DumpMainThread(IsBreak: int) -> int: return 0 # CONTEXT: zero it first, then set ContextFlags (x64 needs the CONTEXT_AMD64 bit). string.memset(_State.ContextBuf, 0, wp.CONTEXT.__sizeof__()) - ctx: rawptr[wp.CONTEXT] = (rawptr[wp.CONTEXT])(_State.ContextBuf) + ctx: wp.CONTEXT* = (wp.CONTEXT*)(_State.ContextBuf) ctx.ContextFlags = uint32(wp.CONTEXT_FULL) if wp.GetThreadContext(hThread, t.CPtr(_State.ContextBuf)) == 0: N = stdio.snprintf(_State.LineBuf, sizet(TRACEBACK_LINE_CAP), @@ -1878,7 +1878,7 @@ def DumpCrashThread(Info: VOIDPTR) -> int: AtomicLeaveDump() return 0 Base: uint64 = uint64(GetModuleHandleA(None)) - ctx: rawptr[wp.CONTEXT] = (rawptr[wp.CONTEXT])(_State.ContextBuf) + ctx: wp.CONTEXT* = (wp.CONTEXT*)(_State.ContextBuf) Rip: uint64 = uint64(ctx.Rip) Rsp: uint64 = uint64(ctx.Rsp) Rbp: uint64 = uint64(ctx.Rbp) diff --git a/zlib/pyzlib.vp b/zlib/pyzlib.vp index 8054722..9ab4b65 100644 --- a/zlib/pyzlib.vp +++ b/zlib/pyzlib.vp @@ -67,7 +67,7 @@ pyzlib_error_code_val: int = 0 # Structures # ============================================================ class Compress: - pool: rawptr[memhub.MemManager] + pool: memhub.MemManager* stream: VOIDPTR is_initialized: int is_finished: int @@ -140,7 +140,7 @@ class Compress: if not out_len: set_error(Z_STREAM_ERROR, "out_len is None") return None - s: rawptr[zdeflate.zdeflate_stream] = self.stream # implicit type conversion + s: zdeflate.zdeflate_stream* = self.stream # implicit type conversion if mode == Z_FINISH: if not self.header_written: self.header_written = 1 @@ -231,7 +231,7 @@ class Compress: set_error(Z_MEM_ERROR, "out of memory") return None copy_obj.pool = self.pool - s: rawptr[zdeflate.zdeflate_stream] = self.stream # implicit type conversion + s: zdeflate.zdeflate_stream* = self.stream # implicit type conversion copy_obj.stream = s.copy() if not copy_obj.stream: if self.pool == None: @@ -274,7 +274,7 @@ class Compress: def delete(self): if self.is_initialized and self.stream: - s: rawptr[zdeflate.zdeflate_stream] = self.stream # implicit type conversion + s: zdeflate.zdeflate_stream* = self.stream # implicit type conversion s.destroy() if self.pool == None: stdlib.free(self.zdict) @@ -290,7 +290,7 @@ class Compress: class Decompress: - pool: rawptr[memhub.MemManager] + pool: memhub.MemManager* stream: VOIDPTR is_initialized: int eof: int @@ -338,7 +338,7 @@ class Decompress: p7: BYTEPTR = BYTEPTR(self.pool.alloc(1)) string.memset(p7, 0, 1) return p7 - s: rawptr[zinflate.zinflate_stream] = zinflate.zinflate_create(self.pool, self.wbits) + s: zinflate.zinflate_stream* = zinflate.zinflate_create(self.pool, self.wbits) if not s: set_error(Z_MEM_ERROR, "out of memory") return None @@ -473,7 +473,7 @@ def set_error(code: int, msg: str): else: pyzlib_error_msg[0] = '\0' -def clone_bytes(pool: rawptr[memhub.MemManager], src: BYTEPTR, length: sizet) -> BYTEPTR: +def clone_bytes(pool: memhub.MemManager*, src: BYTEPTR, length: sizet) -> BYTEPTR: if not src or length == 0: return None if pool == None: dst: BYTEPTR = BYTEPTR(stdlib.malloc(length)) @@ -483,7 +483,7 @@ def clone_bytes(pool: rawptr[memhub.MemManager], src: BYTEPTR, length: sizet) -> return dst # buf is a "pointer to pointer" (i8**). Do NOT write `BYTE | t.CPtr[t.CPtr]`: with an embedded `t.CPtr[...]` subscript the declare side (StubGen/VpiReader) does not recognize it as a CPtr marker and collapses it to BYTE = i8, mismatching the definition side's i8** (cross-module ABI mismatch; see includes/zlib/zinflate.vp decompress). Use "pointer alias | t.CPtr" instead. -def append_bytes(pool: rawptr[memhub.MemManager], buf: BYTEPTR*, length: sizet*, cap: sizet*, +def append_bytes(pool: memhub.MemManager*, buf: BYTEPTR*, length: sizet*, cap: sizet*, data: BYTEPTR, data_len: sizet) -> int: if not data or data_len == 0: return 0 needed: sizet = *length + data_len @@ -505,7 +505,7 @@ def append_bytes(pool: rawptr[memhub.MemManager], buf: BYTEPTR*, length: sizet*, return 0 -def shrink_to_fit(pool: rawptr[memhub.MemManager], buf: BYTEPTR, length: sizet) -> BYTEPTR: +def shrink_to_fit(pool: memhub.MemManager*, buf: BYTEPTR, length: sizet) -> BYTEPTR: if length == 0: if pool == None: stdlib.free(buf) @@ -541,7 +541,7 @@ def clear_error(): pyzlib_error_msg[0] = '\0' pyzlib_error_code_val = 0 -def compress(pool: rawptr[memhub.MemManager], data: BYTEPTR, data_len: sizet, +def compress(pool: memhub.MemManager*, data: BYTEPTR, data_len: sizet, level: int, wbits: int, out_len: sizet*) -> BYTEPTR: if not data and data_len > 0: set_error(Z_STREAM_ERROR, "data is None but data_len > 0") @@ -604,7 +604,7 @@ def compress(pool: rawptr[memhub.MemManager], data: BYTEPTR, data_len: sizet, return shrink_to_fit(pool, raw_result, *out_len) -def decompress(pool: rawptr[memhub.MemManager], data: BYTEPTR, data_len: sizet, +def decompress(pool: memhub.MemManager*, data: BYTEPTR, data_len: sizet, wbits: int, bufsize: sizet, out_len: sizet*) -> BYTEPTR: if not data and data_len > 0: set_error(Z_STREAM_ERROR, "data is None but data_len > 0") @@ -618,7 +618,7 @@ def decompress(pool: rawptr[memhub.MemManager], data: BYTEPTR, data_len: sizet, return None return shrink_to_fit(pool, result, *out_len) -def compressobj(pool: rawptr[memhub.MemManager], level: int, method: int, wbits: int, +def compressobj(pool: memhub.MemManager*, level: int, method: int, wbits: int, memLevel: int, strategy: int, zdict: BYTEPTR, zdict_len: sizet) -> Compress*: if pool == None: @@ -632,7 +632,7 @@ def compressobj(pool: rawptr[memhub.MemManager], level: int, method: int, wbits: obj.pool = pool actual_wbits: int = wbits if wbits > MAX_WBITS: actual_wbits = wbits - 16 - s: rawptr[zdeflate.zdeflate_stream] = zdeflate.zdeflate_create(pool, level, actual_wbits, memLevel, strategy) + s: zdeflate.zdeflate_stream* = zdeflate.zdeflate_create(pool, level, actual_wbits, memLevel, strategy) if not s: if pool == None: stdlib.free(obj) @@ -662,7 +662,7 @@ def compressobj(pool: rawptr[memhub.MemManager], level: int, method: int, wbits: return obj -def decompressobj(pool: rawptr[memhub.MemManager], wbits: int, zdict: BYTEPTR, zdict_len: sizet) -> Decompress*: +def decompressobj(pool: memhub.MemManager*, wbits: int, zdict: BYTEPTR, zdict_len: sizet) -> Decompress*: if pool == None: obj: Decompress* = stdlib.calloc(1, Decompress.__sizeof__()) else: diff --git a/zlib/zdef.vp b/zlib/zdef.vp index 57605da..fbd28ab 100644 --- a/zlib/zdef.vp +++ b/zlib/zdef.vp @@ -95,13 +95,13 @@ zdeflate_codelen_order: t.CArray[int, 19] = [ # Bit writer - writes bits LSB first into a byte buffer # ============================================================ class zbit_writer: - pool: rawptr[memhub.MemManager] + pool: memhub.MemManager* buf: BYTE* cap: sizet byte_pos: sizet bit_pos: int - def __init__(self, pool: rawptr[memhub.MemManager]): + def __init__(self, pool: memhub.MemManager*): self.pool = pool self.cap = 4096 if pool == None: @@ -275,10 +275,10 @@ class zbit_reader: # Memory allocation helper for bare metal # Can be replaced with custom allocator # ============================================================ -def zdef_alloc(pool: rawptr[memhub.MemManager], n: sizet) -> VOIDPTR: +def zdef_alloc(pool: memhub.MemManager*, n: sizet) -> VOIDPTR: if pool == None: return stdlib.malloc(n) return pool.alloc(n) -def zdef_free(pool: rawptr[memhub.MemManager], p: VOIDPTR): +def zdef_free(pool: memhub.MemManager*, p: VOIDPTR): if pool == None: stdlib.free(p) return diff --git a/zlib/zdeflate.vp b/zlib/zdeflate.vp index c086474..0c37343 100644 --- a/zlib/zdeflate.vp +++ b/zlib/zdeflate.vp @@ -8,7 +8,7 @@ import t, c class zdeflate_stream: - pool: rawptr[memhub.MemManager] + pool: memhub.MemManager* writer: zdef.zbit_writer window: BYTE* window_pos: int @@ -92,7 +92,7 @@ class zdeflate_stream: lit_tree.encode_symbol(256, &self.writer) def encode_block_data(self, data: UINT8PTR, length: sizet, - lit_tree: rawptr[zhuff.zhuff_tree], dist_tree: rawptr[zhuff.zhuff_tree]): + lit_tree: zhuff.zhuff_tree*, dist_tree: zhuff.zhuff_tree*): pos: sizet = 0 while pos < length: best_dist: int = 0 @@ -335,7 +335,7 @@ def zdeflate_count_cl_freqs(all_lengths: INTPTR, total: int, cl_freqs: INTPTR): # Remaining 1~2 equal-length values are not silently skipped; the outer loop counts them literally (symbol val), so the covered total is exactly total def zdeflate_write_cl_encoded(all_lengths: INTPTR, total: int, - w: rawptr[zdef.zbit_writer], cl_tree: rawptr[zhuff.zhuff_tree]): + w: zdef.zbit_writer*, cl_tree: zhuff.zhuff_tree*): i: int = 0 while i < total: if all_lengths[i] == 0: @@ -375,7 +375,7 @@ def zdeflate_write_cl_encoded(all_lengths: INTPTR, total: int, -def zdeflate_create(pool: rawptr[memhub.MemManager], level: int, wbits: int, mem_level: int, strategy: int) -> zdeflate_stream*: +def zdeflate_create(pool: memhub.MemManager*, level: int, wbits: int, mem_level: int, strategy: int) -> zdeflate_stream*: n: sizet = zdeflate_stream.__sizeof__() s: zdeflate_stream* = zdef.zdef_alloc(pool, n) if not s: return None @@ -402,7 +402,7 @@ def zdeflate_create(pool: rawptr[memhub.MemManager], level: int, wbits: int, mem return s -def zdeflate_one_shot(pool: rawptr[memhub.MemManager], data: UINT8PTR, length: sizet, +def zdeflate_one_shot(pool: memhub.MemManager*, data: UINT8PTR, length: sizet, level: int, wbits: int, out_len: sizet*) -> uint8*: s: zdeflate_stream* = zdeflate_create(pool, level, wbits, 8, 0) if not s: return None diff --git a/zlib/zhuff.vp b/zlib/zhuff.vp index d21f32c..ff2d25f 100644 --- a/zlib/zhuff.vp +++ b/zlib/zhuff.vp @@ -15,7 +15,7 @@ class zhuff_code: @t.Object class zhuff_tree: - pool: rawptr[memhub.MemManager] + pool: memhub.MemManager* codes: t.CArray[zhuff_code, ZHUFF_MAX_CODES] count: int max_bits: int @@ -95,7 +95,7 @@ class zhuff_tree: else: self.codes[i].code = 0 - def encode_symbol(self, symbol: int, writer: rawptr[zdef.zbit_writer]): + def encode_symbol(self, symbol: int, writer: zdef.zbit_writer*): if symbol < 0 or symbol >= self.count: return if self.codes[symbol].bits == 0: @@ -304,7 +304,7 @@ class zhuff_decode_node: class zhuff_decode_tree: - pool: rawptr[memhub.MemManager] + pool: memhub.MemManager* nodes: t.CArray[zhuff_decode_node, 2 * ZHUFF_MAX_CODES] node_count: int root: int @@ -345,7 +345,7 @@ class zhuff_decode_tree: else: self.nodes[self.nodes[node].children[dir]].symbol = i - def decode_symbol(self, reader: rawptr[zdef.zbit_reader]) -> int: + def decode_symbol(self, reader: zdef.zbit_reader*) -> int: node: int = self.root while self.nodes[node].symbol == -1: bit: uint diff --git a/zlib/zinflate.vp b/zlib/zinflate.vp index ba6418c..eee1b65 100644 --- a/zlib/zinflate.vp +++ b/zlib/zinflate.vp @@ -8,7 +8,7 @@ import t, c class zinflate_stream: - pool: rawptr[memhub.MemManager] + pool: memhub.MemManager* reader: zdef.zbit_reader window: BYTEPTR @@ -108,7 +108,7 @@ class zinflate_stream: return 0 - def read_huffman(self, dt: rawptr[zhuff.zhuff_decode_tree]) -> int: + def read_huffman(self, dt: zhuff.zhuff_decode_tree*) -> int: node: int = dt.root while dt.nodes[node].symbol == -1: bit: UINT @@ -141,8 +141,8 @@ class zinflate_stream: lit_tree.build_fixed_lit_tree() dist_tree.build_fixed_dist_tree() - lit_dt: rawptr[zhuff.zhuff_decode_tree] = zdef.zdef_alloc(self.pool, zhuff.zhuff_decode_tree.__sizeof__()) - dist_dt: rawptr[zhuff.zhuff_decode_tree] = zdef.zdef_alloc(self.pool, zhuff.zhuff_decode_tree.__sizeof__()) + lit_dt: zhuff.zhuff_decode_tree* = zdef.zdef_alloc(self.pool, zhuff.zhuff_decode_tree.__sizeof__()) + dist_dt: zhuff.zhuff_decode_tree* = zdef.zdef_alloc(self.pool, zhuff.zhuff_decode_tree.__sizeof__()) if not lit_dt or not dist_dt: if lit_dt: zdef.zdef_free(self.pool, lit_dt) if dist_dt: zdef.zdef_free(self.pool, dist_dt) @@ -430,7 +430,7 @@ class zinflate_stream: zdef.zdef_free(self.pool, self) -def zinflate_one_shot(pool: rawptr[memhub.MemManager], data: UINT8PTR, length: sizet, +def zinflate_one_shot(pool: memhub.MemManager*, data: UINT8PTR, length: sizet, wbits: int, bufsize: sizet, out_len: sizet*) -> uint8*: s: zinflate_stream* = zinflate_create(pool, wbits) if not s: return None @@ -441,7 +441,7 @@ def zinflate_one_shot(pool: rawptr[memhub.MemManager], data: UINT8PTR, length: s return out -def zinflate_create(pool: rawptr[memhub.MemManager], wbits: int) -> zinflate_stream*: +def zinflate_create(pool: memhub.MemManager*, wbits: int) -> zinflate_stream*: s: zinflate_stream* = zdef.zdef_alloc(pool, zinflate_stream.__sizeof__()) if not s: return None string.memset(s, 0, zinflate_stream.__sizeof__())