862 lines
37 KiB
PowerShell
862 lines
37 KiB
PowerShell
#Requires -Version 5.1
|
|
<#
|
|
.SYNOPSIS
|
|
Tiefen-Pruefung aller t(key, *args) i18n-Aufrufe im gesamten Projekt
|
|
inklusive verschachtelter Konstanten, Variablenketten, Modul-Importen,
|
|
Tupel/Dict-Unpacking, Funktionsparametern und f-Strings.
|
|
#>
|
|
param(
|
|
[switch]$RebuildDb,
|
|
[switch]$ShowDynamic
|
|
)
|
|
|
|
$ErrorActionPreference = "Stop"
|
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
|
|
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
|
|
$ProjectRoot = (Resolve-Path (Join-Path $ScriptDir "..")).Path
|
|
|
|
function Find-PythonExe {
|
|
$venvPy = Join-Path $ProjectRoot ".venv\Scripts\python.exe"
|
|
if (Test-Path $venvPy) { return $venvPy }
|
|
|
|
foreach ($cmd in @("python", "python3")) {
|
|
$found = Get-Command $cmd -ErrorAction SilentlyContinue
|
|
if ($found) { return $found.Source }
|
|
}
|
|
foreach ($candidate in @(
|
|
"C:\Python311\python.exe",
|
|
"C:\Python312\python.exe",
|
|
"$env:LocalAppData\Programs\Python\Python311\python.exe",
|
|
"$env:ProgramFiles\Python311\python.exe"
|
|
)) {
|
|
if (Test-Path $candidate) { return $candidate }
|
|
}
|
|
throw "Keine Python-Installation gefunden!"
|
|
}
|
|
|
|
$PyExe = Find-PythonExe
|
|
|
|
if ($RebuildDb) {
|
|
$rebuildScript = Join-Path $ProjectRoot "build_scripts\rebuild_internal_db.py"
|
|
if (-not (Test-Path $rebuildScript)) {
|
|
$rebuildScript = Join-Path $ProjectRoot "rebuild_internal_db.py"
|
|
}
|
|
if (Test-Path $rebuildScript) {
|
|
Write-Host "---> Aktualisiere vorab internal_base.db..." -ForegroundColor Cyan
|
|
& $PyExe $rebuildScript
|
|
}
|
|
}
|
|
|
|
$AnalyzerPy = @'
|
|
# -*- coding: utf-8 -*-
|
|
import ast
|
|
import os
|
|
import re
|
|
import sqlite3
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(sys.argv[1]).resolve()
|
|
SHOW_DYNAMIC = "--show-dynamic" in sys.argv[2:]
|
|
|
|
EXCLUDE_DIRS = {".git", ".venv", ".venv_build_win", ".venv_build_macos", "build", "dist", "__pycache__"}
|
|
SQL_DIR = ROOT / "resources" / "code_res" / "sql"
|
|
DB_PATH = ROOT / "resources" / "code_res" / "internal_base.db"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 1. SQL & SQLite-DB Uebersetzungen einlesen
|
|
# ---------------------------------------------------------------------------
|
|
def load_sql_translations(sql_dir: Path):
|
|
sql_map = {} # key -> {"DE": val, "EN": val}
|
|
variants = set()
|
|
if not sql_dir.is_dir():
|
|
return sql_map, variants
|
|
|
|
tuple_re = re.compile(
|
|
r"\(\s*'((?:''|[^'])*)'\s*,\s*'(DE|EN)'\s*,\s*'((?:''|[^'])*)'\s*\)"
|
|
)
|
|
var_re = re.compile(
|
|
r"\(\s*\d+\s*,\s*'[^']*'\s*,\s*'[^']*'\s*,\s*'([^']+)'\s*,"
|
|
)
|
|
for sql_file in sorted(sql_dir.glob("*.sql")):
|
|
content = sql_file.read_text(encoding="utf-8", errors="replace")
|
|
for m in tuple_re.finditer(content):
|
|
k = m.group(1).replace("''", "'")
|
|
lang = m.group(2)
|
|
val = m.group(3).replace("''", "'")
|
|
sql_map.setdefault(k, {})[lang] = val
|
|
for vm in var_re.finditer(content):
|
|
variants.add(vm.group(1))
|
|
return sql_map, variants
|
|
|
|
|
|
def load_db_translations(db_path: Path):
|
|
db_map = {}
|
|
if not db_path.is_file():
|
|
return db_map
|
|
conn = sqlite3.connect(f"{db_path.as_uri()}?mode=ro", uri=True)
|
|
try:
|
|
for k, lang, val in conn.execute("SELECT key, lang, val FROM base_i18n"):
|
|
db_map.setdefault(k, {})[lang] = val
|
|
finally:
|
|
conn.close()
|
|
return db_map
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 2. Abstrakte Werte fuer tiefenverschachtelte Konstanten- & Datenfluss-Analyse
|
|
# ---------------------------------------------------------------------------
|
|
class Val:
|
|
"""Repräsentiert mögliche String-Werte, Tupel/Listen, Dicts oder f-String-Muster."""
|
|
__slots__ = ("strings", "patterns", "items", "mapping")
|
|
|
|
def __init__(self, strings=None, patterns=None, items=None, mapping=None):
|
|
self.strings = set(strings) if strings else set()
|
|
self.patterns = set(patterns) if patterns else set()
|
|
self.items = list(items) if items else [] # list[Val] fuer Tuple/List
|
|
self.mapping = dict(mapping) if mapping else {} # dict[str, Val] fuer Dict
|
|
|
|
def copy(self):
|
|
return Val(
|
|
set(self.strings),
|
|
set(self.patterns),
|
|
[v.copy() for v in self.items],
|
|
{k: v.copy() for k, v in self.mapping.items()},
|
|
)
|
|
|
|
def merge(self, other: "Val") -> bool:
|
|
if other is None:
|
|
return False
|
|
changed = False
|
|
before_s = len(self.strings)
|
|
self.strings |= other.strings
|
|
if len(self.strings) != before_s:
|
|
changed = True
|
|
|
|
before_p = len(self.patterns)
|
|
self.patterns |= other.patterns
|
|
if len(self.patterns) != before_p:
|
|
changed = True
|
|
|
|
if len(other.items) > len(self.items):
|
|
for i in range(len(self.items), len(other.items)):
|
|
self.items.append(other.items[i].copy())
|
|
changed = True
|
|
for i in range(min(len(self.items), len(other.items))):
|
|
if self.items[i].merge(other.items[i]):
|
|
changed = True
|
|
|
|
for k, ov in other.mapping.items():
|
|
if k not in self.mapping:
|
|
self.mapping[k] = ov.copy()
|
|
changed = True
|
|
elif self.mapping[k].merge(ov):
|
|
changed = True
|
|
return changed
|
|
|
|
def all_leaf_strings(self) -> set:
|
|
out = set(self.strings)
|
|
for it in self.items:
|
|
out |= it.all_leaf_strings()
|
|
for mv in self.mapping.values():
|
|
out |= mv.all_leaf_strings()
|
|
return out
|
|
|
|
@property
|
|
def is_empty(self) -> bool:
|
|
return not (self.strings or self.patterns or self.items or self.mapping)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 3. Projektweite Python-Dateien parsen & Modulnamen bestimmen
|
|
# ---------------------------------------------------------------------------
|
|
def collect_py_files(root: Path):
|
|
modules = {} # mod_name -> (Path, ast.Module)
|
|
for dirpath, dirnames, filenames in os.walk(root):
|
|
dirnames[:] = [d for d in dirnames if d not in EXCLUDE_DIRS]
|
|
for fn in sorted(filenames):
|
|
if not fn.endswith(".py"):
|
|
continue
|
|
fpath = Path(dirpath) / fn
|
|
rel = fpath.relative_to(root)
|
|
parts = list(rel.with_suffix("").parts)
|
|
if parts[-1] == "__init__":
|
|
parts = parts[:-1]
|
|
mod_name = ".".join(parts) if parts else "__root__"
|
|
try:
|
|
src = fpath.read_text(encoding="utf-8", errors="replace")
|
|
tree = ast.parse(src, filename=str(fpath))
|
|
modules[mod_name] = (fpath, tree)
|
|
except SyntaxError as exc:
|
|
print(f"[SYNTAX-WARNUNG] {rel}: {exc}")
|
|
return modules
|
|
|
|
|
|
class ProjectAnalyzer:
|
|
def __init__(self, modules: dict):
|
|
self.modules = modules
|
|
# Globale Modul-Umgebungen: mod_name -> {var_name: Val}
|
|
self.mod_envs = {m: {} for m in modules}
|
|
# Klassen-Attribute & Instanz-Felder (self.xyz): (mod_name, cls_name) -> {attr: Val}
|
|
self.cls_attrs = {}
|
|
# Funktions-/Methoden-Parameter aus Aufrufen: func_key -> {param_name: Val}
|
|
self.func_param_envs = {}
|
|
# Funktions-Definitionen nach Schluessel fuer Call-Propagation
|
|
self.func_defs = {} # (mod_name, cls_name_or_None, func_name) -> ast.FunctionDef
|
|
# Import-Aliase fuer i18n.t pro Modul: mod_name -> (set_of_direct_t_names, set_of_i18n_mod_aliases)
|
|
self.t_aliases = {m: (set(), set()) for m in modules}
|
|
# Modul-Aliase (import foo.bar as fb): mod_name -> {alias: target_mod}
|
|
self.mod_imports = {m: {} for m in modules}
|
|
# From-Importe (from foo import BAR as B): mod_name -> {local_name: (target_mod, orig_name)}
|
|
self.sym_imports = {m: {} for m in modules}
|
|
|
|
self._index_definitions_and_imports()
|
|
|
|
def _resolve_import_target(self, cur_mod: str, module_str: str | None, level: int) -> str:
|
|
if level == 0:
|
|
return module_str or ""
|
|
cur_parts = cur_mod.split(".")[:-1]
|
|
up = max(0, level - 1)
|
|
base = cur_parts[: max(0, len(cur_parts) - up)]
|
|
if module_str:
|
|
base.extend(module_str.split("."))
|
|
return ".".join(base)
|
|
|
|
def _index_definitions_and_imports(self):
|
|
for mod_name, (_fpath, tree) in self.modules.items():
|
|
t_direct, t_mods = self.t_aliases[mod_name]
|
|
if mod_name.endswith(".i18n") or mod_name == "i18n":
|
|
t_direct.add("t")
|
|
|
|
for node in tree.body:
|
|
if isinstance(node, ast.Import):
|
|
for alias in node.names:
|
|
asname = alias.asname or alias.name.split(".")[0]
|
|
if alias.name in self.modules:
|
|
self.mod_imports[mod_name][asname] = alias.name
|
|
if alias.name.endswith(".i18n") or alias.name == "i18n":
|
|
t_mods.add(asname)
|
|
|
|
elif isinstance(node, ast.ImportFrom):
|
|
target_mod = self._resolve_import_target(mod_name, node.module, node.level)
|
|
is_i18n = target_mod.endswith(".i18n") or target_mod == "i18n"
|
|
for alias in node.names:
|
|
local = alias.asname or alias.name
|
|
if is_i18n and alias.name == "t":
|
|
t_direct.add(local)
|
|
full_submod = f"{target_mod}.{alias.name}" if target_mod else alias.name
|
|
if full_submod in self.modules:
|
|
self.mod_imports[mod_name][local] = full_submod
|
|
else:
|
|
self.sym_imports[mod_name][local] = (target_mod, alias.name)
|
|
|
|
elif isinstance(node, ast.FunctionDef):
|
|
self.func_defs[(mod_name, None, node.name)] = node
|
|
|
|
elif isinstance(node, ast.ClassDef):
|
|
self.cls_attrs.setdefault((mod_name, node.name), {})
|
|
for item in node.body:
|
|
if isinstance(item, ast.FunctionDef):
|
|
self.func_defs[(mod_name, node.name, item.name)] = item
|
|
|
|
def eval_expr(self, node, mod_name: str, local_env: dict, cur_cls: str | None = None) -> Val:
|
|
if node is None:
|
|
return Val()
|
|
|
|
# String- oder Zahlen-Literal
|
|
if isinstance(node, ast.Constant):
|
|
if isinstance(node.value, (str, int, float)) and not isinstance(node.value, bool):
|
|
return Val(strings={str(node.value)})
|
|
return Val()
|
|
|
|
# Variablen-Name (Lokal -> Klasse -> Modul -> Import)
|
|
if isinstance(node, ast.Name):
|
|
nm = node.id
|
|
if nm in local_env:
|
|
return local_env[nm].copy()
|
|
if cur_cls and nm in self.cls_attrs.get((mod_name, cur_cls), {}):
|
|
return self.cls_attrs[(mod_name, cur_cls)][nm].copy()
|
|
if nm in self.mod_envs.get(mod_name, {}):
|
|
return self.mod_envs[mod_name][nm].copy()
|
|
if nm in self.sym_imports.get(mod_name, {}):
|
|
t_mod, orig = self.sym_imports[mod_name][nm]
|
|
if t_mod in self.mod_envs and orig in self.mod_envs[t_mod]:
|
|
return self.mod_envs[t_mod][orig].copy()
|
|
return Val()
|
|
|
|
# Attribut-Zugriff: self.xyz oder modul.KONSTANTE oder Klasse.KONSTANTE
|
|
if isinstance(node, ast.Attribute):
|
|
if isinstance(node.value, ast.Name):
|
|
base = node.value.id
|
|
if base == "self" and cur_cls:
|
|
return self.cls_attrs.get((mod_name, cur_cls), {}).get(node.attr, Val()).copy()
|
|
if base in self.mod_imports.get(mod_name, {}):
|
|
t_mod = self.mod_imports[mod_name][base]
|
|
return self.mod_envs.get(t_mod, {}).get(node.attr, Val()).copy()
|
|
if (mod_name, base) in self.cls_attrs:
|
|
return self.cls_attrs[(mod_name, base)].get(node.attr, Val()).copy()
|
|
if base in self.sym_imports.get(mod_name, {}):
|
|
t_mod, orig_cls = self.sym_imports[mod_name][base]
|
|
if (t_mod, orig_cls) in self.cls_attrs:
|
|
return self.cls_attrs[(t_mod, orig_cls)].get(node.attr, Val()).copy()
|
|
return Val()
|
|
|
|
# Tupel / Liste / Set
|
|
if isinstance(node, (ast.Tuple, ast.List, ast.Set)):
|
|
elems = [self.eval_expr(e, mod_name, local_env, cur_cls) for e in node.elts]
|
|
v = Val(items=elems)
|
|
for el in elems:
|
|
v.strings |= el.strings
|
|
v.patterns |= el.patterns
|
|
return v
|
|
|
|
# Dict-Literal
|
|
if isinstance(node, ast.Dict):
|
|
mp = {}
|
|
all_s = set()
|
|
for k_node, v_node in zip(node.keys, node.values):
|
|
vv = self.eval_expr(v_node, mod_name, local_env, cur_cls)
|
|
all_s |= vv.strings
|
|
if k_node is not None:
|
|
kv = self.eval_expr(k_node, mod_name, local_env, cur_cls)
|
|
for ks in kv.strings:
|
|
mp.setdefault(ks, Val()).merge(vv)
|
|
return Val(strings=all_s, mapping=mp)
|
|
|
|
# Subscript: d[key] oder tup[0]
|
|
if isinstance(node, ast.Subscript):
|
|
container = self.eval_expr(node.value, mod_name, local_env, cur_cls)
|
|
idx_val = self.eval_expr(node.slice, mod_name, local_env, cur_cls)
|
|
out = Val()
|
|
if container.mapping:
|
|
if idx_val.strings:
|
|
for ks in idx_val.strings:
|
|
if ks in container.mapping:
|
|
out.merge(container.mapping[ks])
|
|
else:
|
|
for mv in container.mapping.values():
|
|
out.merge(mv)
|
|
if container.items:
|
|
matched_idx = False
|
|
for ks in idx_val.strings:
|
|
if ks.lstrip("-").isdigit():
|
|
i = int(ks)
|
|
if -len(container.items) <= i < len(container.items):
|
|
out.merge(container.items[i])
|
|
matched_idx = True
|
|
if not matched_idx and not container.mapping:
|
|
for it in container.items:
|
|
out.merge(it)
|
|
return out
|
|
|
|
# Ternary: a if cond else b
|
|
if isinstance(node, ast.IfExp):
|
|
res = self.eval_expr(node.body, mod_name, local_env, cur_cls)
|
|
res.merge(self.eval_expr(node.orelse, mod_name, local_env, cur_cls))
|
|
return res
|
|
|
|
# BoolOp: a or b
|
|
if isinstance(node, ast.BoolOp):
|
|
res = Val()
|
|
for v_node in node.values:
|
|
res.merge(self.eval_expr(v_node, mod_name, local_env, cur_cls))
|
|
return res
|
|
|
|
# String-Verkettung: "variant_" + key
|
|
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
|
|
lv = self.eval_expr(node.left, mod_name, local_env, cur_cls)
|
|
rv = self.eval_expr(node.right, mod_name, local_env, cur_cls)
|
|
return self._combine_parts([lv, rv])
|
|
|
|
# f-String: f"variant_{self.variant_key}"
|
|
if isinstance(node, ast.JoinedStr):
|
|
parts = []
|
|
for p in node.values:
|
|
if isinstance(p, ast.Constant) and isinstance(p.value, str):
|
|
parts.append(Val(strings={p.value}))
|
|
elif isinstance(p, ast.FormattedValue):
|
|
sub = self.eval_expr(p.value, mod_name, local_env, cur_cls)
|
|
if sub.strings:
|
|
parts.append(Val(strings=sub.strings))
|
|
else:
|
|
parts.append(Val(patterns={".*"}))
|
|
return self._combine_parts(parts)
|
|
|
|
# Aufrufe wie dict(STAT_GAME_GROUPS) oder my_dict.get(key, default)
|
|
if isinstance(node, ast.Call):
|
|
if isinstance(node.func, ast.Name) and node.func.id == "dict" and node.args:
|
|
arg0 = self.eval_expr(node.args[0], mod_name, local_env, cur_cls)
|
|
mp = {}
|
|
for pair in arg0.items:
|
|
if len(pair.items) >= 2:
|
|
for ks in pair.items[0].strings:
|
|
mp.setdefault(ks, Val()).merge(pair.items[1])
|
|
return Val(mapping=mp)
|
|
|
|
if isinstance(node.func, ast.Attribute) and node.func.attr == "get":
|
|
recv = self.eval_expr(node.func.value, mod_name, local_env, cur_cls)
|
|
out = Val()
|
|
if recv.mapping:
|
|
if node.args:
|
|
kv = self.eval_expr(node.args[0], mod_name, local_env, cur_cls)
|
|
if kv.strings:
|
|
for ks in kv.strings:
|
|
if ks in recv.mapping:
|
|
out.merge(recv.mapping[ks])
|
|
else:
|
|
for mv in recv.mapping.values():
|
|
out.merge(mv)
|
|
if len(node.args) >= 2:
|
|
out.merge(self.eval_expr(node.args[1], mod_name, local_env, cur_cls))
|
|
return out
|
|
|
|
return Val()
|
|
|
|
@staticmethod
|
|
def _combine_parts(parts: list) -> Val:
|
|
"""Kartesisches Produkt fuer f-Strings / '+'-Verkettung; faellt bei Unbekannten auf Regex-Muster zurueck."""
|
|
has_wildcard = any(bool(p.patterns) and not p.strings for p in parts)
|
|
if not has_wildcard:
|
|
acc = {""}
|
|
for p in parts:
|
|
if not p.strings:
|
|
return Val()
|
|
nxt = set()
|
|
for prefix in acc:
|
|
for s in p.strings:
|
|
if len(nxt) < 128:
|
|
nxt.add(prefix + s)
|
|
acc = nxt
|
|
return Val(strings=acc)
|
|
|
|
regex_pieces = []
|
|
for p in parts:
|
|
if p.strings and not p.patterns:
|
|
escaped = [re.escape(s) for s in sorted(p.strings)]
|
|
regex_pieces.append(f"(?:{'|'.join(escaped)})" if len(escaped) > 1 else escaped[0])
|
|
else:
|
|
regex_pieces.append(".+")
|
|
return Val(patterns={f"^{''.join(regex_pieces)}$"})
|
|
|
|
def _bind_target(self, target, val: Val, mod_name: str, env: dict, cur_cls: str | None, is_mod_scope: bool) -> bool:
|
|
changed = False
|
|
if isinstance(target, ast.Name):
|
|
dest = self.mod_envs[mod_name] if is_mod_scope else env
|
|
if target.id not in dest:
|
|
dest[target.id] = val.copy()
|
|
return not val.is_empty
|
|
return dest[target.id].merge(val)
|
|
|
|
if isinstance(target, ast.Attribute) and cur_cls:
|
|
if isinstance(target.value, ast.Name) and target.value.id == "self":
|
|
cdict = self.cls_attrs.setdefault((mod_name, cur_cls), {})
|
|
if target.attr not in cdict:
|
|
cdict[target.attr] = val.copy()
|
|
return not val.is_empty
|
|
return cdict[target.attr].merge(val)
|
|
|
|
if isinstance(target, (ast.Tuple, ast.List)):
|
|
for idx, sub_t in enumerate(target.elts):
|
|
sub_val = val.items[idx] if idx < len(val.items) else Val()
|
|
if self._bind_target(sub_t, sub_val, mod_name, env, cur_cls, is_mod_scope):
|
|
changed = True
|
|
return changed
|
|
|
|
def _propagate_call_args(self, call_node: ast.Call, mod_name: str, local_env: dict, cur_cls: str | None) -> bool:
|
|
"""Leitet Argument-Werte von Aufrufstellen an Funktions- und Konstruktor-Parameter weiter."""
|
|
target_key = None
|
|
is_method_or_init = False
|
|
|
|
if isinstance(call_node.func, ast.Name):
|
|
fn = call_node.func.id
|
|
if (mod_name, None, fn) in self.func_defs:
|
|
target_key = (mod_name, None, fn)
|
|
elif (mod_name, fn, "__init__") in self.func_defs:
|
|
target_key = (mod_name, fn, "__init__")
|
|
is_method_or_init = True
|
|
elif fn in self.sym_imports.get(mod_name, {}):
|
|
t_mod, orig = self.sym_imports[mod_name][fn]
|
|
if (t_mod, None, orig) in self.func_defs:
|
|
target_key = (t_mod, None, orig)
|
|
elif (t_mod, orig, "__init__") in self.func_defs:
|
|
target_key = (t_mod, orig, "__init__")
|
|
is_method_or_init = True
|
|
|
|
elif isinstance(call_node.func, ast.Attribute):
|
|
if isinstance(call_node.func.value, ast.Name) and call_node.func.value.id == "self" and cur_cls:
|
|
mname = call_node.func.attr
|
|
if (mod_name, cur_cls, mname) in self.func_defs:
|
|
target_key = (mod_name, cur_cls, mname)
|
|
is_method_or_init = True
|
|
|
|
if target_key is None:
|
|
return False
|
|
|
|
fdef = self.func_defs[target_key]
|
|
param_names = [a.arg for a in fdef.args.args]
|
|
if is_method_or_init and param_names and param_names[0] in ("self", "cls"):
|
|
param_names = param_names[1:]
|
|
|
|
penv = self.func_param_envs.setdefault(target_key, {})
|
|
changed = False
|
|
|
|
for i, arg_node in enumerate(call_node.args):
|
|
if i < len(param_names):
|
|
av = self.eval_expr(arg_node, mod_name, local_env, cur_cls)
|
|
if not av.is_empty:
|
|
pname = param_names[i]
|
|
if pname not in penv:
|
|
penv[pname] = av.copy()
|
|
changed = True
|
|
elif penv[pname].merge(av):
|
|
changed = True
|
|
|
|
for kw in call_node.keywords:
|
|
if kw.arg and kw.arg in param_names:
|
|
kv = self.eval_expr(kw.value, mod_name, local_env, cur_cls)
|
|
if not kv.is_empty:
|
|
if kw.arg not in penv:
|
|
penv[kw.arg] = kv.copy()
|
|
changed = True
|
|
elif penv[kw.arg].merge(kv):
|
|
changed = True
|
|
return changed
|
|
|
|
def _walk_statements(self, stmts, mod_name: str, env: dict, cur_cls: str | None, is_mod_scope: bool, collect_calls: list | None):
|
|
changed = False
|
|
for stmt in stmts:
|
|
if isinstance(stmt, ast.Assign):
|
|
val = self.eval_expr(stmt.value, mod_name, env, cur_cls)
|
|
for tgt in stmt.targets:
|
|
if self._bind_target(tgt, val, mod_name, env, cur_cls, is_mod_scope):
|
|
changed = True
|
|
elif isinstance(stmt, ast.AnnAssign) and stmt.value is not None:
|
|
val = self.eval_expr(stmt.value, mod_name, env, cur_cls)
|
|
if self._bind_target(stmt.target, val, mod_name, env, cur_cls, is_mod_scope):
|
|
changed = True
|
|
elif isinstance(stmt, ast.For):
|
|
iter_val = self._eval_iter_items(stmt.iter, mod_name, env, cur_cls)
|
|
for elem_val in iter_val:
|
|
if self._bind_target(stmt.target, elem_val, mod_name, env, cur_cls, False):
|
|
changed = True
|
|
if self._walk_statements(stmt.body, mod_name, env, cur_cls, False, collect_calls):
|
|
changed = True
|
|
if self._walk_statements(stmt.orelse, mod_name, env, cur_cls, False, collect_calls):
|
|
changed = True
|
|
elif isinstance(stmt, (ast.If, ast.While)):
|
|
if self._walk_statements(stmt.body, mod_name, env, cur_cls, is_mod_scope, collect_calls):
|
|
changed = True
|
|
if self._walk_statements(stmt.orelse, mod_name, env, cur_cls, is_mod_scope, collect_calls):
|
|
changed = True
|
|
elif isinstance(stmt, ast.With):
|
|
if self._walk_statements(stmt.body, mod_name, env, cur_cls, is_mod_scope, collect_calls):
|
|
changed = True
|
|
elif isinstance(stmt, ast.Try):
|
|
if self._walk_statements(stmt.body, mod_name, env, cur_cls, is_mod_scope, collect_calls):
|
|
changed = True
|
|
for h in stmt.handlers:
|
|
if self._walk_statements(h.body, mod_name, env, cur_cls, is_mod_scope, collect_calls):
|
|
changed = True
|
|
if self._walk_statements(stmt.orelse, mod_name, env, cur_cls, is_mod_scope, collect_calls):
|
|
changed = True
|
|
if self._walk_statements(stmt.finalbody, mod_name, env, cur_cls, is_mod_scope, collect_calls):
|
|
changed = True
|
|
elif isinstance(stmt, ast.ClassDef):
|
|
cls_env = {}
|
|
for c_stmt in stmt.body:
|
|
if isinstance(c_stmt, ast.Assign):
|
|
val = self.eval_expr(c_stmt.value, mod_name, cls_env, stmt.name)
|
|
for tgt in c_stmt.targets:
|
|
if isinstance(tgt, ast.Name):
|
|
cdict = self.cls_attrs.setdefault((mod_name, stmt.name), {})
|
|
if tgt.id not in cdict:
|
|
cdict[tgt.id] = val.copy()
|
|
changed = changed or (not val.is_empty)
|
|
elif cdict[tgt.id].merge(val):
|
|
changed = True
|
|
elif isinstance(c_stmt, ast.FunctionDef):
|
|
if self._analyze_function(c_stmt, mod_name, env, stmt.name, collect_calls):
|
|
changed = True
|
|
elif isinstance(stmt, ast.FunctionDef):
|
|
if self._analyze_function(stmt, mod_name, env, cur_cls, collect_calls):
|
|
changed = True
|
|
|
|
# Ausdruecke innerhalb des aktuellen Statements (ohne verschachtelte defs/classes) scannen
|
|
if not isinstance(stmt, (ast.FunctionDef, ast.ClassDef, ast.For, ast.If, ast.While, ast.With, ast.Try)):
|
|
if self._scan_expr_tree(stmt, mod_name, env, cur_cls, collect_calls):
|
|
changed = True
|
|
elif isinstance(stmt, (ast.If, ast.While)):
|
|
if self._scan_expr_tree(stmt.test, mod_name, env, cur_cls, collect_calls):
|
|
changed = True
|
|
return changed
|
|
|
|
def _eval_iter_items(self, iter_node, mod_name: str, env: dict, cur_cls: str | None) -> list:
|
|
"""Extrahiert Element-Werte aus Schleifen wie `for i, (a, b) in enumerate(STAT_FIELD_KEYS):`."""
|
|
if isinstance(iter_node, ast.Call) and isinstance(iter_node.func, ast.Name):
|
|
fn = iter_node.func.id
|
|
if fn == "enumerate" and iter_node.args:
|
|
sub_items = self._eval_iter_items(iter_node.args[0], mod_name, env, cur_cls)
|
|
return [Val(items=[Val(strings={str(i)}), it]) for i, it in enumerate(sub_items)]
|
|
if fn in ("reversed", "sorted", "list", "tuple") and iter_node.args:
|
|
return self._eval_iter_items(iter_node.args[0], mod_name, env, cur_cls)
|
|
if fn == "range":
|
|
nums = [self.eval_expr(a, mod_name, env, cur_cls) for a in iter_node.args]
|
|
if len(nums) == 1 and len(nums[0].strings) == 1 and list(nums[0].strings)[0].isdigit():
|
|
n = min(32, int(list(nums[0].strings)[0]))
|
|
return [Val(strings={str(i)}) for i in range(n)]
|
|
|
|
v = self.eval_expr(iter_node, mod_name, env, cur_cls)
|
|
if v.items:
|
|
return v.items
|
|
if v.strings:
|
|
return [Val(strings={s}) for s in v.strings]
|
|
return []
|
|
|
|
def _analyze_function(self, fnode: ast.FunctionDef, mod_name: str, outer_env: dict, cur_cls: str | None, collect_calls: list | None) -> bool:
|
|
f_env = {k: v.copy() for k, v in outer_env.items()}
|
|
fkey = (mod_name, cur_cls, fnode.name)
|
|
|
|
# Default-Parameterwerte binden
|
|
all_args = fnode.args.args
|
|
defaults = fnode.args.defaults
|
|
if defaults:
|
|
offset = len(all_args) - len(defaults)
|
|
for idx, d_node in enumerate(defaults):
|
|
pname = all_args[offset + idx].arg
|
|
f_env[pname] = self.eval_expr(d_node, mod_name, outer_env, cur_cls)
|
|
|
|
# Aus Aufrufstellen propagierte Parameterwerte einmischen
|
|
for pname, pval in self.func_param_envs.get(fkey, {}).items():
|
|
if pname in f_env:
|
|
f_env[pname].merge(pval)
|
|
else:
|
|
f_env[pname] = pval.copy()
|
|
|
|
return self._walk_statements(fnode.body, mod_name, f_env, cur_cls, False, collect_calls)
|
|
|
|
def _is_t_call(self, call_node: ast.Call, mod_name: str) -> bool:
|
|
t_direct, t_mods = self.t_aliases[mod_name]
|
|
if isinstance(call_node.func, ast.Name) and call_node.func.id in t_direct:
|
|
return True
|
|
if (
|
|
isinstance(call_node.func, ast.Attribute)
|
|
and call_node.func.attr == "t"
|
|
and isinstance(call_node.func.value, ast.Name)
|
|
and call_node.func.value.id in t_mods
|
|
):
|
|
return True
|
|
return False
|
|
|
|
def _scan_expr_tree(self, root_node, mod_name: str, env: dict, cur_cls: str | None, collect_calls: list | None) -> bool:
|
|
changed = False
|
|
|
|
def visit(n, cur_env):
|
|
nonlocal changed
|
|
if n is None or isinstance(n, (ast.FunctionDef, ast.ClassDef)):
|
|
return
|
|
|
|
if isinstance(n, ast.Lambda):
|
|
l_env = {k: v.copy() for k, v in cur_env.items()}
|
|
l_args = n.args.args
|
|
l_defs = n.args.defaults
|
|
if l_defs:
|
|
off = len(l_args) - len(l_defs)
|
|
for i, dn in enumerate(l_defs):
|
|
l_env[l_args[off + i].arg] = self.eval_expr(dn, mod_name, cur_env, cur_cls)
|
|
visit(n.body, l_env)
|
|
return
|
|
|
|
if isinstance(n, (ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp)):
|
|
c_env = {k: v.copy() for k, v in cur_env.items()}
|
|
for gen in n.generators:
|
|
visit(gen.iter, c_env)
|
|
for elem_v in self._eval_iter_items(gen.iter, mod_name, c_env, cur_cls):
|
|
self._bind_target(gen.target, elem_v, mod_name, c_env, cur_cls, False)
|
|
for if_n in gen.ifs:
|
|
visit(if_n, c_env)
|
|
if isinstance(n, ast.DictComp):
|
|
visit(n.key, c_env)
|
|
visit(n.value, c_env)
|
|
else:
|
|
visit(n.elt, c_env)
|
|
return
|
|
|
|
if isinstance(n, ast.Call):
|
|
if collect_calls is None:
|
|
if self._propagate_call_args(n, mod_name, cur_env, cur_cls):
|
|
changed = True
|
|
elif self._is_t_call(n, mod_name) and n.args:
|
|
key_node = n.args[0]
|
|
resolved = self.eval_expr(key_node, mod_name, cur_env, cur_cls)
|
|
has_star = any(isinstance(a, ast.Starred) for a in n.args[1:])
|
|
pos_argc = None if has_star else (len(n.args) - 1)
|
|
try:
|
|
expr_src = ast.unparse(key_node)
|
|
except Exception:
|
|
expr_src = "<expr>"
|
|
collect_calls.append({
|
|
"mod": mod_name,
|
|
"file": self.modules[mod_name][0],
|
|
"line": getattr(n, "lineno", 0),
|
|
"expr": expr_src,
|
|
"val": resolved,
|
|
"argc": pos_argc,
|
|
})
|
|
|
|
for child in ast.iter_child_nodes(n):
|
|
visit(child, cur_env)
|
|
|
|
visit(root_node, env)
|
|
return changed
|
|
|
|
def run_analysis(self, max_passes: int = 5):
|
|
for _ in range(max_passes):
|
|
any_change = False
|
|
for mod_name, (_fpath, tree) in self.modules.items():
|
|
if self._walk_statements(tree.body, mod_name, {}, None, True, collect_calls=None):
|
|
any_change = True
|
|
if not any_change:
|
|
break
|
|
|
|
calls = []
|
|
for mod_name, (_fpath, tree) in self.modules.items():
|
|
self._walk_statements(tree.body, mod_name, {}, None, True, collect_calls=calls)
|
|
return calls
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 4. Auswertung & Bericht
|
|
# ---------------------------------------------------------------------------
|
|
sql_map, sql_variants = load_sql_translations(SQL_DIR)
|
|
db_map = load_db_translations(DB_PATH)
|
|
ref_map = sql_map if sql_map else db_map
|
|
|
|
modules = collect_py_files(ROOT)
|
|
analyzer = ProjectAnalyzer(modules)
|
|
t_calls = analyzer.run_analysis()
|
|
|
|
missing_keys = [] # (key, rel_file, line, expr, missing_where)
|
|
incomplete_langs = [] # (key, missing_lang)
|
|
db_drift_keys = [] # Keys in SQL, aber noch nicht in internal_base.db
|
|
placeholder_issues = [] # (key, rel_file, line, lang, max_ph, given_argc)
|
|
unmatched_patterns = [] # (pattern, rel_file, line, expr)
|
|
unresolved_dynamic = [] # (rel_file, line, expr)
|
|
|
|
# 1. Alle SQL-Keys auf Vollständigkeit (DE & EN) und DB-Sync prüfen
|
|
for k in sorted(sql_map.keys()):
|
|
langs = sql_map[k]
|
|
if "DE" not in langs:
|
|
incomplete_langs.append((k, "DE fehlt in SQL"))
|
|
if "EN" not in langs:
|
|
incomplete_langs.append((k, "EN fehlt in SQL"))
|
|
if db_map and (k not in db_map or "DE" not in db_map[k] or "EN" not in db_map[k]):
|
|
db_drift_keys.append(k)
|
|
|
|
# Prüfen, ob jede registrierte Spielvariante ein 'variant_<key>' hat
|
|
for vk in sorted(sql_variants):
|
|
full_vk = f"variant_{vk}"
|
|
if full_vk not in ref_map:
|
|
missing_keys.append((full_vk, "resources/code_res/sql/*.sql", 0, f"game_variants.{vk}", "FEHLT in base_i18n"))
|
|
|
|
ph_re = re.compile(r"\{(\d+)\}")
|
|
checked_unique_keys = set()
|
|
|
|
for entry in t_calls:
|
|
rel_file = entry["file"].relative_to(ROOT).as_posix()
|
|
line = entry["line"]
|
|
expr = entry["expr"]
|
|
val: Val = entry["val"]
|
|
argc = entry["argc"]
|
|
|
|
if val.strings:
|
|
for k in sorted(val.strings):
|
|
checked_unique_keys.add(k)
|
|
in_sql = k in sql_map
|
|
in_db = (k in db_map) if db_map else in_sql
|
|
|
|
if not in_sql and not in_db:
|
|
missing_keys.append((k, rel_file, line, expr, "FEHLT in SQL & DB"))
|
|
elif not in_sql and in_db:
|
|
missing_keys.append((k, rel_file, line, expr, "Nur in DB, FEHLT in SQL-Dateien"))
|
|
else:
|
|
src_entry = sql_map.get(k) or db_map.get(k, {})
|
|
if argc is not None:
|
|
for lg in ("DE", "EN"):
|
|
txt = src_entry.get(lg, "")
|
|
idxs = [int(m.group(1)) for m in ph_re.finditer(txt)]
|
|
if idxs and max(idxs) >= argc:
|
|
placeholder_issues.append((k, rel_file, line, lg, max(idxs) + 1, argc))
|
|
|
|
elif val.patterns:
|
|
for pat in sorted(val.patterns):
|
|
rx = re.compile(pat)
|
|
matches = [k for k in ref_map if rx.match(k)]
|
|
if not matches:
|
|
unmatched_patterns.append((pat, rel_file, line, expr))
|
|
else:
|
|
checked_unique_keys.update(matches)
|
|
else:
|
|
unresolved_dynamic.append((rel_file, line, expr))
|
|
|
|
print("=" * 74)
|
|
print(" GOTH CARDGAME COLLECTION - i18n TIEFEN-PRUEFUNG (AST + KONSTANTEN)")
|
|
print("=" * 74)
|
|
print(f" Gepruefte Python-Module : {len(modules)}")
|
|
print(f" Gefundene t(...)-Aufrufe: {len(t_calls)} ({len(checked_unique_keys)} eindeutige Keys aufgeloest)")
|
|
print(f" Keys in SQL-Dateien : {len(sql_map)} | Keys in internal_base.db: {len(db_map)}")
|
|
print("-" * 74)
|
|
|
|
has_errors = False
|
|
|
|
if missing_keys:
|
|
has_errors = True
|
|
print(f"\n[FEHLER] {len(missing_keys)} fehlende i18n-Keys im Code gefunden:")
|
|
for k, rf, ln, ex, reason in missing_keys:
|
|
trace = f" (aus `{ex}`)" if ex not in (f"'{k}'", f'"{k}"') else ""
|
|
print(f" - '{k}' -> {rf}:{ln}{trace} [{reason}]")
|
|
|
|
if unmatched_patterns:
|
|
has_errors = True
|
|
print(f"\n[FEHLER] {len(unmatched_patterns)} f-String-Muster ohne jeglichen Treffer in SQL/DB:")
|
|
for pat, rf, ln, ex in unmatched_patterns:
|
|
print(f" - Muster {pat} aus `{ex}` -> {rf}:{ln}")
|
|
|
|
if incomplete_langs:
|
|
has_errors = True
|
|
print(f"\n[FEHLER] {len(incomplete_langs)} unvollstaendige Sprach-Paare (DE/EN):")
|
|
for k, msg in incomplete_langs:
|
|
print(f" - '{k}': {msg}")
|
|
|
|
if placeholder_issues:
|
|
has_errors = True
|
|
print(f"\n[WARNUNG] {len(placeholder_issues)} Platzhalter-Abweichungen ({{0}}, {{1}}, ...):")
|
|
for k, rf, ln, lg, need_n, got_n in placeholder_issues:
|
|
print(f" - '{k}' [{lg}] erwartet {need_n} Argument(e), Aufruf uebergibt {got_n} -> {rf}:{ln}")
|
|
|
|
if db_drift_keys:
|
|
print(f"\n[HINWEIS] {len(db_drift_keys)} Key(s) stehen in .sql, fehlen aber noch in internal_base.db:")
|
|
for k in db_drift_keys[:15]:
|
|
print(f" - '{k}'")
|
|
if len(db_drift_keys) > 15:
|
|
print(f" ... und {len(db_drift_keys) - 15} weitere.")
|
|
print(" -> Tipp: `python build_scripts/rebuild_internal_db.py` oder `-RebuildDb` ausfuehren!")
|
|
|
|
if SHOW_DYNAMIC and unresolved_dynamic:
|
|
print(f"\n[INFO] {len(unresolved_dynamic)} rein dynamische Laufzeit-Aufrufe:")
|
|
for rf, ln, ex in unresolved_dynamic:
|
|
print(f" - {rf}:{ln} -> t({ex})")
|
|
|
|
if not has_errors and not db_drift_keys:
|
|
print("\n[OK] Alles sauber! Alle aufgeloesten t(...)-Keys existieren vollstaendig in DE & EN.")
|
|
print("=" * 74)
|
|
|
|
sys.exit(1 if has_errors else 0)
|
|
'@
|
|
|
|
$extraArgs = @($ProjectRoot)
|
|
if ($ShowDynamic) { $extraArgs += "--show-dynamic" }
|
|
|
|
$AnalyzerPy | & $PyExe - @extraArgs
|
|
exit $LASTEXITCODE |