-
Notifications
You must be signed in to change notification settings - Fork 307
Refactor TestClassModelBuilder into focused files (#9910) #9911
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
be55819
Refactor TestClassModelBuilder into focused files (#9910)
Evangelink a84587b
Address review: use explicit .Where/.Any filtering over implicit fore…
Evangelink 2aaab3b
Update .xlf files to be in sync with .resx
Evangelink 9aa25d9
Merge branch 'main' into dev/amauryleve/glowing-fortnight
Evangelink 1b17423
Merge branch 'main' into dev/amauryleve/glowing-fortnight
Evangelink File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
245 changes: 245 additions & 0 deletions
245
src/Analyzers/MSTest.SourceGeneration/Generators/AttributeMaterializationHelper.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,245 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
|
Evangelink marked this conversation as resolved.
|
||
| // Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
|
||
| using System.Collections.Immutable; | ||
|
|
||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.SourceGeneration.Models; | ||
|
|
||
| using MSTest.Analyzers.Shared; | ||
|
|
||
| namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.SourceGeneration.Generators; | ||
|
|
||
| /// <summary> | ||
| /// Decides which attribute applications survive Native AOT trimming and converts the surviving | ||
| /// <see cref="AttributeData"/> into the emitter-facing <see cref="AttributeApplicationModel"/>. Attributes the | ||
| /// generated <c>new T(...)</c> could not reconstruct from the consuming assembly are dropped so the adapter | ||
| /// falls back to runtime reflection for them. | ||
| /// </summary> | ||
| internal static class AttributeMaterializationHelper | ||
| { | ||
| // Mirror the runtime behavior of MemberInfo.GetCustomAttributes(inherit: true): walk the | ||
| // overridden-member chain, honor AttributeUsageAttribute.Inherited, and keep only the | ||
| // most-derived application for attributes that do not allow multiple instances. | ||
| internal static ImmutableArray<AttributeData> CollectInheritedAttributes(IMethodSymbol method) | ||
| { | ||
| ImmutableArray<AttributeData> own = method.GetAttributes(); | ||
| if (method.OverriddenMethod is null) | ||
| { | ||
| return own; | ||
| } | ||
|
|
||
| var seen = new HashSet<string>(StringComparer.Ordinal); | ||
| ImmutableArray<AttributeData>.Builder builder = ImmutableArray.CreateBuilder<AttributeData>(); | ||
| AppendAttributes(builder, seen, own, inheritedOnly: false); | ||
| for (IMethodSymbol? baseMethod = method.OverriddenMethod; baseMethod is not null; baseMethod = baseMethod.OverriddenMethod) | ||
| { | ||
| AppendAttributes(builder, seen, baseMethod.GetAttributes(), inheritedOnly: true); | ||
| } | ||
|
|
||
| return builder.ToImmutable(); | ||
| } | ||
|
|
||
| internal static ImmutableArray<AttributeData> CollectInheritedAttributes(IPropertySymbol property) | ||
| { | ||
| ImmutableArray<AttributeData> own = property.GetAttributes(); | ||
| if (property.OverriddenProperty is null) | ||
| { | ||
| return own; | ||
| } | ||
|
|
||
| var seen = new HashSet<string>(StringComparer.Ordinal); | ||
| ImmutableArray<AttributeData>.Builder builder = ImmutableArray.CreateBuilder<AttributeData>(); | ||
| AppendAttributes(builder, seen, own, inheritedOnly: false); | ||
| for (IPropertySymbol? baseProperty = property.OverriddenProperty; baseProperty is not null; baseProperty = baseProperty.OverriddenProperty) | ||
| { | ||
| AppendAttributes(builder, seen, baseProperty.GetAttributes(), inheritedOnly: true); | ||
| } | ||
|
|
||
| return builder.ToImmutable(); | ||
| } | ||
|
|
||
| private static void AppendAttributes( | ||
| ImmutableArray<AttributeData>.Builder builder, | ||
| HashSet<string> seen, | ||
| ImmutableArray<AttributeData> attributes, | ||
| bool inheritedOnly) | ||
| { | ||
| foreach (AttributeData attribute in attributes) | ||
| { | ||
| if (attribute.AttributeClass is not { } attributeClass) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| AttributeUsageMetadata usage = GetAttributeUsage(attributeClass); | ||
| if (inheritedOnly && !usage.Inherited) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| string key = attributeClass.ToDisplayString(SymbolDisplayFormats.FullyQualified); | ||
| if (usage.AllowMultiple || seen.Add(key)) | ||
| { | ||
| builder.Add(attribute); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static AttributeUsageMetadata GetAttributeUsage(INamedTypeSymbol attributeClass) | ||
| { | ||
| bool inherited = true; | ||
| bool allowMultiple = false; | ||
|
|
||
| // [AttributeUsage] is itself inherited (its own AttributeUsage declares Inherited=true). | ||
| // Roslyn's GetAttributes() does NOT walk the base-type chain, so we have to walk it | ||
| // ourselves to honor an [AttributeUsage] declared on a base attribute type (e.g. when | ||
| // a user-defined attribute derives from one of MSTest's attributes without re-declaring | ||
| // its own [AttributeUsage]). | ||
| for (INamedTypeSymbol? current = attributeClass; | ||
| current is not null && current.SpecialType != SpecialType.System_Object; | ||
| current = current.BaseType) | ||
| { | ||
| if (TryReadAttributeUsage(current, out bool currentInherited, out bool currentAllowMultiple)) | ||
| { | ||
| inherited = currentInherited; | ||
| allowMultiple = currentAllowMultiple; | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| return new AttributeUsageMetadata(inherited, allowMultiple); | ||
| } | ||
|
|
||
| private static bool TryReadAttributeUsage(INamedTypeSymbol attributeClass, out bool inherited, out bool allowMultiple) | ||
| { | ||
| inherited = true; | ||
| allowMultiple = false; | ||
|
|
||
| foreach (AttributeData attribute in attributeClass.GetAttributes()) | ||
| { | ||
| if (attribute.AttributeClass?.ToDisplayString(SymbolDisplayFormats.FullyQualified) != "global::System.AttributeUsageAttribute") | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| foreach (KeyValuePair<string, TypedConstant> namedArgument in attribute.NamedArguments) | ||
| { | ||
| if (namedArgument.Value.Value is not bool value) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| switch (namedArgument.Key) | ||
| { | ||
| case nameof(AttributeUsageAttribute.Inherited): | ||
| inherited = value; | ||
| break; | ||
| case nameof(AttributeUsageAttribute.AllowMultiple): | ||
| allowMultiple = value; | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| private readonly record struct AttributeUsageMetadata(bool Inherited, bool AllowMultiple); | ||
|
|
||
| public static EquatableArray<AttributeApplicationModel> BuildAttributes( | ||
| ImmutableArray<AttributeData> attributes, | ||
| IAssemblySymbol consumingAssembly) | ||
| => attributes.IsDefaultOrEmpty | ||
| ? EquatableArray<AttributeApplicationModel>.Empty | ||
| : attributes | ||
| .Select(attribute => BuildAttribute(attribute, consumingAssembly)) | ||
| .WhereNotNull() | ||
| .ToEquatableArray(); | ||
|
|
||
| private static AttributeApplicationModel? BuildAttribute(AttributeData attribute, IAssemblySymbol consumingAssembly) | ||
| { | ||
| if (attribute.AttributeClass is not { } attributeClass) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| // Safener: only materialize attributes the generated code can actually reconstruct with | ||
| // `new T(...)`. Anything that would not compile from the consuming assembly (inaccessible | ||
| // attribute type or constructor, or an argument referencing an inaccessible type) is omitted | ||
| // so the adapter falls back to runtime reflection for it. Omission is always safe; emitting | ||
| // an un-compilable expression would break the build. | ||
| if (!IsAttributeMaterializable(attribute, attributeClass, consumingAssembly)) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| IEnumerable<TypedConstantModel> ctorArgs = attribute.ConstructorArguments.Select(ToModel); | ||
| IEnumerable<NamedArgumentModel> namedArgs = attribute.NamedArguments.Select(static kv => new NamedArgumentModel(kv.Key, ToModel(kv.Value))); | ||
|
|
||
| return new AttributeApplicationModel( | ||
| FullyQualifiedAttributeType: attributeClass.ToDisplayString(SymbolDisplayFormats.FullyQualified), | ||
| ConstructorArguments: ctorArgs.ToEquatableArray(), | ||
| NamedArguments: namedArgs.ToEquatableArray()); | ||
| } | ||
|
|
||
| private static bool IsAttributeMaterializable(AttributeData attribute, INamedTypeSymbol attributeClass, IAssemblySymbol consumingAssembly) | ||
| // The attribute type (and every enclosing type) must be referenceable; the constructor the | ||
| // generated `new T(...)` binds to must be callable (a null AttributeConstructor — Roslyn could | ||
| // not resolve it — is treated as not materializable); and every argument type the emitter | ||
| // writes out (enum casts, typeof targets, typed nulls, nested array elements) must also be | ||
| // referenceable. | ||
| => SymbolReferenceabilityHelper.IsTypeReferenceableFrom(attributeClass, consumingAssembly) | ||
| && attribute.AttributeConstructor is { } constructor | ||
| && SymbolReferenceabilityHelper.IsMemberAccessibleFrom(constructor.DeclaredAccessibility, constructor.ContainingType, consumingAssembly) | ||
| && attribute.ConstructorArguments.All(argument => AreArgumentTypesReferenceable(argument, consumingAssembly)) | ||
| && attribute.NamedArguments.All(named => AreArgumentTypesReferenceable(named.Value, consumingAssembly)); | ||
|
|
||
| private static bool AreArgumentTypesReferenceable(TypedConstant constant, IAssemblySymbol consumingAssembly) | ||
| => constant.Kind switch | ||
| { | ||
| TypedConstantKind.Array => constant.Values.All(element => AreArgumentTypesReferenceable(element, consumingAssembly)), | ||
|
|
||
| // typeof(X): the target type must be referenceable. Non-named targets (arrays, type | ||
| // parameters) are conservatively rejected. | ||
| TypedConstantKind.Type => constant.Value is null | ||
| || (constant.Value is INamedTypeSymbol typeofTarget && SymbolReferenceabilityHelper.IsTypeReferenceableFrom(typeofTarget, consumingAssembly)), | ||
|
|
||
| // Enum casts and typed nulls emit a `(Type)` cast, so the constant's declared type must be | ||
| // referenceable. Untyped values (Type is null) are plain literals. | ||
| _ => constant.Type is not INamedTypeSymbol namedType | ||
| || SymbolReferenceabilityHelper.IsTypeReferenceableFrom(namedType, consumingAssembly), | ||
| }; | ||
|
|
||
| internal static TypedConstantModel ToModel(TypedConstant constant) | ||
| => constant switch | ||
| { | ||
| { IsNull: true } => new TypedConstantModel( | ||
| ConstantValueKind.Null, | ||
| constant.Type?.ToDisplayString(SymbolDisplayFormats.FullyQualified), | ||
| null, | ||
| EquatableArray<TypedConstantModel>.Empty), | ||
| { Kind: TypedConstantKind.Array } => new TypedConstantModel( | ||
| ConstantValueKind.Array, | ||
| constant.Type?.ToDisplayString(SymbolDisplayFormats.FullyQualified), | ||
| null, | ||
| constant.Values.Select(ToModel).ToEquatableArray()), | ||
| { Kind: TypedConstantKind.Enum } => new TypedConstantModel( | ||
| ConstantValueKind.Enum, | ||
| constant.Type?.ToDisplayString(SymbolDisplayFormats.FullyQualified), | ||
| constant.Value, | ||
| EquatableArray<TypedConstantModel>.Empty), | ||
| { Kind: TypedConstantKind.Type } => new TypedConstantModel( | ||
| ConstantValueKind.Type, | ||
| (constant.Value as ITypeSymbol)?.ToDisplayString(SymbolDisplayFormats.FullyQualified), | ||
| null, | ||
| EquatableArray<TypedConstantModel>.Empty), | ||
| _ => new TypedConstantModel( | ||
| ConstantValueKind.Primitive, | ||
| constant.Type?.ToDisplayString(SymbolDisplayFormats.FullyQualified), | ||
| constant.Value, | ||
| EquatableArray<TypedConstantModel>.Empty), | ||
| }; | ||
| } | ||
74 changes: 74 additions & 0 deletions
74
src/Analyzers/MSTest.SourceGeneration/Generators/DataRowBuilder.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
|
Evangelink marked this conversation as resolved.
|
||
| // Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
|
||
| using System.Collections.Immutable; | ||
|
|
||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.SourceGeneration.Helpers; | ||
| using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.SourceGeneration.Models; | ||
|
|
||
| using MSTest.Analyzers.Shared; | ||
|
|
||
| namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.SourceGeneration.Generators; | ||
|
|
||
| /// <summary> | ||
| /// Parses <c>[DataRow(...)]</c> applications on a test method into flat <see cref="DataRowModel"/> rows the | ||
| /// emitter can consume. | ||
| /// </summary> | ||
| internal static class DataRowBuilder | ||
| { | ||
| // Walks the attribute list and reifies each [DataRow(...)] application into a flat | ||
| // object?[] row. Mirrors DataRowAttribute's runtime behavior: when the constructor uses | ||
| // the variadic overload (object? data1, params object?[] moreData), Roslyn surfaces the | ||
| // tail as a single Array TypedConstant, which we flatten back so the consumer sees the | ||
| // same shape as DataRowAttribute.Data. | ||
| internal static EquatableArray<DataRowModel> BuildDataRows(ImmutableArray<AttributeData> attributes) | ||
| { | ||
| if (attributes.IsDefaultOrEmpty) | ||
| { | ||
| return EquatableArray<DataRowModel>.Empty; | ||
| } | ||
|
|
||
| ImmutableArray<DataRowModel>.Builder builder = ImmutableArray.CreateBuilder<DataRowModel>(); | ||
| foreach (AttributeData attribute in attributes) | ||
| { | ||
| if (attribute.AttributeClass is not { } attributeClass) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| if (attributeClass.ToDisplayString(SymbolDisplayFormats.FullyQualified) != "global::" + MSTestAttributeNames.DataRow) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| ImmutableArray<TypedConstant> ctorArgs = attribute.ConstructorArguments; | ||
| ImmutableArray<TypedConstantModel>.Builder rowBuilder = ImmutableArray.CreateBuilder<TypedConstantModel>(); | ||
|
|
||
| bool lastIsParamsArray = | ||
| attribute.AttributeConstructor is { Parameters: { IsDefaultOrEmpty: false } parameters } | ||
| && parameters[parameters.Length - 1].IsParams | ||
| && !ctorArgs.IsDefaultOrEmpty | ||
| && ctorArgs[ctorArgs.Length - 1].Kind == TypedConstantKind.Array; | ||
|
|
||
| for (int i = 0; i < ctorArgs.Length; i++) | ||
| { | ||
| if (i == ctorArgs.Length - 1 && lastIsParamsArray) | ||
| { | ||
| foreach (TypedConstant element in ctorArgs[i].Values) | ||
| { | ||
| rowBuilder.Add(AttributeMaterializationHelper.ToModel(element)); | ||
| } | ||
| } | ||
| else | ||
| { | ||
| rowBuilder.Add(AttributeMaterializationHelper.ToModel(ctorArgs[i])); | ||
| } | ||
| } | ||
|
|
||
| builder.Add(new DataRowModel(new EquatableArray<TypedConstantModel>(rowBuilder.ToImmutable()))); | ||
| } | ||
|
|
||
| return new EquatableArray<DataRowModel>(builder.ToImmutable()); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.