示例工程 40-type-checker-in-python

40-type-checker-in-python/03-error-reporting/README.md

markdown · 0.8 KB

# 03 · error-reporting
 
**演示**:诊断记录 `code/line/column/message`,渲染成 `sample.py:3:6: error: ...  [E001]` + 源码行 + 插入符;多条诊断按行列排序,末尾输出 `Found N errors`。
**运行**:
 
```sh
uv run python examples/40-type-checker-in-python/03-error-reporting/error_reporting.py
```
 
**预期输出**(3.12.9):
 
```text
sample.py:3:6: error: unsupported operands: int and str  [E001]
bad = x + "a"
      ^
sample.py:4:8: error: unsupported operands: int and str  [E001]
worse = y + "a"
        ^
Found 2 errors
```
 
**依赖**:仅标准库(`ast`)。
**注意**:列号用 0-based 的 `col_offset` 时,显示给人看通常要 +1 或直接用偏移打插入符(mypy 的 `--show-column-numbers` 是 1-based)。`^` 要按字符而不是字节定位,遇到中文/制表符需额外换算。