diff --git a/src/compiler/compiler.c b/src/compiler/compiler.c index e44057c7..70a9e808 100644 --- a/src/compiler/compiler.c +++ b/src/compiler/compiler.c @@ -1766,7 +1766,28 @@ static Error* exprGroup(Compiler* self) { Ctx__s_push(ctx(), (Expr*)TupleExpr__new(line, 0)); return NULL; } - check(EXPR_TUPLE(self)); // () is just for change precedence + check(EXPR(self)); // parse first expression + // check for generator expression + if(match(TK_FOR)) { + check(consume_comp(self, OP_BUILD_LIST, OP_LIST_APPEND)); + consume(TK_RPAREN); + return NULL; + } + // not a generator, continue with tuple/grouped expression logic + if(match(TK_COMMA)) { + // tuple expression + int count = 1; + do { + if(curr()->type == TK_RPAREN) break; + check(EXPR(self)); + count += 1; + } while(match(TK_COMMA)); + SequenceExpr* e = TupleExpr__new(line, count); + for(int i = count - 1; i >= 0; i--) { + e->items[i] = Ctx__s_popx(ctx()); + } + Ctx__s_push(ctx(), (Expr*)e); + } consume(TK_RPAREN); if(Ctx__s_top(ctx())->vt->is_tuple) return NULL; GroupedExpr* g = GroupedExpr__new(line, Ctx__s_popx(ctx())); diff --git a/tests/510_yield.py b/tests/510_yield.py index d218e05c..a7ed8cde 100644 --- a/tests/510_yield.py +++ b/tests/510_yield.py @@ -127,4 +127,16 @@ def f(): a = yield from g() yield a -assert list(f()) == [1, 2, 3] \ No newline at end of file +assert list(f()) == [1, 2, 3] + + +# Generator expressions +squares = (x**2 for x in range(5)) +assert list(squares) == [0, 1, 4, 9, 16] + +evens = (x for x in range(10) if x % 2 == 0) +assert list(evens) == [0, 2, 4, 6, 8] + +# Generator expression with nested iteration +pairs = ((i, j) for i in range(3) for j in range(2)) +assert list(pairs) == [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]