From 40c106ab6ab270151bc9948a5917abad212471a0 Mon Sep 17 00:00:00 2001 From: pca006132 Date: Mon, 21 Dec 2020 09:51:05 +0800 Subject: [PATCH] supports slice --- toy-impl/parse_expr.py | 21 ++++++++++++++++----- toy-impl/test_expr.py | 5 +++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/toy-impl/parse_expr.py b/toy-impl/parse_expr.py index 3e26a92..9d64954 100644 --- a/toy-impl/parse_expr.py +++ b/toy-impl/parse_expr.py @@ -170,11 +170,22 @@ def parse_subscript(ctx: Context, value = parse_expr(ctx, sym_table, node.value) if not isinstance(value, ListType): raise CustomError(f'cannot take index of {value}') - s = parse_expr(ctx, sym_table, node.slice) i32 = ctx.types['int32'] - if s == i32: - return value.params[0] + if isinstance(node.slice, ast.Slice): + if node.slice.lower is not None: + if parse_expr(ctx, sym_table, node.slice.lower) != i32: + raise CustomError(f'slice index must be int32') + if node.slice.upper is not None: + if parse_expr(ctx, sym_table, node.slice.upper) != i32: + raise CustomError(f'slice index must be int32') + if node.slice.step is not None: + if parse_expr(ctx, sym_table, node.slice.step) != i32: + raise CustomError(f'slice index must be int32') + return value else: - # will support slice - raise CustomError(f'index of type {s} is not supported') + s = parse_expr(ctx, sym_table, node.slice) + if s == i32: + return value.params[0] + else: + raise CustomError(f'index of type {s} is not supported') diff --git a/toy-impl/test_expr.py b/toy-impl/test_expr.py index 6caa5b2..d43ff9b 100644 --- a/toy-impl/test_expr.py +++ b/toy-impl/test_expr.py @@ -69,6 +69,11 @@ test_expr('a - a', {'a': A}) test_expr('[1, 2, 3][2]') test_expr('[[1], [2], [3]][2]') test_expr('[[1], [2], [3]][a]', {'a': i32}) +test_expr('[][:]', {}) +test_expr('[1,2,3][:]', {}) +test_expr('[1,2,3][1:3]', {}) +test_expr('[1,2,3][:a:2]', {'a': I}) +test_expr('[1,2,3][:a:2]', {'a': i32}) test_expr('a == a == a', {'a': I}) test_expr('a == a and 1 == 2', {'a': I})