|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +"""Debugger-Modul für CodeBox — Datenstrukturen und Parser für Stack-Frames und Watch-Expressions.""" |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +from dataclasses import dataclass, field |
| 8 | +from pathlib import Path |
| 9 | +import re |
| 10 | +from typing import Any, Dict, List, Optional, Tuple |
| 11 | + |
| 12 | + |
| 13 | +@dataclass |
| 14 | +class StackFrame: |
| 15 | + """Repräsentiert einen einzelnen Frame im Aufruf-Stapel (Call-Stack).""" |
| 16 | + |
| 17 | + file_path: str |
| 18 | + line_number: int |
| 19 | + function_name: str |
| 20 | + code_line: str = "" |
| 21 | + is_current: bool = False |
| 22 | + frame_index: int = 0 |
| 23 | + |
| 24 | + @property |
| 25 | + def file_name(self) -> str: |
| 26 | + """Liefert den reinen Dateinamen des Stack-Frames.""" |
| 27 | + if not self.file_path: |
| 28 | + return "" |
| 29 | + return Path(self.file_path).name |
| 30 | + |
| 31 | + def display_frame(self) -> str: |
| 32 | + """Formatierte Anzeige für die Baumansicht.""" |
| 33 | + prefix = "▶ " if self.is_current else " " |
| 34 | + func = self.function_name if self.function_name else "<unknown>" |
| 35 | + return f"{prefix}[{self.frame_index}] {func}" |
| 36 | + |
| 37 | + def location(self) -> str: |
| 38 | + """Kurze Pfadangabe mit Dateiname und Zeilennummer.""" |
| 39 | + return f"{self.file_name}:{self.line_number}" |
| 40 | + |
| 41 | + def to_dict(self) -> Dict[str, Any]: |
| 42 | + """Serialisiert den Frame zu einem Dictionary.""" |
| 43 | + return { |
| 44 | + "file_path": self.file_path, |
| 45 | + "line_number": self.line_number, |
| 46 | + "function_name": self.function_name, |
| 47 | + "code_line": self.code_line, |
| 48 | + "is_current": self.is_current, |
| 49 | + "frame_index": self.frame_index, |
| 50 | + } |
| 51 | + |
| 52 | + |
| 53 | +@dataclass |
| 54 | +class WatchExpression: |
| 55 | + """Repräsentiert einen benutzerdefinierten Überwachungsausdruck.""" |
| 56 | + |
| 57 | + expression: str |
| 58 | + value: str = "<nicht ausgewertet>" |
| 59 | + type_name: str = "" |
| 60 | + status: str = "pending" # "ok", "error", "pending" |
| 61 | + metadata: Dict[str, Any] = field(default_factory=dict) |
| 62 | + |
| 63 | + def to_dict(self) -> Dict[str, Any]: |
| 64 | + """Serialisiert die Watch-Expression zu einem Dictionary.""" |
| 65 | + return { |
| 66 | + "expression": self.expression, |
| 67 | + "value": self.value, |
| 68 | + "type_name": self.type_name, |
| 69 | + "status": self.status, |
| 70 | + "metadata": dict(self.metadata), |
| 71 | + } |
| 72 | + |
| 73 | + |
| 74 | +_PDB_FRAME_REGEX = re.compile( |
| 75 | + r"^\s*(?P<current>>)?\s*(?P<path>[a-zA-Z]:[\\/][^():\r\n]+|/[^():\r\n]+|[a-zA-Z0-9_.\-]+(?:\.py|\.pyw)?)\((?P<line>\d+)\)\s*(?P<func>[^\r\n]*)" |
| 76 | +) |
| 77 | +_PDB_CODE_REGEX = re.compile(r"^\s*->\s*(?P<code>.*)$") |
| 78 | + |
| 79 | + |
| 80 | +def parse_pdb_stack(text: str) -> List[StackFrame]: |
| 81 | + """Parst die Textausgabe eines PDB 'where'- oder Traceback-Befehls in eine Liste von StackFrames. |
| 82 | +
|
| 83 | + Unterstützt sowohl Windows- als auch POSIX-Pfade, aktuelle Frame-Markierungen ('>') |
| 84 | + und Quelltext-Pfeile ('->'). |
| 85 | + """ |
| 86 | + if not text: |
| 87 | + return [] |
| 88 | + |
| 89 | + lines = text.splitlines() |
| 90 | + frames: List[StackFrame] = [] |
| 91 | + idx = 0 |
| 92 | + i = 0 |
| 93 | + |
| 94 | + while i < len(lines): |
| 95 | + line = lines[i] |
| 96 | + match = _PDB_FRAME_REGEX.match(line) |
| 97 | + if match: |
| 98 | + is_current = bool(match.group("current")) |
| 99 | + fpath = match.group("path").strip() |
| 100 | + try: |
| 101 | + fline = int(match.group("line")) |
| 102 | + except ValueError: |
| 103 | + fline = 1 |
| 104 | + |
| 105 | + raw_func = match.group("func").strip() |
| 106 | + # Bereinige Funktionssignaturen wie "foo()" oder "<module>()" |
| 107 | + func_name = raw_func if raw_func else "<module>()" |
| 108 | + |
| 109 | + code_line = "" |
| 110 | + if i + 1 < len(lines): |
| 111 | + code_match = _PDB_CODE_REGEX.match(lines[i + 1]) |
| 112 | + if code_match: |
| 113 | + code_line = code_match.group("code").strip() |
| 114 | + i += 1 |
| 115 | + |
| 116 | + frame = StackFrame( |
| 117 | + file_path=fpath, |
| 118 | + line_number=fline, |
| 119 | + function_name=func_name, |
| 120 | + code_line=code_line, |
| 121 | + is_current=is_current, |
| 122 | + frame_index=idx, |
| 123 | + ) |
| 124 | + frames.append(frame) |
| 125 | + idx += 1 |
| 126 | + i += 1 |
| 127 | + |
| 128 | + return frames |
| 129 | + |
| 130 | + |
| 131 | +def parse_pdb_eval_response(expression: str, output: str) -> Tuple[str, str, str]: |
| 132 | + """Parst die PDB-Ausgabe nach Ausführung von 'p <expression>' oder 'print(...)'. |
| 133 | +
|
| 134 | + Gibt (value_str, type_str, status) zurück. |
| 135 | + """ |
| 136 | + if not output: |
| 137 | + return ("<keine Ausgabe>", "", "pending") |
| 138 | + |
| 139 | + clean = output.strip() |
| 140 | + # PDB Prompts und führende Echos entfernen |
| 141 | + lines = [ |
| 142 | + ln.strip() |
| 143 | + for ln in clean.splitlines() |
| 144 | + if ln.strip() and not ln.strip().startswith("(Pdb)") |
| 145 | + ] |
| 146 | + if not lines: |
| 147 | + return ("None", "NoneType", "ok") |
| 148 | + |
| 149 | + full_text = "\n".join(lines) |
| 150 | + |
| 151 | + # Auf Python-Fehlermeldungen prüfen |
| 152 | + if "***" in full_text or "Error:" in full_text: |
| 153 | + # Extrahiere Fehlertyp wenn möglich |
| 154 | + err_match = re.search(r"(\w+Error):\s*(.*)", full_text) |
| 155 | + if err_match: |
| 156 | + err_type = err_match.group(1) |
| 157 | + err_msg = err_match.group(2).strip() |
| 158 | + return (f"<{err_type}: {err_msg}>", err_type, "error") |
| 159 | + return (f"<{full_text}>", "Error", "error") |
| 160 | + |
| 161 | + # Ergebnis-Typ heuristisch ableiten |
| 162 | + first_val = lines[-1] |
| 163 | + if (first_val.startswith("'") and first_val.endswith("'")) or ( |
| 164 | + first_val.startswith('"') and first_val.endswith('"') |
| 165 | + ): |
| 166 | + return (first_val, "str", "ok") |
| 167 | + if first_val in ("True", "False"): |
| 168 | + return (first_val, "bool", "ok") |
| 169 | + if first_val == "None": |
| 170 | + return ("None", "NoneType", "ok") |
| 171 | + if re.match(r"^-?\d+$", first_val): |
| 172 | + return (first_val, "int", "ok") |
| 173 | + if re.match(r"^-?\d+\.\d+$", first_val): |
| 174 | + return (first_val, "float", "ok") |
| 175 | + if first_val.startswith("[") and first_val.endswith("]"): |
| 176 | + return (first_val, "list", "ok") |
| 177 | + if first_val.startswith("{") and first_val.endswith("}"): |
| 178 | + return (first_val, "dict", "ok") |
| 179 | + if first_val.startswith("(") and first_val.endswith(")"): |
| 180 | + return (first_val, "tuple", "ok") |
| 181 | + |
| 182 | + return (first_val, "object", "ok") |
| 183 | + |
| 184 | + |
| 185 | +def safe_eval_expression( |
| 186 | + expression: str, context: Optional[Dict[str, Any]] = None |
| 187 | +) -> Tuple[str, str, str]: |
| 188 | + """Wertet einen Ausdruck in einem kontrollierten Kontext sicher aus. |
| 189 | +
|
| 190 | + Gibt (value_repr, type_name, status) zurück. |
| 191 | + """ |
| 192 | + expr_clean = expression.strip() |
| 193 | + if not expr_clean: |
| 194 | + return ("", "", "pending") |
| 195 | + |
| 196 | + eval_ctx = dict(context or {}) |
| 197 | + # Erlaube grundlegende Builtins zur Auswertung arithmetischer und logischer Ausdrücke |
| 198 | + safe_builtins = { |
| 199 | + "len": len, |
| 200 | + "str": str, |
| 201 | + "int": int, |
| 202 | + "float": float, |
| 203 | + "bool": bool, |
| 204 | + "list": list, |
| 205 | + "dict": dict, |
| 206 | + "set": set, |
| 207 | + "tuple": tuple, |
| 208 | + "min": min, |
| 209 | + "max": max, |
| 210 | + "sum": sum, |
| 211 | + "abs": abs, |
| 212 | + "round": round, |
| 213 | + "repr": repr, |
| 214 | + "type": type, |
| 215 | + } |
| 216 | + globals_dict = {"__builtins__": safe_builtins} |
| 217 | + |
| 218 | + try: |
| 219 | + result = eval(expr_clean, globals_dict, eval_ctx) |
| 220 | + val_str = repr(result) |
| 221 | + type_str = type(result).__name__ |
| 222 | + return (val_str, type_str, "ok") |
| 223 | + except Exception as exc: |
| 224 | + err_type = type(exc).__name__ |
| 225 | + return (f"<{err_type}: {exc}>", err_type, "error") |
0 commit comments