Skip to content

Commit ad2ed0a

Browse files
committed
WIP async repl implementation
This now works: import asyncio import types print('here') L = { 'asyncio': asyncio, 'a': 'something' } code = compile(''' async with asyncio.Lock(): a = await asyncio.sleep(1, result=42) ''', '', 'single', 0x2000) f = types.FunctionType(code, L) print('before', L) asyncio.run(f()) print('after', L)
1 parent 3d37ea2 commit ad2ed0a

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

Include/compile.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ PyAPI_FUNC(PyCodeObject *) PyNode_Compile(struct _node *, const char *);
2323
#define PyCF_ONLY_AST 0x0400
2424
#define PyCF_IGNORE_COOKIE 0x0800
2525
#define PyCF_TYPE_COMMENTS 0x1000
26+
#define PyCF_AWAIT 0x2000
2627

2728
#ifndef Py_LIMITED_API
2829
typedef struct {

Python/compile.c

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4551,7 +4551,9 @@ compiler_async_with(struct compiler *c, stmt_ty s, int pos)
45514551

45524552
assert(s->kind == AsyncWith_kind);
45534553
if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
4554-
return compiler_error(c, "'async with' outside async function");
4554+
if (!(c->c_flags->cf_flags & 0x2000)) {
4555+
return compiler_error(c, "'async with' outside async function");
4556+
}
45554557
}
45564558

45574559
block = compiler_new_block(c);
@@ -4759,12 +4761,19 @@ compiler_visit_expr1(struct compiler *c, expr_ty e)
47594761
ADDOP(c, YIELD_FROM);
47604762
break;
47614763
case Await_kind:
4762-
if (c->u->u_ste->ste_type != FunctionBlock)
4763-
return compiler_error(c, "'await' outside function");
4764+
if (c->u->u_ste->ste_type != FunctionBlock) {
4765+
if (!(c->c_flags->cf_flags & 0x2000)) {
4766+
return compiler_error(c, "'await' outside function");
4767+
}
4768+
4769+
c->u->u_ste->ste_coroutine = 1;
4770+
}
47644771

4765-
if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4766-
c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
4767-
return compiler_error(c, "'await' outside async function");
4772+
if (!(c->c_flags->cf_flags & 0x2000)) {
4773+
if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4774+
c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
4775+
return compiler_error(c, "'await' outside async function");
4776+
}
47684777

47694778
VISIT(c, expr, e->v.Await.value);
47704779
ADDOP(c, GET_AWAITABLE);
@@ -5699,6 +5708,10 @@ compute_code_flags(struct compiler *c)
56995708
/* (Only) inherit compilerflags in PyCF_MASK */
57005709
flags |= (c->c_flags->cf_flags & PyCF_MASK);
57015710

5711+
if ((c->c_flags->cf_flags & 0x2000) && c->u->u_ste->ste_coroutine) {
5712+
flags |= CO_COROUTINE;
5713+
}
5714+
57025715
return flags;
57035716
}
57045717

0 commit comments

Comments
 (0)