Repository navigation
Fix source generation for one-element ValueTuple parameters #7467
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
b651ab5
8fd9980
e629658
89f979d
89fc832
17eb68b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -26,7 +26,7 @@ | |
|
|
||
| private static readonly DiagnosticDescriptor GenerationErrorDescriptor = new( | ||
| "TUNIT0999", | ||
| "Source Generation Error", | ||
|
Check warning on line 29 in src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs
|
||
| "Failed to generate test metadata for {0}.{1}: {2}", | ||
| "TUnit", | ||
| DiagnosticSeverity.Error, | ||
|
|
@@ -2471,7 +2471,24 @@ | |
| writer.AppendLine($"dependencies: {depsExpr},"); | ||
| } | ||
|
|
||
| writer.AppendLine($"methodMetadata: __mm_0,"); | ||
| if (TryGetClosedParametersForSharedBinder(testMethod, entry) is { } closedParameters | ||
| && HasSingleElementTupleParameter(closedParameters)) | ||
| { | ||
| // The factories and engine bind using ParameterMetadata.Type, so close that metadata | ||
| // as well as the invoker. Keep attributes and lazy reflection access from the original. | ||
| var parameters = testMethod.MethodSymbol.Parameters.Select(parameter => | ||
| { | ||
| var closed = closedParameters.FirstOrDefault(p => p.Ordinal == parameter.Ordinal); | ||
| var original = $"__mm_0.Parameters[{parameter.Ordinal.ToString(CultureInfo.InvariantCulture)}]"; | ||
| return closed is null ? original | ||
| : $"{original} with {{ Type = typeof({closed.Type.GloballyQualified()}), TypeInfo = new global::TUnit.Core.ConcreteType(typeof({closed.Type.GloballyQualified()})) }}"; | ||
| }); | ||
| writer.AppendLine($"methodMetadata: __mm_0 with {{ Parameters = new global::TUnit.Core.ParameterMetadata[] {{ {string.Join(", ", parameters)} }} }},"); | ||
| } | ||
| else | ||
| { | ||
| writer.AppendLine($"methodMetadata: __mm_0,"); | ||
| } | ||
| writer.AppendLine($"createInstance: __CreateInstance_{groupIndex.ToString(CultureInfo.InvariantCulture)},"); | ||
| writer.AppendLine($"invokeBody: __Invoke_{groupIndex.ToString(CultureInfo.InvariantCulture)},"); | ||
| writer.AppendLine($"methodIndex: {entryIndex.ToString(CultureInfo.InvariantCulture)},"); | ||
|
|
@@ -2534,6 +2551,11 @@ | |
| } | ||
| } | ||
|
|
||
| // Match the concrete invoker: an open T may close to a one-element tuple. | ||
| var keepSingleElementTupleWhole = TryGetClosedParametersForSharedBinder(testMethod, entry) is { } closedParameters | ||
| ? HasSingleElementTupleParameter(closedParameters) | ||
| : HasSingleElementTupleParameter(methodSymbol.Parameters); | ||
|
|
||
| // Method data sources | ||
| List<AttributeData> methodDataSources; | ||
| AttributeData[] classDataSources; | ||
|
|
@@ -2623,7 +2645,7 @@ | |
| foreach (var rowSourceAttribute in rowSources) | ||
| { | ||
| var rowWriter = new CodeWriter(includeHeader: false); | ||
| GenerateDataSourceAttribute(rowWriter, testMethod.CompilationContext, rowSourceAttribute, methodSymbol, concreteTypeSymbol); | ||
| GenerateDataSourceAttribute(rowWriter, testMethod.CompilationContext, rowSourceAttribute, methodSymbol, concreteTypeSymbol, keepSingleElementTupleWhole); | ||
| dsWriter.AppendLine($"global::TUnit.Core.GenericConstraintViolationDataSource.Create({message}, {rowWriter.ToString().Trim().TrimEnd(',')}),"); | ||
| } | ||
| } | ||
|
|
@@ -2653,7 +2675,7 @@ | |
| dsWriter.Indent(); | ||
| foreach (var attr in methodDataSources) | ||
| { | ||
| GenerateDataSourceAttribute(dsWriter, testMethod.CompilationContext, attr, methodSymbol, concreteTypeSymbol); | ||
| GenerateDataSourceAttribute(dsWriter, testMethod.CompilationContext, attr, methodSymbol, concreteTypeSymbol, keepSingleElementTupleWhole); | ||
| } | ||
| dsWriter.Unindent(); | ||
| dsWriter.Append("}"); | ||
|
|
@@ -3014,7 +3036,7 @@ | |
| GeneratePropertyDataSources(writer, testMethod); | ||
| } | ||
|
|
||
| private static void GenerateDataSourceAttribute(CodeWriter writer, CompilationContext compilationContext, AttributeData attr, IMethodSymbol methodSymbol, INamedTypeSymbol typeSymbol) | ||
| private static void GenerateDataSourceAttribute(CodeWriter writer, CompilationContext compilationContext, AttributeData attr, IMethodSymbol methodSymbol, INamedTypeSymbol typeSymbol, bool? keepSingleElementTupleWhole = null) | ||
| { | ||
| var attrClass = attr.AttributeClass; | ||
| if (attrClass == null) | ||
|
|
@@ -3029,7 +3051,7 @@ | |
| // finds no trimmed field or property metadata (#7225). | ||
| if (attrName is "global::TUnit.Core.MethodDataSourceAttribute" or InstanceMethodDataSourceAttributeName) | ||
| { | ||
| GenerateMethodDataSourceAttribute(writer, attr, typeSymbol, compilationContext.Compilation); | ||
| GenerateMethodDataSourceAttribute(writer, attr, typeSymbol, methodSymbol, compilationContext.Compilation, keepSingleElementTupleWhole); | ||
| } | ||
| else if (attrName == "global::TUnit.Core.ArgumentsAttribute") | ||
| { | ||
|
|
@@ -3318,7 +3340,7 @@ | |
| return true; | ||
| } | ||
|
|
||
| private static void GenerateMethodDataSourceAttribute(CodeWriter writer, AttributeData attr, INamedTypeSymbol typeSymbol, Compilation compilation) | ||
| private static void GenerateMethodDataSourceAttribute(CodeWriter writer, AttributeData attr, INamedTypeSymbol typeSymbol, IMethodSymbol methodSymbol, Compilation compilation, bool? keepSingleElementTupleWhole) | ||
| { | ||
| // Extract method name and target type | ||
| string? methodName = null; | ||
|
|
@@ -3463,20 +3485,42 @@ | |
| // a per-data-source compiler-generated state machine class (#6227). Only the per-test-unique | ||
| // invocation is emitted, as a static lambda. | ||
| writer.Append("Factory = static dataGeneratorMetadata => "); | ||
| EmitDataSourceFactoryInvocation(writer, dataSourceMember, targetType, usesTestClassInstance, hasArguments ? argumentsProperty.Value : (TypedConstant?)null, compilation, isDeclaredInstanceAttribute); | ||
| keepSingleElementTupleWhole ??= HasSingleElementTupleParameter(methodSymbol.Parameters); | ||
| EmitDataSourceFactoryInvocation(writer, dataSourceMember, targetType, usesTestClassInstance, hasArguments ? argumentsProperty.Value : (TypedConstant?)null, compilation, isDeclaredInstanceAttribute, keepSingleElementTupleWhole.Value); | ||
| writer.AppendLine(","); | ||
|
|
||
| writer.Unindent(); | ||
| writer.AppendLine("},"); | ||
| } | ||
|
|
||
| private static bool HasSingleElementTupleParameter(IEnumerable<IParameterSymbol> parameters) | ||
| { | ||
| ITypeSymbol? dataType = null; | ||
| foreach (var parameter in parameters) | ||
| { | ||
| if (parameter.Type.IsCancellationToken()) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| if (dataType is not null) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| dataType = parameter.Type; | ||
| } | ||
|
|
||
| return dataType is INamedTypeSymbol { IsTupleType: true, TupleElements.Length: 1 }; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Emits a call to a <c>TUnit.Core.Helpers.DataSourceFactories</c> helper, passing the | ||
| /// data source member invocation as a static lambda. The helper is selected from the | ||
| /// member's declared return type (mirroring the previous inline-iterator branch order) | ||
| /// and whether the member is static or instance-based. | ||
| /// </summary> | ||
| private static void EmitDataSourceFactoryInvocation(CodeWriter writer, ISymbol dataSourceMember, ITypeSymbol targetType, bool usesTestClassInstance, TypedConstant? arguments, Compilation compilation, bool decidesRowsFromRuntimeValue) | ||
| private static void EmitDataSourceFactoryInvocation(CodeWriter writer, ISymbol dataSourceMember, ITypeSymbol targetType, bool usesTestClassInstance, TypedConstant? arguments, Compilation compilation, bool decidesRowsFromRuntimeValue, bool keepSingleElementTupleWhole) | ||
| { | ||
| var dataSourceMethod = dataSourceMember as IMethodSymbol; | ||
|
|
||
|
|
@@ -3561,7 +3605,8 @@ | |
| // The instance helpers take the metadata anyway. [InstanceMethodDataSource] read its member by reflection before | ||
| // #7225, and that path keeps a tuple row whole when the test takes a single tuple, so its static helpers get the | ||
| // metadata too: without the parameter types, a one-element tuple holding null would reach the test as null. | ||
| var metadataArgument = usesTestClassInstance || decidesRowsFromRuntimeValue ? "dataGeneratorMetadata, " : ""; | ||
| // Preserve one-element rows before unwrapping: their element can itself have the expected tuple type. | ||
| var metadataArgument = usesTestClassInstance || decidesRowsFromRuntimeValue || keepSingleElementTupleWhole ? "dataGeneratorMetadata, " : ""; | ||
|
|
||
| // A declared type such as object does not say whether the value is one row or many. Reflection mode, and the | ||
| // attribute's reflection fallback that read every field and every private or protected property before the | ||
|
|
@@ -4413,22 +4458,29 @@ | |
|
|
||
| // Special case: Single tuple parameter (same as in TestInvoker) | ||
| // If we have exactly one parameter that's a tuple type, we need to handle it specially | ||
| // In source-generated mode, tuples are always unwrapped into their elements | ||
| // Generated factories unwrap tuples; instance sources can preserve the whole tuple. | ||
| if (parametersFromArgs is | ||
| [ | ||
| { Type: INamedTypeSymbol { IsTupleType: true } singleTupleParam } | ||
| ]) | ||
| { | ||
| writer.AppendLine("// Special handling for single tuple parameter"); | ||
| writer.AppendLine($"if (args.Length == {singleTupleParam.TupleElements.Length.ToString(CultureInfo.InvariantCulture)})"); | ||
| // Factories preserve one-element tuple rows, so a matching tuple is the whole row, | ||
| // even when its element is another tuple of the same type. | ||
| var unwrappedCheck = singleTupleParam.TupleElements.Length == 1 | ||
| ? $" && args[0] is not {singleTupleParam.GloballyQualified()}" | ||
| : ""; | ||
| writer.AppendLine($"if (args.Length == {singleTupleParam.TupleElements.Length.ToString(CultureInfo.InvariantCulture)}{unwrappedCheck})"); | ||
| writer.AppendLine("{"); | ||
| writer.Indent(); | ||
| writer.AppendLine("// Arguments are unwrapped tuple elements, reconstruct the tuple"); | ||
|
|
||
| // Build tuple reconstruction with proper casting | ||
| var tupleElements = singleTupleParam.TupleElements.Select((elem, i) => | ||
| $"global::TUnit.Core.Helpers.CastHelper.Cast<{elem.Type.GloballyQualified()}>(args[{i.ToString(CultureInfo.InvariantCulture)}])"); | ||
| var tupleConstruction = $"({string.Join(", ", tupleElements)})"; | ||
| var tupleConstruction = singleTupleParam.TupleElements.Length == 1 | ||
| ? $"new {singleTupleParam.GloballyQualified()}({string.Join(", ", tupleElements)})" | ||
| : $"({string.Join(", ", tupleElements)})"; | ||
|
thomhurst marked this conversation as resolved.
Resolved
|
||
|
|
||
| var methodCallReconstructed = $"instance.{methodName}({FormatSingleArgumentCall(tupleConstruction, hasCancellationToken, parametersFromArgs)})"; | ||
| GenerateReturnHandling(writer, methodCallReconstructed, returnPattern); | ||
|
|
@@ -7598,7 +7650,7 @@ | |
| if (inferredTypes.Count == typeParameters.Length) | ||
| { | ||
| var result = new ITypeSymbol[typeParameters.Length]; | ||
| for (var i = 0; i < typeParameters.Length; i++) | ||
|
Check warning on line 7653 in src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs
|
||
| { | ||
| if (inferredTypes.TryGetValue(typeParameters[i].Name, out var type)) | ||
| { | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.