修复了大量存在的问题,增加了假鸭子类型等等机制
This commit is contained in:
@@ -3,13 +3,18 @@ from __future__ import annotations
|
||||
import ast
|
||||
import os
|
||||
import re
|
||||
from typing import Any
|
||||
import llvmlite.ir as ir
|
||||
|
||||
from lib.core.LlvmCodeGenerator import LlvmCodeGenerator
|
||||
from lib.core.Handles.HandlesBase import CTypeInfo
|
||||
from lib.core.Handles.HandlesBase import CTypeInfo as _CTypeInfo, CTypeHelper
|
||||
from lib.includes import t
|
||||
from lib.constants.config import mode as _config_mode
|
||||
from lib.core.VLogger import get_logger as _vlog
|
||||
from lib.core.DecoratorPass import run as _run_decorator_pass
|
||||
from lib.core.Translator.BaseTranslator import _StrictLog
|
||||
from lib.core.SymbolUtils import IsTModule, AnnotationContainsName
|
||||
|
||||
|
||||
class LlvmGeneratorMixin:
|
||||
@@ -18,8 +23,25 @@ class LlvmGeneratorMixin:
|
||||
提供 LLVM IR 直接生成、模块级 LLVM IR 处理与 C 代码生成入口能力。
|
||||
"""
|
||||
|
||||
def GenerateLlvmDirect(self, Tree):
|
||||
Gen = self.LlvmGen
|
||||
def GenerateLlvmDirect(self, Tree: ast.Module) -> str:
|
||||
Gen: LlvmCodeGenerator = self.LlvmGen
|
||||
|
||||
# === 新增:轻量 AST 遍历,收集类图信息,解决前向引用 ===
|
||||
Gen._class_graph: dict[str, dict[str, bool | list[str]]] = {}
|
||||
for Node in ast.iter_child_nodes(Tree):
|
||||
if isinstance(Node, ast.ClassDef):
|
||||
bases: list[str] = []
|
||||
for base in Node.bases:
|
||||
if hasattr(base, 'id'):
|
||||
bases.append(base.id)
|
||||
elif hasattr(base, 'attr'):
|
||||
bases.append(base.attr)
|
||||
has_methods: bool = any(isinstance(item, ast.FunctionDef) for item in Node.body)
|
||||
Gen._class_graph[Node.name] = {
|
||||
'bases': bases,
|
||||
'has_methods': has_methods,
|
||||
}
|
||||
# === 结束新增 ===
|
||||
|
||||
# 预扫描:为所有 -> str 注解的函数注册正确的返回类型 i8*
|
||||
# 这样在类方法中调用这些函数时,前向声明会使用正确的类型
|
||||
@@ -29,7 +51,7 @@ class LlvmGeneratorMixin:
|
||||
Gen.known_return_types[Node.name] = ir.PointerType(ir.IntType(8))
|
||||
|
||||
# 首先收集所有 CDefine 常量,确保类定义中可以引用
|
||||
def _extract_call_const_val(node):
|
||||
def _extract_call_const_val(node: ast.AST) -> int | str | float | None:
|
||||
if isinstance(node, ast.Call):
|
||||
if isinstance(node.func, ast.Attribute):
|
||||
if getattr(node.func.value, 'id', None) == 't':
|
||||
@@ -42,48 +64,44 @@ class LlvmGeneratorMixin:
|
||||
|
||||
for Node in ast.iter_child_nodes(Tree):
|
||||
if isinstance(Node, ast.AnnAssign) and isinstance(Node.target, ast.Name) and Node.value:
|
||||
TypeInfo = self.TypeMergeHandler.GetCTypeInfo(Node.annotation)
|
||||
if TypeInfo and TypeInfo.BaseType and hasattr(TypeInfo.BaseType, 'CName') and TypeInfo.BaseType.CName == '#define':
|
||||
val = None
|
||||
TypeInfo: CTypeInfo | None = self.TypeMergeHandler.GetCTypeInfo(Node.annotation)
|
||||
if TypeInfo and TypeInfo.BaseType and ((isinstance(TypeInfo.BaseType, type) and issubclass(TypeInfo.BaseType, t.CDefine)) or isinstance(TypeInfo.BaseType, t.CDefine)):
|
||||
val: int | str | float | None = None
|
||||
if isinstance(Node.value, ast.Constant):
|
||||
val = Node.value.value
|
||||
else:
|
||||
val = _extract_call_const_val(Node.value)
|
||||
if val is not None:
|
||||
if not hasattr(Gen, '_define_constants'):
|
||||
Gen._define_constants = {}
|
||||
Gen._define_constants: dict[str, int | str | float | bool] = {}
|
||||
Gen._define_constants[Node.target.id] = val
|
||||
from lib.core.Handles.HandlesBase import CTypeInfo as _CTypeInfo
|
||||
sym_info = _CTypeInfo()
|
||||
sym_info: _CTypeInfo = _CTypeInfo()
|
||||
sym_info.IsDefine = True
|
||||
sym_info.DefineValue = val
|
||||
self.SymbolTable.insert(Node.target.id, sym_info)
|
||||
elif isinstance(Node, ast.Assign):
|
||||
for target in Node.targets:
|
||||
if isinstance(target, ast.Name):
|
||||
TypeInfo = None
|
||||
TypeInfo: CTypeInfo | None = None
|
||||
if Node.type_comment:
|
||||
try:
|
||||
tc_ast = ast.parse(Node.type_comment, mode='eval')
|
||||
tc_ast: ast.Expression = ast.parse(Node.type_comment, mode='eval')
|
||||
TypeInfo = self.TypeMergeHandler.GetCTypeInfo(tc_ast.body)
|
||||
except Exception as _e:
|
||||
from lib.core.VLogger import get_logger as _vlog
|
||||
from lib.constants.config import mode as _config_mode
|
||||
if _config_mode == "strict":
|
||||
raise
|
||||
_vlog().warning(f"解析类型注释失败: {_e}", "Exception")
|
||||
if TypeInfo and TypeInfo.BaseType and hasattr(TypeInfo.BaseType, 'CName') and TypeInfo.BaseType.CName == '#define':
|
||||
val = None
|
||||
if TypeInfo and TypeInfo.BaseType and ((isinstance(TypeInfo.BaseType, type) and issubclass(TypeInfo.BaseType, t.CDefine)) or isinstance(TypeInfo.BaseType, t.CDefine)):
|
||||
val: int | str | float | None = None
|
||||
if isinstance(Node.value, ast.Constant):
|
||||
val = Node.value.value
|
||||
else:
|
||||
val = _extract_call_const_val(Node.value)
|
||||
if val is not None:
|
||||
if not hasattr(Gen, '_define_constants'):
|
||||
Gen._define_constants = {}
|
||||
Gen._define_constants: dict[str, int | str | float | bool] = {}
|
||||
Gen._define_constants[target.id] = val
|
||||
from lib.core.Handles.HandlesBase import CTypeInfo as _CTypeInfo
|
||||
sym_info = _CTypeInfo()
|
||||
sym_info: _CTypeInfo = _CTypeInfo()
|
||||
sym_info.IsDefine = True
|
||||
sym_info.DefineValue = val
|
||||
self.SymbolTable.insert(target.id, sym_info)
|
||||
@@ -92,7 +110,7 @@ class LlvmGeneratorMixin:
|
||||
# 这样类方法编译时遇到未声明的函数可以按需前向声明
|
||||
for Node in ast.iter_child_nodes(Tree):
|
||||
if isinstance(Node, ast.FunctionDef):
|
||||
FuncName = Node.name
|
||||
FuncName: str = Node.name
|
||||
if FuncName not in self.FunctionDefCache:
|
||||
self.FunctionDefCache[FuncName] = Node
|
||||
|
||||
@@ -105,17 +123,17 @@ class LlvmGeneratorMixin:
|
||||
elif isinstance(Node, ast.ImportFrom):
|
||||
self.ImportHandler._EmitImportFromDeclarationsLlvm(Node, Gen)
|
||||
except Exception as e:
|
||||
lineno = getattr(Node, 'lineno', 0)
|
||||
source_line = Gen._get_source_line(lineno)
|
||||
src_file = getattr(Gen, '_current_source_file', '')
|
||||
src_path = src_file if src_file else 'unknown'
|
||||
line_info = "源代码 (%s, line %d)" % (src_path, lineno)
|
||||
lineno: int = getattr(Node, 'lineno', 0)
|
||||
source_line: str | None = Gen._get_source_line(lineno)
|
||||
src_file: str = getattr(Gen, '_current_source_file', '')
|
||||
src_path: str = src_file if src_file else 'unknown'
|
||||
line_info: str = "源代码 (%s, line %d)" % (src_path, lineno)
|
||||
if source_line:
|
||||
line_info += ":\n %d | %s" % (lineno, source_line)
|
||||
self._ErrorStack.append((type(e).__name__, str(e), line_info))
|
||||
|
||||
# 预创建全局变量(带初始化器),确保类方法编译时能引用全局数组等
|
||||
Gen._current_tree = Tree
|
||||
Gen._current_tree: ast.Module = Tree
|
||||
for Node in ast.iter_child_nodes(Tree):
|
||||
if isinstance(Node, ast.AnnAssign):
|
||||
self.AssignHandler._EmitGlobalAnnAssignLlvm(Node, Gen)
|
||||
@@ -155,42 +173,41 @@ class LlvmGeneratorMixin:
|
||||
elif isinstance(Node, ast.Expr):
|
||||
self._HandleModuleLevelExprLlvm(Node, Gen)
|
||||
except Exception as e:
|
||||
lineno = getattr(Node, 'lineno', 0)
|
||||
source_line = Gen._get_source_line(lineno)
|
||||
src_file = getattr(Gen, '_current_source_file', '')
|
||||
src_path = src_file if src_file else 'unknown'
|
||||
line_info = "源代码 (%s, line %d)" % (src_path, lineno)
|
||||
lineno: int = getattr(Node, 'lineno', 0)
|
||||
source_line: str | None = Gen._get_source_line(lineno)
|
||||
src_file: str = getattr(Gen, '_current_source_file', '')
|
||||
src_path: str = src_file if src_file else 'unknown'
|
||||
line_info: str = "源代码 (%s, line %d)" % (src_path, lineno)
|
||||
if source_line:
|
||||
line_info += ":\n %d | %s" % (lineno, source_line)
|
||||
self._ErrorStack.append((type(e).__name__, str(e), line_info))
|
||||
raise
|
||||
Gen._set_Vtable_initializers()
|
||||
# 执行 DecoratorPass:为带自定义装饰器的函数生成 wrapper
|
||||
from lib.core.DecoratorPass import run as _run_decorator_pass
|
||||
_run_decorator_pass(Gen)
|
||||
ir_code = Gen.finalize()
|
||||
ir_code: str = Gen.finalize()
|
||||
return ir_code
|
||||
|
||||
def _HandleModuleLevelExprLlvm(self, Node, Gen):
|
||||
def _HandleModuleLevelExprLlvm(self, Node: ast.Expr, Gen: LlvmCodeGenerator) -> None:
|
||||
if not isinstance(Node.value, ast.Call):
|
||||
return
|
||||
call = Node.value
|
||||
call: ast.Call = Node.value
|
||||
if not isinstance(call.func, ast.Attribute):
|
||||
return
|
||||
if not isinstance(call.func.value, ast.Name) or call.func.value.id != 'c':
|
||||
return
|
||||
func_name = call.func.attr
|
||||
func_name: str = call.func.attr
|
||||
if func_name == 'LLVMIR':
|
||||
self._HandleModuleLevelLLVMIR(call, Gen)
|
||||
|
||||
def _HandleModuleLevelLLVMIR(self, Node, Gen):
|
||||
def _HandleModuleLevelLLVMIR(self, Node: ast.Call, Gen: LlvmCodeGenerator) -> None:
|
||||
if not Node.args:
|
||||
return
|
||||
first_arg = Node.args[0]
|
||||
first_arg: ast.expr = Node.args[0]
|
||||
if isinstance(first_arg, ast.Constant) and isinstance(first_arg.value, str):
|
||||
ir_text = first_arg.value
|
||||
ir_text: str = first_arg.value
|
||||
elif isinstance(first_arg, ast.JoinedStr):
|
||||
parts = []
|
||||
parts: list[str] = []
|
||||
for value in first_arg.values:
|
||||
if isinstance(value, ast.Constant) and isinstance(value.value, str):
|
||||
parts.append(value.value)
|
||||
@@ -201,79 +218,78 @@ class LlvmGeneratorMixin:
|
||||
return
|
||||
self._InsertModuleLevelLLVMIR(Gen, ir_text)
|
||||
|
||||
def _InsertModuleLevelLLVMIR(self, Gen, ir_text):
|
||||
import re
|
||||
def _InsertModuleLevelLLVMIR(self, Gen: LlvmCodeGenerator, ir_text: str) -> None:
|
||||
for line in ir_text.strip().split('\n'):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
module_flags_match = re.match(r'!llvm\.module\.flags\s*=\s*!\{(!\d+)\}', line)
|
||||
module_flags_match: re.Match[str] | None = re.match(r'!llvm\.module\.flags\s*=\s*!\{(!\d+)\}', line)
|
||||
if module_flags_match:
|
||||
ref = module_flags_match.group(1)
|
||||
ref: str = module_flags_match.group(1)
|
||||
if not hasattr(Gen, '_pending_module_flags'):
|
||||
Gen._pending_module_flags = []
|
||||
Gen._pending_module_flags_refs = ref
|
||||
Gen._pending_module_flags: list = []
|
||||
Gen._pending_module_flags_refs: str = ref
|
||||
continue
|
||||
metadata_match = re.match(r'(!\d+)\s*=\s*!\{(.+)\}', line)
|
||||
metadata_match: re.Match[str] | None = re.match(r'(!\d+)\s*=\s*!\{(.+)\}', line)
|
||||
if metadata_match:
|
||||
md_id = metadata_match.group(1)
|
||||
md_body = metadata_match.group(2)
|
||||
fields = []
|
||||
md_id: str = metadata_match.group(1)
|
||||
md_body: str = metadata_match.group(2)
|
||||
fields: list[ir.Constant | ir.MetaDataString | str] = []
|
||||
for field_str in re.split(r',\s*', md_body):
|
||||
field_str = field_str.strip()
|
||||
if not field_str:
|
||||
continue
|
||||
int_m = re.match(r'^i32\s+(\d+)$', field_str)
|
||||
int_m: re.Match[str] | None = re.match(r'^i32\s+(\d+)$', field_str)
|
||||
if int_m:
|
||||
fields.append(ir.Constant(ir.IntType(32), int(int_m.group(1))))
|
||||
continue
|
||||
str_m = re.match(r'^"([^"]*)"$', field_str)
|
||||
str_m: re.Match[str] | None = re.match(r'^"([^"]*)"$', field_str)
|
||||
if str_m:
|
||||
fields.append(ir.MetaDataString(Gen.module, str_m.group(1)))
|
||||
continue
|
||||
mdstr_m = re.match(r'^!"([^"]*)"$', field_str)
|
||||
mdstr_m: re.Match[str] | None = re.match(r'^!"([^"]*)"$', field_str)
|
||||
if mdstr_m:
|
||||
fields.append(ir.MetaDataString(Gen.module, mdstr_m.group(1)))
|
||||
continue
|
||||
int_m2 = re.match(r'^(\d+)$', field_str)
|
||||
int_m2: re.Match[str] | None = re.match(r'^(\d+)$', field_str)
|
||||
if int_m2:
|
||||
fields.append(ir.Constant(ir.IntType(32), int(int_m2.group(1))))
|
||||
continue
|
||||
ref_m = re.match(r'^(!\d+)$', field_str)
|
||||
ref_m: re.Match[str] | None = re.match(r'^(!\d+)$', field_str)
|
||||
if ref_m:
|
||||
fields.append(ref_m.group(1))
|
||||
continue
|
||||
if fields:
|
||||
if not hasattr(Gen, '_pending_metadata'):
|
||||
Gen._pending_metadata = []
|
||||
Gen._pending_metadata: list[tuple[str, list]] = []
|
||||
Gen._pending_metadata.append((md_id, fields))
|
||||
continue
|
||||
self._FlushModuleMetadata(Gen)
|
||||
|
||||
def _FlushModuleMetadata(self, Gen):
|
||||
def _FlushModuleMetadata(self, Gen: LlvmCodeGenerator) -> None:
|
||||
if not hasattr(Gen, '_pending_metadata') or not Gen._pending_metadata:
|
||||
return
|
||||
md_map = {}
|
||||
md_map: dict[str, ir.MetaDataString] = {}
|
||||
for md_id, fields in Gen._pending_metadata:
|
||||
resolved = []
|
||||
resolved: list[ir.Constant | ir.MetaDataString] = []
|
||||
for f in fields:
|
||||
if isinstance(f, str) and f.startswith('!'):
|
||||
ref = md_map.get(f)
|
||||
ref: ir.MetaDataString | None = md_map.get(f)
|
||||
if ref:
|
||||
resolved.append(ref)
|
||||
else:
|
||||
resolved.append(f)
|
||||
md_value = Gen.module.add_metadata(resolved)
|
||||
md_value: ir.MetaDataString = Gen.module.add_metadata(resolved)
|
||||
md_map[md_id] = md_value
|
||||
if hasattr(Gen, '_pending_module_flags_refs'):
|
||||
ref = Gen._pending_module_flags_refs
|
||||
md_node = md_map.get(ref)
|
||||
ref: str = Gen._pending_module_flags_refs
|
||||
md_node: ir.MetaDataString | None = md_map.get(ref)
|
||||
if md_node:
|
||||
Gen.module.add_named_metadata('llvm.module.flags', md_node)
|
||||
Gen._pending_metadata = []
|
||||
Gen._pending_module_flags_refs = None
|
||||
|
||||
def GenerateCCode(self, Tree, target='llvm'):
|
||||
def GenerateCCode(self, Tree: ast.Module, target: str = 'llvm') -> str:
|
||||
"""生成代码
|
||||
|
||||
Args:
|
||||
@@ -283,23 +299,23 @@ class LlvmGeneratorMixin:
|
||||
Returns:
|
||||
生成的代码字符串
|
||||
"""
|
||||
self._generated_vars = set()
|
||||
self._generated_vars: set[str] = set()
|
||||
self.VarScopes = [{}] # 全局作用域
|
||||
|
||||
# 预扫描 import 语句,注册别名,确保类型解析时能正确解析模块别名
|
||||
if not getattr(self, '_ImportedModules', None):
|
||||
self._ImportedModules = set()
|
||||
self._ImportedModules: set[str] = set()
|
||||
for Node in ast.iter_child_nodes(Tree):
|
||||
if isinstance(Node, ast.Import):
|
||||
for alias in Node.names:
|
||||
name = alias.name
|
||||
name: str = alias.name
|
||||
if name in ('c', 't'):
|
||||
continue
|
||||
self._ImportedModules.add(name)
|
||||
if alias.asname:
|
||||
self.SymbolTable.import_aliases[alias.asname] = name
|
||||
elif isinstance(Node, ast.ImportFrom):
|
||||
module_name = Node.module
|
||||
module_name: str | None = Node.module
|
||||
if module_name and module_name not in ('c', 't'):
|
||||
self._ImportedModules.add(module_name)
|
||||
for alias in Node.names:
|
||||
@@ -308,10 +324,10 @@ class LlvmGeneratorMixin:
|
||||
|
||||
for Node in ast.iter_child_nodes(Tree):
|
||||
if isinstance(Node, ast.ClassDef):
|
||||
ClassName = Node.name
|
||||
ClassName: str = Node.name
|
||||
|
||||
# 检查是否是特殊类型(枚举或联合体)
|
||||
IsSpecialType = False
|
||||
IsSpecialType: bool = False
|
||||
if Node.bases:
|
||||
for base in Node.bases:
|
||||
if hasattr(base, 'attr'):
|
||||
@@ -327,13 +343,13 @@ class LlvmGeneratorMixin:
|
||||
if IsSpecialType:
|
||||
continue
|
||||
|
||||
members = {}
|
||||
IsTypedef = False
|
||||
TypedefName = None
|
||||
members: dict[str, CTypeInfo] = {}
|
||||
IsTypedef: bool = False
|
||||
TypedefName: str | None = None
|
||||
|
||||
if hasattr(Node, 'annotation') and Node.annotation:
|
||||
try:
|
||||
AnnotationStr = ast.dump(Node.annotation)
|
||||
AnnotationStr: str = ast.dump(Node.annotation)
|
||||
if 'CTypedef' in AnnotationStr:
|
||||
IsTypedef = True
|
||||
if isinstance(Node.annotation, ast.Call):
|
||||
@@ -341,8 +357,6 @@ class LlvmGeneratorMixin:
|
||||
if isinstance(Node.annotation.args[0], ast.Constant):
|
||||
TypedefName = Node.annotation.args[0].value
|
||||
except Exception as _e:
|
||||
from lib.core.VLogger import get_logger as _vlog
|
||||
from lib.constants.config import mode as _config_mode
|
||||
if _config_mode == "strict":
|
||||
raise
|
||||
_vlog().warning(f"解析 typedef 注解失败: {_e}", "Exception")
|
||||
@@ -355,7 +369,7 @@ class LlvmGeneratorMixin:
|
||||
if isinstance(item.value, ast.Dict):
|
||||
for key, value in zip(item.value.keys, item.value.values):
|
||||
if isinstance(key, ast.Constant) and key.value == '__type__':
|
||||
value_str = ast.dump(value)
|
||||
value_str: str = ast.dump(value)
|
||||
if 'CTypedef' in value_str:
|
||||
IsTypedef = True
|
||||
if isinstance(value, ast.Call):
|
||||
@@ -364,8 +378,8 @@ class LlvmGeneratorMixin:
|
||||
TypedefName = value.args[0].value
|
||||
|
||||
if IsTypedef:
|
||||
TypedefKey = TypedefName if TypedefName else ClassName
|
||||
TypedefNode = CTypeInfo()
|
||||
TypedefKey: str = TypedefName if TypedefName else ClassName
|
||||
TypedefNode: CTypeInfo = CTypeInfo()
|
||||
TypedefNode.Name = TypedefKey
|
||||
TypedefNode.IsTypedef = True
|
||||
TypedefNode.OriginalType = f'struct {ClassName}'
|
||||
@@ -375,80 +389,79 @@ class LlvmGeneratorMixin:
|
||||
|
||||
for item in Node.body:
|
||||
if isinstance(item, ast.AnnAssign) and isinstance(item.target, ast.Name):
|
||||
VarName = item.target.id
|
||||
VarName: str = item.target.id
|
||||
try:
|
||||
TypeInfo = self.TypeMergeHandler.GetCTypeInfo(item.annotation)
|
||||
TypeInfo: CTypeInfo | None = self.TypeMergeHandler.GetCTypeInfo(item.annotation)
|
||||
if TypeInfo is None:
|
||||
TypeInfo = CTypeInfo()
|
||||
TypeInfo.BaseType = t.CInt()
|
||||
IsPtr = TypeInfo.IsPtr
|
||||
IsPtr: bool = TypeInfo.IsPtr
|
||||
if not IsPtr:
|
||||
if isinstance(item.annotation, ast.BinOp) and isinstance(item.annotation.op, ast.BitOr):
|
||||
LeftStr = ast.dump(item.annotation.left)
|
||||
RightStr = ast.dump(item.annotation.right)
|
||||
if 'CPtr' in LeftStr or 'CPtr' in RightStr:
|
||||
if AnnotationContainsName(item.annotation, 'CPtr'):
|
||||
IsPtr = True
|
||||
dims = []
|
||||
dims: list[int] = []
|
||||
if hasattr(item.annotation, 'slice') and isinstance(item.annotation.slice, ast.Constant):
|
||||
if isinstance(item.annotation.value, ast.Name):
|
||||
if item.annotation.value.id == 't':
|
||||
if IsTModule(item.annotation.value.id, self.SymbolTable):
|
||||
if hasattr(item.annotation, 'slice'):
|
||||
try:
|
||||
dims.append(int(item.annotation.slice.value))
|
||||
except Exception as _e:
|
||||
if __import__('lib.constants.config', fromlist=['mode']).mode == "strict":
|
||||
if _config_mode == "strict":
|
||||
self.LogWarning(f"异常被忽略: {_e}")
|
||||
MemberInfo = TypeInfo.Copy()
|
||||
MemberInfo: CTypeInfo = TypeInfo.Copy()
|
||||
if dims:
|
||||
MemberInfo.ArrayDims = [str(d) for d in dims]
|
||||
members[VarName] = MemberInfo
|
||||
except Exception as _e:
|
||||
if __import__('lib.constants.config', fromlist=['mode']).mode == "strict":
|
||||
if _config_mode == "strict":
|
||||
self.LogWarning(f"异常被忽略: {_e}")
|
||||
|
||||
if not IsTypedef:
|
||||
StructNode = CTypeInfo()
|
||||
StructNode: CTypeInfo = CTypeInfo()
|
||||
StructNode.Name = ClassName
|
||||
StructNode.IsStruct = True
|
||||
StructNode.Members = members or {}
|
||||
StructNode.file = '<stdin>'
|
||||
if self.SymbolTable.has(ClassName):
|
||||
existing = self.SymbolTable[ClassName]
|
||||
existing: CTypeInfo | None = self.SymbolTable.lookup(ClassName)
|
||||
if existing:
|
||||
if hasattr(existing, 'IsCpythonObject') and existing.IsCpythonObject:
|
||||
StructNode.IsCpythonObject = True
|
||||
self.SymbolTable.insert(ClassName, StructNode)
|
||||
elif isinstance(Node, ast.FunctionDef):
|
||||
FuncName = Node.name
|
||||
FuncNode = CTypeInfo()
|
||||
FuncNode.Name = FuncName
|
||||
FuncNode.IsFunction = True
|
||||
FuncNode.file = '<stdin>'
|
||||
self.SymbolTable.insert(FuncName, FuncNode)
|
||||
FuncName: str = Node.name
|
||||
if not self.SymbolTable.has(FuncName):
|
||||
FuncNode: CTypeInfo = CTypeInfo()
|
||||
FuncNode.Name = FuncName
|
||||
FuncNode.IsFunction = True
|
||||
FuncNode.file = '<stdin>'
|
||||
self.SymbolTable.insert(FuncName, FuncNode)
|
||||
elif isinstance(Node, ast.AnnAssign):
|
||||
if isinstance(Node.target, ast.Name):
|
||||
VarName = Node.target.id
|
||||
VarName: str = Node.target.id
|
||||
|
||||
VarType = 'unknown'
|
||||
IsPtr = False
|
||||
IsTypedef_assignment = False
|
||||
VarType: str = 'unknown'
|
||||
IsPtr: bool = False
|
||||
IsTypedef_assignment: bool = False
|
||||
|
||||
if Node.annotation:
|
||||
try:
|
||||
AnnotationStr = ast.dump(Node.annotation)
|
||||
AnnotationStr: str = ast.dump(Node.annotation)
|
||||
if 'CTypedef' in AnnotationStr:
|
||||
IsTypedef_assignment = True
|
||||
except Exception as _e:
|
||||
if __import__('lib.constants.config', fromlist=['mode']).mode == "strict":
|
||||
if _config_mode == "strict":
|
||||
self.LogWarning(f"异常被忽略: {_e}")
|
||||
|
||||
if IsTypedef_assignment and Node.value:
|
||||
if isinstance(Node.value, ast.Name):
|
||||
OriginalType = Node.value.id
|
||||
OriginalType: str = Node.value.id
|
||||
if OriginalType in self.GeneratedTypes:
|
||||
if self.SymbolTable.has(OriginalType):
|
||||
OriginalInfo = self.SymbolTable[OriginalType]
|
||||
OriginalInfo: CTypeInfo | None = self.SymbolTable.lookup(OriginalType)
|
||||
if OriginalInfo:
|
||||
if isinstance(OriginalInfo, dict):
|
||||
actual_type = OriginalInfo.get('type', 'struct')
|
||||
actual_type: str = OriginalInfo.get('type', 'struct')
|
||||
elif isinstance(OriginalInfo, CTypeInfo):
|
||||
if OriginalInfo.IsEnum:
|
||||
actual_type = 'enum'
|
||||
@@ -461,7 +474,7 @@ class LlvmGeneratorMixin:
|
||||
else:
|
||||
actual_type = 'struct'
|
||||
if actual_type == 'enum':
|
||||
TypedefNode = CTypeInfo()
|
||||
TypedefNode: CTypeInfo = CTypeInfo()
|
||||
TypedefNode.Name = VarName
|
||||
TypedefNode.IsTypedef = True
|
||||
TypedefNode.OriginalType = f'enum {OriginalType}'
|
||||
@@ -491,10 +504,10 @@ class LlvmGeneratorMixin:
|
||||
self.GeneratedTypes.add(VarName)
|
||||
continue
|
||||
else:
|
||||
if self.SymbolTable.has(OriginalType):
|
||||
OriginalInfo = self.SymbolTable[OriginalType]
|
||||
OriginalInfo: CTypeInfo | None = self.SymbolTable.lookup(OriginalType)
|
||||
if OriginalInfo:
|
||||
if isinstance(OriginalInfo, dict):
|
||||
actual_type = OriginalInfo.get('type', 'struct')
|
||||
actual_type: str = OriginalInfo.get('type', 'struct')
|
||||
elif isinstance(OriginalInfo, CTypeInfo):
|
||||
if OriginalInfo.IsEnum:
|
||||
actual_type = 'enum'
|
||||
@@ -507,7 +520,7 @@ class LlvmGeneratorMixin:
|
||||
else:
|
||||
actual_type = 'struct'
|
||||
if actual_type == 'typedef':
|
||||
TypedefNode = CTypeInfo()
|
||||
TypedefNode: CTypeInfo = CTypeInfo()
|
||||
TypedefNode.Name = VarName
|
||||
TypedefNode.IsTypedef = True
|
||||
if isinstance(OriginalInfo, dict):
|
||||
@@ -548,10 +561,9 @@ class LlvmGeneratorMixin:
|
||||
OriginalInfo['skip_generation'] = True
|
||||
continue
|
||||
elif isinstance(Node.value, ast.Attribute):
|
||||
from lib.core.Handles.HandlesBase import CTypeHelper
|
||||
CName = CTypeHelper.GetCName(Node.value.attr)
|
||||
CName: str | None = CTypeHelper.GetCName(Node.value.attr)
|
||||
if CName:
|
||||
TypedefNode = CTypeInfo()
|
||||
TypedefNode: CTypeInfo = CTypeInfo()
|
||||
TypedefNode.Name = VarName
|
||||
TypedefNode.IsTypedef = True
|
||||
TypedefNode.OriginalType = CName
|
||||
@@ -562,19 +574,19 @@ class LlvmGeneratorMixin:
|
||||
|
||||
if Node.annotation:
|
||||
try:
|
||||
TypeInfo = self.TypeMergeHandler.GetCTypeInfo(Node.annotation)
|
||||
TypeInfo: CTypeInfo | None = self.TypeMergeHandler.GetCTypeInfo(Node.annotation)
|
||||
IsPtr = TypeInfo.IsPtr if TypeInfo else False
|
||||
except Exception as _e:
|
||||
if __import__('lib.constants.config', fromlist=['mode']).mode == "strict":
|
||||
if _config_mode == "strict":
|
||||
self.LogWarning(f"异常被忽略: {_e}")
|
||||
var_node = CTypeInfo()
|
||||
var_node: CTypeInfo = CTypeInfo()
|
||||
var_node.Name = VarName
|
||||
var_node.IsVariable = True
|
||||
var_node.PtrCount = 1 if IsPtr else 0
|
||||
var_node.file = '<stdin>'
|
||||
self.SymbolTable.insert(VarName, var_node)
|
||||
|
||||
self.LlvmGen = LlvmCodeGenerator(
|
||||
self.LlvmGen: LlvmCodeGenerator = LlvmCodeGenerator(
|
||||
triple=getattr(self, 'triple', None),
|
||||
datalayout=getattr(self, 'datalayout', None),
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user