Skip to content

Commit b455f65

Browse files
authored
perf(generator): return the request task instead of awaiting it (#2302)
- Emit the reflection fallback path without async/await so a generated method hands back the request builder's task. Awaiting allocated a second state machine per call whose only job was to re-wrap that task. - Drop the async and configure-await plumbing from the method-opening and return-statement emitters, which is now constant either way. - Pin the fallback emission shape with a test; it had no coverage.
1 parent 51368ea commit b455f65

5 files changed

Lines changed: 65 additions & 35 deletions

File tree

‎src/InterfaceStubGenerator.Shared/Emitter.Helpers.cs‎

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -89,21 +89,23 @@ internal static string ToHttpMethodExpression(string httpMethod) =>
8989
_ => $"new global::System.Net.Http.HttpMethod({ToCSharpStringLiteral(httpMethod)})"
9090
};
9191

92-
/// <summary>Gets the invocation text used for a generated method return type.</summary>
92+
/// <summary>Gets the statement prefix used for a generated method return type.</summary>
9393
/// <param name="returnTypeInfo">The method return type shape.</param>
94-
/// <returns>The async flag, return prefix, and configure-await suffix.</returns>
94+
/// <returns>The return statement prefix, empty for a shape that discards the call's result.</returns>
9595
/// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="returnTypeInfo"/> is unsupported.</exception>
96-
internal static (bool IsAsync, string ReturnPrefix, string ConfigureAwaitSuffix) GetReturnInvocationParts(
97-
ReturnTypeInfo returnTypeInfo) =>
96+
/// <remarks>An awaitable shape hands its task straight back rather than awaiting it. Awaiting here would build a
97+
/// second state machine per call that forwards the task the request builder already produced, changing nothing but
98+
/// the allocation count; the awaitable is the caller's to consume.</remarks>
99+
internal static string GetReturnStatementPrefix(ReturnTypeInfo returnTypeInfo) =>
98100
returnTypeInfo switch
99101
{
100-
ReturnTypeInfo.AsyncVoid => (true, "await (", ").ConfigureAwait(false)"),
101-
ReturnTypeInfo.AsyncResult => (true, "return await (", ").ConfigureAwait(false)"),
102-
ReturnTypeInfo.AsyncEnumerable
102+
ReturnTypeInfo.AsyncVoid
103+
or ReturnTypeInfo.AsyncResult
104+
or ReturnTypeInfo.AsyncEnumerable
103105
or ReturnTypeInfo.Observable
104106
or ReturnTypeInfo.RequestMessage
105-
or ReturnTypeInfo.Return => (false, ReturnStatementPrefix, string.Empty),
106-
ReturnTypeInfo.SyncVoid => (false, string.Empty, string.Empty),
107+
or ReturnTypeInfo.Return => ReturnStatementPrefix,
108+
ReturnTypeInfo.SyncVoid => string.Empty,
107109
_ => throw new ArgumentOutOfRangeException(
108110
nameof(returnTypeInfo),
109111
returnTypeInfo,
@@ -223,26 +225,25 @@ internal static string StripExplicitInterfacePrefix(string name)
223225
/// <param name="isDerivedExplicitImpl">True if the method is a derived explicit implementation.</param>
224226
/// <param name="isExplicitInterface">True if the method is an explicit interface implementation.</param>
225227
/// <param name="supportsNullable">Whether the consumer compilation supports nullable reference type syntax.</param>
226-
/// <param name="isAsync">True if the method should be emitted as async.</param>
227228
/// <param name="methodAttributes">Attribute lines emitted between the documentation and the signature.</param>
229+
/// <remarks>Every generated method is emitted synchronously: an awaitable return type is handed back to the caller
230+
/// rather than awaited, so no generated method carries an async state machine.</remarks>
228231
internal static void AppendMethodOpening(
229232
PooledStringBuilder builder,
230233
in MethodModel methodModel,
231234
bool isDerivedExplicitImpl,
232235
bool isExplicitInterface,
233236
bool supportsNullable,
234-
bool isAsync = false,
235237
string methodAttributes = "")
236238
{
237239
var visibility = !isExplicitInterface ? "public " : string.Empty;
238-
var asyncKeyword = isAsync ? "async " : string.Empty;
239240
var explicitInterface = BuildExplicitInterfacePrefix(methodModel, isExplicitInterface);
240241
var methodIndent = Indent(MethodMemberIndentation);
241242

242243
_ = builder
243244
.AppendLine()
244245
.Append(methodIndent).AppendLine("/// <inheritdoc />")
245-
.Append(methodAttributes).Append(methodIndent).Append(visibility).Append(asyncKeyword)
246+
.Append(methodAttributes).Append(methodIndent).Append(visibility)
246247
.Append(methodModel.ReturnType).Append(' ').Append(explicitInterface).Append(methodModel.DeclaredMethod)
247248
.Append('(').Append(BuildParameterList(methodModel.Parameters, supportsNullable)).Append(')').AppendLine();
248249
AppendConstraints(builder, methodModel.Constraints, isDerivedExplicitImpl || isExplicitInterface, MethodBodyIndentation);
@@ -254,19 +255,17 @@ internal static void AppendMethodOpening(
254255
/// <param name="isDerivedExplicitImpl">True if the method is a derived explicit implementation.</param>
255256
/// <param name="isExplicitInterface">True if the method is an explicit interface implementation.</param>
256257
/// <param name="supportsNullable">Whether the consumer compilation supports nullable reference type syntax.</param>
257-
/// <param name="isAsync">True if the method should be emitted as async.</param>
258258
/// <param name="methodAttributes">Attribute lines emitted between the documentation and the signature.</param>
259259
/// <returns>The generated method opening.</returns>
260260
internal static string BuildMethodOpening(
261261
in MethodModel methodModel,
262262
bool isDerivedExplicitImpl,
263263
bool isExplicitInterface,
264264
bool supportsNullable,
265-
bool isAsync = false,
266265
string methodAttributes = "")
267266
{
268267
var builder = new PooledStringBuilder();
269-
AppendMethodOpening(builder, methodModel, isDerivedExplicitImpl, isExplicitInterface, supportsNullable, isAsync, methodAttributes);
268+
AppendMethodOpening(builder, methodModel, isDerivedExplicitImpl, isExplicitInterface, supportsNullable, methodAttributes);
270269
return builder.ToString();
271270
}
272271

‎src/InterfaceStubGenerator.Shared/Emitter.Inline.cs‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,12 +71,12 @@ internal static void BuildRefitMethod(
7171
methodModel,
7272
uniqueNames);
7373
var returnType = methodModel.ReturnType;
74-
var (isAsync, @return, configureAwait) = GetReturnInvocationParts(methodModel.ReturnTypeMetadata);
74+
var @return = GetReturnStatementPrefix(methodModel.ReturnTypeMetadata);
7575
var isExplicit = methodModel.IsExplicitInterface || !isTopLevel;
7676
var lookupName = StripExplicitInterfacePrefix(methodModel.Name);
7777
var typeParameterExpression = BuildTypeParameterExpression(methodModel.Parameters, cachedTypeParameterFieldName);
7878
var genericTypesArgument = BuildGenericTypesArgument(methodModel);
79-
var returnStatement = BuildRefitReturnStatement(methodModel, @return, returnType, configureAwait, funcLocal, argumentsLocal);
79+
var returnStatement = BuildRefitReturnStatement(methodModel, @return, returnType, funcLocal, argumentsLocal);
8080
var methodIndent = Indent(MethodMemberIndentation);
8181
var bodyIndent = Indent(MethodBodyIndentation);
8282
var requestBuilderInit =
@@ -89,7 +89,6 @@ internal static void BuildRefitMethod(
8989
isExplicit,
9090
isExplicit,
9191
interfaceModel.SupportsNullable,
92-
isAsync,
9392
BuildReflectionFallbackSuppressions(
9493
methodModel.RequiresUnreferencedCode,
9594
methodModel.RequiresDynamicCode)))

‎src/InterfaceStubGenerator.Shared/Emitter.ReflectionArguments.cs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -229,21 +229,19 @@ internal static string BuildParameterTypeList(ImmutableEquatableArray<ParameterM
229229
/// <param name="methodModel">The method model being emitted.</param>
230230
/// <param name="returnPrefix">The return statement prefix.</param>
231231
/// <param name="returnType">The generated return type.</param>
232-
/// <param name="configureAwait">The generated configure-await suffix.</param>
233232
/// <param name="funcLocal">The generated request-func local name.</param>
234233
/// <param name="argumentsLocal">The generated arguments-array local name.</param>
235234
/// <returns>The generated return statement.</returns>
236235
internal static string BuildRefitReturnStatement(
237236
in MethodModel methodModel,
238237
string returnPrefix,
239238
string returnType,
240-
string configureAwait,
241239
string funcLocal,
242240
string argumentsLocal)
243241
{
244242
var bodyIndent = Indent(MethodBodyIndentation);
245243
return methodModel.ReturnTypeMetadata == ReturnTypeInfo.SyncVoid
246244
? $"{bodyIndent}{funcLocal}(this.Client, {argumentsLocal});\n"
247-
: $"{bodyIndent}{returnPrefix}({returnType}){funcLocal}(this.Client, {argumentsLocal}){configureAwait};\n";
245+
: $"{bodyIndent}{returnPrefix}({returnType}){funcLocal}(this.Client, {argumentsLocal});\n";
248246
}
249247
}

‎src/tests/Refit.GeneratorTests/GeneratedRequestBuildingTests.InlineEmissionAndFallbacks.cs‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,34 @@ public async Task SwitchOnFallsBackForInvalidHeaderCollection()
2323
await Assert.That(generated).DoesNotContain("GeneratedRequestRunner.AddHeaderCollection");
2424
}
2525

26+
/// <summary>Verifies a reflection-fallback method hands its task straight back to the caller rather than awaiting
27+
/// it, so no generated method carries an async state machine that only forwards the request builder's task.</summary>
28+
/// <returns>A task representing the asynchronous test.</returns>
29+
[Test]
30+
public async Task SwitchOnFallbackReturnsTheRequestBuilderTaskWithoutAwaiting()
31+
{
32+
var generated = Fixture.GenerateForBody(
33+
"""
34+
[Get("/query-map")]
35+
Task<string> Search(object filters);
36+
37+
[Get("/ping-map")]
38+
Task Ping(object filters);
39+
""",
40+
GeneratedClientHintName,
41+
generatedRequestBuilding: true);
42+
43+
await Assert.That(generated).Contains(ReflectiveRequestBuilderCall);
44+
await Assert.That(generated).Contains("public global::System.Threading.Tasks.Task<string> Search(");
45+
await Assert.That(generated).Contains("public global::System.Threading.Tasks.Task Ping(");
46+
await Assert.That(generated).Contains("return (global::System.Threading.Tasks.Task<string>)refitFunc(");
47+
await Assert.That(generated).Contains("return (global::System.Threading.Tasks.Task)refitFunc(");
48+
49+
// No state machine and therefore nothing to configure: the awaitable is the caller's to consume.
50+
await Assert.That(generated).DoesNotContain("public async ");
51+
await Assert.That(generated).DoesNotContain("ConfigureAwait");
52+
}
53+
2654
/// <summary>Verifies unsupported inline path forms and metadata fall back to the runtime builder.</summary>
2755
/// <returns>A task representing the asynchronous test.</returns>
2856
[Test]

‎src/tests/Refit.GeneratorTests/GeneratorComponentTests.EmitterHelpers.cs‎

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ public class EmitterHelperTests
2424
/// <summary>The non-standard HTTP method attribute name used by candidate-combining tests.</summary>
2525
private const string CustomMethodName = "Custom";
2626

27+
/// <summary>The generated return statement prefix.</summary>
28+
private const string ReturnPrefix = "return ";
29+
2730
/// <summary>The generated false literal.</summary>
2831
private const string FalseLiteral = "false";
2932

@@ -297,20 +300,20 @@ public async Task LiteralAndHttpMethodHelpers_HandleKnownAndInvalidValues()
297300
await Assert.That(Emitter.ToHttpMethodExpression("TRACE")).IsEqualTo("new global::System.Net.Http.HttpMethod(\"TRACE\")");
298301
}
299302

300-
/// <summary>Verifies generated return invocation text for every return type shape.</summary>
303+
/// <summary>Verifies the generated return statement prefix for every return type shape, including that an
304+
/// awaitable shape returns its task rather than awaiting it.</summary>
301305
/// <returns>A task representing the asynchronous test.</returns>
302306
[Test]
303-
public async Task ReturnInvocationParts_HandleKnownAndInvalidValues()
307+
public async Task ReturnStatementPrefix_HandlesKnownAndInvalidValues()
304308
{
305-
await Assert.That(Emitter.GetReturnInvocationParts(ReturnTypeInfo.AsyncVoid))
306-
.IsEqualTo((true, "await (", ").ConfigureAwait(false)"));
307-
await Assert.That(Emitter.GetReturnInvocationParts(ReturnTypeInfo.AsyncResult))
308-
.IsEqualTo((true, "return await (", ").ConfigureAwait(false)"));
309-
await Assert.That(Emitter.GetReturnInvocationParts(ReturnTypeInfo.Return))
310-
.IsEqualTo((false, "return ", string.Empty));
311-
await Assert.That(Emitter.GetReturnInvocationParts(ReturnTypeInfo.SyncVoid))
312-
.IsEqualTo((false, string.Empty, string.Empty));
313-
await Assert.That(static () => Emitter.GetReturnInvocationParts((ReturnTypeInfo)int.MaxValue))
309+
await Assert.That(Emitter.GetReturnStatementPrefix(ReturnTypeInfo.AsyncVoid)).IsEqualTo(ReturnPrefix);
310+
await Assert.That(Emitter.GetReturnStatementPrefix(ReturnTypeInfo.AsyncResult)).IsEqualTo(ReturnPrefix);
311+
await Assert.That(Emitter.GetReturnStatementPrefix(ReturnTypeInfo.AsyncEnumerable)).IsEqualTo(ReturnPrefix);
312+
await Assert.That(Emitter.GetReturnStatementPrefix(ReturnTypeInfo.Observable)).IsEqualTo(ReturnPrefix);
313+
await Assert.That(Emitter.GetReturnStatementPrefix(ReturnTypeInfo.RequestMessage)).IsEqualTo(ReturnPrefix);
314+
await Assert.That(Emitter.GetReturnStatementPrefix(ReturnTypeInfo.Return)).IsEqualTo(ReturnPrefix);
315+
await Assert.That(Emitter.GetReturnStatementPrefix(ReturnTypeInfo.SyncVoid)).IsEqualTo(string.Empty);
316+
await Assert.That(static () => Emitter.GetReturnStatementPrefix((ReturnTypeInfo)int.MaxValue))
314317
.ThrowsExactly<ArgumentOutOfRangeException>();
315318
}
316319

@@ -332,10 +335,13 @@ public async Task BuildMethodOpening_QualifiesExplicitInterfaceMethods()
332335
false,
333336
false);
334337

335-
var source = Emitter.BuildMethodOpening(method, true, true, supportsNullable: true, isAsync: true);
338+
var source = Emitter.BuildMethodOpening(method, true, true, supportsNullable: true);
336339

337340
await Assert.That(source)
338-
.Contains("async global::System.Threading.Tasks.Task global::RefitGeneratorTest.IBase.Ping(");
341+
.Contains("global::System.Threading.Tasks.Task global::RefitGeneratorTest.IBase.Ping(");
342+
343+
// A task-returning method hands its task back, so no generated method is emitted async.
344+
await Assert.That(source).DoesNotContain("async ");
339345
}
340346

341347
/// <summary>Verifies emitted XML documentation text escapes special characters.</summary>

0 commit comments

Comments
 (0)
⌂ 换网址