Skip to content

Comments

Implement PEP 492: async/await support#2004

Open
mikasoukhov wants to merge 5 commits intoIronLanguages:mainfrom
StockSharp:main
Open

Implement PEP 492: async/await support#2004
mikasoukhov wants to merge 5 commits intoIronLanguages:mainfrom
StockSharp:main

Conversation

@mikasoukhov
Copy link

  • Tokenizer/Parser: async def, async for, async with, await keywords
  • AST nodes: AwaitExpression, AsyncForStatement, AsyncWithStatement
  • Runtime: PythonCoroutine, CoroutineWrapper types
  • Code generation: coroutines reuse generator state machine via yield from desugaring (await → yield from expr.await())
  • Fix GeneratorRewriter VisitExtension to reduce one level at a time, preventing "must be reducible node" with DebugInfoRemovalExpression

Verified against CPython 3.14: 20/20 comparison tests identical.

- Tokenizer/Parser: async def, async for, async with, await keywords
- AST nodes: AwaitExpression, AsyncForStatement, AsyncWithStatement
- Runtime: PythonCoroutine, CoroutineWrapper types
- Code generation: coroutines reuse generator state machine via
  yield from desugaring (await → yield from expr.__await__())
- Fix GeneratorRewriter VisitExtension to reduce one level at a time,
  preventing "must be reducible node" with DebugInfoRemovalExpression

Verified against CPython 3.14: 20/20 comparison tests identical.
Copilot AI review requested due to automatic review settings February 24, 2026 08:54
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds core language, AST, runtime, and codegen support for Python’s PEP 492 async/await features in IronPython, including coroutine objects and async control-flow constructs.

Changes:

  • Extend tokenizer/parser and AST to support await, async for, and async with.
  • Introduce coroutine runtime types (PythonCoroutine, CoroutineWrapper) and propagate coroutine flags through FunctionCode/codegen.
  • Update generator rewriting to support coroutine wrapping and fix extension-node reduction behavior.

Reviewed changes

Copilot reviewed 16 out of 16 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
src/core/IronPython/Runtime/Operations/PythonOps.cs Adds coroutine construction helpers and passes coroutine intent into generator transformation.
src/core/IronPython/Runtime/FunctionCode.cs Treats coroutine functions like generators for rewriting, threading an isCoroutine flag.
src/core/IronPython/Runtime/FunctionAttributes.cs Introduces FunctionAttributes.Coroutine.
src/core/IronPython/Runtime/Coroutine.cs Adds PythonCoroutine and CoroutineWrapper runtime types.
src/core/IronPython/Modules/_ast.cs Adds _ast nodes/conversion for Await, AsyncFor, AsyncWith.
src/core/IronPython/Compiler/Tokenizer.cs Tokenizes await as a keyword.
src/core/IronPython/Compiler/TokenKind.Generated.cs Adds KeywordAwait and updates keyword range.
src/core/IronPython/Compiler/Parser.cs Parses await, async for, async with.
src/core/IronPython/Compiler/GeneratorRewriter.cs Wraps coroutine generators and adjusts extension-node reduction strategy.
src/core/IronPython/Compiler/Ast/PythonWalker.Generated.cs Adds walker hooks for new AST nodes.
src/core/IronPython/Compiler/Ast/PythonNameBinder.cs Binds new nodes into scope/binding passes.
src/core/IronPython/Compiler/Ast/FunctionDefinition.cs Marks async functions as generator-like and sets coroutine flags for codegen.
src/core/IronPython/Compiler/Ast/AwaitExpression.cs Implements await via yield from expr.__await__() desugaring.
src/core/IronPython/Compiler/Ast/AsyncWithStatement.cs Implements async with via desugaring.
src/core/IronPython/Compiler/Ast/AsyncForStatement.cs Implements async for via desugaring.
src/core/IronPython/Compiler/Ast/AstMethods.cs Adds a cached MakeCoroutine MethodInfo.
Comments suppressed due to low confidence (6)

src/core/IronPython/Compiler/Ast/AstMethods.cs:82

  • AstMethods.MakeCoroutine is added but appears unused (no references found in the repo). If codegen no longer calls it, consider removing it to avoid dead API surface; otherwise, update the coroutine codegen to use this cached MethodInfo instead of repeated reflection lookups.
        public static readonly MethodInfo GeneratorCheckThrowableAndReturnSendValue = GetMethod((Func<object, object>)PythonOps.GeneratorCheckThrowableAndReturnSendValue);
        public static readonly MethodInfo MakeCoroutine = GetMethod((Func<PythonFunction, MutableTuple, object, PythonCoroutine>)PythonOps.MakeCoroutine);

src/core/IronPython/Runtime/Operations/PythonOps.cs:3205

  • MakeCoroutineWrapper currently returns a PythonCoroutine, not a CoroutineWrapper, which makes the name misleading (and MakeCoroutine appears unused). Consider renaming to something like MakeCoroutineFromGenerator (and returning PythonCoroutine directly instead of object) or wiring codegen to use MakeCoroutine and dropping the extra wrapper method to reduce confusion.
        public static PythonCoroutine MakeCoroutine(PythonFunction function, MutableTuple data, object generatorCode) {
            return new PythonCoroutine(MakeGenerator(function, data, generatorCode));
        }

        public static object MakeCoroutineWrapper(PythonGenerator generator) {
            return new PythonCoroutine(generator);
        }

src/core/IronPython/Compiler/Parser.cs:1996

  • There are no existing test cases in tests/ exercising async def / await / async for / async with (searching the suite finds no async def). Given the amount of new parsing + desugaring behavior introduced here, please add targeted tests (e.g., precedence like await a ** b, unary like await -x, async with exception suppression, and async for finalization) to prevent regressions.
        // power: ['await'] atom trailer* ['**' factor]
        private Expression ParsePower() {
            if (MaybeEat(TokenKind.KeywordAwait)) {
                return ParseAwaitExpression();
            }
            Expression ret = ParseAtom();
            ret = AddTrailers(ret);
            if (MaybeEat(TokenKind.Power)) {
                var start = ret.StartIndex;
                ret = new BinaryExpression(PythonOperator.Power, ret, ParseFactor());
                ret.SetLoc(_globalParent, start, GetEnd());
            }
            return ret;
        }

        // await_expr: 'await' unary_expr (essentially power level)
        private Expression ParseAwaitExpression() {
            FunctionDefinition current = CurrentFunction;
            if (current == null || !current.IsAsync) {
                ReportSyntaxError("'await' outside async function");
            }

            if (current != null) {
                current.IsGenerator = true;
                current.GeneratorStop = GeneratorStop;
            }

            var start = GetStart();

            // Parse the awaitable expression at the unary level
            Expression expr = ParsePower();

            var ret = new AwaitExpression(expr);
            ret.SetLoc(_globalParent, start, GetEnd());
            return ret;
        }

src/core/IronPython/Compiler/Parser.cs:1500

  • ParseAsyncForStmt declares var start = GetStart(); but never uses it. This will generate an unused-local warning and can be removed (or used for SetLoc if that was the intent).
            Eat(TokenKind.KeywordFor);
            var start = GetStart();

src/core/IronPython/Compiler/Ast/AsyncWithStatement.cs:110

  • Reduce() assumes _desugared was built during Walk() and will null-deref if Reduce() is called before a walk pass. Either build _desugared lazily in Reduce() as well (when Parent/IndexSpan are available) or throw a clearer exception explaining the required initialization order.
        public override MSAst.Expression Reduce() {
            return _desugared!.Reduce();
        }

src/core/IronPython/Compiler/Ast/AsyncForStatement.cs:131

  • Reduce() assumes _desugared was built during Walk() and will null-deref if Reduce() is called before Walk(). Consider building _desugared lazily in Reduce() too (or failing with a clearer message) to avoid fragile initialization ordering.
        public override MSAst.Expression Reduce() {
            return _desugared!.Reduce();
        }

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.


internal override Statement Revert() {
Statement statement = RevertStmts(this.body);
foreach (withitem item in items) {
Copy link

Copilot AI Feb 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AsyncWith.Revert() nests multiple context managers in the wrong order: iterating items forward makes the last item become the outermost AsyncWithStatement, reversing evaluation/exit order compared to CPython. Iterate items in reverse (like ParseWithStmt) so the first item remains outermost.

Suggested change
foreach (withitem item in items) {
for (int i = items.Count - 1; i >= 0; i--) {
withitem item = (withitem)items[i];

Copilot uses AI. Check for mistakes.
Comment on lines +1483 to +1489
var withItem = ParseWithItem();
var header = GetEnd();
Statement body = ParseSuite();
AsyncWithStatement ret = new AsyncWithStatement(withItem.ContextManager, withItem.Variable, body);
ret.HeaderIndex = header;
ret.SetLoc(_globalParent, asyncStart, GetEnd());
return ret;
Copy link

Copilot AI Feb 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

async with currently parses only a single with_item and ignores the comma-separated form (async with a as x, b as y:). with_stmt already supports multiple items by looping on commas and nesting; async with should mirror that logic (parse all items and create nested AsyncWithStatement nodes in reverse order).

Suggested change
var withItem = ParseWithItem();
var header = GetEnd();
Statement body = ParseSuite();
AsyncWithStatement ret = new AsyncWithStatement(withItem.ContextManager, withItem.Variable, body);
ret.HeaderIndex = header;
ret.SetLoc(_globalParent, asyncStart, GetEnd());
return ret;
var withItems = new List<WithItem>();
withItems.Add(ParseWithItem());
while (MaybeEat(TokenKind.Comma)) {
withItems.Add(ParseWithItem());
}
var header = GetEnd();
Statement body = ParseSuite();
// Build nested AsyncWithStatement nodes in reverse order of withItems
Statement currentBody = body;
AsyncWithStatement outermost = null;
for (int i = withItems.Count - 1; i >= 0; i--) {
var withItem = withItems[i];
var asyncWith = new AsyncWithStatement(withItem.ContextManager, withItem.Variable, currentBody);
if (i == 0) {
// Preserve existing header and location behavior on the outermost node
asyncWith.HeaderIndex = header;
asyncWith.SetLoc(_globalParent, asyncStart, GetEnd());
outermost = asyncWith;
}
currentBody = asyncWith;
}
return outermost;

Copilot uses AI. Check for mistakes.
Comment on lines +85 to +100
// await mgr.__aexit__(None, None, None)
var aexitAttr = new MemberExpression(MakeName("__asyncwith_mgr"), "__aexit__") { Parent = parent };
aexitAttr.IndexSpan = span;
var none1 = new ConstantExpression(null) { Parent = parent }; none1.IndexSpan = span;
var none2 = new ConstantExpression(null) { Parent = parent }; none2.IndexSpan = span;
var none3 = new ConstantExpression(null) { Parent = parent }; none3.IndexSpan = span;
var aexitCallNormal = new CallExpression(aexitAttr,
new Expression[] { none1, none2, none3 }, null) { Parent = parent };
aexitCallNormal.IndexSpan = span;
var awaitExitNormal = new AwaitExpression(aexitCallNormal);

// try/finally: await __aexit__ on normal exit
var finallyExprStmt = new ExpressionStatement(awaitExitNormal) { Parent = parent };
finallyExprStmt.IndexSpan = span;
var tryFinally = new TryStatement(bodyStmt, null, null, finallyExprStmt) { Parent = parent };
tryFinally.IndexSpan = span;
Copy link

Copilot AI Feb 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current desugaring always calls await mgr.__aexit__(None, None, None) in a finally block, which is not equivalent to CPython semantics for async with: on exceptions it must pass exception details to __aexit__ and must respect its truthy return value to decide whether to suppress or re-raise. This needs a try/except/finally structure analogous to WithStatement.Reduce(), but using await for __aenter__/__aexit__.

Copilot uses AI. Check for mistakes.
Comment on lines +1990 to +1991
// Parse the awaitable expression at the unary level
Expression expr = ParsePower();
Copy link

Copilot AI Feb 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ParseAwaitExpression parses the operand via ParsePower(), which prevents valid syntax like await -x (operand starts with a unary operator) and also gives await the wrong precedence relative to ** (it will parse await a ** b as (await a) ** b instead of await (a ** b)). Parse the operand at the unary/factor level (e.g., ParseFactor() / unary_expr) rather than ParsePower() so unary ops and exponentiation bind correctly.

Suggested change
// Parse the awaitable expression at the unary level
Expression expr = ParsePower();
// Parse the awaitable expression at the unary/factor level so unary ops and '**' bind correctly
Expression expr = ParseFactor();

Copilot uses AI. Check for mistakes.
Comment on lines +120 to +126
// while __running: try/except/else
var whileStmt = new WhileStatement(MakeName(runningName), tryExcept, Else);
whileStmt.SetLoc(GlobalParent, span.Start, span.End, span.End);
whileStmt.Parent = parent;

var suite = WithSpan(new SuiteStatement(new Statement[] { assignIter, assignRunning, whileStmt }) { Parent = parent });
return suite;
Copy link

Copilot AI Feb 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The async for desugaring doesn't perform iterator finalization on early loop exit (e.g., break, return, or exception). In CPython, async for ensures aclose() is awaited for async generators / async iterators that provide it, to avoid leaking resources. Consider wrapping the loop in a try/finally that conditionally awaits __asyncfor_iter?.aclose() when the loop is exited prematurely.

Copilot uses AI. Check for mistakes.
@mikasoukhov
Copy link
Author

@mikasoukhov please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@dotnet-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@dotnet-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@dotnet-policy-service agree company="Microsoft"

Contributor License Agreement

@dotnet-policy-service agree [company="StockSharp"]

23 tests covering async def, await, async with, async for,
coroutine properties, __await__ protocol, custom awaitables,
break/continue/else, nested loops, and combined patterns.
@dotnet-policy-service
Copy link

@mikasoukhov please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@dotnet-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@dotnet-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@dotnet-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement ( “Agreement” ) is agreed to by the party signing below ( “You” ),
and conveys certain license rights to the .NET Foundation ( “.NET Foundation” ) for Your contributions to
.NET Foundation open source projects. This Agreement is effective as of the latest signature date below.

1. Definitions.

“Code” means the computer software code, whether in human-readable or machine-executable form,
that is delivered by You to .NET Foundation under this Agreement.

“Project” means any of the projects owned or managed by .NET Foundation and offered under a license
approved by the Open Source Initiative (www.opensource.org).

“Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
Project, including but not limited to communication on electronic mailing lists, source code control
systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
discussing and improving that Project, but excluding communication that is conspicuously marked or
otherwise designated in writing by You as “Not a Submission.”

“Submission” means the Code and any other copyrightable material Submitted by You, including any
associated comments and documentation.

2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
Project. This Agreement covers any and all Submissions that You, now or in the future (except as
described in Section 4 below), Submit to any Project.

3. Originality of Work. You represent that each of Your Submissions is entirely Your
original work. Should You wish to Submit materials that are not Your original work,
You may Submit them separately to the Project if You (a) retain all copyright and
license information that was in the materials as you received them, (b) in the
description accompanying your Submission, include the phrase "Submission
containing materials of a third party:" followed by the names of the third party and any
licenses or other restrictions of which You are aware, and (c) follow any other
instructions in the Project's written guidelines concerning Submissions.

4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
Submission is made in the course of Your work for an employer or Your employer has intellectual
property rights in Your Submission by contract or applicable law, You must secure permission from Your
employer to make the Submission before signing this Agreement. In that case, the term “You” in this
Agreement will refer to You and the employer collectively. If You change employers in the future and
desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
and secure permission from the new employer before Submitting those Submissions.

5. Licenses.

a. Copyright License. You grant .NET Foundation, and those who receive the Submission directly
or indirectly from .NET Foundation, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable
license in the Submission to reproduce, prepare derivative works of, publicly display, publicly perform,
and distribute the Submission and such derivative works, and to sublicense any or all of the foregoing
rights to third parties.

b. Patent License. You grant .NET Foundation, and those who receive the Submission directly or
indirectly from .NET Foundation, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license
under Your patent claims that are necessarily infringed by the Submission or the combination of the
Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
import or otherwise dispose of the Submission alone or with the Project.

c. Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
granted by implication, exhaustion, estoppel or otherwise.

6. Representations and Warranties. You represent that You are legally entitled to grant the above
licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
have disclosed under Section 3 ). You represent that You have secured permission from Your employer to
make the Submission in cases where Your Submission is made in the course of Your work for Your
employer or Your employer has intellectual property rights in Your Submission by contract or applicable
law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
EXPRESSLY STATED IN SECTIONS 3, 4, AND 6 , THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.

7. Notice to .NET Foundation. You agree to notify .NET Foundation in writing of any facts or
circumstances of which You later become aware that would make Your representations in this
Agreement inaccurate in any respect.

8. Information about Submissions. You agree that contributions to Projects and information about
contributions may be maintained indefinitely and disclosed publicly, including Your name and other
information that You submit with Your Submission.

9. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
defenses of lack of personal jurisdiction and forum non-conveniens.

10. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
supersedes any and all prior agreements, understandings or communications, written or oral, between
the parties relating to the subject matter hereof. This Agreement may be assigned by .NET Foundation.

.NET Foundation dedicates this Contribution License Agreement to the public domain according to the Creative Commons CC0 1.

…numerable, CancelledError

- Add TaskAwaitable/ValueTaskAwaitable wrappers enabling `await` on
  Task, Task<T>, ValueTask and ValueTask<T> from Python async code
- Add AsyncEnumerableWrapper enabling `async for` over IAsyncEnumerable<T>
- Map OperationCanceledException to new CancelledError Python exception
- Add __await__, __aiter__, __anext__ resolvers in PythonTypeInfo
- Add bridge methods in InstanceOps for the resolver pattern
- ValueTask/IAsyncEnumerable support gated behind #if NET (requires .NET Core)
- Handle Task<VoidTaskResult> (internal type arg) by falling back to
  non-generic TaskAwaitable via IsVisible check
- Add 'await' keyword to generate_ops.py kwlist
- Add CancelledError factory-only exception to generate_exceptions.py
- Regenerate TokenKind, Tokenizer, PythonWalker, PythonNameBinder
- Fix CancelledError placement in ToPythonHelper to match generator order
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant