if exprssion

This commit is contained in:
pca006132 2020-12-21 10:08:05 +08:00 committed by pca006132
parent b296e67ad1
commit 5d679d88b5
2 changed files with 21 additions and 3 deletions

View File

@ -38,6 +38,8 @@ def parse_expr(ctx: Context,
return parse_call(ctx, sym_table, body) return parse_call(ctx, sym_table, body)
if isinstance(body, ast.Subscript): if isinstance(body, ast.Subscript):
return parse_subscript(ctx, sym_table, body) return parse_subscript(ctx, sym_table, body)
if isinstance(body, ast.IfExp):
return parse_if_expr(ctx, sym_table, body)
raise CustomError(f'{body} is not yet supported') raise CustomError(f'{body} is not yet supported')
@ -65,10 +67,10 @@ def parse_constant(ctx: Context,
sym_table: dict[str, Type], sym_table: dict[str, Type],
node): node):
v = node.value v = node.value
if isinstance(v, int): if isinstance(v, bool):
return ctx.types['int32']
elif isinstance(v, bool):
return ctx.types['bool'] return ctx.types['bool']
elif isinstance(v, int):
return ctx.types['int32']
else: else:
raise CustomError(f'unknown constant {v}') raise CustomError(f'unknown constant {v}')
@ -189,3 +191,16 @@ def parse_subscript(ctx: Context,
else: else:
raise CustomError(f'index of type {s} is not supported') raise CustomError(f'index of type {s} is not supported')
def parse_if_expr(ctx: Context,
sym_table: dict[str, Type],
node):
b = ctx.types['bool']
t = parse_expr(ctx, sym_table, node.test)
if t != b:
raise CustomError(f'type of conditional must be bool instead of {t}')
ty1 = parse_expr(ctx, sym_table, node.body)
ty2 = parse_expr(ctx, sym_table, node.orelse)
if ty1 != ty2:
raise CustomError(f'divergent type for if expression: {ty1} != {ty2}')
return ty1

View File

@ -76,6 +76,9 @@ test_expr('[1,2,3][:a:2]', {'a': I})
test_expr('[1,2,3][:a:2]', {'a': i32}) test_expr('[1,2,3][:a:2]', {'a': i32})
test_expr('a == a == a', {'a': I}) test_expr('a == a == a', {'a': I})
test_expr('a == a and 1 == 2', {'a': I}) test_expr('a == a and 1 == 2', {'a': I})
test_expr('1 if a == b else 0', {'a': I, 'b': I})
test_expr('a if a == b else 1', {'a': I, 'b': I})
test_expr('a if a == b else b', {'a': I, 'b': I})
test_classes = """ test_classes = """
class Foo: class Foo: