示例工程 40-type-checker-in-python
40-type-checker-in-python/05-cli/cli.py
"""迷你类型检查器 CLI:检查文件,有错退出 1。"""
from __future__ import annotations
import argparse
import ast
import sys
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class Diagnostic:
line: int
column: int
code: str
message: str
def check_source(source: str) -> list[Diagnostic]:
env: dict[str, str] = {}
errors: list[Diagnostic] = []
def error(node: ast.AST, code: str, message: str) -> None:
errors.append(
Diagnostic(
getattr(node, "lineno", 0),
getattr(node, "col_offset", 0),
code,
message,
)
)
def infer(node: ast.expr) -> str:
if isinstance(node, ast.Constant):
if isinstance(node.value, bool):
return "bool"
if isinstance(node.value, int):
return "int"
if isinstance(node.value, str):
return "str"
return "unknown"
if isinstance(node, ast.Name):
if node.id not in env:
error(node, "E002", f"undefined variable {node.id!r}")
return "unknown"
return env[node.id]
if isinstance(node, ast.BinOp):
left = infer(node.left)
right = infer(node.right)
if isinstance(node.op, ast.Add) and left == right == "str":
return "str"
if isinstance(node.op, (ast.Add, ast.Sub, ast.Mult)) and left == right == "int":
return "int"
error(node, "E001", f"unsupported operands: {left} and {right}")
return "unknown"
error(node, "E000", f"unsupported expression {type(node).__name__}")
return "unknown"
for statement in ast.parse(source).body:
if not isinstance(statement, ast.Assign):
continue
value_type = infer(statement.value)
for target in statement.targets:
if not isinstance(target, ast.Name):
continue
previous = env.get(target.id)
if previous is not None and previous != value_type:
error(target, "E003", f"{target.id} was {previous}, now {value_type}")
env[target.id] = value_type
return errors
def run(paths: list[Path]) -> int:
total = 0
for path in paths:
try:
source = path.read_text(encoding="utf-8")
except OSError as exc:
print(f"error: cannot read {path}: {exc}", file=sys.stderr)
return 2
for diagnostic in check_source(source):
total += 1
print(
f"{path}:{diagnostic.line}:{diagnostic.column}: "
f"error: {diagnostic.message} [{diagnostic.code}]"
)
if total:
print(f"Found {total} error{'s' if total != 1 else ''}")
return 1
print(f"OK: {len(paths)} file(s)")
return 0
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="minimal type checker")
parser.add_argument("files", nargs="+", type=Path)
args = parser.parse_args(argv)
return run(args.files)
if __name__ == "__main__":
sys.exit(main())