feat(cli): 编译期错误按 Viper 模拟堆栈输出

TypeError/SyntaxError 输出 Traceback (compile-time) + File/line + 源码行 + Err,不再打印 Python 内部调用链。
This commit is contained in:
TermiNexus committed 2026-10-18 18:07:19 +08:00
1 parent 2d0ab9c11f
commit 7911b4de54
2 files changed
+22 -1

No files matched your search

+18 -1
View File
@@ -41,7 +41,24 @@ if __name__ == '__main__':
_timing_status: str = '成功'
except (TypeError, SyntaxError) as _e:
_timing_status = '失败'
_sys.stderr.write(f'{_e}\n')
import re as _re
_lines: list[str] = ['Traceback (most recent call last, compile-time):']
_file: str = getattr(_e, 'Filename', '') or ''
_lineno: int = 0
_m = _re.search(r'(?:第\s*|line\s*)(\d+)', str(_e))
if _m:
_lineno = int(_m.group(1))
if _file:
_lines.append(f' File "{_file}", line {_lineno}, in <module>')
try:
with open(_file, 'r', encoding='utf-8') as _f:
_src: list[str] = _f.read().splitlines()
if 0 < _lineno <= len(_src):
_lines.append(f' {_src[_lineno - 1].strip()}')
except Exception:
pass
_lines.append(f'Err: {_e}')
_sys.stderr.write('\n'.join(_lines) + '\n')
raise SystemExit(1)
except BaseException:
_timing_status = '失败'
+4
View File
@@ -92,6 +92,10 @@ def parse_python_file(filepath: str) -> tuple[str, ast.Module] | tuple[str, None
tree: ast.Module = ast.parse(ExpandSoftKeywords(content), filepath)
except SyntaxError:
return (content, None)
except TypeError as _e:
if not getattr(_e, 'Filename', ''):
_e.Filename = filepath
raise
_FILE_AST_CACHE[norm_path] = (mtime, content, tree)
return (content, tree)