From b2ec75e1578b587e6a3b726cc2c22ccef4188a60 Mon Sep 17 00:00:00 2001 From: pca006132 Date: Wed, 23 Dec 2020 11:54:48 +0800 Subject: [PATCH] fixed type guard --- toy-impl/examples/a.py | 6 ++++-- toy-impl/parse_stmt.py | 14 +++++++------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/toy-impl/examples/a.py b/toy-impl/examples/a.py index 98c9a21..15165db 100644 --- a/toy-impl/examples/a.py +++ b/toy-impl/examples/a.py @@ -1,4 +1,4 @@ -I = TypeVar('I', int32, Vec) +I = TypeVar('I', int32, float, Vec) class Vec: v: list[int32] @@ -6,8 +6,10 @@ class Vec: self.v = v def __add__(self, other: I) -> Vec: - if other is int32: + if type(other) == int32: return Vec([v + other for v in self.v]) + elif type(other) == float: + return Vec([v + int32(other) for v in self.v]) else: return Vec([self.v[i] + other.v[i] for i in range(len(self.v))]) diff --git a/toy-impl/parse_stmt.py b/toy-impl/parse_stmt.py index 4e17212..0ca2f7a 100644 --- a/toy-impl/parse_stmt.py +++ b/toy-impl/parse_stmt.py @@ -115,14 +115,14 @@ def parse_if_stmt(ctx: Context, return_ty: Type, node): if isinstance(node.test, ast.Compare) and \ + isinstance(node.test.left, ast.Call) and \ + isinstance(node.test.left.func, ast.Name) and \ + node.test.left.func.id == 'type' and \ + len(node.test.left.args) == 1 and \ len(node.test.ops) == 1 and \ - (isinstance(node.test.ops[0], ast.Is) or\ - isinstance(node.test.ops[0], ast.IsNot)): - if not isinstance(node.test.left, ast.Name): - raise CustomError( - 'type guard only support testing variables', - node.test) - t = parse_expr(ctx, sym_table, node.test.left) + (isinstance(node.test.ops[0], ast.Eq) or\ + isinstance(node.test.ops[0], ast.NotEq)): + t = parse_expr(ctx, sym_table, node.test.left.args[0]) if not isinstance(t, TypeVariable) or len(t.constraints) < 2: raise CustomError( 'type guard only support basic type variables with constraints',