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

40-type-checker-in-python/02-scope-and-functions/scope_and_functions.py

python · 5.1 KB

"""函数签名、参数检查、返回类型与作用域。"""
 
from __future__ import annotations
 
import ast
from dataclasses import dataclass
 
 
@dataclass(frozen=True)
class Signature:
    params: tuple[tuple[str, str], ...]
    returns: str
 
 
@dataclass(frozen=True)
class Diagnostic:
    code: str
    line: int
    message: str
 
 
class FunctionChecker:
    def __init__(self) -> None:
        self.functions: dict[str, Signature] = {}
        self.globals: dict[str, str] = {}
        self.errors: list[Diagnostic] = []
 
    def check(self, source: str) -> list[Diagnostic]:
        tree = ast.parse(source)
        for statement in tree.body:
            if isinstance(statement, ast.FunctionDef):
                self.register(statement)
        for statement in tree.body:
            if isinstance(statement, ast.FunctionDef):
                self.check_function(statement)
            elif isinstance(statement, ast.Assign):
                self.check_assign(statement, self.globals)
        return self.errors
 
    def register(self, node: ast.FunctionDef) -> None:
        params: list[tuple[str, str]] = []
        for arg in node.args.args:
            params.append((arg.arg, self.annotation(arg.annotation)))
        returns = self.annotation(node.returns) if node.returns is not None else "None"
        self.functions[node.name] = Signature(tuple(params), returns)
 
    @staticmethod
    def annotation(node: ast.expr | None) -> str:
        if isinstance(node, ast.Name):
            return node.id
        return "unknown"
 
    def check_function(self, node: ast.FunctionDef) -> None:
        signature = self.functions[node.name]
        local = dict(signature.params)
        for statement in node.body:
            if isinstance(statement, ast.Return):
                actual = "None" if statement.value is None else self.infer(statement.value, local)
                if actual != "unknown" and actual != signature.returns:
                    self.error(
                        "E004",
                        statement,
                        f"{node.name} returns {actual}, declared {signature.returns}",
                    )
            elif isinstance(statement, ast.Assign):
                self.check_assign(statement, local)
 
    def check_assign(self, node: ast.Assign, env: dict[str, str]) -> None:
        value_type = self.infer(node.value, env)
        for target in node.targets:
            if isinstance(target, ast.Name):
                env[target.id] = value_type
 
    def infer(self, node: ast.expr, env: dict[str, str]) -> 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:
                self.error("E002", node, f"undefined variable {node.id!r}")
                return "unknown"
            return env[node.id]
        if isinstance(node, ast.BinOp):
            left = self.infer(node.left, env)
            right = self.infer(node.right, env)
            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"
            self.error("E001", node, f"unsupported operands: {left} and {right}")
            return "unknown"
        if isinstance(node, ast.Call):
            return self.check_call(node, env)
        self.error("E000", node, f"unsupported expression {type(node).__name__}")
        return "unknown"
 
    def check_call(self, node: ast.Call, env: dict[str, str]) -> str:
        if not isinstance(node.func, ast.Name) or node.func.id not in self.functions:
            self.error("E008", node, "call to unknown function")
            return "unknown"
        signature = self.functions[node.func.id]
        arguments = [self.infer(argument, env) for argument in node.args]
        if len(arguments) != len(signature.params):
            self.error(
                "E006",
                node,
                f"{node.func.id} expects {len(signature.params)} args, got {len(arguments)}",
            )
            return signature.returns
        for (name, expected), actual in zip(signature.params, arguments, strict=True):
            if expected != actual:
                self.error("E007", node, f"{node.func.id}({name}) expects {expected}, got {actual}")
        return signature.returns
 
    def error(self, code: str, node: ast.AST, message: str) -> None:
        self.errors.append(Diagnostic(code, getattr(node, "lineno", 0), message))
 
 
SOURCE = """def add(a: int, b: int) -> int:
    return a + b
 
def bad(a: int) -> str:
    return a + 1
 
x = add(1, 2)
y = add("a", 2)
z = add(1)
w = bad(3)
"""
 
 
def main() -> None:
    errors = FunctionChecker().check(SOURCE)
    print(f"codes: {[error.code for error in errors]}")
    print(f"messages: {[error.message for error in errors]}")
 
 
if __name__ == "__main__":
    main()