mirror of
https://github.com/pocketpy/pocketpy
synced 2026-05-11 12:43:36 +00:00
feat: add generator expression support fixes #449
This commit is contained in:
parent
0676b21da2
commit
1b7ce102ee
@ -1766,7 +1766,28 @@ static Error* exprGroup(Compiler* self) {
|
|||||||
Ctx__s_push(ctx(), (Expr*)TupleExpr__new(line, 0));
|
Ctx__s_push(ctx(), (Expr*)TupleExpr__new(line, 0));
|
||||||
return NULL;
|
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);
|
consume(TK_RPAREN);
|
||||||
if(Ctx__s_top(ctx())->vt->is_tuple) return NULL;
|
if(Ctx__s_top(ctx())->vt->is_tuple) return NULL;
|
||||||
GroupedExpr* g = GroupedExpr__new(line, Ctx__s_popx(ctx()));
|
GroupedExpr* g = GroupedExpr__new(line, Ctx__s_popx(ctx()));
|
||||||
|
|||||||
@ -127,4 +127,16 @@ def f():
|
|||||||
a = yield from g()
|
a = yield from g()
|
||||||
yield a
|
yield a
|
||||||
|
|
||||||
assert list(f()) == [1, 2, 3]
|
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)]
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user