feat(cdef): define 常量带类型注册——按声明类型物化(DWORD(-11) → i32 位型)
方案 C:CDefine 不再只存无类型 int,而是把**声明整数类型**(位宽 + 符号性)一并登记,使用点按该类型物化,而不是按数值大小猜 i32/i64。链路:① SymbolUtils 新增 DefineIntSignednessOf / DefineDeclIntTypeFromAnnotation(由 T | t.CDefine 注解经符号表 typedef 链解析宽度与符号性)/ DefineDeclTypeValue(按声明类型把值归一成 (位宽, 位型值));② 同模块注册(LlvmGenerator._register_cdefine_constant)与跨模块提取(Phase2Translator._ExtractCDefineConstantsFromPyi,含 _shared_all_decl_types 的 pickle 传递)分别写 Gen._define_decl_types / translator._define_decl_types;③ 物化处(HandlesExpr 裸名两处、HandlesExprAttr._make_define_constant,及 from-import 注册)优先按声明类型出常量。这样 win32file 的 STD_*_HANDLE(DWORD(-10/-11/-12))解析为 i32 位型 0xFFFFFFF5 等,与 GetStdHandle(ULONG) 使用点一致。
This commit is contained in:
1 parent
e1a0fbf9c0
commit
d5b4e9a8b9
6 files changed
+198
-20
No files matched your search
@@ -18,7 +18,7 @@ from lib.constants.config import mode as _config_mode
|
||||
from lib.core.Handles.HandlesBase import CTypeInfo
|
||||
from lib.core.SymbolData import ModuleSymbols
|
||||
from lib.includes import t
|
||||
from lib.core.SymbolUtils import AnnotationContainsName, ExpandSoftKeywords
|
||||
from lib.core.SymbolUtils import AnnotationContainsName, ExpandSoftKeywords, DefineDeclIntTypeFromAnnotation
|
||||
from lib.core.SymbolUtils import ClassHasFuncLevelCVTable, IsVtableSlotMethod
|
||||
from lib.Projectrans.Utils import compute_sha1, _check_annotation_for_export, find_reachable_files_from_entries, topological_sort_files, parse_python_file
|
||||
from lib.Projectrans.Phase1Generator import _TryGlobalCache, _SaveToGlobalCache, _GLOBAL_CACHE_DIR
|
||||
@@ -469,9 +469,9 @@ _JOBS_ENV: str = 'TPC_JOBS'
|
||||
_MemProbeDone: set[int] = set()
|
||||
# 预分配校验的分块大小(MB):分块提交并**全部持有**到校验结束(峰值 = 预算),
|
||||
# 结束后立即整体释放 —— 紧接其后就创建 worker 进程,OS 直接复用这批刚释放的页。
|
||||
_MEM_PROBE_CHUNK_MB: int = 256
|
||||
# 自动并行度上限(用户 2026-10-01 定:16 worker 太多)。只约束**自动**取值,
|
||||
# 显式 TPC_JOBS=N 仍按硬件/文件数上限生效。
|
||||
_MEM_PROBE_CHUNK_MB: int = 256
|
||||
# 自动并行度上限(用户 2026-10-01 定:16 worker 太多)。只约束**自动**取值,
|
||||
# 显式 TPC_JOBS=N 仍按硬件/文件数上限生效。
|
||||
_MAX_WORKERS: int = 8
|
||||
|
||||
|
||||
@@ -583,7 +583,9 @@ def _PickWorkerCount(n_files: int, per_worker_mb: int = 350) -> int:
|
||||
return base
|
||||
|
||||
|
||||
def _ExtractCDefineConstantsFromPyi(pyi_path: str, all_dc: dict[str, object]) -> None:
|
||||
def _ExtractCDefineConstantsFromPyi(pyi_path: str, all_dc: dict[str, object],
|
||||
symtab: object | None = None,
|
||||
all_dt: dict[str, tuple[int, bool]] | None = None) -> None:
|
||||
"""从 .pyi 文件中提取 CDefine 常量到 all_dc。文件不存在时静默跳过。
|
||||
|
||||
治本修复:原实现只支持 ast.Constant 和 float() 调用,
|
||||
@@ -632,6 +634,12 @@ def _ExtractCDefineConstantsFromPyi(pyi_path: str, all_dc: dict[str, object]) ->
|
||||
val = ConstEvaluator.eval_full(node.value.args[0], ctx)
|
||||
if val is not None and isinstance(val, (int, float, str)):
|
||||
all_dc[node.target.id] = val
|
||||
# 带类型注册:记录该 define 的**声明整数类型**(如 `DWORD` → (32, False)),
|
||||
# 供使用点按声明类型物化(u32 用 i32 + 位型,而不是按值大小猜 i32/i64)。
|
||||
if all_dt is not None and isinstance(val, int) and not isinstance(val, bool):
|
||||
decl_type: tuple[int, bool] | None = DefineDeclIntTypeFromAnnotation(symtab, node.annotation)
|
||||
if decl_type is not None:
|
||||
all_dt[node.target.id] = decl_type
|
||||
except Exception as e:
|
||||
_vlog().warning(f"Phase2Translator: 忽略异常 {e}", exc_info=e)
|
||||
|
||||
@@ -706,6 +714,7 @@ def _parallel_translate_worker(src_path: str, out_path: str, src_root: str, temp
|
||||
trans._shared_symbol_table = pickle.loads(_sym_bytes)
|
||||
trans._shared_source_module_sig_files = shared_data['source_module_sig_files']
|
||||
trans._shared_all_dc = shared_data['all_dc']
|
||||
trans._shared_all_decl_types = shared_data.get('all_decl_types', {})
|
||||
trans._shared_export_extern_funcs = shared_data['export_extern_funcs']
|
||||
trans.inline_func_symbols = shared_data['inline_func_symbols']
|
||||
trans.function_default_args = shared_data['function_default_args']
|
||||
@@ -776,6 +785,7 @@ def _parallel_translate_batch(batch: list, src_root: str, temp_dir: str, output_
|
||||
trans._shared_symbol_table = pickle.loads(symbol_table_bytes)
|
||||
trans._shared_source_module_sig_files = shared_data['source_module_sig_files']
|
||||
trans._shared_all_dc = shared_data['all_dc']
|
||||
trans._shared_all_decl_types = shared_data.get('all_decl_types', {})
|
||||
trans._shared_export_extern_funcs = shared_data['export_extern_funcs']
|
||||
trans.inline_func_symbols = shared_data['inline_func_symbols']
|
||||
trans.function_default_args = shared_data['function_default_args']
|
||||
@@ -1332,6 +1342,7 @@ class Phase2Translator:
|
||||
self._shared_symbol_table: object | None = None
|
||||
self._shared_source_module_sig_files: dict[str, str] = {}
|
||||
self._shared_all_dc: dict[str, dict] = {}
|
||||
self._shared_all_decl_types: dict[str, tuple[int, bool]] = {}
|
||||
self._shared_export_extern_funcs: dict[str, str] = {}
|
||||
self.include_dirs: list[str] = []
|
||||
self.struct_sha1_map: dict[str, str] = {}
|
||||
@@ -1650,6 +1661,7 @@ class Phase2Translator:
|
||||
'symbol_table_bytes': symbol_table_bytes,
|
||||
'source_module_sig_files': self._shared_source_module_sig_files,
|
||||
'all_dc': self._shared_all_dc,
|
||||
'all_decl_types': self._shared_all_decl_types,
|
||||
'export_extern_funcs': self._shared_export_extern_funcs,
|
||||
'inline_func_symbols': self.inline_func_symbols,
|
||||
'function_default_args': self.function_default_args,
|
||||
@@ -2340,6 +2352,7 @@ class Phase2Translator:
|
||||
self._shared_symbol_table.translator = trans.translator
|
||||
trans.translator._source_module_sig_files = self._shared_source_module_sig_files
|
||||
trans.translator._all_define_constants = self._shared_all_dc
|
||||
trans.translator._define_decl_types = self._shared_all_decl_types
|
||||
trans.translator._export_extern_funcs = self._shared_export_extern_funcs
|
||||
if self._shared_generic_class_templates:
|
||||
if not hasattr(trans.translator.ClassHandler, '_generic_class_templates'):
|
||||
@@ -2408,6 +2421,7 @@ class Phase2Translator:
|
||||
trans.translator._source_module_sig_files[short_name] = sig_path
|
||||
|
||||
all_dc = {}
|
||||
all_dt: dict[str, tuple[int, bool]] = {}
|
||||
for sha1_key, stub_path in self.stub_files.items():
|
||||
if sha1_key == sha1:
|
||||
continue
|
||||
@@ -2429,9 +2443,11 @@ class Phase2Translator:
|
||||
for sha1_key, pyi_path in self.sig_files.items():
|
||||
if sha1_key == sha1:
|
||||
continue
|
||||
_ExtractCDefineConstantsFromPyi(pyi_path, all_dc)
|
||||
_ExtractCDefineConstantsFromPyi(pyi_path, all_dc, trans.translator.SymbolTable, all_dt)
|
||||
if all_dc:
|
||||
trans.translator._all_define_constants = all_dc
|
||||
if all_dt:
|
||||
trans.translator._define_decl_types = all_dt
|
||||
|
||||
for sym_name, sym_info in self.inline_func_symbols.items():
|
||||
if sym_name not in trans.translator.SymbolTable:
|
||||
@@ -3324,19 +3340,19 @@ class Phase2Translator:
|
||||
_vlog().warning(f"发现 include 传递依赖失败: {_e}", "Exception")
|
||||
|
||||
def _try_add_include_dep(self, module_name: str, includes_dir: str, discovered: set, py_index: set[str] | None = None):
|
||||
"""尝试将模块添加为 include 依赖(支持子包,如 w32.win32base)
|
||||
"""尝试将模块添加为 include 依赖(支持子包,如 win32.win32base)
|
||||
|
||||
py_index 非空时用 set 查询替代 os.path.isfile(O(1) vs 24ms/次)。
|
||||
"""
|
||||
# 候选路径:子包路径(w32/win32base.vp/.py)、顶层模块(w32.vp/.py)、子包 __init__.vp/__init__.py
|
||||
# 候选路径:子包路径(win32/win32base.vp/.py)、顶层模块(win32.vp/.py)、子包 __init__.vp/__init__.py
|
||||
candidates: list[str] = []
|
||||
# 子包路径:w32.win32base → w32/win32base.vp / .py
|
||||
# 子包路径:win32.win32base → win32/win32base.vp / .py
|
||||
candidates.append(os.path.join(includes_dir, module_name.replace('.', os.sep) + '.vp'))
|
||||
candidates.append(os.path.join(includes_dir, module_name.replace('.', os.sep) + '.py'))
|
||||
# 子包 __init__.vp/__init__.py:w32.win32base → w32/win32base/__init__.vp / .py
|
||||
# 子包 __init__.vp/__init__.py:win32.win32base → win32/win32base/__init__.vp / .py
|
||||
candidates.append(os.path.join(includes_dir, module_name.replace('.', os.sep), '__init__.vp'))
|
||||
candidates.append(os.path.join(includes_dir, module_name.replace('.', os.sep), '__init__.py'))
|
||||
# 顶层模块:取第一个组件 → w32.vp / .py
|
||||
# 顶层模块:取第一个组件 → win32.vp / .py
|
||||
top_module = module_name.split('.')[0]
|
||||
if top_module != module_name:
|
||||
candidates.append(os.path.join(includes_dir, top_module + '.vp'))
|
||||
@@ -3568,7 +3584,7 @@ class Phase2Translator:
|
||||
hotspot_on: bool = bool(self.hotspot_sites_file)
|
||||
|
||||
# --traceback:include 模块也必须带 DWARF 行表(否则运行时 Ctrl+C 的栈里
|
||||
# 落在 includes/*(memhub/string/viperlib/w32…)的帧取不到源行,只能落到
|
||||
# 落在 includes/*(memhub/string/viperlib/win32…)的帧取不到源行,只能落到
|
||||
# 邻行或 "+0x…(unknown)")。为此翻译时给 include 透传 dwarf_enabled=True
|
||||
# (见下方 worker/串行四处的 dwarf_enabled=self.traceback_enabled),并把
|
||||
# 旧目标文件(output 目录 {sha1}.obj 及隔离缓存 includes.binary_traceback
|
||||
@@ -3694,6 +3710,7 @@ class Phase2Translator:
|
||||
'symbol_table_bytes': pickle.dumps(self._shared_symbol_table),
|
||||
'source_module_sig_files': self._shared_source_module_sig_files,
|
||||
'all_dc': self._shared_all_dc,
|
||||
'all_decl_types': self._shared_all_decl_types,
|
||||
'export_extern_funcs': self._shared_export_extern_funcs,
|
||||
'inline_func_symbols': self.inline_func_symbols,
|
||||
'function_default_args': self.function_default_args,
|
||||
@@ -4434,6 +4451,7 @@ class Phase2Translator:
|
||||
self._register_package_reexports(base_trans, sig_path, package_name)
|
||||
|
||||
all_dc = {}
|
||||
all_dt: dict[str, tuple[int, bool]] = {}
|
||||
for sha1_key, stub_path in self.stub_files.items():
|
||||
if os.path.exists(stub_path):
|
||||
try:
|
||||
@@ -4452,7 +4470,7 @@ class Phase2Translator:
|
||||
_vlog().warning(f"Phase2Translator: 忽略异常 {e}", exc_info=e)
|
||||
|
||||
for sha1_key, pyi_path in self.sig_files.items():
|
||||
_ExtractCDefineConstantsFromPyi(pyi_path, all_dc)
|
||||
_ExtractCDefineConstantsFromPyi(pyi_path, all_dc, base_trans.translator.SymbolTable, all_dt)
|
||||
|
||||
export_extern_funcs = {}
|
||||
for sha1_key, sig_path in self.sig_files.items():
|
||||
@@ -4483,6 +4501,7 @@ class Phase2Translator:
|
||||
self._shared_symbol_table = base_trans.translator.SymbolTable
|
||||
self._shared_source_module_sig_files = dict(base_trans.translator._source_module_sig_files)
|
||||
self._shared_all_dc = all_dc
|
||||
self._shared_all_decl_types = all_dt
|
||||
self._shared_export_extern_funcs = export_extern_funcs
|
||||
|
||||
generic_class_templates = {}
|
||||
|
||||
@@ -9,7 +9,7 @@ import llvmlite.ir as ir
|
||||
from lib.core.Handles.HandlesBase import BaseHandle
|
||||
from lib.constants.config import mode as _config_mode
|
||||
from lib.includes.t import CTypeRegistry as _CR
|
||||
from lib.core.SymbolUtils import RequireDefineUseWidthAt, RequireIntLiteralStorable, RequireNameDefined
|
||||
from lib.core.SymbolUtils import RequireDefineUseWidthAt, RequireIntLiteralStorable, RequireNameDefined, DefineDeclTypeValue
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
@@ -455,6 +455,12 @@ class ExprHandle(BaseHandle):
|
||||
RequireDefineUseWidthAt(Gen, self.Trans, Node, _cdefine_val,
|
||||
int(_use_ty.width), VarName, _use_ctx)
|
||||
return ir.Constant(_use_ty, val & ((1 << _use_ty.width) - 1))
|
||||
# 带类型注册:无使用处宽度提示时,按 define 的**声明类型**物化
|
||||
# (`define X: DWORD = -11` → i32 位型 0xFFFFFFF5,而不是按值大小猜 i64)。
|
||||
_dtv: tuple[int, int] | None = DefineDeclTypeValue(
|
||||
getattr(Gen, '_define_decl_types', None) or getattr(self.Trans, '_define_decl_types', None), VarName, val)
|
||||
if _dtv is not None:
|
||||
return ir.Constant(ir.IntType(_dtv[0]), _dtv[1])
|
||||
if VarName in Gen.var_signedness and Gen.var_signedness[VarName]:
|
||||
if val < -(1 << 31) or val > 0xFFFFFFFF:
|
||||
return ir.Constant(ir.IntType(64), val & 0xFFFFFFFFFFFFFFFF)
|
||||
@@ -493,6 +499,11 @@ class ExprHandle(BaseHandle):
|
||||
RequireDefineUseWidthAt(Gen, self.Trans, Node, val,
|
||||
int(_use_ty2.width), VarName, _use_ctx2)
|
||||
return ir.Constant(_use_ty2, val & ((1 << _use_ty2.width) - 1))
|
||||
# 带类型注册:同本模块路径——按声明类型物化(见上)。
|
||||
_dtv2: tuple[int, int] | None = DefineDeclTypeValue(
|
||||
getattr(Gen, '_define_decl_types', None) or getattr(self.Trans, '_define_decl_types', None), VarName, val)
|
||||
if _dtv2 is not None:
|
||||
return ir.Constant(ir.IntType(_dtv2[0]), _dtv2[1])
|
||||
if val < -(1 << 31) or val > 0xFFFFFFFF:
|
||||
return ir.Constant(ir.IntType(64), val & 0xFFFFFFFFFFFFFFFF)
|
||||
return ir.Constant(ir.IntType(32), val & 0xFFFFFFFF)
|
||||
|
||||
@@ -5,6 +5,7 @@ if TYPE_CHECKING:
|
||||
from lib.core.LlvmCodeGenerator import LlvmCodeGenerator
|
||||
from lib.core.Handles.HandlesBase import BaseHandle, FuncMeta
|
||||
from lib.core.VLogger import get_logger as _vlog
|
||||
from lib.core.SymbolUtils import DefineDeclTypeValue
|
||||
import vast as ast
|
||||
import llvmlite.ir as ir
|
||||
|
||||
@@ -388,8 +389,18 @@ class ExprAttrHandle(BaseHandle):
|
||||
return self._gep_and_Load_member(Gen, CastedObj, offset, Node.attr, lookup_CN, spec_st)
|
||||
return None
|
||||
|
||||
def _make_define_constant(self, Gen: LlvmCodeGenerator, val: int | float | str) -> ir.Value | None:
|
||||
"""将 CDefine 值转为 LLVM 常量"""
|
||||
def _make_define_constant(self, Gen: LlvmCodeGenerator, val: int | float | str, Name: str | None = None) -> ir.Value | None:
|
||||
"""将 CDefine 值转为 LLVM 常量。
|
||||
|
||||
带类型注册优先:若该 define 登记了**声明整数类型**(`Gen._define_decl_types`),
|
||||
按该类型的位宽与符号性物化(u32 `DWORD(-11)` → `i32 0xFFFFFFF5`),而不是按
|
||||
数值大小猜 i32/i64(后者会把 `4294967285` 误判成 i64,与 i32/ULONG 使用点不符)。
|
||||
"""
|
||||
if isinstance(val, int) and not isinstance(val, bool):
|
||||
_dt: tuple[int, int] | None = DefineDeclTypeValue(
|
||||
getattr(Gen, '_define_decl_types', None) or getattr(self.Trans, '_define_decl_types', None), Name, val)
|
||||
if _dt is not None:
|
||||
return ir.Constant(ir.IntType(_dt[0]), _dt[1])
|
||||
if isinstance(val, int):
|
||||
if abs(val) > 2147483647:
|
||||
return ir.Constant(ir.IntType(64), val)
|
||||
@@ -419,12 +430,12 @@ class ExprAttrHandle(BaseHandle):
|
||||
for lookup_key in PossibleKeys:
|
||||
SymInfo: Any = self.Trans.SymbolTable.lookup(lookup_key)
|
||||
if SymInfo and SymInfo.IsDefine and SymInfo.DefineValue is not None:
|
||||
return self._make_define_constant(Gen, SymInfo.DefineValue)
|
||||
return self._make_define_constant(Gen, SymInfo.DefineValue, AttrName)
|
||||
# 也检查 _define_constants(LlvmGenerator 预扫描阶段填充)
|
||||
define_constants: Any = getattr(Gen, '_define_constants', {})
|
||||
for key in (f"{VarName}.{AttrName}", AttrName):
|
||||
if key in define_constants:
|
||||
return self._make_define_constant(Gen, define_constants[key])
|
||||
return self._make_define_constant(Gen, define_constants[key], AttrName)
|
||||
# 回退:_all_define_constants(Phase2Translator 从所有 .pyi 预提取的跨模块 CDefine,
|
||||
# 与 _HandleNameLlvm 的裸名回退同源)。**模块属性访问**(`win32file.STD_OUTPUT_HANDLE`)
|
||||
# 此前只查 SymbolTable/_define_constants → 未命中就落到 _lookup_module_global 生成
|
||||
@@ -436,7 +447,7 @@ class ExprAttrHandle(BaseHandle):
|
||||
all_dc: dict[str, Any] = getattr(Gen, '_all_define_constants', None) or getattr(self.Trans, '_all_define_constants', None) or {}
|
||||
for key2 in (f"{VarName}.{AttrName}", AttrName):
|
||||
if key2 in all_dc:
|
||||
return self._make_define_constant(Gen, all_dc[key2])
|
||||
return self._make_define_constant(Gen, all_dc[key2], AttrName)
|
||||
return None
|
||||
|
||||
def _NormalizeModuleGlobalValue(self, Gen: LlvmCodeGenerator, Val: Any, AttrName: str) -> Any:
|
||||
@@ -688,7 +699,7 @@ class ExprAttrHandle(BaseHandle):
|
||||
for _cdefine_key in (AttrName, f"{VarName}.{AttrName}"):
|
||||
_sym: Any = self.Trans.SymbolTable.lookup(_cdefine_key)
|
||||
if _sym and _sym.IsDefine and _sym.DefineValue is not None:
|
||||
_const_val: Any = self._make_define_constant(Gen, _sym.DefineValue)
|
||||
_const_val: Any = self._make_define_constant(Gen, _sym.DefineValue, AttrName)
|
||||
if _const_val is not None:
|
||||
return _const_val
|
||||
|
||||
|
||||
@@ -521,6 +521,13 @@ class ImportHandle(BaseHandle):
|
||||
all_dc: dict = getattr(Gen, '_all_define_constants', None) or getattr(self.Trans, '_all_define_constants', None) or {}
|
||||
if name in all_dc:
|
||||
define_constants[name] = all_dc[name]
|
||||
# 带类型注册:把跨模块 define 的**声明整数类型**一并带入本模块,
|
||||
# 供使用点按声明类型(如 DWORD=u32)物化,而不是按值大小猜 i32/i64。
|
||||
all_dt: dict = getattr(Gen, '_define_decl_types', None) or getattr(self.Trans, '_define_decl_types', None) or {}
|
||||
if name in all_dt:
|
||||
_dt_map: dict = vars(Gen).setdefault('_define_decl_types', {})
|
||||
if name not in _dt_map:
|
||||
_dt_map[name] = all_dt[name]
|
||||
continue
|
||||
if not hasattr(self.Trans, '_t_c_imported_names'):
|
||||
self.Trans._t_c_imported_names = {}
|
||||
|
||||
@@ -1861,6 +1861,126 @@ def DefineIntWidthOf(BaseType: object | None) -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
def DefineIntSignednessOf(BaseType: object | None) -> bool | None:
|
||||
"""声明类型 → 是否有符号;非整数/无法判定 → None(与 DefineIntWidthOf 同口径)。
|
||||
|
||||
兼容"类形态"(未实例化的 CType 子类)与"实例形态"两种 BaseType。
|
||||
"""
|
||||
if BaseType is None:
|
||||
return None
|
||||
v: object | None = getattr(BaseType, 'IsSigned', None)
|
||||
if v is not None:
|
||||
return bool(v)
|
||||
if isinstance(BaseType, type) and issubclass(BaseType, t.CType) and BaseType is not t.CType:
|
||||
try:
|
||||
inst: object = BaseType()
|
||||
except Exception:
|
||||
return None
|
||||
v2: object | None = getattr(inst, 'IsSigned', None)
|
||||
return bool(v2) if v2 is not None else None
|
||||
return None
|
||||
|
||||
|
||||
# CDefine 注解里参与"类型"判定的 t 标记(联合写法 `T | t.CDefine`、`T | t.State` 等):
|
||||
# 它们不是类型本身,取"声明类型"时必须跳过。
|
||||
_DEFINE_TYPE_MARKER_NAMES: frozenset[str] = frozenset({
|
||||
'CDefine', 'State', 'CExport', 'CExtern', 'CStatic', 'CTypedef',
|
||||
})
|
||||
|
||||
|
||||
def _FirstTypeNameInAnnotation(node: object) -> str | None:
|
||||
"""从注解 AST 中取**第一个真正的类型名**(跳过 t.CDefine/State 等标记)。
|
||||
|
||||
`DWORD | t.CDefine` → 'DWORD';`HANDLE | t.State` → 'HANDLE'。
|
||||
"""
|
||||
if node is None:
|
||||
return None
|
||||
if isinstance(node, ast.Name):
|
||||
nm: str = node.id
|
||||
return None if nm in _DEFINE_TYPE_MARKER_NAMES else nm
|
||||
if isinstance(node, ast.Attribute):
|
||||
at: str = node.attr
|
||||
return None if at in _DEFINE_TYPE_MARKER_NAMES else at
|
||||
if isinstance(node, ast.BinOp):
|
||||
left: str | None = _FirstTypeNameInAnnotation(node.left)
|
||||
if left is not None:
|
||||
return left
|
||||
return _FirstTypeNameInAnnotation(node.right)
|
||||
if isinstance(node, ast.Tuple):
|
||||
for elt in node.elts:
|
||||
found: str | None = _FirstTypeNameInAnnotation(elt)
|
||||
if found is not None:
|
||||
return found
|
||||
return None
|
||||
if isinstance(node, ast.Subscript):
|
||||
# rawptr[X] / t.CArray[X, N]:指针/聚合,非整数 typedef → 不参与"声明整数类型"判定
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def DefineDeclIntTypeFromAnnotation(symtab: object, annotation: object) -> tuple[int, bool] | None:
|
||||
"""由 define 的**注解**(`T | t.CDefine`)解析声明整数类型 → (位宽, 是否有符号)。
|
||||
|
||||
仅当 T 能经符号表的 typedef 链解析到整数 C 类型时返回;否则 None(指针/聚合/未知)。
|
||||
供"带类型注册"用:跨模块 define 只能从 .vpi 注解恢复声明类型。
|
||||
"""
|
||||
name: str | None = _FirstTypeNameInAnnotation(annotation)
|
||||
if name is None or symtab is None:
|
||||
return None
|
||||
lookup = getattr(symtab, 'lookup', None)
|
||||
if lookup is None:
|
||||
return None
|
||||
entry: object | None = lookup(name)
|
||||
if entry is None or not getattr(entry, 'IsTypedef', False):
|
||||
return None
|
||||
base: object | None = getattr(entry, 'BaseType', None)
|
||||
# 别名链:OriginalType 可能是内层 CTypeInfo(同一 typedef 的底层解析结果)
|
||||
depth: int = 0
|
||||
while base is None and depth < 8:
|
||||
orig: object | None = getattr(entry, 'OriginalType', None)
|
||||
if not isinstance(orig, type(base)) and orig is not None and hasattr(orig, 'BaseType'):
|
||||
entry = orig
|
||||
base = getattr(entry, 'BaseType', None)
|
||||
else:
|
||||
break
|
||||
depth += 1
|
||||
width: int | None = DefineIntWidthOf(base)
|
||||
if width is None:
|
||||
return None
|
||||
signed: bool | None = DefineIntSignednessOf(base)
|
||||
return (width, bool(signed) if signed is not None else False)
|
||||
|
||||
|
||||
def DefineDeclTypeValue(DeclTypes: object | None, Name: str | None, Value: object) -> tuple[int, int] | None:
|
||||
"""按 define 的**声明类型**归一常量值 → (位宽, 位型值);无声明类型/非整数 → None。
|
||||
|
||||
位型值:无符号 ⇒ 掩码后原样;有符号 ⇒ 掩码后按补码解释(可能为负)。
|
||||
调用方据此物化 `ir.Constant(IntType(位宽), 位型值)` —— 例如 `define X: DWORD = -11`
|
||||
得到 (32, 0xFFFFFFF5),即 u32 位型,而不是按数值大小猜 i32/i64。
|
||||
"""
|
||||
if not DeclTypes or Name is None or isinstance(Value, bool) or not isinstance(Value, int):
|
||||
return None
|
||||
get = getattr(DeclTypes, 'get', None)
|
||||
if get is None:
|
||||
return None
|
||||
ent: object | None = get(Name)
|
||||
if ent is None:
|
||||
return None
|
||||
try:
|
||||
width: int
|
||||
signed: bool
|
||||
width, signed = ent
|
||||
except Exception:
|
||||
return None
|
||||
if not isinstance(width, int) or width <= 0 or width > 64:
|
||||
return None
|
||||
mask: int = (1 << width) - 1
|
||||
v: int = int(Value) & mask
|
||||
if signed and v >= (1 << (width - 1)):
|
||||
v -= (1 << width)
|
||||
return (width, v)
|
||||
|
||||
|
||||
def RequireDefineIntStorable(Value: object, BaseType: object | None, Name: str,
|
||||
AnnotationText: str, Lineno: int, Col: int,
|
||||
FilePath: str, CodeLine: str) -> None:
|
||||
|
||||
@@ -13,6 +13,7 @@ from lib.core.VLogger import get_logger as _vlog
|
||||
from lib.core.DecoratorPass import run as _run_decorator_pass
|
||||
from lib.core.SymbolUtils import (
|
||||
IsTModule, AnnotationContainsName, RequireDefineConstStorable,
|
||||
DefineIntWidthOf, DefineIntSignednessOf,
|
||||
)
|
||||
# 治本修复:导入 ConstEvaluator 用于预扫描 CDefine 常量的复杂表达式求值
|
||||
from lib.core.ConstEvaluator import ConstEvaluator
|
||||
@@ -108,6 +109,15 @@ class LlvmGeneratorMixin:
|
||||
if not hasattr(Gen, '_define_constants'):
|
||||
Gen._define_constants: dict[str, int | str | float | bool] = {}
|
||||
Gen._define_constants[NameNode.id] = val
|
||||
# 带类型注册:记录声明整数类型(位宽 + 符号性),供使用点按该类型物化
|
||||
# (如 `define X: DWORD = 5` → i32/u32,而不是按值大小猜 i32/i64)。
|
||||
if isinstance(val, int) and not isinstance(val, bool):
|
||||
_w: int | None = DefineIntWidthOf(TypeInfo.BaseType)
|
||||
if _w is not None:
|
||||
_s: bool | None = DefineIntSignednessOf(TypeInfo.BaseType)
|
||||
if not hasattr(Gen, '_define_decl_types'):
|
||||
Gen._define_decl_types: dict[str, tuple[int, bool]] = {}
|
||||
Gen._define_decl_types[NameNode.id] = (_w, bool(_s) if _s is not None else False)
|
||||
existing = self.SymbolTable.lookup(NameNode.id)
|
||||
if not (existing and existing.IsTypedef and existing.OriginalType):
|
||||
sym_info: _CTypeInfo = _CTypeInfo()
|
||||
|
||||
Reference in new issue
Block a user