From e8b4e3ed58917ec1cc038a0cfa134369ef6edd6b Mon Sep 17 00:00:00 2001 From: Sven Boemer Date: Wed, 2 Jul 2025 17:47:22 +0000 Subject: [PATCH 1/6] Fix formatting in ILLink - Format ILCompiler.TrimmingTests - Fix ILLink.RoslynAnalyzer generated tests - Fix whitespace in comments and #if'd out code - Remove suppression for spacing around keywords --- .../Extensions/CecilExtensions.cs | 717 ++-- .../Extensions/NiceIO.cs | 1698 ++++---- .../TestCases/TestCase.cs | 193 +- .../TestCases/TestDatabase.cs | 222 +- .../TestCases/TestSuites.cs | 299 +- .../TestCasesRunner/AssemblyChecker.cs | 3402 ++++++++------- .../TestCasesRunner/AssemblyQualifiedToken.cs | 75 +- .../TestCasesRunner/ILCompilerOptions.cs | 32 +- .../ILCompilerTestPInvokePolicy.cs | 16 +- .../TestCasesRunner/ILInputCompiler.cs | 117 +- .../MemberAssertionsCollector.cs | 368 +- .../TestCasesRunner/NameUtils.cs | 129 +- .../TestCasesRunner/ResultChecker.cs | 987 +++-- .../TestCasesRunner/TestCaseCollector.cs | 292 +- .../TestCaseCompilationMetadataProvider.cs | 494 ++- .../TestCasesRunner/TestCaseCompiler.cs | 777 ++-- .../TestCasesRunner/TestCaseLinkerOptions.cs | 56 +- .../TestCaseMetadataProvider.cs | 277 +- .../TestCasesRunner/TestCaseSandbox.cs | 24 +- ...estInfraMultiFileCompilationModuleGroup.cs | 93 +- .../TestCasesRunner/TestRunner.cs | 92 +- .../TestCasesRunner/TrimmedTestCaseResult.cs | 54 +- .../TrimmingArgumentBuilder.cs | 573 +-- .../TestCasesRunner/TrimmingCustomizations.cs | 6 +- .../TestCasesRunner/TrimmingDriver.cs | 388 +- .../TestCasesRunner/TrimmingTestLogger.cs | 87 +- .../DocumentationSignatureParserTests.cs | 1084 ++--- .../InteropServices/LibraryImportAttribute.cs | 6 +- src/tools/illink/.editorconfig | 3 - .../illink/external/Mono.Options/Options.cs | 3270 +++++++------- ...namicallyAccessedMembersCodeFixProvider.cs | 22 +- ...nditionalSuppressMessageCodeFixProvider.cs | 2 +- .../DataFlow/FeatureChecksValue.cs | 2 +- .../DataFlow/LocalDataFlowVisitor.cs | 12 +- .../TrimAnalysis/ReflectionAccessAnalyzer.cs | 4 +- .../TrimAnalysis/HandleCallAction.cs | 174 +- .../ILLink.Shared/TrimAnalysis/Intrinsics.cs | 208 +- .../LinkerAnalyzerCore/DependencyGraph.cs | 10 +- .../Linker.Dataflow/CompilerGeneratedState.cs | 8 +- .../Linker.Dataflow/MethodBodyScanner.cs | 4 +- .../Linker.Steps/LinkAttributesParser.cs | 6 +- .../src/linker/Linker.Steps/MarkStep.cs | 2 +- .../src/linker/Linker/DynamicDependency.cs | 2 +- .../src/linker/Linker/TypeNameResolver.cs | 3 +- src/tools/illink/src/tlens/README.md | 14 +- src/tools/illink/src/tlens/TLens/Driver.cs | 16 +- .../src/tlens/TLens/LensesCollection.cs | 52 +- .../TestCaseGenerator.cs | 18 +- ...DynamicallyAccessedMembersAnalyzerTests.cs | 1756 ++++---- .../DynamicallyAccessedMembersCodeFixTests.cs | 3776 ++++++++--------- .../RequiresAssemblyFilesAnalyzerTests.cs | 980 ++--- .../RequiresDynamicCodeAnalyzerTests.cs | 590 +-- .../RequiresUnreferencedCodeAnalyzerTests.cs | 576 +-- .../TestChecker.cs | 2 +- ...nconditionalSuppressMessageCodeFixTests.cs | 142 +- .../AdvancedTests.g.cs | 36 +- .../Attributes.CscTests.g.cs | 228 +- ...ibutes.Debugger.KeepDebugMembersTests.g.cs | 180 +- .../Attributes.DebuggerTests.g.cs | 108 +- .../Attributes.NoSecurityTests.g.cs | 38 +- .../Attributes.OnlyKeepUsedTests.g.cs | 384 +- .../Attributes.StructLayoutTests.g.cs | 48 +- .../AttributesTests.g.cs | 348 +- .../BCLFeatures.ETWTests.g.cs | 28 +- .../BCLFeaturesTests.g.cs | 18 +- .../BasicTests.g.cs | 348 +- .../CodegenAnnotationTests.g.cs | 18 +- .../CommandLine.MvidTests.g.cs | 48 +- .../CommandLineTests.g.cs | 84 +- .../ComponentModelTests.g.cs | 38 +- .../CoreLinkTests.g.cs | 118 +- .../CppCLITests.g.cs | 28 +- .../DataFlowTests.g.cs | 104 +- .../DynamicDependenciesTests.g.cs | 228 +- .../ExtensibilityTests.g.cs | 108 +- .../FeatureSettingsTests.g.cs | 48 +- .../FunctionPointersTests.g.cs | 28 +- .../GenericsTests.g.cs | 200 +- ...asses.NoKeptCtor.OverrideRemovalTests.g.cs | 98 +- ...ance.AbstractClasses.NotKeptCtorTests.g.cs | 84 +- .../Inheritance.AbstractClassesTests.g.cs | 108 +- .../Inheritance.Complex.NoKeptCtorTests.g.cs | 28 +- ...es.BaseProvidesInterfaceEdgeCaseTests.g.cs | 18 +- ...terfaces.DefaultInterfaceMethodsTests.g.cs | 118 +- ...Type.BaseProvidesInterfaceMemberTests.g.cs | 360 +- ...s.OnReferenceType.NoInstanceCtorTests.g.cs | 96 +- ...ype.NoKeptCtorButInterfaceNeededTests.g.cs | 288 +- ...faces.OnReferenceType.NoKeptCtorTests.g.cs | 240 +- ...tance.Interfaces.OnReferenceTypeTests.g.cs | 360 +- ...nterfaces.OnValueType.NoKeptCtorTests.g.cs | 48 +- ...heritance.Interfaces.OnValueTypeTests.g.cs | 108 +- ...e.Interfaces.RecursiveInterfacesTests.g.cs | 48 +- ...nterfaces.StaticInterfaceMethodsTests.g.cs | 46 +- .../Inheritance.InterfacesTests.g.cs | 84 +- ...tance.VirtualMethods.NotKeptCtorTests.g.cs | 18 +- .../Inheritance.VirtualMethodsTests.g.cs | 108 +- .../InteropTests.g.cs | 18 +- .../LibrariesTests.g.cs | 168 +- .../LinkAttributesTests.g.cs | 104 +- .../LinkXmlTests.g.cs | 444 +- .../LinqExpressionsTests.g.cs | 84 +- .../LoggingTests.g.cs | 28 +- .../MetadataTests.g.cs | 96 +- .../PreserveDependenciesTests.g.cs | 192 +- .../References.DependenciesTests.g.cs | 18 +- .../References.IndividualTests.g.cs | 18 +- .../ReferencesTests.g.cs | 168 +- .../ReflectionTests.g.cs | 116 +- .../ReproTests.g.cs | 18 +- .../ResourcesTests.g.cs | 118 +- .../SealerTests.g.cs | 28 +- .../SerializationTests.g.cs | 96 +- .../SingleFileTests.g.cs | 18 +- .../Statics.DisableBeforeFieldInitTests.g.cs | 18 +- .../StaticsTests.g.cs | 84 +- .../SubstitutionsTests.g.cs | 176 +- .../SymbolsTests.g.cs | 456 +- .../TestFrameworkTests.g.cs | 204 +- .../TopLevelStatementsTests.g.cs | 16 +- .../Tracing.DependencyRecorderTests.g.cs | 18 +- .../Tracing.IndividualTests.g.cs | 48 +- .../TypeForwardingTests.g.cs | 516 +-- .../UnreachableBlockTests.g.cs | 236 +- .../UnreachableBodyTests.g.cs | 384 +- .../Warnings.DependenciesTests.g.cs | 28 +- .../Warnings.IndividualTests.g.cs | 48 +- .../Warnings.WarningSuppressionTests.g.cs | 248 +- .../WarningsTests.g.cs | 224 +- .../CombineLinkerXmlFilesTests.cs | 4 +- .../ILLink.Tasks.Tests/ILLink.Tasks.Tests.cs | 102 +- .../illink/test/ILLink.Tasks.Tests/Mock.cs | 2 +- .../Assertions/RemovedOverrideAttribute.cs | 2 +- .../Helpers/PlatformAssemblies.cs | 2 +- .../Metadata/SetupLinkerArgumentAttribute.cs | 2 +- .../RemoveAttributeInstancesAttribute.cs | 2 +- ...layAttributeOnTypeWithNonExistentMethod.cs | 8 +- .../AssemblyAttributeAccessesMembers.cs | 4 +- .../Attributes/BoxedValues.cs | 12 +- .../CoreLibraryAssemblyAttributesAreKept.cs | 4 +- .../Attributes/Dependencies/IVTUnused_Lib.cs | 4 +- .../Attributes/Dependencies/IVTUsed_Lib.cs | 2 +- ...braryUnusedAssemblyAttributesAreRemoved.cs | 2 +- ...oreLibraryUsedAssemblyAttributesAreKept.cs | 2 +- ...sedAttributeOnGenericParameterIsRemoved.cs | 4 +- .../UnusedAttributeOnReturnTypeIsRemoved.cs | 8 +- .../Dependencies/CustomStepDummy.cs | 14 +- .../Dependencies/CustomStepUser.cs | 16 +- .../TypeDescriptionProviderAttributeOnType.cs | 4 +- .../Dependencies/CallCppCLIFromManaged.cs | 14 +- .../DataFlow/ArrayDataFlow.cs | 18 +- .../DataFlow/AttributeConstructorDataflow.cs | 20 +- .../DataFlow/ByRefDataflow.cs | 24 +- .../DataFlow/ConstructedTypesDataFlow.cs | 10 +- .../DataFlow/DynamicObjects.cs | 14 +- .../DataFlow/ExceptionalDataFlow.cs | 2 +- .../DataFlow/ExponentialDataFlow.cs | 40 +- .../DataFlow/FeatureGuardAttributeDataFlow.cs | 2 +- .../DataFlow/FieldDataFlow.cs | 8 +- .../DataFlow/GenericParameterDataFlow.cs | 2 +- .../DataFlow/IReflectDataflow.cs | 4 +- .../DataFlow/LocalDataFlow.cs | 2 +- .../DataFlow/MemberTypes.cs | 6 +- .../DataFlow/MethodParametersDataFlow.cs | 24 +- .../DataFlow/MethodReturnParameterDataFlow.cs | 6 +- .../DataFlow/MethodThisDataFlow.cs | 14 +- .../DataFlow/ModifierDataFlow.cs | 14 +- .../DataFlow/NullableAnnotations.cs | 2 +- .../DataFlow/PropertyDataFlow.cs | 2 +- .../DataFlow/StaticInterfaceMethodDataflow.cs | 2 +- .../DataFlow/TypeInfoIntrinsics.cs | 18 +- .../DataFlow/UnresolvedMembers.cs | 6 +- ...odHierarchyDataflowAnnotationValidation.cs | 54 +- ...ributeXmlOnNonReferencedAssemblyLibrary.cs | 2 +- .../Dependencies/FacadeAssembly.cs | 4 +- .../DynamicDependencyFromAttributeXml.cs | 2 +- ...FromAttributeXmlOnNonReferencedAssembly.cs | 2 +- .../DynamicDependencyMethod.cs | 76 +- ...onReferencedAssemblyWithSweptReferences.cs | 2 +- .../CustomStepCanFixAbstractMethods.cs | 8 +- .../Dependencies/CustomMarkHandler.cs | 84 +- .../CustomStepsWithSharedState.cs | 88 +- .../Dependencies/CustomSubStep.cs | 10 +- .../Dependencies/CustomSubStepFields.cs | 10 +- .../Dependencies/CustomWarning.cs | 22 +- .../Dependencies/FixAbstractMethods.cs | 54 +- .../Dependencies/InterfaceType.cs | 4 +- .../Dependencies/MyDispatcher.cs | 16 +- .../Dependencies/MyMarkSubStepsDispatcher.cs | 24 +- .../Dependencies/PreserveMethodsSubStep.cs | 68 +- .../Dependencies/ResolveTypesSubStep.cs | 46 +- .../DimProvidedByRecursiveInterface.cs | 66 +- .../InterfaceWithAttributeOnImplementation.cs | 2 +- ...ultipleDimsProvidedByRecursiveInterface.cs | 100 +- ...mProvidedByUnreferencedIfaceInHierarchy.cs | 70 +- ...nterfaceImplementedThroughBaseInterface.cs | 2 +- ...dTypePreserveFieldsWithInterfacesMarked.cs | 2 +- ...TypePreserveMethodsWithInterfacesMarked.cs | 2 +- .../GenericInterfaceImplementedRecursively.cs | 18 +- .../InterfaceImplementedRecursively.cs | 18 +- .../OverrideOfRecursiveInterfaceIsRemoved.cs | 4 +- .../RecursiveInterfaceKept.cs | 18 +- .../Dependencies/CustomStepSaveAssembly.cs | 4 +- .../InstanceMethodsWithOverridesSwept.cs | 76 +- .../OverrideInCopyAssembly.cs | 12 +- .../OverrideInSaveAssembly.cs | 12 +- .../StaticAbstractInterfaceMethods.cs | 4 +- ...IfImplementingMethodGetsInvokedDirectly.cs | 2 +- .../Libraries/Dependencies/RootAllLibrary.cs | 2 +- .../Libraries/RootLibraryInternalsWithIVT.cs | 16 +- .../Libraries/RootLibraryVisibleForwarders.cs | 2 +- ...ibraryVisibleForwardersWithoutReference.cs | 2 +- .../LinkAttributes/LinkerAttributeRemoval.cs | 6 +- .../LinkerAttributeRemovalConditional.cs | 2 +- .../OverrideAttributeRemoval.cs | 4 +- .../CanPreserveAnExportedType_Forwarder.cs | 2 +- ...equiredExportedTypeIsKeptWhenRooted_fwd.cs | 2 +- .../UsedNonRequiredExportedTypeIsKept_fwd.cs | 6 +- .../Logging/Dependencies/LogStep.cs | 28 +- .../PreserveDependencyDeprecated.cs | 8 +- .../PreserveDependencyMethod.cs | 8 +- .../CustomMarkHandlerSaveAssembly.cs | 6 +- .../Reflection/ActivatorCreateInstance.cs | 12 +- ...mportedViaReflectionWithSweptReferences.cs | 2 +- .../ConstructorUsedViaReflection.cs | 2 +- .../Dependencies/CoreLibEmulator.cs | 78 +- .../EventHanderTypeGetInvokeMethod.cs | 164 +- .../Reflection/MemberUsedViaReflection.cs | 14 +- .../Reflection/MembersUsedViaReflection.cs | 14 +- .../Reflection/ObjectGetType.cs | 2 +- .../Reflection/TypeDelegator.cs | 4 +- .../TypeHierarchyReflectionWarnings.cs | 12 +- .../Reflection/TypeHierarchySuppressions.cs | 12 +- .../RequiresInCompilerGeneratedCode.cs | 2 +- .../RequiresCapability/RequiresOnClass.cs | 4 +- .../RequiresWithCopyAssembly.cs | 2 +- .../Dependencies/TestFeatures.cs | 10 +- .../FeatureGuardSubstitutions.cs | 10 +- .../FeatureGuardSubstitutionsDisabled.cs | 2 +- ...ReferenceWithPdbAndSymbolLinkingEnabled.cs | 2 +- ...ymbolLinkingEnabledAndDeterministicMvid.cs | 2 +- ...ithPdbAndSymbolLinkingEnabledAndNewMvid.cs | 2 +- ...ithPdbCopyActionAndSymbolLinkingEnabled.cs | 2 +- ...MixedSymbolTypesAndSymbolLinkingEnabled.cs | 2 +- ...mbolTypesWithMdbAndSymbolLinkingEnabled.cs | 2 +- .../TestFramework/CanCompileILAssembly.cs | 2 +- .../CanCompileTestCaseWithCsc.cs | 2 +- .../CanCompileTestCaseWithMcs.cs | 2 +- .../TestFramework/ILVerificationWorks.cs | 2 +- .../VerifyDefineAttributeBehavior.cs | 2 +- .../BasicDataFlow/Program.cs | 8 +- .../InvalidAnnotations/Program.cs | 4 +- .../AttributeArgumentForwarded.cs | 12 +- .../Dependencies/AnotherLibraryForwarder.cs | 2 +- .../AnotherLibraryReferenceImplementation.cs | 8 +- .../Dependencies/AttributeWithEnumArgument.cs | 2 +- .../ForwardedNestedTypeLibrary.cs | 20 +- .../Dependencies/ForwarderLibrary.cs | 4 +- .../ForwarderLibraryWithUnusedReference.cs | 4 +- .../Dependencies/ForwarderLibrary_2.cs | 4 +- .../Dependencies/ForwarderLibrary_3.cs | 10 +- .../Dependencies/ImplementationLibrary.cs | 2 +- .../Dependencies/ImplementationLibrary_3.cs | 12 +- .../Dependencies/MyEnumForwarder.cs | 2 +- .../ReferenceImplementationLibrary.cs | 92 +- ...renceImplementationUsedAndUnusedLibrary.cs | 14 +- ...TypeForwardedIsUpdatedForMissingTypeFwd.cs | 2 +- .../TypeForwardersModifiersLibFwd.cs | 2 +- .../TypeForwardersRewriteForwarders.cs | 8 +- .../TypeForwarding/MissingTargetReference.cs | 2 +- .../TypeForwarding/SecurityAttributeScope.cs | 2 +- .../TypeForwarding/TypeForwardersModifiers.cs | 2 +- ...DynamicallyAccessedWithAssemblyCopyUsed.cs | 2 +- ...DynamicallyAccessedWithAssemblyCopyUsed.cs | 2 +- ...rderInCopyAssemblyIsDynamicallyAccessed.cs | 2 +- ...InCopyUsedAssemblyIsDynamicallyAccessed.cs | 2 +- ...ransitiveForwarderIsDynamicallyAccessed.cs | 2 +- .../UnreachableBlock/ComplexConditions.cs | 4 +- .../UnreachableBlock/EndScopeOnMethoEnd.cs | 4 +- .../MethodWithParametersSubstitutions.cs | 44 +- .../UnreachableBlock/SizeOfInConditions.cs | 2 +- .../UnreachableBlock/UninitializedLocals.cs | 4 +- .../DoesNotApplyToCopiedAssembly2.cs | 12 +- .../LinkedOtherIncludedLibrary.cs | 2 +- ...inkedOtherIncludedLibraryNoInstanceCtor.cs | 14 +- .../Warnings/CanDisableWarningsByCategory.cs | 2 +- .../Warnings/CanWarnAsErrorGlobal.cs | 22 +- .../Warnings/Dependencies/CustomStep.cs | 56 +- ...CanGenerateWarningSuppressionFileCSharp.cs | 4 +- .../CanGenerateWarningSuppressionFileXml.cs | 2 +- .../Warnings/Individual/WarningsAreSorted.cs | 2 +- ...MultipleMethodsUseSameAsyncStateMachine.cs | 2 +- .../SuppressWarningsInAssembly.cs | 2 +- .../SuppressWarningsInCopyAssembly.cs | 2 +- .../SuppressWarningsInMembersAndTypes.cs | 2 +- ...essWarningsInMembersAndTypesUsingTarget.cs | 2 +- .../SuppressWarningsInModule.cs | 2 +- .../TestCasesRunner/AssemblyChecker.cs | 24 +- .../TestCasesRunner/ILCompiler.cs | 6 +- .../ILVerification/ILChecker.cs | 2 +- .../TestCasesRunner/TestCaseCompiler.cs | 4 +- .../TrimmingArgumentBuilder.cs | 8 +- .../DocumentationSignatureParserTests.cs | 8 +- 302 files changed, 18286 insertions(+), 17804 deletions(-) diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Extensions/CecilExtensions.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Extensions/CecilExtensions.cs index 5e4dc5ffa1e137..5afa83d0a8957f 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Extensions/CecilExtensions.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Extensions/CecilExtensions.cs @@ -10,355 +10,376 @@ namespace Mono.Linker.Tests.Extensions { - public static class CecilExtensions - { - public static IEnumerable AllDefinedTypes (this AssemblyDefinition assemblyDefinition) - { - return assemblyDefinition.Modules.SelectMany (m => m.AllDefinedTypes ()); - } - - public static IEnumerable AllDefinedTypes (this ModuleDefinition moduleDefinition) - { - foreach (var typeDefinition in moduleDefinition.Types) { - yield return typeDefinition; - - foreach (var definition in typeDefinition.AllDefinedTypes ()) - yield return definition; - } - } - - public static IEnumerable AllDefinedTypes (this TypeDefinition typeDefinition) - { - foreach (var nestedType in typeDefinition.NestedTypes) { - yield return nestedType; - - foreach (var definition in nestedType.AllDefinedTypes ()) - yield return definition; - } - } - - public static IEnumerable AllMembers (this ModuleDefinition module) - { - foreach (var type in module.AllDefinedTypes ()) { - yield return type; - - foreach (var member in type.AllMembers ()) - yield return member; - } - } - - public static IEnumerable AllMembers (this TypeDefinition type) - { - foreach (var field in type.Fields) - yield return field; - - foreach (var prop in type.Properties) - yield return prop; - - foreach (var method in type.Methods) - yield return method; - - foreach (var @event in type.Events) - yield return @event; - } - - public static IEnumerable AllMethods (this TypeDefinition type) - { - foreach (var m in type.AllMembers ()) { - switch (m) { - case MethodDefinition method: - yield return method; - break; - case PropertyDefinition @property: - if (@property.GetMethod != null) - yield return @property.GetMethod; - - if (@property.SetMethod != null) - yield return @property.SetMethod; - - break; - case EventDefinition @event: - if (@event.AddMethod != null) - yield return @event.AddMethod; - - if (@event.RemoveMethod != null) - yield return @event.RemoveMethod; - - break; - - default: - break; - } - } - } - - public static bool HasAttribute (this ICustomAttributeProvider provider, string name) - { - return provider.CustomAttributes.Any (ca => ca.AttributeType.Name == name); - } - - public static bool HasAttributeDerivedFrom (this ICustomAttributeProvider provider, string name) - { - return provider.CustomAttributes.Any (ca => ca.AttributeType.Resolve ().DerivesFrom (name)); - } - - public static bool DerivesFrom (this TypeDefinition type, string baseTypeName) - { - if (type.Name == baseTypeName) - return true; - - if (type.BaseType == null) - return false; - - if (type.BaseType.Name == baseTypeName) - return true; - - return type.BaseType.Resolve ()?.DerivesFrom (baseTypeName) ?? false; - } - - public static PropertyDefinition GetPropertyDefinition (this MethodDefinition method) - { - if (!method.IsSetter && !method.IsGetter) + public static class CecilExtensions + { + public static IEnumerable AllDefinedTypes(this AssemblyDefinition assemblyDefinition) + { + return assemblyDefinition.Modules.SelectMany(m => m.AllDefinedTypes()); + } + + public static IEnumerable AllDefinedTypes(this ModuleDefinition moduleDefinition) + { + foreach (var typeDefinition in moduleDefinition.Types) + { + yield return typeDefinition; + + foreach (var definition in typeDefinition.AllDefinedTypes()) + yield return definition; + } + } + + public static IEnumerable AllDefinedTypes(this TypeDefinition typeDefinition) + { + foreach (var nestedType in typeDefinition.NestedTypes) + { + yield return nestedType; + + foreach (var definition in nestedType.AllDefinedTypes()) + yield return definition; + } + } + + public static IEnumerable AllMembers(this ModuleDefinition module) + { + foreach (var type in module.AllDefinedTypes()) + { + yield return type; + + foreach (var member in type.AllMembers()) + yield return member; + } + } + + public static IEnumerable AllMembers(this TypeDefinition type) + { + foreach (var field in type.Fields) + yield return field; + + foreach (var prop in type.Properties) + yield return prop; + + foreach (var method in type.Methods) + yield return method; + + foreach (var @event in type.Events) + yield return @event; + } + + public static IEnumerable AllMethods(this TypeDefinition type) + { + foreach (var m in type.AllMembers()) + { + switch (m) + { + case MethodDefinition method: + yield return method; + break; + case PropertyDefinition @property: + if (@property.GetMethod != null) + yield return @property.GetMethod; + + if (@property.SetMethod != null) + yield return @property.SetMethod; + + break; + case EventDefinition @event: + if (@event.AddMethod != null) + yield return @event.AddMethod; + + if (@event.RemoveMethod != null) + yield return @event.RemoveMethod; + + break; + + default: + break; + } + } + } + + public static bool HasAttribute(this ICustomAttributeProvider provider, string name) + { + return provider.CustomAttributes.Any(ca => ca.AttributeType.Name == name); + } + + public static bool HasAttributeDerivedFrom(this ICustomAttributeProvider provider, string name) + { + return provider.CustomAttributes.Any(ca => ca.AttributeType.Resolve().DerivesFrom(name)); + } + + public static bool DerivesFrom(this TypeDefinition type, string baseTypeName) + { + if (type.Name == baseTypeName) + return true; + + if (type.BaseType == null) + return false; + + if (type.BaseType.Name == baseTypeName) + return true; + + return type.BaseType.Resolve()?.DerivesFrom(baseTypeName) ?? false; + } + + public static PropertyDefinition GetPropertyDefinition(this MethodDefinition method) + { + if (!method.IsSetter && !method.IsGetter) #pragma warning disable CA2208 // Instantiate argument exceptions correctly - throw new ArgumentException (); + throw new ArgumentException(); #pragma warning restore CA2208 // Instantiate argument exceptions correctly - var propertyName = method.Name.Substring (4); - return method.DeclaringType.Properties.First (p => p.Name == propertyName); - } - - public static string GetSignature (this MethodDefinition method) - { - var builder = new StringBuilder (); - builder.Append (method.Name); - if (method.HasGenericParameters) { - builder.Append ($"<#{method.GenericParameters.Count}>"); - } - - builder.Append ('('); - - if (method.HasParameters) { - for (int i = 0; i < method.Parameters.Count - 1; i++) { - // TODO: modifiers - // TODO: default values - builder.Append ($"{method.Parameters[i].ParameterType},"); - } - - builder.Append (method.Parameters[method.Parameters.Count - 1].ParameterType); - } - - builder.Append (')'); - - return builder.ToString (); - } - - public static object GetConstructorArgumentValue (this CustomAttribute attr, int argumentIndex) - { - return attr.ConstructorArguments[argumentIndex].Value; - } - - public static object? GetPropertyValue (this CustomAttribute attr, string propertyName) - { - foreach (var prop in attr.Properties) - if (prop.Name == propertyName) - return prop.Argument.Value; - - return null; - } - - public static bool IsEventMethod (this MethodDefinition md) - { - return (md.SemanticsAttributes & MethodSemanticsAttributes.AddOn) != 0 || - (md.SemanticsAttributes & MethodSemanticsAttributes.Fire) != 0 || - (md.SemanticsAttributes & MethodSemanticsAttributes.RemoveOn) != 0; - } - - public static string GetDisplayName (this MethodReference method) - { - var sb = new System.Text.StringBuilder (); - - // Match C# syntaxis name if setter or getter - var methodDefinition = method.Resolve (); - if (methodDefinition != null && (methodDefinition.IsSetter || methodDefinition.IsGetter)) { - // Append property name - string name = GetPropertyNameFromAccessorName (methodDefinition.Name, methodDefinition.IsSetter); - sb.Append (name); - // Insert declaring type name and namespace - sb.Insert (0, '.').Insert (0, method.DeclaringType?.GetDisplayName ()); - return sb.ToString (); - } - - if (methodDefinition != null && methodDefinition.IsEventMethod ()) { - // Append event name - string name = methodDefinition.SemanticsAttributes switch { - MethodSemanticsAttributes.AddOn => string.Concat (methodDefinition.Name.AsSpan (4), ".add"), - MethodSemanticsAttributes.RemoveOn => string.Concat (methodDefinition.Name.AsSpan (7), ".remove"), - MethodSemanticsAttributes.Fire => string.Concat (methodDefinition.Name.AsSpan (6), ".raise"), - _ => throw new NotSupportedException (), - }; - sb.Append (name); - // Insert declaring type name and namespace - sb.Insert (0, '.').Insert (0, method.DeclaringType.GetDisplayName ()); - return sb.ToString (); - } - - // Append parameters - sb.Append ('('); - if (method.HasParameters) { - for (int i = 0; i < method.Parameters.Count - 1; i++) - sb.Append (method.Parameters[i].ParameterType.GetDisplayNameWithoutNamespace ()).Append (", "); - - sb.Append (method.Parameters[method.Parameters.Count - 1].ParameterType.GetDisplayNameWithoutNamespace ()); - } - - sb.Append (')'); - - // Insert generic parameters - if (method.HasGenericParameters) { - PrependGenericParameters (method.GenericParameters, sb); - } - - // Insert method name - if (method.Name == ".ctor") - sb.Insert (0, method.DeclaringType.Name); - else - sb.Insert (0, method.Name); - - // Insert declaring type name and namespace - if (method.DeclaringType != null) - sb.Insert (0, '.').Insert (0, method.DeclaringType.GetDisplayName ()); - - return sb.ToString (); - } - - private static string GetPropertyNameFromAccessorName (string methodName, bool isSetter) => - isSetter ? - string.Concat (methodName.StartsWith ("set_") ? methodName.AsSpan (4) : methodName.Replace (".set_", "."), ".set") : - string.Concat (methodName.StartsWith ("get_") ? methodName.AsSpan (4) : methodName.Replace (".get_", "."), ".get"); - - public static string GetDisplayName (this TypeReference type) - { - var builder = GetDisplayNameWithoutNamespace (type); - var namespaceDisplayName = type.GetNamespaceDisplayName (); - if (!string.IsNullOrEmpty (namespaceDisplayName)) { - builder.Insert (0, "."); - builder.Insert (0, namespaceDisplayName); - } - - return builder.ToString (); - } - - public static string GetDisplayName (this FieldReference field) - { - var builder = new StringBuilder (); - if (field.DeclaringType != null) { - builder.Append (field.DeclaringType.GetDisplayName ()); - builder.Append ('.'); - } - - builder.Append (field.Name); - - return builder.ToString (); - } - - public static string GetNamespaceDisplayName (this MemberReference member) - { - var type = member is TypeReference typeReference ? typeReference : member.DeclaringType; - while (type.DeclaringType != null) - type = type.DeclaringType; - - return type.Namespace; - } - - public static StringBuilder GetDisplayNameWithoutNamespace (this TypeReference type) - { - var sb = new StringBuilder (); - if (type == null) - return sb; - - Stack? genericArguments = null; - while (true) { - switch (type) { - case ArrayType arrayType: - AppendArrayType (arrayType, sb); - break; - case GenericInstanceType genericInstanceType: - genericArguments = new Stack (genericInstanceType.GenericArguments); - type = genericInstanceType.ElementType; - continue; - default: - if (type.HasGenericParameters) { - int genericParametersCount = type.GenericParameters.Count; - int declaringTypeGenericParametersCount = type.DeclaringType?.GenericParameters?.Count ?? 0; - - string simpleName; - if (genericParametersCount > declaringTypeGenericParametersCount) { - if (genericArguments?.Count > 0) - PrependGenericArguments (genericArguments, genericParametersCount - declaringTypeGenericParametersCount, sb); - else - PrependGenericParameters (type.GenericParameters.Skip (declaringTypeGenericParametersCount).ToList (), sb); - - int explicitArityIndex = type.Name.IndexOf ('`'); - simpleName = explicitArityIndex != -1 ? type.Name.Substring (0, explicitArityIndex) : type.Name; - } else - simpleName = type.Name; - - sb.Insert (0, simpleName); - break; - } - - sb.Insert (0, type.Name); - break; - } - - type = type.GetElementType (); - if (type.DeclaringType is not TypeReference declaringType) - break; - - type = declaringType; - - sb.Insert (0, '.'); - } - - return sb; - } - - public static void PrependGenericParameters (IList genericParameters, StringBuilder sb) - { - sb.Insert (0, '>').Insert (0, genericParameters[genericParameters.Count - 1]); - for (int i = genericParameters.Count - 2; i >= 0; i--) - sb.Insert (0, ',').Insert (0, genericParameters[i]); - - sb.Insert (0, '<'); - } - - private static void PrependGenericArguments (Stack genericArguments, int argumentsToTake, StringBuilder sb) - { - sb.Insert (0, '>').Insert (0, genericArguments.Pop ().GetDisplayNameWithoutNamespace ().ToString ()); - while (--argumentsToTake > 0) - sb.Insert (0, ',').Insert (0, genericArguments.Pop ().GetDisplayNameWithoutNamespace ().ToString ()); - - sb.Insert (0, '<'); - } - - private static void AppendArrayType (ArrayType arrayType, StringBuilder sb) - { - void parseArrayDimensions (ArrayType at) - { - sb.Append ('['); - for (int i = 0; i < at.Dimensions.Count - 1; i++) - sb.Append (','); - - sb.Append (']'); - } - - sb.Append (arrayType.Name.AsSpan (0, arrayType.Name.IndexOf ('['))); - parseArrayDimensions (arrayType); - var element = arrayType.ElementType as ArrayType; - while (element != null) { - parseArrayDimensions (element); - element = element.ElementType as ArrayType; - } - } - } + var propertyName = method.Name.Substring(4); + return method.DeclaringType.Properties.First(p => p.Name == propertyName); + } + + public static string GetSignature(this MethodDefinition method) + { + var builder = new StringBuilder(); + builder.Append(method.Name); + if (method.HasGenericParameters) + { + builder.Append($"<#{method.GenericParameters.Count}>"); + } + + builder.Append('('); + + if (method.HasParameters) + { + for (int i = 0; i < method.Parameters.Count - 1; i++) + { + // TODO: modifiers + // TODO: default values + builder.Append($"{method.Parameters[i].ParameterType},"); + } + + builder.Append(method.Parameters[method.Parameters.Count - 1].ParameterType); + } + + builder.Append(')'); + + return builder.ToString(); + } + + public static object GetConstructorArgumentValue(this CustomAttribute attr, int argumentIndex) + { + return attr.ConstructorArguments[argumentIndex].Value; + } + + public static object? GetPropertyValue(this CustomAttribute attr, string propertyName) + { + foreach (var prop in attr.Properties) + if (prop.Name == propertyName) + return prop.Argument.Value; + + return null; + } + + public static bool IsEventMethod(this MethodDefinition md) + { + return (md.SemanticsAttributes & MethodSemanticsAttributes.AddOn) != 0 || + (md.SemanticsAttributes & MethodSemanticsAttributes.Fire) != 0 || + (md.SemanticsAttributes & MethodSemanticsAttributes.RemoveOn) != 0; + } + + public static string GetDisplayName(this MethodReference method) + { + var sb = new System.Text.StringBuilder(); + + // Match C# syntaxis name if setter or getter + var methodDefinition = method.Resolve(); + if (methodDefinition != null && (methodDefinition.IsSetter || methodDefinition.IsGetter)) + { + // Append property name + string name = GetPropertyNameFromAccessorName(methodDefinition.Name, methodDefinition.IsSetter); + sb.Append(name); + // Insert declaring type name and namespace + sb.Insert(0, '.').Insert(0, method.DeclaringType?.GetDisplayName()); + return sb.ToString(); + } + + if (methodDefinition != null && methodDefinition.IsEventMethod()) + { + // Append event name + string name = methodDefinition.SemanticsAttributes switch + { + MethodSemanticsAttributes.AddOn => string.Concat(methodDefinition.Name.AsSpan(4), ".add"), + MethodSemanticsAttributes.RemoveOn => string.Concat(methodDefinition.Name.AsSpan(7), ".remove"), + MethodSemanticsAttributes.Fire => string.Concat(methodDefinition.Name.AsSpan(6), ".raise"), + _ => throw new NotSupportedException(), + }; + sb.Append(name); + // Insert declaring type name and namespace + sb.Insert(0, '.').Insert(0, method.DeclaringType.GetDisplayName()); + return sb.ToString(); + } + + // Append parameters + sb.Append('('); + if (method.HasParameters) + { + for (int i = 0; i < method.Parameters.Count - 1; i++) + sb.Append(method.Parameters[i].ParameterType.GetDisplayNameWithoutNamespace()).Append(", "); + + sb.Append(method.Parameters[method.Parameters.Count - 1].ParameterType.GetDisplayNameWithoutNamespace()); + } + + sb.Append(')'); + + // Insert generic parameters + if (method.HasGenericParameters) + { + PrependGenericParameters(method.GenericParameters, sb); + } + + // Insert method name + if (method.Name == ".ctor") + sb.Insert(0, method.DeclaringType.Name); + else + sb.Insert(0, method.Name); + + // Insert declaring type name and namespace + if (method.DeclaringType != null) + sb.Insert(0, '.').Insert(0, method.DeclaringType.GetDisplayName()); + + return sb.ToString(); + } + + private static string GetPropertyNameFromAccessorName(string methodName, bool isSetter) => + isSetter ? + string.Concat(methodName.StartsWith("set_") ? methodName.AsSpan(4) : methodName.Replace(".set_", "."), ".set") : + string.Concat(methodName.StartsWith("get_") ? methodName.AsSpan(4) : methodName.Replace(".get_", "."), ".get"); + + public static string GetDisplayName(this TypeReference type) + { + var builder = GetDisplayNameWithoutNamespace(type); + var namespaceDisplayName = type.GetNamespaceDisplayName(); + if (!string.IsNullOrEmpty(namespaceDisplayName)) + { + builder.Insert(0, "."); + builder.Insert(0, namespaceDisplayName); + } + + return builder.ToString(); + } + + public static string GetDisplayName(this FieldReference field) + { + var builder = new StringBuilder(); + if (field.DeclaringType != null) + { + builder.Append(field.DeclaringType.GetDisplayName()); + builder.Append('.'); + } + + builder.Append(field.Name); + + return builder.ToString(); + } + + public static string GetNamespaceDisplayName(this MemberReference member) + { + var type = member is TypeReference typeReference ? typeReference : member.DeclaringType; + while (type.DeclaringType != null) + type = type.DeclaringType; + + return type.Namespace; + } + + public static StringBuilder GetDisplayNameWithoutNamespace(this TypeReference type) + { + var sb = new StringBuilder(); + if (type == null) + return sb; + + Stack? genericArguments = null; + while (true) + { + switch (type) + { + case ArrayType arrayType: + AppendArrayType(arrayType, sb); + break; + case GenericInstanceType genericInstanceType: + genericArguments = new Stack(genericInstanceType.GenericArguments); + type = genericInstanceType.ElementType; + continue; + default: + if (type.HasGenericParameters) + { + int genericParametersCount = type.GenericParameters.Count; + int declaringTypeGenericParametersCount = type.DeclaringType?.GenericParameters?.Count ?? 0; + + string simpleName; + if (genericParametersCount > declaringTypeGenericParametersCount) + { + if (genericArguments?.Count > 0) + PrependGenericArguments(genericArguments, genericParametersCount - declaringTypeGenericParametersCount, sb); + else + PrependGenericParameters(type.GenericParameters.Skip(declaringTypeGenericParametersCount).ToList(), sb); + + int explicitArityIndex = type.Name.IndexOf('`'); + simpleName = explicitArityIndex != -1 ? type.Name.Substring(0, explicitArityIndex) : type.Name; + } + else + simpleName = type.Name; + + sb.Insert(0, simpleName); + break; + } + + sb.Insert(0, type.Name); + break; + } + + type = type.GetElementType(); + if (type.DeclaringType is not TypeReference declaringType) + break; + + type = declaringType; + + sb.Insert(0, '.'); + } + + return sb; + } + + public static void PrependGenericParameters(IList genericParameters, StringBuilder sb) + { + sb.Insert(0, '>').Insert(0, genericParameters[genericParameters.Count - 1]); + for (int i = genericParameters.Count - 2; i >= 0; i--) + sb.Insert(0, ',').Insert(0, genericParameters[i]); + + sb.Insert(0, '<'); + } + + private static void PrependGenericArguments(Stack genericArguments, int argumentsToTake, StringBuilder sb) + { + sb.Insert(0, '>').Insert(0, genericArguments.Pop().GetDisplayNameWithoutNamespace().ToString()); + while (--argumentsToTake > 0) + sb.Insert(0, ',').Insert(0, genericArguments.Pop().GetDisplayNameWithoutNamespace().ToString()); + + sb.Insert(0, '<'); + } + + private static void AppendArrayType(ArrayType arrayType, StringBuilder sb) + { + void parseArrayDimensions(ArrayType at) + { + sb.Append('['); + for (int i = 0; i < at.Dimensions.Count - 1; i++) + sb.Append(','); + + sb.Append(']'); + } + + sb.Append(arrayType.Name.AsSpan(0, arrayType.Name.IndexOf('['))); + parseArrayDimensions(arrayType); + var element = arrayType.ElementType as ArrayType; + while (element != null) + { + parseArrayDimensions(element); + element = element.ElementType as ArrayType; + } + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Extensions/NiceIO.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Extensions/NiceIO.cs index 791d6b4d408539..30e04ade65b183 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Extensions/NiceIO.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Extensions/NiceIO.cs @@ -35,829 +35,877 @@ namespace Mono.Linker.Tests.Extensions { - public class NPath : IEquatable, IComparable - { - private static readonly StringComparison PathStringComparison = IsLinux () ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; - - private readonly string[] _elements; - private readonly bool _isRelative; - private readonly string? _driveLetter; - - #region construction - - public NPath (string path) - { - ArgumentNullException.ThrowIfNull (path); - - path = ParseDriveLetter (path, out _driveLetter); - - if (path == "/") { - _isRelative = false; - _elements = Array.Empty (); - } else { - var split = path.Split ('/', '\\'); - - _isRelative = _driveLetter == null && IsRelativeFromSplitString (split); - - _elements = ParseSplitStringIntoElements (split.Where (s => s.Length > 0).ToArray ()); - } - } - - private NPath (string[] elements, bool isRelative, string? driveLetter) - { - _elements = elements; - _isRelative = isRelative; - _driveLetter = driveLetter; - } - - private string[] ParseSplitStringIntoElements (IEnumerable inputs) - { - var stack = new List (); - - foreach (var input in inputs.Where (input => input.Length != 0)) { - if (input == ".") { - if ((stack.Count > 0) && (stack.Last () != ".")) - continue; - } else if (input == "..") { - if (HasNonDotDotLastElement (stack)) { - stack.RemoveAt (stack.Count - 1); - continue; - } - if (!_isRelative) - throw new ArgumentException ("You cannot create a path that tries to .. past the root"); - } - stack.Add (input); - } - return stack.ToArray (); - } - - private static bool HasNonDotDotLastElement (List stack) - { - return stack.Count > 0 && stack[stack.Count - 1] != ".."; - } - - private static string ParseDriveLetter (string path, out string? driveLetter) - { - if (path.Length >= 2 && path[1] == ':') { - driveLetter = path[0].ToString (); - return path.Substring (2); - } - - driveLetter = null; - return path; - } - - private static bool IsRelativeFromSplitString (string[] split) - { - if (split.Length < 2) - return true; - - return split[0].Length != 0 || !split.Any (s => s.Length > 0); - } - - public NPath Combine (params string[] append) - { - return Combine (append.Select (a => new NPath (a)).ToArray ()); - } - - public NPath Combine (params NPath[] append) - { - if (!append.All (p => p.IsRelative)) - throw new ArgumentException ("You cannot .Combine a non-relative path"); - - return new NPath (ParseSplitStringIntoElements (_elements.Concat (append.SelectMany (p => p._elements))), _isRelative, _driveLetter); - } - - public NPath Parent { - get { - if (_elements.Length == 0) - throw new InvalidOperationException ("Parent is called on an empty path"); - - var newElements = _elements.Take (_elements.Length - 1).ToArray (); - - return new NPath (newElements, _isRelative, _driveLetter); - } - } - - public NPath RelativeTo (NPath path) - { - if (!IsChildOf (path)) { - if (!IsRelative && !path.IsRelative && _driveLetter != path._driveLetter) - throw new ArgumentException ("Path.RelativeTo() was invoked with two paths that are on different volumes. invoked on: " + ToString () + " asked to be made relative to: " + path); - - NPath? commonParent = null; - foreach (var parent in RecursiveParents) { - commonParent = path.RecursiveParents.FirstOrDefault (otherParent => otherParent == parent); - - if (commonParent != null) - break; - } - - if (commonParent == null) - throw new ArgumentException ("Path.RelativeTo() was unable to find a common parent between " + ToString () + " and " + path); - - if (IsRelative && path.IsRelative && commonParent.IsEmpty ()) - throw new ArgumentException ("Path.RelativeTo() was invoked with two relative paths that do not share a common parent. Invoked on: " + ToString () + " asked to be made relative to: " + path); - - var depthDiff = path.Depth - commonParent.Depth; - return new NPath (Enumerable.Repeat ("..", depthDiff).Concat (_elements.Skip (commonParent.Depth)).ToArray (), true, null); - } - - return new NPath (_elements.Skip (path._elements.Length).ToArray (), true, null); - } - - public NPath ChangeExtension (string extension) - { - ThrowIfRoot (); - - var newElements = (string[]) _elements.Clone (); - newElements[newElements.Length - 1] = Path.ChangeExtension (_elements[_elements.Length - 1], WithDot (extension)); - if (extension == string.Empty) - newElements[newElements.Length - 1] = newElements[newElements.Length - 1].TrimEnd ('.'); - return new NPath (newElements, _isRelative, _driveLetter); - } - #endregion construction - - #region inspection - - public bool IsRelative { - get { return _isRelative; } - } - - public string FileName { - get { - ThrowIfRoot (); - - return _elements.Last (); - } - } - - public string FileNameWithoutExtension { - get { return Path.GetFileNameWithoutExtension (FileName); } - } - - public IEnumerable Elements { - get { return _elements; } - } - - public int Depth { - get { return _elements.Length; } - } - - public bool Exists (string append = "") - { - return Exists (new NPath (append)); - } - - public bool Exists (NPath append) - { - return FileExists (append) || DirectoryExists (append); - } - - public bool DirectoryExists (string append = "") - { - return DirectoryExists (new NPath (append)); - } - - public bool DirectoryExists (NPath append) - { - return Directory.Exists (Combine (append).ToString ()); - } - - public bool FileExists (string append = "") - { - return FileExists (new NPath (append)); - } - - public bool FileExists (NPath append) - { - return File.Exists (Combine (append).ToString ()); - } - - public string ExtensionWithDot { - get { - if (IsRoot) - throw new ArgumentException ("A root directory does not have an extension"); - - var last = _elements.Last (); - var index = last.LastIndexOf ("."); - if (index < 0) return string.Empty; - return last.Substring (index); - } - } - - public string InQuotes () - { - return "\"" + ToString () + "\""; - } - - public string InQuotes (SlashMode slashMode) - { - return "\"" + ToString (slashMode) + "\""; - } - - public override string ToString () - { - return ToString (SlashMode.Native); - } - - public string ToString (SlashMode slashMode) - { - // Check if it's linux root / - if (IsRoot && string.IsNullOrEmpty (_driveLetter)) - return Slash (slashMode).ToString (); - - if (_isRelative && _elements.Length == 0) - return "."; - - var sb = new StringBuilder (); - if (_driveLetter != null) { - sb.Append (_driveLetter); - sb.Append (':'); - } - if (!_isRelative) - sb.Append (Slash (slashMode)); - var first = true; - foreach (var element in _elements) { - if (!first) - sb.Append (Slash (slashMode)); - - sb.Append (element); - first = false; - } - return sb.ToString (); - } - - public static implicit operator string (NPath path) - { - return path.ToString (); - } - - private static char Slash (SlashMode slashMode) - { - return slashMode switch { - SlashMode.Backward => '\\', - SlashMode.Forward => '/', - _ => Path.DirectorySeparatorChar, - }; - } - - public override bool Equals (object? obj) - { - if (obj == null) - return false; - - // If parameter cannot be cast to Point return false. - if (!(obj is NPath p)) - return false; - - return Equals (p); - } - - public bool Equals (NPath? p) - { - if (p == null) - return false; - - if (p._isRelative != _isRelative) - return false; - - if (!string.Equals (p._driveLetter, _driveLetter, PathStringComparison)) - return false; - - if (p._elements.Length != _elements.Length) - return false; - - for (var i = 0; i < _elements.Length; i++) - if (!string.Equals (p._elements[i], _elements[i], PathStringComparison)) - return false; - - return true; - } - - public static bool operator == (NPath? a, NPath? b) - { - // If both are null, or both are same instance, return true. - if (ReferenceEquals (a, b)) - return true; - - // If one is null, but not both, return false. - if ((a is null) || (b is null)) - return false; - - // Return true if the fields match: - return a.Equals (b); - } - - public override int GetHashCode () - { - unchecked { - int hash = 17; - // Suitable nullity checks etc, of course :) - hash = hash * 23 + _isRelative.GetHashCode (); - foreach (var element in _elements) - hash = hash * 23 + element.GetHashCode (); - if (_driveLetter != null) - hash = hash * 23 + _driveLetter.GetHashCode (); - return hash; - } - } - - public int CompareTo (object? obj) - { - if (obj == null) - return -1; - - return this.ToString ().CompareTo (((NPath) obj).ToString ()); - } - - public static bool operator != (NPath? a, NPath? b) - { - return !(a == b); - } - - public bool HasExtension (params string[] extensions) - { - var extensionWithDotLower = ExtensionWithDot.ToLowerInvariant (); - return extensions.Any (e => WithDot (e).ToLowerInvariant () == extensionWithDotLower); - } - - private static string WithDot (string extension) - { - return extension.StartsWith (".") ? extension : "." + extension; - } - - private bool IsEmpty () - { - return _elements.Length == 0; - } - - public bool IsRoot { - get { return _elements.Length == 0 && !_isRelative; } - } - - #endregion inspection - - #region directory enumeration - - public IEnumerable Files (string filter, bool recurse = false) - { - return Directory.GetFiles (ToString (), filter, recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).Select (s => new NPath (s)); - } - - public IEnumerable Files (bool recurse = false) - { - return Files ("*", recurse); - } - - public IEnumerable Contents (string filter, bool recurse = false) - { - return Files (filter, recurse).Concat (Directories (filter, recurse)); - } - - public IEnumerable Contents (bool recurse = false) - { - return Contents ("*", recurse); - } - - public IEnumerable Directories (string filter, bool recurse = false) - { - return Directory.GetDirectories (ToString (), filter, recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).Select (s => new NPath (s)); - } - - public IEnumerable Directories (bool recurse = false) - { - return Directories ("*", recurse); - } - - #endregion - - #region filesystem writing operations - public NPath CreateFile () - { - ThrowIfRelative (); - ThrowIfRoot (); - EnsureParentDirectoryExists (); - File.WriteAllBytes (ToString (), Array.Empty ()); - return this; - } - - public NPath CreateFile (string file) - { - return CreateFile (new NPath (file)); - } - - public NPath CreateFile (NPath file) - { - if (!file.IsRelative) - throw new ArgumentException ("You cannot call CreateFile() on an existing path with a non relative argument"); - return Combine (file).CreateFile (); - } - - public NPath CreateDirectory () - { - ThrowIfRelative (); - - if (IsRoot) - throw new NotSupportedException ("CreateDirectory is not supported on a root level directory because it would be dangerous:" + ToString ()); - - Directory.CreateDirectory (ToString ()); - return this; - } - - public NPath CreateDirectory (string directory) - { - return CreateDirectory (new NPath (directory)); - } - - public NPath CreateDirectory (NPath directory) - { - if (!directory.IsRelative) - throw new ArgumentException ("Cannot call CreateDirectory with an absolute argument"); - - return Combine (directory).CreateDirectory (); - } - - public NPath? Copy (string dest) - { - return Copy (new NPath (dest)); - } - - public NPath? Copy (string dest, Func fileFilter) - { - return Copy (new NPath (dest), fileFilter); - } - - public NPath? Copy (NPath dest) - { - return Copy (dest, p => true); - } - - public NPath? Copy (NPath dest, Func fileFilter) - { - ThrowIfRelative (); - if (dest.IsRelative) - dest = Parent.Combine (dest); - - if (dest.DirectoryExists ()) - return CopyWithDeterminedDestination (dest.Combine (FileName), fileFilter); - - return CopyWithDeterminedDestination (dest, fileFilter); - } - - public NPath MakeAbsolute () - { - if (!IsRelative) - return this; - - return CurrentDirectory.Combine (this); - } - - private NPath? CopyWithDeterminedDestination (NPath absoluteDestination, Func fileFilter) - { - if (absoluteDestination.IsRelative) - throw new ArgumentException ("absoluteDestination must be absolute"); - - if (FileExists ()) { - if (!fileFilter (absoluteDestination)) - return null; - - absoluteDestination.EnsureParentDirectoryExists (); - - File.Copy (ToString (), absoluteDestination.ToString (), true); - return absoluteDestination; - } - - if (DirectoryExists ()) { - absoluteDestination.EnsureDirectoryExists (); - foreach (var thing in Contents ()) - thing.CopyWithDeterminedDestination (absoluteDestination.Combine (thing.RelativeTo (this)), fileFilter); - return absoluteDestination; - } - - throw new ArgumentException ("Copy() called on path that doesnt exist: " + ToString ()); - } - - public void Delete (DeleteMode deleteMode = DeleteMode.Normal) - { - ThrowIfRelative (); - - if (IsRoot) - throw new NotSupportedException ("Delete is not supported on a root level directory because it would be dangerous:" + ToString ()); - - if (FileExists ()) - File.Delete (ToString ()); - else if (DirectoryExists ()) - try { - Directory.Delete (ToString (), true); - } catch (IOException) { - if (deleteMode == DeleteMode.Normal) - throw; - } - else - throw new InvalidOperationException ("Trying to delete a path that does not exist: " + ToString ()); - } - - public void DeleteIfExists (DeleteMode deleteMode = DeleteMode.Normal) - { - ThrowIfRelative (); - - if (FileExists () || DirectoryExists ()) - Delete (deleteMode); - } - - public NPath DeleteContents () - { - ThrowIfRelative (); - - if (IsRoot) - throw new NotSupportedException ("DeleteContents is not supported on a root level directory because it would be dangerous:" + ToString ()); - - if (FileExists ()) - throw new InvalidOperationException ("It is not valid to perform this operation on a file"); - - if (DirectoryExists ()) { - try { - Files ().Delete (); - Directories ().Delete (); - } catch (IOException) { - if (Files (true).Any ()) - throw; - } - - return this; - } - - return EnsureDirectoryExists (); - } - - public static NPath CreateTempDirectory (string myprefix) - { - var random = new Random (); - while (true) { - var candidate = new NPath (Path.GetTempPath () + "/" + myprefix + "_" + random.Next ()); - if (!candidate.Exists ()) - return candidate.CreateDirectory (); - } - } - - public NPath Move (string dest) - { - return Move (new NPath (dest)); - } - - public NPath Move (NPath dest) - { - ThrowIfRelative (); - - if (IsRoot) - throw new NotSupportedException ("Move is not supported on a root level directory because it would be dangerous:" + ToString ()); - - if (dest.IsRelative) - return Move (Parent.Combine (dest)); - - if (dest.DirectoryExists ()) - return Move (dest.Combine (FileName)); - - if (FileExists ()) { - dest.EnsureParentDirectoryExists (); - File.Move (ToString (), dest.ToString ()); - return dest; - } - - if (DirectoryExists ()) { - Directory.Move (ToString (), dest.ToString ()); - return dest; - } - - throw new ArgumentException ("Move() called on a path that doesn't exist: " + ToString ()); - } - - #endregion - - #region special paths - - public static NPath CurrentDirectory { - get { - return new NPath (Directory.GetCurrentDirectory ()); - } - } - - public static NPath HomeDirectory { - get { - if (Path.DirectorySeparatorChar == '\\') - return new NPath (Environment.GetEnvironmentVariable ("USERPROFILE")!); - return new NPath (Environment.GetEnvironmentVariable ("HOME")!); - } - } - - public static NPath SystemTemp { - get { - return new NPath (Path.GetTempPath ()); - } - } - - #endregion - - private void ThrowIfRelative () - { - if (_isRelative) - throw new ArgumentException ("You are attempting an operation on a Path that requires an absolute path, but the path is relative"); - } - - private void ThrowIfRoot () - { - if (IsRoot) - throw new ArgumentException ("You are attempting an operation that is not valid on a root level directory"); - } - - public NPath EnsureDirectoryExists (string append = "") - { - return EnsureDirectoryExists (new NPath (append)); - } - - public NPath EnsureDirectoryExists (NPath append) - { - var combined = Combine (append); - if (combined.DirectoryExists ()) - return combined; - combined.EnsureParentDirectoryExists (); - combined.CreateDirectory (); - return combined; - } - - public NPath EnsureParentDirectoryExists () - { - var parent = Parent; - parent.EnsureDirectoryExists (); - return parent; - } - - public NPath FileMustExist () - { - if (!FileExists ()) - throw new FileNotFoundException ("File was expected to exist : " + ToString ()); - - return this; - } - - public NPath DirectoryMustExist () - { - if (!DirectoryExists ()) - throw new DirectoryNotFoundException ("Expected directory to exist : " + ToString ()); - - return this; - } - - public bool IsChildOf (string potentialBasePath) - { - return IsChildOf (new NPath (potentialBasePath)); - } - - public bool IsChildOf (NPath potentialBasePath) - { - if ((IsRelative && !potentialBasePath.IsRelative) || !IsRelative && potentialBasePath.IsRelative) - throw new ArgumentException ("You can only call IsChildOf with two relative paths, or with two absolute paths"); - - // If the other path is the root directory, then anything is a child of it as long as it's not a Windows path - if (potentialBasePath.IsRoot) { - if (_driveLetter != potentialBasePath._driveLetter) - return false; - return true; - } - - if (IsEmpty ()) - return false; - - if (Equals (potentialBasePath)) - return true; - - return Parent.IsChildOf (potentialBasePath); - } - - public IEnumerable RecursiveParents { - get { - var candidate = this; - while (true) { - if (candidate.IsEmpty ()) - yield break; - - candidate = candidate.Parent; - yield return candidate; - } - } - } - - public NPath WriteAllText (string contents) - { - ThrowIfRelative (); - EnsureParentDirectoryExists (); - File.WriteAllText (ToString (), contents); - return this; - } - - public string ReadAllText () - { - ThrowIfRelative (); - return File.ReadAllText (ToString ()); - } - - public NPath WriteAllLines (string[] contents) - { - ThrowIfRelative (); - EnsureParentDirectoryExists (); - File.WriteAllLines (ToString (), contents); - return this; - } - - public string[] ReadAllLines () - { - ThrowIfRelative (); - return File.ReadAllLines (ToString ()); - } - - public IEnumerable CopyFiles (NPath destination, bool recurse, Func? fileFilter = null) - { - destination.EnsureDirectoryExists (); - return Files (recurse).Where (fileFilter ?? AlwaysTrue).Select (file => file.Copy (destination.Combine (file.RelativeTo (this)))).ToArray (); - } - - public IEnumerable MoveFiles (NPath destination, bool recurse, Func? fileFilter = null) - { - if (IsRoot) - throw new NotSupportedException ("MoveFiles is not supported on this directory because it would be dangerous:" + ToString ()); - - destination.EnsureDirectoryExists (); - return Files (recurse).Where (fileFilter ?? AlwaysTrue).Select (file => file.Move (destination.Combine (file.RelativeTo (this)))).ToArray (); - } - - private static bool AlwaysTrue (NPath p) - { - return true; - } - - private static bool IsLinux () - { - return Directory.Exists ("/proc"); - } - } - - public static class Extensions - { - public static IEnumerable Copy (this IEnumerable self, string dest) - { - return Copy (self, new NPath (dest)); - } - - public static IEnumerable Copy (this IEnumerable self, NPath dest) - { - if (dest.IsRelative) - throw new ArgumentException ("When copying multiple files, the destination cannot be a relative path"); - dest.EnsureDirectoryExists (); - return self.Select (p => p.Copy (dest.Combine (p.FileName))).ToArray (); - } - - public static IEnumerable Move (this IEnumerable self, string dest) - { - return Move (self, new NPath (dest)); - } - - public static IEnumerable Move (this IEnumerable self, NPath dest) - { - if (dest.IsRelative) - throw new ArgumentException ("When moving multiple files, the destination cannot be a relative path"); - dest.EnsureDirectoryExists (); - return self.Select (p => p.Move (dest.Combine (p.FileName))).ToArray (); - } - - public static IEnumerable Delete (this IEnumerable self) - { - foreach (var p in self) - p.Delete (); - return self; - } - - public static IEnumerable InQuotes (this IEnumerable self, SlashMode forward = SlashMode.Native) - { - return self.Select (p => p.InQuotes (forward)); - } - - public static NPath ToNPath (this string path) - { - return new NPath (path); - } - } - - public enum SlashMode - { - Native, - Forward, - Backward - } - - public enum DeleteMode - { - Normal, - Soft - } + public class NPath : IEquatable, IComparable + { + private static readonly StringComparison PathStringComparison = IsLinux() ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; + + private readonly string[] _elements; + private readonly bool _isRelative; + private readonly string? _driveLetter; + + #region construction + + public NPath(string path) + { + ArgumentNullException.ThrowIfNull(path); + + path = ParseDriveLetter(path, out _driveLetter); + + if (path == "/") + { + _isRelative = false; + _elements = Array.Empty(); + } + else + { + var split = path.Split('/', '\\'); + + _isRelative = _driveLetter == null && IsRelativeFromSplitString(split); + + _elements = ParseSplitStringIntoElements(split.Where(s => s.Length > 0).ToArray()); + } + } + + private NPath(string[] elements, bool isRelative, string? driveLetter) + { + _elements = elements; + _isRelative = isRelative; + _driveLetter = driveLetter; + } + + private string[] ParseSplitStringIntoElements(IEnumerable inputs) + { + var stack = new List(); + + foreach (var input in inputs.Where(input => input.Length != 0)) + { + if (input == ".") + { + if ((stack.Count > 0) && (stack.Last() != ".")) + continue; + } + else if (input == "..") + { + if (HasNonDotDotLastElement(stack)) + { + stack.RemoveAt(stack.Count - 1); + continue; + } + if (!_isRelative) + throw new ArgumentException("You cannot create a path that tries to .. past the root"); + } + stack.Add(input); + } + return stack.ToArray(); + } + + private static bool HasNonDotDotLastElement(List stack) + { + return stack.Count > 0 && stack[stack.Count - 1] != ".."; + } + + private static string ParseDriveLetter(string path, out string? driveLetter) + { + if (path.Length >= 2 && path[1] == ':') + { + driveLetter = path[0].ToString(); + return path.Substring(2); + } + + driveLetter = null; + return path; + } + + private static bool IsRelativeFromSplitString(string[] split) + { + if (split.Length < 2) + return true; + + return split[0].Length != 0 || !split.Any(s => s.Length > 0); + } + + public NPath Combine(params string[] append) + { + return Combine(append.Select(a => new NPath(a)).ToArray()); + } + + public NPath Combine(params NPath[] append) + { + if (!append.All(p => p.IsRelative)) + throw new ArgumentException("You cannot .Combine a non-relative path"); + + return new NPath(ParseSplitStringIntoElements(_elements.Concat(append.SelectMany(p => p._elements))), _isRelative, _driveLetter); + } + + public NPath Parent + { + get + { + if (_elements.Length == 0) + throw new InvalidOperationException("Parent is called on an empty path"); + + var newElements = _elements.Take(_elements.Length - 1).ToArray(); + + return new NPath(newElements, _isRelative, _driveLetter); + } + } + + public NPath RelativeTo(NPath path) + { + if (!IsChildOf(path)) + { + if (!IsRelative && !path.IsRelative && _driveLetter != path._driveLetter) + throw new ArgumentException("Path.RelativeTo() was invoked with two paths that are on different volumes. invoked on: " + ToString() + " asked to be made relative to: " + path); + + NPath? commonParent = null; + foreach (var parent in RecursiveParents) + { + commonParent = path.RecursiveParents.FirstOrDefault(otherParent => otherParent == parent); + + if (commonParent != null) + break; + } + + if (commonParent == null) + throw new ArgumentException("Path.RelativeTo() was unable to find a common parent between " + ToString() + " and " + path); + + if (IsRelative && path.IsRelative && commonParent.IsEmpty()) + throw new ArgumentException("Path.RelativeTo() was invoked with two relative paths that do not share a common parent. Invoked on: " + ToString() + " asked to be made relative to: " + path); + + var depthDiff = path.Depth - commonParent.Depth; + return new NPath(Enumerable.Repeat("..", depthDiff).Concat(_elements.Skip(commonParent.Depth)).ToArray(), true, null); + } + + return new NPath(_elements.Skip(path._elements.Length).ToArray(), true, null); + } + + public NPath ChangeExtension(string extension) + { + ThrowIfRoot(); + + var newElements = (string[])_elements.Clone(); + newElements[newElements.Length - 1] = Path.ChangeExtension(_elements[_elements.Length - 1], WithDot(extension)); + if (extension == string.Empty) + newElements[newElements.Length - 1] = newElements[newElements.Length - 1].TrimEnd('.'); + return new NPath(newElements, _isRelative, _driveLetter); + } + #endregion construction + + #region inspection + + public bool IsRelative + { + get { return _isRelative; } + } + + public string FileName + { + get + { + ThrowIfRoot(); + + return _elements.Last(); + } + } + + public string FileNameWithoutExtension + { + get { return Path.GetFileNameWithoutExtension(FileName); } + } + + public IEnumerable Elements + { + get { return _elements; } + } + + public int Depth + { + get { return _elements.Length; } + } + + public bool Exists(string append = "") + { + return Exists(new NPath(append)); + } + + public bool Exists(NPath append) + { + return FileExists(append) || DirectoryExists(append); + } + + public bool DirectoryExists(string append = "") + { + return DirectoryExists(new NPath(append)); + } + + public bool DirectoryExists(NPath append) + { + return Directory.Exists(Combine(append).ToString()); + } + + public bool FileExists(string append = "") + { + return FileExists(new NPath(append)); + } + + public bool FileExists(NPath append) + { + return File.Exists(Combine(append).ToString()); + } + + public string ExtensionWithDot + { + get + { + if (IsRoot) + throw new ArgumentException("A root directory does not have an extension"); + + var last = _elements.Last(); + var index = last.LastIndexOf("."); + if (index < 0) return string.Empty; + return last.Substring(index); + } + } + + public string InQuotes() + { + return "\"" + ToString() + "\""; + } + + public string InQuotes(SlashMode slashMode) + { + return "\"" + ToString(slashMode) + "\""; + } + + public override string ToString() + { + return ToString(SlashMode.Native); + } + + public string ToString(SlashMode slashMode) + { + // Check if it's linux root / + if (IsRoot && string.IsNullOrEmpty(_driveLetter)) + return Slash(slashMode).ToString(); + + if (_isRelative && _elements.Length == 0) + return "."; + + var sb = new StringBuilder(); + if (_driveLetter != null) + { + sb.Append(_driveLetter); + sb.Append(':'); + } + if (!_isRelative) + sb.Append(Slash(slashMode)); + var first = true; + foreach (var element in _elements) + { + if (!first) + sb.Append(Slash(slashMode)); + + sb.Append(element); + first = false; + } + return sb.ToString(); + } + + public static implicit operator string(NPath path) + { + return path.ToString(); + } + + private static char Slash(SlashMode slashMode) + { + return slashMode switch + { + SlashMode.Backward => '\\', + SlashMode.Forward => '/', + _ => Path.DirectorySeparatorChar, + }; + } + + public override bool Equals(object? obj) + { + if (obj == null) + return false; + + // If parameter cannot be cast to Point return false. + if (!(obj is NPath p)) + return false; + + return Equals(p); + } + + public bool Equals(NPath? p) + { + if (p == null) + return false; + + if (p._isRelative != _isRelative) + return false; + + if (!string.Equals(p._driveLetter, _driveLetter, PathStringComparison)) + return false; + + if (p._elements.Length != _elements.Length) + return false; + + for (var i = 0; i < _elements.Length; i++) + if (!string.Equals(p._elements[i], _elements[i], PathStringComparison)) + return false; + + return true; + } + + public static bool operator ==(NPath? a, NPath? b) + { + // If both are null, or both are same instance, return true. + if (ReferenceEquals(a, b)) + return true; + + // If one is null, but not both, return false. + if ((a is null) || (b is null)) + return false; + + // Return true if the fields match: + return a.Equals(b); + } + + public override int GetHashCode() + { + unchecked + { + int hash = 17; + // Suitable nullity checks etc, of course :) + hash = hash * 23 + _isRelative.GetHashCode(); + foreach (var element in _elements) + hash = hash * 23 + element.GetHashCode(); + if (_driveLetter != null) + hash = hash * 23 + _driveLetter.GetHashCode(); + return hash; + } + } + + public int CompareTo(object? obj) + { + if (obj == null) + return -1; + + return this.ToString().CompareTo(((NPath)obj).ToString()); + } + + public static bool operator !=(NPath? a, NPath? b) + { + return !(a == b); + } + + public bool HasExtension(params string[] extensions) + { + var extensionWithDotLower = ExtensionWithDot.ToLowerInvariant(); + return extensions.Any(e => WithDot(e).ToLowerInvariant() == extensionWithDotLower); + } + + private static string WithDot(string extension) + { + return extension.StartsWith(".") ? extension : "." + extension; + } + + private bool IsEmpty() + { + return _elements.Length == 0; + } + + public bool IsRoot + { + get { return _elements.Length == 0 && !_isRelative; } + } + + #endregion inspection + + #region directory enumeration + + public IEnumerable Files(string filter, bool recurse = false) + { + return Directory.GetFiles(ToString(), filter, recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).Select(s => new NPath(s)); + } + + public IEnumerable Files(bool recurse = false) + { + return Files("*", recurse); + } + + public IEnumerable Contents(string filter, bool recurse = false) + { + return Files(filter, recurse).Concat(Directories(filter, recurse)); + } + + public IEnumerable Contents(bool recurse = false) + { + return Contents("*", recurse); + } + + public IEnumerable Directories(string filter, bool recurse = false) + { + return Directory.GetDirectories(ToString(), filter, recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).Select(s => new NPath(s)); + } + + public IEnumerable Directories(bool recurse = false) + { + return Directories("*", recurse); + } + + #endregion + + #region filesystem writing operations + public NPath CreateFile() + { + ThrowIfRelative(); + ThrowIfRoot(); + EnsureParentDirectoryExists(); + File.WriteAllBytes(ToString(), Array.Empty()); + return this; + } + + public NPath CreateFile(string file) + { + return CreateFile(new NPath(file)); + } + + public NPath CreateFile(NPath file) + { + if (!file.IsRelative) + throw new ArgumentException("You cannot call CreateFile() on an existing path with a non relative argument"); + return Combine(file).CreateFile(); + } + + public NPath CreateDirectory() + { + ThrowIfRelative(); + + if (IsRoot) + throw new NotSupportedException("CreateDirectory is not supported on a root level directory because it would be dangerous:" + ToString()); + + Directory.CreateDirectory(ToString()); + return this; + } + + public NPath CreateDirectory(string directory) + { + return CreateDirectory(new NPath(directory)); + } + + public NPath CreateDirectory(NPath directory) + { + if (!directory.IsRelative) + throw new ArgumentException("Cannot call CreateDirectory with an absolute argument"); + + return Combine(directory).CreateDirectory(); + } + + public NPath? Copy(string dest) + { + return Copy(new NPath(dest)); + } + + public NPath? Copy(string dest, Func fileFilter) + { + return Copy(new NPath(dest), fileFilter); + } + + public NPath? Copy(NPath dest) + { + return Copy(dest, p => true); + } + + public NPath? Copy(NPath dest, Func fileFilter) + { + ThrowIfRelative(); + if (dest.IsRelative) + dest = Parent.Combine(dest); + + if (dest.DirectoryExists()) + return CopyWithDeterminedDestination(dest.Combine(FileName), fileFilter); + + return CopyWithDeterminedDestination(dest, fileFilter); + } + + public NPath MakeAbsolute() + { + if (!IsRelative) + return this; + + return CurrentDirectory.Combine(this); + } + + private NPath? CopyWithDeterminedDestination(NPath absoluteDestination, Func fileFilter) + { + if (absoluteDestination.IsRelative) + throw new ArgumentException("absoluteDestination must be absolute"); + + if (FileExists()) + { + if (!fileFilter(absoluteDestination)) + return null; + + absoluteDestination.EnsureParentDirectoryExists(); + + File.Copy(ToString(), absoluteDestination.ToString(), true); + return absoluteDestination; + } + + if (DirectoryExists()) + { + absoluteDestination.EnsureDirectoryExists(); + foreach (var thing in Contents()) + thing.CopyWithDeterminedDestination(absoluteDestination.Combine(thing.RelativeTo(this)), fileFilter); + return absoluteDestination; + } + + throw new ArgumentException("Copy() called on path that doesnt exist: " + ToString()); + } + + public void Delete(DeleteMode deleteMode = DeleteMode.Normal) + { + ThrowIfRelative(); + + if (IsRoot) + throw new NotSupportedException("Delete is not supported on a root level directory because it would be dangerous:" + ToString()); + + if (FileExists()) + File.Delete(ToString()); + else if (DirectoryExists()) + try + { + Directory.Delete(ToString(), true); + } + catch (IOException) + { + if (deleteMode == DeleteMode.Normal) + throw; + } + else + throw new InvalidOperationException("Trying to delete a path that does not exist: " + ToString()); + } + + public void DeleteIfExists(DeleteMode deleteMode = DeleteMode.Normal) + { + ThrowIfRelative(); + + if (FileExists() || DirectoryExists()) + Delete(deleteMode); + } + + public NPath DeleteContents() + { + ThrowIfRelative(); + + if (IsRoot) + throw new NotSupportedException("DeleteContents is not supported on a root level directory because it would be dangerous:" + ToString()); + + if (FileExists()) + throw new InvalidOperationException("It is not valid to perform this operation on a file"); + + if (DirectoryExists()) + { + try + { + Files().Delete(); + Directories().Delete(); + } + catch (IOException) + { + if (Files(true).Any()) + throw; + } + + return this; + } + + return EnsureDirectoryExists(); + } + + public static NPath CreateTempDirectory(string myprefix) + { + var random = new Random(); + while (true) + { + var candidate = new NPath(Path.GetTempPath() + "/" + myprefix + "_" + random.Next()); + if (!candidate.Exists()) + return candidate.CreateDirectory(); + } + } + + public NPath Move(string dest) + { + return Move(new NPath(dest)); + } + + public NPath Move(NPath dest) + { + ThrowIfRelative(); + + if (IsRoot) + throw new NotSupportedException("Move is not supported on a root level directory because it would be dangerous:" + ToString()); + + if (dest.IsRelative) + return Move(Parent.Combine(dest)); + + if (dest.DirectoryExists()) + return Move(dest.Combine(FileName)); + + if (FileExists()) + { + dest.EnsureParentDirectoryExists(); + File.Move(ToString(), dest.ToString()); + return dest; + } + + if (DirectoryExists()) + { + Directory.Move(ToString(), dest.ToString()); + return dest; + } + + throw new ArgumentException("Move() called on a path that doesn't exist: " + ToString()); + } + + #endregion + + #region special paths + + public static NPath CurrentDirectory + { + get + { + return new NPath(Directory.GetCurrentDirectory()); + } + } + + public static NPath HomeDirectory + { + get + { + if (Path.DirectorySeparatorChar == '\\') + return new NPath(Environment.GetEnvironmentVariable("USERPROFILE")!); + return new NPath(Environment.GetEnvironmentVariable("HOME")!); + } + } + + public static NPath SystemTemp + { + get + { + return new NPath(Path.GetTempPath()); + } + } + + #endregion + + private void ThrowIfRelative() + { + if (_isRelative) + throw new ArgumentException("You are attempting an operation on a Path that requires an absolute path, but the path is relative"); + } + + private void ThrowIfRoot() + { + if (IsRoot) + throw new ArgumentException("You are attempting an operation that is not valid on a root level directory"); + } + + public NPath EnsureDirectoryExists(string append = "") + { + return EnsureDirectoryExists(new NPath(append)); + } + + public NPath EnsureDirectoryExists(NPath append) + { + var combined = Combine(append); + if (combined.DirectoryExists()) + return combined; + combined.EnsureParentDirectoryExists(); + combined.CreateDirectory(); + return combined; + } + + public NPath EnsureParentDirectoryExists() + { + var parent = Parent; + parent.EnsureDirectoryExists(); + return parent; + } + + public NPath FileMustExist() + { + if (!FileExists()) + throw new FileNotFoundException("File was expected to exist : " + ToString()); + + return this; + } + + public NPath DirectoryMustExist() + { + if (!DirectoryExists()) + throw new DirectoryNotFoundException("Expected directory to exist : " + ToString()); + + return this; + } + + public bool IsChildOf(string potentialBasePath) + { + return IsChildOf(new NPath(potentialBasePath)); + } + + public bool IsChildOf(NPath potentialBasePath) + { + if ((IsRelative && !potentialBasePath.IsRelative) || !IsRelative && potentialBasePath.IsRelative) + throw new ArgumentException("You can only call IsChildOf with two relative paths, or with two absolute paths"); + + // If the other path is the root directory, then anything is a child of it as long as it's not a Windows path + if (potentialBasePath.IsRoot) + { + if (_driveLetter != potentialBasePath._driveLetter) + return false; + return true; + } + + if (IsEmpty()) + return false; + + if (Equals(potentialBasePath)) + return true; + + return Parent.IsChildOf(potentialBasePath); + } + + public IEnumerable RecursiveParents + { + get + { + var candidate = this; + while (true) + { + if (candidate.IsEmpty()) + yield break; + + candidate = candidate.Parent; + yield return candidate; + } + } + } + + public NPath WriteAllText(string contents) + { + ThrowIfRelative(); + EnsureParentDirectoryExists(); + File.WriteAllText(ToString(), contents); + return this; + } + + public string ReadAllText() + { + ThrowIfRelative(); + return File.ReadAllText(ToString()); + } + + public NPath WriteAllLines(string[] contents) + { + ThrowIfRelative(); + EnsureParentDirectoryExists(); + File.WriteAllLines(ToString(), contents); + return this; + } + + public string[] ReadAllLines() + { + ThrowIfRelative(); + return File.ReadAllLines(ToString()); + } + + public IEnumerable CopyFiles(NPath destination, bool recurse, Func? fileFilter = null) + { + destination.EnsureDirectoryExists(); + return Files(recurse).Where(fileFilter ?? AlwaysTrue).Select(file => file.Copy(destination.Combine(file.RelativeTo(this)))).ToArray(); + } + + public IEnumerable MoveFiles(NPath destination, bool recurse, Func? fileFilter = null) + { + if (IsRoot) + throw new NotSupportedException("MoveFiles is not supported on this directory because it would be dangerous:" + ToString()); + + destination.EnsureDirectoryExists(); + return Files(recurse).Where(fileFilter ?? AlwaysTrue).Select(file => file.Move(destination.Combine(file.RelativeTo(this)))).ToArray(); + } + + private static bool AlwaysTrue(NPath p) + { + return true; + } + + private static bool IsLinux() + { + return Directory.Exists("/proc"); + } + } + + public static class Extensions + { + public static IEnumerable Copy(this IEnumerable self, string dest) + { + return Copy(self, new NPath(dest)); + } + + public static IEnumerable Copy(this IEnumerable self, NPath dest) + { + if (dest.IsRelative) + throw new ArgumentException("When copying multiple files, the destination cannot be a relative path"); + dest.EnsureDirectoryExists(); + return self.Select(p => p.Copy(dest.Combine(p.FileName))).ToArray(); + } + + public static IEnumerable Move(this IEnumerable self, string dest) + { + return Move(self, new NPath(dest)); + } + + public static IEnumerable Move(this IEnumerable self, NPath dest) + { + if (dest.IsRelative) + throw new ArgumentException("When moving multiple files, the destination cannot be a relative path"); + dest.EnsureDirectoryExists(); + return self.Select(p => p.Move(dest.Combine(p.FileName))).ToArray(); + } + + public static IEnumerable Delete(this IEnumerable self) + { + foreach (var p in self) + p.Delete(); + return self; + } + + public static IEnumerable InQuotes(this IEnumerable self, SlashMode forward = SlashMode.Native) + { + return self.Select(p => p.InQuotes(forward)); + } + + public static NPath ToNPath(this string path) + { + return new NPath(path); + } + } + + public enum SlashMode + { + Native, + Forward, + Backward + } + + public enum DeleteMode + { + Normal, + Soft + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestCase.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestCase.cs index be690ac7a60df9..a306238fffe03f 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestCase.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestCase.cs @@ -9,98 +9,103 @@ namespace Mono.Linker.Tests.TestCases { - public class TestCase - { - public TestCase (NPath sourceFile, NPath rootCasesDirectory, NPath originalTestCaseAssemblyPath) - { - SourceFile = sourceFile; - RootCasesDirectory = rootCasesDirectory; - OriginalTestCaseAssemblyPath = originalTestCaseAssemblyPath; - Name = sourceFile.FileNameWithoutExtension; - var fullyRelative = sourceFile.RelativeTo (rootCasesDirectory); - var displayNameRelative = fullyRelative.RelativeTo (new NPath (fullyRelative.Elements.First ())); - string displayNameBase = displayNameRelative.Depth == 1 ? "" : displayNameRelative.Parent.ToString (SlashMode.Forward).Replace ('/', '.'); - DisplayName = sourceFile.FileNameWithoutExtension == "Program" && sourceFile.Parent.FileName == originalTestCaseAssemblyPath.FileNameWithoutExtension - ? displayNameBase - : $"{displayNameBase}.{sourceFile.FileNameWithoutExtension}"; - if (DisplayName.StartsWith(".")) - DisplayName = DisplayName.Substring(1); - - // A little hacky, but good enough for name. No reason why namespace & type names - // should not follow the directory structure - //ReconstructedFullTypeName = $"{sourceFile.Parent.RelativeTo (rootCasesDirectory.Parent).ToString (SlashMode.Forward).Replace ('/', '.')}.{sourceFile.FileNameWithoutExtension}"; - reconstructedFullTypeName = $"Mono.Linker.Tests.Cases.{fullyRelative.Parent.ToString (SlashMode.Forward).Replace ('/', '.')}.{sourceFile.FileNameWithoutExtension}"; - - var firstParentRelativeToRoot = SourceFile.RelativeTo (rootCasesDirectory).Elements.First (); - TestSuiteDirectory = rootCasesDirectory.Combine (firstParentRelativeToRoot); - } - - public NPath RootCasesDirectory { get; } - - public string Name { get; } - - public string DisplayName { get; } - - public NPath SourceFile { get; } - - public NPath OriginalTestCaseAssemblyPath { get; } - - private string reconstructedFullTypeName; - - public bool HasLinkXmlFile { - get { return SourceFile.ChangeExtension ("xml").FileExists (); } - } - - public NPath LinkXmlFile { - get { - if (!HasLinkXmlFile) - throw new InvalidOperationException ("This test case does not have a link xml file"); - - return SourceFile.ChangeExtension ("xml"); - } - } - - public NPath TestSuiteDirectory { get; } - - public TypeDefinition FindTypeDefinition (AssemblyDefinition assemblyDefinition) - => TryFindTypeDefinition (assemblyDefinition) is TypeDefinition typeDefinition - ? typeDefinition - : throw new InvalidOperationException ($"Could not find the type definition for {Name} in {assemblyDefinition.Name}"); - - public TypeDefinition? TryFindTypeDefinition (AssemblyDefinition caseAssemblyDefinition) - { - var typeDefinition = caseAssemblyDefinition.MainModule.GetType (reconstructedFullTypeName); - - // For all of the Test Cases, the full type name we constructed from the directory structure will be correct and we can successfully find - // the type from GetType. - if (typeDefinition != null) - return typeDefinition; - - // However, some of types are supporting types rather than test cases and may not follow the standardized naming scheme of the test cases. - // We still need to be able to locate these type defs so that we can parse some of the metadata on them. - // One example, Unity run's into this with its tests that require a type UnityEngine.MonoBehaviours to exist. This type is defined in its own - // file and it cannot follow our standardized naming directory & namespace naming scheme since the namespace must be UnityEngine. - // Also look for compiler-generated Program type for top-level statements. - foreach (var type in caseAssemblyDefinition.MainModule.Types) { - if (type.Name == "Program" && - type.CustomAttributes.Any (attr => attr.AttributeType.Name == nameof (CompilerGeneratedAttribute))) - return type; - - // Let's assume we should never have to search for a test case that has no namespace. If we don't find the type from GetType, then o well, that's not a test case. - if (string.IsNullOrEmpty (type.Namespace)) - continue; - - if (type.Name == Name) { - // This isn't foolproof, but let's do a little extra vetting to make sure the type we found corresponds to the source file we are - // processing. - if (!SourceFile.ReadAllText ().Contains ($"namespace {type.Namespace}")) - continue; - - return type; - } - } - - return null; - } - } + public class TestCase + { + public TestCase(NPath sourceFile, NPath rootCasesDirectory, NPath originalTestCaseAssemblyPath) + { + SourceFile = sourceFile; + RootCasesDirectory = rootCasesDirectory; + OriginalTestCaseAssemblyPath = originalTestCaseAssemblyPath; + Name = sourceFile.FileNameWithoutExtension; + var fullyRelative = sourceFile.RelativeTo(rootCasesDirectory); + var displayNameRelative = fullyRelative.RelativeTo(new NPath(fullyRelative.Elements.First())); + string displayNameBase = displayNameRelative.Depth == 1 ? "" : displayNameRelative.Parent.ToString(SlashMode.Forward).Replace('/', '.'); + DisplayName = sourceFile.FileNameWithoutExtension == "Program" && sourceFile.Parent.FileName == originalTestCaseAssemblyPath.FileNameWithoutExtension + ? displayNameBase + : $"{displayNameBase}.{sourceFile.FileNameWithoutExtension}"; + if (DisplayName.StartsWith(".")) + DisplayName = DisplayName.Substring(1); + + // A little hacky, but good enough for name. No reason why namespace & type names + // should not follow the directory structure + //ReconstructedFullTypeName = $"{sourceFile.Parent.RelativeTo (rootCasesDirectory.Parent).ToString (SlashMode.Forward).Replace ('/', '.')}.{sourceFile.FileNameWithoutExtension}"; + reconstructedFullTypeName = $"Mono.Linker.Tests.Cases.{fullyRelative.Parent.ToString(SlashMode.Forward).Replace('/', '.')}.{sourceFile.FileNameWithoutExtension}"; + + var firstParentRelativeToRoot = SourceFile.RelativeTo(rootCasesDirectory).Elements.First(); + TestSuiteDirectory = rootCasesDirectory.Combine(firstParentRelativeToRoot); + } + + public NPath RootCasesDirectory { get; } + + public string Name { get; } + + public string DisplayName { get; } + + public NPath SourceFile { get; } + + public NPath OriginalTestCaseAssemblyPath { get; } + + private string reconstructedFullTypeName; + + public bool HasLinkXmlFile + { + get { return SourceFile.ChangeExtension("xml").FileExists(); } + } + + public NPath LinkXmlFile + { + get + { + if (!HasLinkXmlFile) + throw new InvalidOperationException("This test case does not have a link xml file"); + + return SourceFile.ChangeExtension("xml"); + } + } + + public NPath TestSuiteDirectory { get; } + + public TypeDefinition FindTypeDefinition(AssemblyDefinition assemblyDefinition) + => TryFindTypeDefinition(assemblyDefinition) is TypeDefinition typeDefinition + ? typeDefinition + : throw new InvalidOperationException($"Could not find the type definition for {Name} in {assemblyDefinition.Name}"); + + public TypeDefinition? TryFindTypeDefinition(AssemblyDefinition caseAssemblyDefinition) + { + var typeDefinition = caseAssemblyDefinition.MainModule.GetType(reconstructedFullTypeName); + + // For all of the Test Cases, the full type name we constructed from the directory structure will be correct and we can successfully find + // the type from GetType. + if (typeDefinition != null) + return typeDefinition; + + // However, some of types are supporting types rather than test cases and may not follow the standardized naming scheme of the test cases. + // We still need to be able to locate these type defs so that we can parse some of the metadata on them. + // One example, Unity run's into this with its tests that require a type UnityEngine.MonoBehaviours to exist. This type is defined in its own + // file and it cannot follow our standardized naming directory & namespace naming scheme since the namespace must be UnityEngine. + // Also look for compiler-generated Program type for top-level statements. + foreach (var type in caseAssemblyDefinition.MainModule.Types) + { + if (type.Name == "Program" && + type.CustomAttributes.Any(attr => attr.AttributeType.Name == nameof(CompilerGeneratedAttribute))) + return type; + + // Let's assume we should never have to search for a test case that has no namespace. If we don't find the type from GetType, then o well, that's not a test case. + if (string.IsNullOrEmpty(type.Namespace)) + continue; + + if (type.Name == Name) + { + // This isn't foolproof, but let's do a little extra vetting to make sure the type we found corresponds to the source file we are + // processing. + if (!SourceFile.ReadAllText().Contains($"namespace {type.Namespace}")) + continue; + + return type; + } + } + + return null; + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestDatabase.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestDatabase.cs index f742d409d9b75a..8f5b20deef2c96 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestDatabase.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestDatabase.cs @@ -10,29 +10,29 @@ namespace Mono.Linker.Tests.TestCases { - public static class TestDatabase - { - private static TestCase[]? _cachedAllCases; - - public static IEnumerable DataFlow () - { - return TestNamesBySuiteName (); - } - - public static IEnumerable DynamicDependencies () - { - return TestNamesBySuiteName (); - } - - public static IEnumerable Generics () - { - return TestNamesBySuiteName (); - } - - public static IEnumerable InlineArrays () - { - return TestNamesBySuiteName(); - } + public static class TestDatabase + { + private static TestCase[]? _cachedAllCases; + + public static IEnumerable DataFlow() + { + return TestNamesBySuiteName(); + } + + public static IEnumerable DynamicDependencies() + { + return TestNamesBySuiteName(); + } + + public static IEnumerable Generics() + { + return TestNamesBySuiteName(); + } + + public static IEnumerable InlineArrays() + { + return TestNamesBySuiteName(); + } public static IEnumerable Inheritance_Interaces() { @@ -45,91 +45,93 @@ public static IEnumerable Libraries() } public static IEnumerable LinkXml() - { - return TestNamesBySuiteName(); - } - - public static IEnumerable Reflection () - { - return TestNamesBySuiteName (); - } - - public static IEnumerable Repro () - { - return TestNamesBySuiteName (); - } - - public static IEnumerable RequiresCapability () - { - return TestNamesBySuiteName (); - } - - public static IEnumerable SingleFile () - { - return TestNamesBySuiteName (); - } - - public static IEnumerable Substitutions () - { - return TestNamesBySuiteName (); - } - - public static IEnumerable TopLevelStatements () - { - return TestNamesBySuiteName (); - } - - public static IEnumerable UnreachableBlock () - { - return TestNamesBySuiteName (); - } - - public static IEnumerable Warnings () - { - return TestNamesBySuiteName (); - } - - public static TestCaseCollector CreateCollector () - { - GetDirectoryPaths (out string rootSourceDirectory, out string testCaseAssemblyRoot); - return new TestCaseCollector (rootSourceDirectory, testCaseAssemblyRoot); - } - - public static NPath TestCasesRootDirectory { - get { - GetDirectoryPaths (out string rootSourceDirectory, out string _); - return rootSourceDirectory.ToNPath (); - } - } - - private static IEnumerable AllCases () - { - _cachedAllCases ??= CreateCollector () - .Collect () - .OrderBy (c => c.DisplayName) - .ToArray (); - - return _cachedAllCases; - } - - public static TestCase? GetTestCaseFromName (string name) - { - return AllCases ().FirstOrDefault (c => c.DisplayName == name); - } - - private static IEnumerable TestNamesBySuiteName ([CallerMemberName] string suiteName = "") - { - return AllCases () - .Where (c => c.TestSuiteDirectory.FileName == suiteName) - .Select (c => c.DisplayName) - .OrderBy (c => c) - .Select (c => new object[] { c }); - } - - private static void GetDirectoryPaths (out string rootSourceDirectory, out string testCaseAssemblyRoot) - { - rootSourceDirectory = Path.GetFullPath (Path.Combine (PathUtilities.GetTestsSourceRootDirectory (), "Mono.Linker.Tests.Cases")); - testCaseAssemblyRoot = PathUtilities.GetTestAssemblyRoot ("Mono.Linker.Tests.Cases"); - } - } + { + return TestNamesBySuiteName(); + } + + public static IEnumerable Reflection() + { + return TestNamesBySuiteName(); + } + + public static IEnumerable Repro() + { + return TestNamesBySuiteName(); + } + + public static IEnumerable RequiresCapability() + { + return TestNamesBySuiteName(); + } + + public static IEnumerable SingleFile() + { + return TestNamesBySuiteName(); + } + + public static IEnumerable Substitutions() + { + return TestNamesBySuiteName(); + } + + public static IEnumerable TopLevelStatements() + { + return TestNamesBySuiteName(); + } + + public static IEnumerable UnreachableBlock() + { + return TestNamesBySuiteName(); + } + + public static IEnumerable Warnings() + { + return TestNamesBySuiteName(); + } + + public static TestCaseCollector CreateCollector() + { + GetDirectoryPaths(out string rootSourceDirectory, out string testCaseAssemblyRoot); + return new TestCaseCollector(rootSourceDirectory, testCaseAssemblyRoot); + } + + public static NPath TestCasesRootDirectory + { + get + { + GetDirectoryPaths(out string rootSourceDirectory, out string _); + return rootSourceDirectory.ToNPath(); + } + } + + private static IEnumerable AllCases() + { + _cachedAllCases ??= CreateCollector() + .Collect() + .OrderBy(c => c.DisplayName) + .ToArray(); + + return _cachedAllCases; + } + + public static TestCase? GetTestCaseFromName(string name) + { + return AllCases().FirstOrDefault(c => c.DisplayName == name); + } + + private static IEnumerable TestNamesBySuiteName([CallerMemberName] string suiteName = "") + { + return AllCases() + .Where(c => c.TestSuiteDirectory.FileName == suiteName) + .Select(c => c.DisplayName) + .OrderBy(c => c) + .Select(c => new object[] { c }); + } + + private static void GetDirectoryPaths(out string rootSourceDirectory, out string testCaseAssemblyRoot) + { + rootSourceDirectory = Path.GetFullPath(Path.Combine(PathUtilities.GetTestsSourceRootDirectory(), "Mono.Linker.Tests.Cases")); + testCaseAssemblyRoot = PathUtilities.GetTestAssemblyRoot("Mono.Linker.Tests.Cases"); + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestSuites.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestSuites.cs index 87d8fc21ce8798..86d94be1f14c7c 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestSuites.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestSuites.cs @@ -7,152 +7,155 @@ namespace Mono.Linker.Tests.TestCases { - public class All - { - [Theory] - [MemberData(nameof(TestDatabase.DataFlow), MemberType = typeof(TestDatabase))] - public void DataFlow(string t) - { - Run(t); - } - - [Theory] - [MemberData (nameof (TestDatabase.DynamicDependencies), MemberType = typeof (TestDatabase))] - public void DynamicDependencies (string t) - { - Run (t); - } - - [Theory] - [MemberData (nameof (TestDatabase.Generics), MemberType = typeof (TestDatabase))] - public void Generics (string t) - { - Run (t); - } - - [Theory] - [MemberData(nameof(TestDatabase.InlineArrays), MemberType = typeof(TestDatabase))] - public void InlineArrays(string t) - { - Run(t); - } - - [Theory] - [MemberData(nameof(TestDatabase.Inheritance_Interaces), MemberType = typeof(TestDatabase))] - public void Inheritance_Interfaces(string t) - { - switch (t) { - case ".InterfaceWithoutNewSlot": - Run (t); - break; - default: - // Skip the rest for now - break; - } - } - - [Theory] - [MemberData(nameof(TestDatabase.Libraries), MemberType = typeof(TestDatabase))] - public void Libraries(string t) - { - Run(t); - } - - [Theory] - [MemberData (nameof (TestDatabase.LinkXml), MemberType = typeof (TestDatabase))] - public void LinkXml (string t) - { - Run (t); - } - - [Theory] - [MemberData (nameof (TestDatabase.Reflection), MemberType = typeof (TestDatabase))] - public void Reflection (string t) - { - switch (t) - { - case "ObjectGetTypeLibraryMode": - case "TypeHierarchyLibraryModeSuppressions": - // No Library mode - break; - default: - Run (t); - break; - } - } - - [Theory] - [MemberData (nameof (TestDatabase.Repro), MemberType = typeof (TestDatabase))] - public void Repro (string t) - { - Run (t); - } - - [Theory] - [MemberData(nameof(TestDatabase.RequiresCapability), MemberType = typeof(TestDatabase))] - public void RequiresCapability(string t) - { - Run(t); - } - - [Theory] - [MemberData (nameof (TestDatabase.SingleFile), MemberType = typeof (TestDatabase))] - public void SingleFile (string t) - { - Run (t); - } - - [Theory] - [MemberData (nameof (TestDatabase.Substitutions), MemberType = typeof (TestDatabase))] - public void Substitutions (string t) - { - switch (t) { - case "FeatureGuardSubstitutions": - Run (t); - break; - default: - // Skip the rest for now - break; - } - } - - [Theory] - [MemberData (nameof (TestDatabase.TopLevelStatements), MemberType = typeof (TestDatabase))] - public void TopLevelStatements (string t) - { - Run (t); - } - - [Theory] - [MemberData (nameof (TestDatabase.UnreachableBlock), MemberType = typeof (TestDatabase))] - public void UnreachableBlock (string t) - { - switch (t) { - case "TryCatchBlocks": - Run (t); - break; - default: - // Skip the rest for now - break; - } - } - - [Theory] - [MemberData (nameof (TestDatabase.Warnings), MemberType = typeof (TestDatabase))] - public void Warnings (string t) - { - Run (t); - } - - protected virtual void Run(string testName) - { - TestCase testCase = TestDatabase.GetTestCaseFromName(testName) ?? throw new InvalidOperationException($"Unknown test {testName}"); - var runner = new TestRunner(new ObjectFactory()); - var linkedResult = runner.Run(testCase); - if (linkedResult != null) - { - new ResultChecker().Check(linkedResult); - } - } - } + public class All + { + [Theory] + [MemberData(nameof(TestDatabase.DataFlow), MemberType = typeof(TestDatabase))] + public void DataFlow(string t) + { + Run(t); + } + + [Theory] + [MemberData(nameof(TestDatabase.DynamicDependencies), MemberType = typeof(TestDatabase))] + public void DynamicDependencies(string t) + { + Run(t); + } + + [Theory] + [MemberData(nameof(TestDatabase.Generics), MemberType = typeof(TestDatabase))] + public void Generics(string t) + { + Run(t); + } + + [Theory] + [MemberData(nameof(TestDatabase.InlineArrays), MemberType = typeof(TestDatabase))] + public void InlineArrays(string t) + { + Run(t); + } + + [Theory] + [MemberData(nameof(TestDatabase.Inheritance_Interaces), MemberType = typeof(TestDatabase))] + public void Inheritance_Interfaces(string t) + { + switch (t) + { + case ".InterfaceWithoutNewSlot": + Run(t); + break; + default: + // Skip the rest for now + break; + } + } + + [Theory] + [MemberData(nameof(TestDatabase.Libraries), MemberType = typeof(TestDatabase))] + public void Libraries(string t) + { + Run(t); + } + + [Theory] + [MemberData(nameof(TestDatabase.LinkXml), MemberType = typeof(TestDatabase))] + public void LinkXml(string t) + { + Run(t); + } + + [Theory] + [MemberData(nameof(TestDatabase.Reflection), MemberType = typeof(TestDatabase))] + public void Reflection(string t) + { + switch (t) + { + case "ObjectGetTypeLibraryMode": + case "TypeHierarchyLibraryModeSuppressions": + // No Library mode + break; + default: + Run(t); + break; + } + } + + [Theory] + [MemberData(nameof(TestDatabase.Repro), MemberType = typeof(TestDatabase))] + public void Repro(string t) + { + Run(t); + } + + [Theory] + [MemberData(nameof(TestDatabase.RequiresCapability), MemberType = typeof(TestDatabase))] + public void RequiresCapability(string t) + { + Run(t); + } + + [Theory] + [MemberData(nameof(TestDatabase.SingleFile), MemberType = typeof(TestDatabase))] + public void SingleFile(string t) + { + Run(t); + } + + [Theory] + [MemberData(nameof(TestDatabase.Substitutions), MemberType = typeof(TestDatabase))] + public void Substitutions(string t) + { + switch (t) + { + case "FeatureGuardSubstitutions": + Run(t); + break; + default: + // Skip the rest for now + break; + } + } + + [Theory] + [MemberData(nameof(TestDatabase.TopLevelStatements), MemberType = typeof(TestDatabase))] + public void TopLevelStatements(string t) + { + Run(t); + } + + [Theory] + [MemberData(nameof(TestDatabase.UnreachableBlock), MemberType = typeof(TestDatabase))] + public void UnreachableBlock(string t) + { + switch (t) + { + case "TryCatchBlocks": + Run(t); + break; + default: + // Skip the rest for now + break; + } + } + + [Theory] + [MemberData(nameof(TestDatabase.Warnings), MemberType = typeof(TestDatabase))] + public void Warnings(string t) + { + Run(t); + } + + protected virtual void Run(string testName) + { + TestCase testCase = TestDatabase.GetTestCaseFromName(testName) ?? throw new InvalidOperationException($"Unknown test {testName}"); + var runner = new TestRunner(new ObjectFactory()); + var linkedResult = runner.Run(testCase); + if (linkedResult != null) + { + new ResultChecker().Check(linkedResult); + } + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyChecker.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyChecker.cs index 2f89b128c32ebe..f2056e508d6a92 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyChecker.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyChecker.cs @@ -19,367 +19,386 @@ namespace Mono.Linker.Tests.TestCasesRunner { - partial class AssemblyChecker - { - class LinkedEntity - { - public TypeSystemEntity Entity { get; init; } - - public LinkedEntity(TypeSystemEntity entity) => Entity = entity; - } - - class LinkedMethodEntity : LinkedEntity - { - public bool IsReflected { get; init; } - - public MethodDesc Method { get => (MethodDesc) Entity; } - - public LinkedMethodEntity (MethodDesc method, bool isReflected) : base (method) => IsReflected = isReflected; - } - - private readonly BaseAssemblyResolver originalsResolver; - private readonly TypeNameResolver originalsTypeNameResolver; - private readonly ReaderParameters originalReaderParameters; - private readonly AssemblyDefinition originalAssembly; - private readonly TrimmedTestCaseResult testResult; - - private readonly Dictionary linkedMembers; - private readonly HashSet verifiedGeneratedFields = new HashSet (); - private readonly HashSet verifiedEventMethods = new HashSet (); - private readonly HashSet verifiedGeneratedTypes = new HashSet (); - private bool checkNames; - - // Note: It's enough to exclude the type name, all of its members will also be excluded then - private static readonly HashSet ExcludeDisplayNames = new () { + partial class AssemblyChecker + { + class LinkedEntity + { + public TypeSystemEntity Entity { get; init; } + + public LinkedEntity(TypeSystemEntity entity) => Entity = entity; + } + + class LinkedMethodEntity : LinkedEntity + { + public bool IsReflected { get; init; } + + public MethodDesc Method { get => (MethodDesc)Entity; } + + public LinkedMethodEntity(MethodDesc method, bool isReflected) : base(method) => IsReflected = isReflected; + } + + private readonly BaseAssemblyResolver originalsResolver; + private readonly TypeNameResolver originalsTypeNameResolver; + private readonly ReaderParameters originalReaderParameters; + private readonly AssemblyDefinition originalAssembly; + private readonly TrimmedTestCaseResult testResult; + + private readonly Dictionary linkedMembers; + private readonly HashSet verifiedGeneratedFields = new HashSet(); + private readonly HashSet verifiedEventMethods = new HashSet(); + private readonly HashSet verifiedGeneratedTypes = new HashSet(); + private bool checkNames; + + // Note: It's enough to exclude the type name, all of its members will also be excluded then + private static readonly HashSet ExcludeDisplayNames = new() { // Ignore compiler injected attributes to describe language version "Microsoft.CodeAnalysis.EmbeddedAttribute", - "System.Runtime.CompilerServices.RefSafetyRulesAttribute", + "System.Runtime.CompilerServices.RefSafetyRulesAttribute", // Ignore NativeAOT injected members ".StartupCodeMain(Int32,IntPtr)", - ".MainMethodWrapper()", - ".MainMethodWrapper(String[])", + ".MainMethodWrapper()", + ".MainMethodWrapper(String[])", // Ignore compiler generated code which can't be reasonably matched to the source method "", - }; - - public AssemblyChecker ( - BaseAssemblyResolver originalsResolver, - ReaderParameters originalReaderParameters, - AssemblyDefinition original, - TrimmedTestCaseResult testResult) - { - this.originalsResolver = originalsResolver; - this.originalsTypeNameResolver = new TypeNameResolver (new TestResolver (), new TestAssemblyNameResolver (originalsResolver)); - this.originalReaderParameters = originalReaderParameters; - this.originalAssembly = original; - this.testResult = testResult; - this.linkedMembers = new (); - - checkNames = original.MainModule.GetTypeReferences ().Any (attr => - attr.Name == nameof (RemovedNameValueAttribute)); - } - - public void Verify () - { - var errors = VerifyImpl().ToList(); - if (errors.Any()) - { - Assert.Fail(string.Join(Environment.NewLine, errors)); - } - - } - - IEnumerable VerifyImpl() - { - // There are no type forwarders left after compilation in Native AOT - // VerifyExportedTypes (originalAssembly, linkedAssembly); - - // TODO - // VerifyCustomAttributes (originalAssembly, linkedAssembly); - // VerifySecurityAttributes (originalAssembly, linkedAssembly); - - // TODO - this is mostly attribute verification - // foreach (var originalModule in originalAssembly.Modules) - // VerifyModule (originalModule, linkedAssembly.Modules.FirstOrDefault (m => m.Name == originalModule.Name)); - - // TODO - // VerifyResources (originalAssembly, linkedAssembly); - - // There are no assembly reference in Native AOT - // VerifyReferences (originalAssembly, linkedAssembly); - - PopulateLinkedMembers (); - - var membersToAssert = originalAssembly.MainModule.Types; - foreach (var originalMember in membersToAssert) { - if (originalMember is TypeDefinition td) { - AssemblyQualifiedToken token = new (td); - - if (td.Name == "") { - linkedMembers.Remove (token); - continue; - } - - linkedMembers.TryGetValue ( - token, - out LinkedEntity? linkedMember); - - foreach(var err in VerifyTypeDefinition (td, linkedMember)) - yield return err; - linkedMembers.Remove (token); - - continue; - } - - throw new NotImplementedException ($"Don't know how to check member of type {originalMember.GetType ()}"); - } - - // Verify anything not in the main assembly - foreach(var err in VerifyLinkingOfOtherAssemblies(this.originalAssembly)) - yield return err; - - // Filter out all members which are not from the main assembly - // The Kept attributes are "optional" for non-main assemblies - string mainModuleName = originalAssembly.Name.Name; - List externalMembers = linkedMembers.Where (m => GetModuleName (m.Value.Entity) != mainModuleName).Select (m => m.Key).ToList (); - foreach (var externalMember in externalMembers) { - linkedMembers.Remove (externalMember); - } - - if (linkedMembers.Count != 0) - yield return "Linked output includes unexpected member:\n " + - string.Join ("\n ", linkedMembers.Values.Select (e => e.Entity.GetDisplayName ())); - } - - private void PopulateLinkedMembers () - { - foreach (TypeDesc type in testResult.TrimmingResults.AllEETypes) { - AddType (type); - } - - foreach (MethodDesc method in testResult.TrimmingResults.CompiledMethodBodies) { - AddMethod (method); - } - - foreach (MethodDesc method in testResult.TrimmingResults.ReflectedMethods) { - AddMethod (method, isReflected: true); - } - - void AddMethod (MethodDesc method, bool isReflected = false) - { - MethodDesc methodDef = method.GetTypicalMethodDefinition (); - - if (!ShouldIncludeMethod (methodDef)) - return; - - TypeDesc owningType = methodDef.OwningType; - - // Skip any methods on a delegate - we handle those in the AddType - // (AOT generates different methods for delegates compared to IL/metadata shapes) - if (owningType?.IsDelegate == true) - return; - - if (!AddTrimmedMethod (methodDef, isReflected)) - return; - - if (owningType is not null) { - AddType (owningType); - } - - if (methodDef.GetPropertyForAccessor () is { } property) - AddProperty (property); - - if (methodDef.GetEventForAccessor () is { } @event) - AddEvent (@event); - } - - void AddType (TypeDesc type) - { - TypeDesc typeDef = type.GetTypeDefinition (); - - if (!ShouldIncludeType (typeDef)) - return; - - if (!AddMember (typeDef)) - return; - - if (typeDef is MetadataType { ContainingType: { } containingType }) { - AddType (containingType); - } - - if (typeDef.IsDelegate) { - // AOT's handling of delegates is very different from the IL/metadata picture - // So to simplify this, we're going to automatically "mark" all of the delegate's methods - foreach (MethodDesc m in typeDef.GetMethods ()) { - if (ShouldIncludeEntityByDisplayName (m)) { - AddTrimmedMethod (m, isReflected: false); - } - } - } - } - - void AddProperty (PropertyPseudoDesc property) - { - // Note that this is currently called from AddMethod which will exit if the owning type is excluded - // and also add the owning type if necessary - if (!ShouldIncludeEntityByDisplayName (property)) - return; - - AddMember (property); - } - - void AddEvent (EventPseudoDesc @event) - { - // Note that this is currently called from AddMethod which will exit if the owning type is excluded - // and also add the owning type if necessary - if (!ShouldIncludeEntityByDisplayName (@event)) - return; - - AddMember (@event); - } - - bool AddMember (TypeSystemEntity entity) - { - Assert.False (entity is MethodDesc, "Use AddTrimmedMethod for all methods instead"); - return linkedMembers.TryAdd (new AssemblyQualifiedToken (entity), new LinkedEntity(entity)); - } - - bool AddTrimmedMethod (MethodDesc method, bool isReflected = false) - { - var token = new AssemblyQualifiedToken (method); - bool addedNew = true; - if (linkedMembers.TryGetValue(token, out var existingValue)) { - addedNew = false; - LinkedMethodEntity existingMethod = (LinkedMethodEntity) existingValue; - if (existingMethod.IsReflected || !isReflected) - return addedNew; - - linkedMembers.Remove (token); - } - - linkedMembers.Add (token, new LinkedMethodEntity (method, isReflected)); - return addedNew; - } - - static bool ShouldIncludeEntityByDisplayName (TypeSystemEntity entity) => !ExcludeDisplayNames.Contains (entity.GetDisplayName ()); - - static bool ShouldIncludeType (TypeDesc type) - { - if (type is MetadataType metadataType) { - if (metadataType.ContainingType is { } containingType) { - if (!ShouldIncludeType (containingType)) - return false; - } - - if (metadataType.Namespace.StartsWith ("Internal")) - return false; - - // Simple way to filter out system assemblies - the best way would be to get a list - // of input/reference assemblies and filter on that, but it's tricky and this should work for basically everything - if (metadataType.Namespace.StartsWith ("System")) - return false; - - - return ShouldIncludeEntityByDisplayName (type); - } - - return false; - } - - static bool ShouldIncludeMethod (MethodDesc method) => ShouldIncludeType (method.OwningType) && ShouldIncludeEntityByDisplayName (method); - } - - private static MetadataType? GetOwningType (TypeSystemEntity? entity) - { - return entity switch - { - MetadataType type => type.ContainingType as MetadataType, - MethodDesc method => method.OwningType as MetadataType, - PropertyPseudoDesc prop => prop.OwningType, - EventPseudoDesc e => e.OwningType, - _ => null - }; - } - - private static string? GetModuleName (TypeSystemEntity entity) - { - return entity switch { - MetadataType type => type.Module.ToString (), - _ => GetOwningType(entity)?.Module.ToString() - }; - } - - protected virtual IEnumerable VerifyModule (ModuleDefinition original, ModuleDefinition? linked) - { - // We never link away a module today so let's make sure the linked one isn't null - if (linked == null) { - yield return $"Linked assembly `{original.Assembly.Name.Name}` is missing module `{original.Name}`"; - yield break; - } - - var expected = original.Assembly.MainModule.AllDefinedTypes () - .SelectMany (t => GetCustomAttributeCtorValues (t, nameof (KeptModuleReferenceAttribute))) - .ToArray (); - - var actual = linked.ModuleReferences - .Select (name => name.Name) - .ToArray (); - - if (!expected.Equals(actual)) - yield return "Module references do not match"; - - foreach(var err in VerifyCustomAttributes (original, linked)) - yield return err; - } - - IEnumerable VerifyTypeDefinition (TypeDefinition original, LinkedEntity? linkedEntity) - { - TypeDesc? linked = linkedEntity?.Entity as TypeDesc; - if (linked != null && NameUtils.GetActualOriginDisplayName (linked) is string linkedDisplayName && verifiedGeneratedTypes.Contains (linkedDisplayName)) - yield break; - - EcmaModule? linkedModule = (linked as MetadataType)?.Module as EcmaModule; - - // - // Little bit complex check to allow easier test writing to match - // - It has [Kept] attribute or any variation of it - // - It contains Main method - // - It contains at least one member which has [Kept] attribute (not recursive) - // - bool expectedKept = - HasActiveKeptDerivedAttribute (original) || - (linked != null && linkedModule?.EntryPoint?.OwningType == linked) || - original.AllMembers ().Any (HasActiveKeptDerivedAttribute); - - if (!expectedKept) { - if (linked == null) - yield break; - - // Compiler generated members can't be annotated with `Kept` attributes directly - // For some of them we have special attributes (backing fields for example), but it's impractical to define - // special attributes for all types of compiler generated members (there are quite a few of them and they're - // going to change/increase over time). - // So we're effectively disabling Kept validation on compiler generated members - // Note that we still want to go "inside" each such member, as it might have additional attributes - // we do want to validate. There's no specific use case right now, but I can easily imagine one - // for more detailed testing of for example custom attributes on local functions, or similar. - if (!IsCompilerGeneratedMember (original)) - yield return $"Type `{original}' should have been removed"; - } - - bool prev = checkNames; - checkNames |= original.HasAttribute (nameof (VerifyMetadataNamesAttribute)); - - foreach(var err in VerifyTypeDefinitionKept (original, linked)) - yield return err; - - checkNames = prev; - - if (original.HasAttribute (nameof (CreatedMemberAttribute))) { - // For now always fail on this attribute since we don't know how to validate it - throw new NotSupportedException ("CreatedMemberAttribute is not yet supported by the test infra"); + }; + + public AssemblyChecker( + BaseAssemblyResolver originalsResolver, + ReaderParameters originalReaderParameters, + AssemblyDefinition original, + TrimmedTestCaseResult testResult) + { + this.originalsResolver = originalsResolver; + this.originalsTypeNameResolver = new TypeNameResolver(new TestResolver(), new TestAssemblyNameResolver(originalsResolver)); + this.originalReaderParameters = originalReaderParameters; + this.originalAssembly = original; + this.testResult = testResult; + this.linkedMembers = new(); + + checkNames = original.MainModule.GetTypeReferences().Any(attr => + attr.Name == nameof(RemovedNameValueAttribute)); + } + + public void Verify() + { + var errors = VerifyImpl().ToList(); + if (errors.Any()) + { + Assert.Fail(string.Join(Environment.NewLine, errors)); + } + + } + + IEnumerable VerifyImpl() + { + // There are no type forwarders left after compilation in Native AOT + // VerifyExportedTypes (originalAssembly, linkedAssembly); + + // TODO + // VerifyCustomAttributes (originalAssembly, linkedAssembly); + // VerifySecurityAttributes (originalAssembly, linkedAssembly); + + // TODO - this is mostly attribute verification + // foreach (var originalModule in originalAssembly.Modules) + // VerifyModule (originalModule, linkedAssembly.Modules.FirstOrDefault (m => m.Name == originalModule.Name)); + + // TODO + // VerifyResources (originalAssembly, linkedAssembly); + + // There are no assembly reference in Native AOT + // VerifyReferences (originalAssembly, linkedAssembly); + + PopulateLinkedMembers(); + + var membersToAssert = originalAssembly.MainModule.Types; + foreach (var originalMember in membersToAssert) + { + if (originalMember is TypeDefinition td) + { + AssemblyQualifiedToken token = new(td); + + if (td.Name == "") + { + linkedMembers.Remove(token); + continue; + } + + linkedMembers.TryGetValue( + token, + out LinkedEntity? linkedMember); + + foreach (var err in VerifyTypeDefinition(td, linkedMember)) + yield return err; + linkedMembers.Remove(token); + + continue; + } + + throw new NotImplementedException($"Don't know how to check member of type {originalMember.GetType()}"); + } + + // Verify anything not in the main assembly + foreach (var err in VerifyLinkingOfOtherAssemblies(this.originalAssembly)) + yield return err; + + // Filter out all members which are not from the main assembly + // The Kept attributes are "optional" for non-main assemblies + string mainModuleName = originalAssembly.Name.Name; + List externalMembers = linkedMembers.Where(m => GetModuleName(m.Value.Entity) != mainModuleName).Select(m => m.Key).ToList(); + foreach (var externalMember in externalMembers) + { + linkedMembers.Remove(externalMember); + } + + if (linkedMembers.Count != 0) + yield return "Linked output includes unexpected member:\n " + + string.Join("\n ", linkedMembers.Values.Select(e => e.Entity.GetDisplayName())); + } + + private void PopulateLinkedMembers() + { + foreach (TypeDesc type in testResult.TrimmingResults.AllEETypes) + { + AddType(type); + } + + foreach (MethodDesc method in testResult.TrimmingResults.CompiledMethodBodies) + { + AddMethod(method); + } + + foreach (MethodDesc method in testResult.TrimmingResults.ReflectedMethods) + { + AddMethod(method, isReflected: true); + } + + void AddMethod(MethodDesc method, bool isReflected = false) + { + MethodDesc methodDef = method.GetTypicalMethodDefinition(); + + if (!ShouldIncludeMethod(methodDef)) + return; + + TypeDesc owningType = methodDef.OwningType; + + // Skip any methods on a delegate - we handle those in the AddType + // (AOT generates different methods for delegates compared to IL/metadata shapes) + if (owningType?.IsDelegate == true) + return; + + if (!AddTrimmedMethod(methodDef, isReflected)) + return; + + if (owningType is not null) + { + AddType(owningType); + } + + if (methodDef.GetPropertyForAccessor() is { } property) + AddProperty(property); + + if (methodDef.GetEventForAccessor() is { } @event) + AddEvent(@event); + } + + void AddType(TypeDesc type) + { + TypeDesc typeDef = type.GetTypeDefinition(); + + if (!ShouldIncludeType(typeDef)) + return; + + if (!AddMember(typeDef)) + return; + + if (typeDef is MetadataType { ContainingType: { } containingType }) + { + AddType(containingType); + } + + if (typeDef.IsDelegate) + { + // AOT's handling of delegates is very different from the IL/metadata picture + // So to simplify this, we're going to automatically "mark" all of the delegate's methods + foreach (MethodDesc m in typeDef.GetMethods()) + { + if (ShouldIncludeEntityByDisplayName(m)) + { + AddTrimmedMethod(m, isReflected: false); + } + } + } + } + + void AddProperty(PropertyPseudoDesc property) + { + // Note that this is currently called from AddMethod which will exit if the owning type is excluded + // and also add the owning type if necessary + if (!ShouldIncludeEntityByDisplayName(property)) + return; + + AddMember(property); + } + + void AddEvent(EventPseudoDesc @event) + { + // Note that this is currently called from AddMethod which will exit if the owning type is excluded + // and also add the owning type if necessary + if (!ShouldIncludeEntityByDisplayName(@event)) + return; + + AddMember(@event); + } + + bool AddMember(TypeSystemEntity entity) + { + Assert.False(entity is MethodDesc, "Use AddTrimmedMethod for all methods instead"); + return linkedMembers.TryAdd(new AssemblyQualifiedToken(entity), new LinkedEntity(entity)); + } + + bool AddTrimmedMethod(MethodDesc method, bool isReflected = false) + { + var token = new AssemblyQualifiedToken(method); + bool addedNew = true; + if (linkedMembers.TryGetValue(token, out var existingValue)) + { + addedNew = false; + LinkedMethodEntity existingMethod = (LinkedMethodEntity)existingValue; + if (existingMethod.IsReflected || !isReflected) + return addedNew; + + linkedMembers.Remove(token); + } + + linkedMembers.Add(token, new LinkedMethodEntity(method, isReflected)); + return addedNew; + } + + static bool ShouldIncludeEntityByDisplayName(TypeSystemEntity entity) => !ExcludeDisplayNames.Contains(entity.GetDisplayName()); + + static bool ShouldIncludeType(TypeDesc type) + { + if (type is MetadataType metadataType) + { + if (metadataType.ContainingType is { } containingType) + { + if (!ShouldIncludeType(containingType)) + return false; + } + + if (metadataType.Namespace.StartsWith("Internal")) + return false; + + // Simple way to filter out system assemblies - the best way would be to get a list + // of input/reference assemblies and filter on that, but it's tricky and this should work for basically everything + if (metadataType.Namespace.StartsWith("System")) + return false; + + + return ShouldIncludeEntityByDisplayName(type); + } + + return false; + } + + static bool ShouldIncludeMethod(MethodDesc method) => ShouldIncludeType(method.OwningType) && ShouldIncludeEntityByDisplayName(method); + } + + private static MetadataType? GetOwningType(TypeSystemEntity? entity) + { + return entity switch + { + MetadataType type => type.ContainingType as MetadataType, + MethodDesc method => method.OwningType as MetadataType, + PropertyPseudoDesc prop => prop.OwningType, + EventPseudoDesc e => e.OwningType, + _ => null + }; + } + + private static string? GetModuleName(TypeSystemEntity entity) + { + return entity switch + { + MetadataType type => type.Module.ToString(), + _ => GetOwningType(entity)?.Module.ToString() + }; + } + + protected virtual IEnumerable VerifyModule(ModuleDefinition original, ModuleDefinition? linked) + { + // We never link away a module today so let's make sure the linked one isn't null + if (linked == null) + { + yield return $"Linked assembly `{original.Assembly.Name.Name}` is missing module `{original.Name}`"; + yield break; + } + + var expected = original.Assembly.MainModule.AllDefinedTypes() + .SelectMany(t => GetCustomAttributeCtorValues(t, nameof(KeptModuleReferenceAttribute))) + .ToArray(); + + var actual = linked.ModuleReferences + .Select(name => name.Name) + .ToArray(); + + if (!expected.Equals(actual)) + yield return "Module references do not match"; + + foreach (var err in VerifyCustomAttributes(original, linked)) + yield return err; + } + + IEnumerable VerifyTypeDefinition(TypeDefinition original, LinkedEntity? linkedEntity) + { + TypeDesc? linked = linkedEntity?.Entity as TypeDesc; + if (linked != null && NameUtils.GetActualOriginDisplayName(linked) is string linkedDisplayName && verifiedGeneratedTypes.Contains(linkedDisplayName)) + yield break; + + EcmaModule? linkedModule = (linked as MetadataType)?.Module as EcmaModule; + + // + // Little bit complex check to allow easier test writing to match + // - It has [Kept] attribute or any variation of it + // - It contains Main method + // - It contains at least one member which has [Kept] attribute (not recursive) + // + bool expectedKept = + HasActiveKeptDerivedAttribute(original) || + (linked != null && linkedModule?.EntryPoint?.OwningType == linked) || + original.AllMembers().Any(HasActiveKeptDerivedAttribute); + + if (!expectedKept) + { + if (linked == null) + yield break; + + // Compiler generated members can't be annotated with `Kept` attributes directly + // For some of them we have special attributes (backing fields for example), but it's impractical to define + // special attributes for all types of compiler generated members (there are quite a few of them and they're + // going to change/increase over time). + // So we're effectively disabling Kept validation on compiler generated members + // Note that we still want to go "inside" each such member, as it might have additional attributes + // we do want to validate. There's no specific use case right now, but I can easily imagine one + // for more detailed testing of for example custom attributes on local functions, or similar. + if (!IsCompilerGeneratedMember(original)) + yield return $"Type `{original}' should have been removed"; + } + + bool prev = checkNames; + checkNames |= original.HasAttribute(nameof(VerifyMetadataNamesAttribute)); + + foreach (var err in VerifyTypeDefinitionKept(original, linked)) + yield return err; + + checkNames = prev; + + if (original.HasAttribute(nameof(CreatedMemberAttribute))) + { + // For now always fail on this attribute since we don't know how to validate it + throw new NotSupportedException("CreatedMemberAttribute is not yet supported by the test infra"); #if false foreach (var attr in original.CustomAttributes.Where (l => l.AttributeType.Name == nameof (CreatedMemberAttribute))) { var newName = original.FullName + "::" + attr.ConstructorArguments[0].Value.ToString (); @@ -391,21 +410,22 @@ IEnumerable VerifyTypeDefinition (TypeDefinition original, LinkedEntity? linkedMembers.Remove (linkedMemberName); } #endif - } - } - - protected virtual IEnumerable VerifyTypeDefinitionKept (TypeDefinition original, TypeDesc? linked) - { - // NativeAOT will not keep delegate backing field type information, it's compiled down to a set of static fields - // this infra currently doesn't track fields in any way. - // Same goes for private implementation detail type. - if (IsDelegateBackingFieldsType (original) || IsPrivateImplementationDetailsType(original)) - yield break; - - if (linked == null) { - yield return $"Type `{original}' should have been kept"; - yield break; - } + } + } + + protected virtual IEnumerable VerifyTypeDefinitionKept(TypeDefinition original, TypeDesc? linked) + { + // NativeAOT will not keep delegate backing field type information, it's compiled down to a set of static fields + // this infra currently doesn't track fields in any way. + // Same goes for private implementation detail type. + if (IsDelegateBackingFieldsType(original) || IsPrivateImplementationDetailsType(original)) + yield break; + + if (linked == null) + { + yield return $"Type `{original}' should have been kept"; + yield break; + } #if false // Skip verification of type metadata for compiler generated types (we don't currently need it yet) @@ -434,39 +454,42 @@ protected virtual IEnumerable VerifyTypeDefinitionKept (TypeDefinition o } #endif - foreach (var td in original.NestedTypes) { - AssemblyQualifiedToken token = new (td); - linkedMembers.TryGetValue ( - token, - out LinkedEntity? linkedMember); - - foreach(var err in VerifyTypeDefinition (td, linkedMember)) - yield return err; - linkedMembers.Remove (token); - } - - //// Need to check properties before fields so that the KeptBackingFieldAttribute is handled correctly - foreach (var p in original.Properties) { - AssemblyQualifiedToken token = new AssemblyQualifiedToken (p); - - linkedMembers.TryGetValue ( - token, - out LinkedEntity? linkedMember); - foreach(var err in VerifyProperty (p, linkedMember, linked)) - yield return err; - linkedMembers.Remove (token); - } - // Need to check events before fields so that the KeptBackingFieldAttribute is handled correctly - foreach (var e in original.Events) { - AssemblyQualifiedToken token = new AssemblyQualifiedToken (e); - - linkedMembers.TryGetValue ( - token, - out LinkedEntity? linkedMember); - foreach(var err in VerifyEvent (e, linkedMember, linked)) - yield return err; - linkedMembers.Remove (token); - } + foreach (var td in original.NestedTypes) + { + AssemblyQualifiedToken token = new(td); + linkedMembers.TryGetValue( + token, + out LinkedEntity? linkedMember); + + foreach (var err in VerifyTypeDefinition(td, linkedMember)) + yield return err; + linkedMembers.Remove(token); + } + + //// Need to check properties before fields so that the KeptBackingFieldAttribute is handled correctly + foreach (var p in original.Properties) + { + AssemblyQualifiedToken token = new AssemblyQualifiedToken(p); + + linkedMembers.TryGetValue( + token, + out LinkedEntity? linkedMember); + foreach (var err in VerifyProperty(p, linkedMember, linked)) + yield return err; + linkedMembers.Remove(token); + } + // Need to check events before fields so that the KeptBackingFieldAttribute is handled correctly + foreach (var e in original.Events) + { + AssemblyQualifiedToken token = new AssemblyQualifiedToken(e); + + linkedMembers.TryGetValue( + token, + out LinkedEntity? linkedMember); + foreach (var err in VerifyEvent(e, linkedMember, linked)) + yield return err; + linkedMembers.Remove(token); + } #if false // Need to check delegate cache fields before the normal field check @@ -480,107 +503,120 @@ protected virtual IEnumerable VerifyTypeDefinitionKept (TypeDefinition o } #endif - foreach (var m in original.Methods) { - if (verifiedEventMethods.Contains (m.FullName)) - continue; - - AssemblyQualifiedToken token = new (m); - linkedMembers.TryGetValue ( - token, - out LinkedEntity? linkedMember); - - foreach(var err in VerifyMethod (m, linkedMember)) - yield return err; - linkedMembers.Remove (token); - } - } - - private IEnumerable VerifyBaseType (TypeDefinition src, TypeDefinition linked) - { - string expectedBaseName; - var expectedBaseGenericAttr = src.CustomAttributes.FirstOrDefault (w => w.AttributeType.Name == nameof (KeptBaseTypeAttribute) && w.ConstructorArguments.Count > 1); - if (expectedBaseGenericAttr != null) { - expectedBaseName = FormatBaseOrInterfaceAttributeValue (expectedBaseGenericAttr); - } else { - var defaultBaseType = src.IsEnum ? "System.Enum" : src.IsValueType ? "System.ValueType" : "System.Object"; - expectedBaseName = GetCustomAttributeCtorValues (src, nameof (KeptBaseTypeAttribute)).FirstOrDefault ()?.ToString () ?? defaultBaseType; - } - - if (expectedBaseName != linked.BaseType?.FullName) { - yield return $"Incorrect base type on : {linked.Name}. Expected {expectedBaseName}, actual {linked.BaseType?.FullName}"; - } - } - - private IEnumerable VerifyInterfaces (TypeDefinition src, TypeDefinition linked) - { - var expectedInterfaces = new HashSet (src.CustomAttributes - .Where (w => w.AttributeType.Name == nameof (KeptInterfaceAttribute)) - .Select (FormatBaseOrInterfaceAttributeValue)); - if (expectedInterfaces.Count == 0) { - if (linked.HasInterfaces) - yield return $"Type `{src}' has unexpected interfaces"; - } else { - foreach (var iface in linked.Interfaces) { - if (!expectedInterfaces.Remove (iface.InterfaceType.FullName)) { - if (true != expectedInterfaces.Remove (iface.InterfaceType.Resolve ().FullName)) - yield return $"Type `{src}' interface `{iface.InterfaceType.Resolve ().FullName}' should have been removed"; - } - } - - if (expectedInterfaces.Count != 0) - yield return $"Expected interfaces were not found on {src}"; - } - } - - private static string FormatBaseOrInterfaceAttributeValue (CustomAttribute attr) - { - if (attr.ConstructorArguments.Count == 1) - return attr.ConstructorArguments[0].Value.ToString ()!; - - StringBuilder builder = new StringBuilder (); - builder.Append (attr.ConstructorArguments[0].Value); - builder.Append ('<'); - bool separator = false; - foreach (var caa in (CustomAttributeArgument[]) attr.ConstructorArguments[1].Value) { - if (separator) - builder.Append (','); - else - separator = true; - - var arg = (CustomAttributeArgument) caa.Value; - builder.Append (arg.Value); - } - - builder.Append ('>'); - return builder.ToString (); - } - - private IEnumerable VerifyField (FieldDefinition src, FieldDesc? linked) - { - bool compilerGenerated = IsCompilerGeneratedMember (src); - bool expectedKept = ShouldBeKept (src) | compilerGenerated; - - if (!expectedKept) { - if (linked != null) - yield return $"Field `{src}' should have been removed"; - - yield break; - } - - foreach(var err in VerifyFieldKept (src, linked, compilerGenerated)) - yield return err; - } - - private static IEnumerable VerifyFieldKept (FieldDefinition src, FieldDesc? linked, bool compilerGenerated) - { - if (linked == null) { - yield return $"Field `{src}' should have been kept"; - yield break; - } - - - if (src.HasConstant) - throw new NotImplementedException ("Constant value for a field is not yet supported by the test infra."); + foreach (var m in original.Methods) + { + if (verifiedEventMethods.Contains(m.FullName)) + continue; + + AssemblyQualifiedToken token = new(m); + linkedMembers.TryGetValue( + token, + out LinkedEntity? linkedMember); + + foreach (var err in VerifyMethod(m, linkedMember)) + yield return err; + linkedMembers.Remove(token); + } + } + + private IEnumerable VerifyBaseType(TypeDefinition src, TypeDefinition linked) + { + string expectedBaseName; + var expectedBaseGenericAttr = src.CustomAttributes.FirstOrDefault(w => w.AttributeType.Name == nameof(KeptBaseTypeAttribute) && w.ConstructorArguments.Count > 1); + if (expectedBaseGenericAttr != null) + { + expectedBaseName = FormatBaseOrInterfaceAttributeValue(expectedBaseGenericAttr); + } + else + { + var defaultBaseType = src.IsEnum ? "System.Enum" : src.IsValueType ? "System.ValueType" : "System.Object"; + expectedBaseName = GetCustomAttributeCtorValues(src, nameof(KeptBaseTypeAttribute)).FirstOrDefault()?.ToString() ?? defaultBaseType; + } + + if (expectedBaseName != linked.BaseType?.FullName) + { + yield return $"Incorrect base type on : {linked.Name}. Expected {expectedBaseName}, actual {linked.BaseType?.FullName}"; + } + } + + private IEnumerable VerifyInterfaces(TypeDefinition src, TypeDefinition linked) + { + var expectedInterfaces = new HashSet(src.CustomAttributes + .Where(w => w.AttributeType.Name == nameof(KeptInterfaceAttribute)) + .Select(FormatBaseOrInterfaceAttributeValue)); + if (expectedInterfaces.Count == 0) + { + if (linked.HasInterfaces) + yield return $"Type `{src}' has unexpected interfaces"; + } + else + { + foreach (var iface in linked.Interfaces) + { + if (!expectedInterfaces.Remove(iface.InterfaceType.FullName)) + { + if (true != expectedInterfaces.Remove(iface.InterfaceType.Resolve().FullName)) + yield return $"Type `{src}' interface `{iface.InterfaceType.Resolve().FullName}' should have been removed"; + } + } + + if (expectedInterfaces.Count != 0) + yield return $"Expected interfaces were not found on {src}"; + } + } + + private static string FormatBaseOrInterfaceAttributeValue(CustomAttribute attr) + { + if (attr.ConstructorArguments.Count == 1) + return attr.ConstructorArguments[0].Value.ToString()!; + + StringBuilder builder = new StringBuilder(); + builder.Append(attr.ConstructorArguments[0].Value); + builder.Append('<'); + bool separator = false; + foreach (var caa in (CustomAttributeArgument[])attr.ConstructorArguments[1].Value) + { + if (separator) + builder.Append(','); + else + separator = true; + + var arg = (CustomAttributeArgument)caa.Value; + builder.Append(arg.Value); + } + + builder.Append('>'); + return builder.ToString(); + } + + private IEnumerable VerifyField(FieldDefinition src, FieldDesc? linked) + { + bool compilerGenerated = IsCompilerGeneratedMember(src); + bool expectedKept = ShouldBeKept(src) | compilerGenerated; + + if (!expectedKept) + { + if (linked != null) + yield return $"Field `{src}' should have been removed"; + + yield break; + } + + foreach (var err in VerifyFieldKept(src, linked, compilerGenerated)) + yield return err; + } + + private static IEnumerable VerifyFieldKept(FieldDefinition src, FieldDesc? linked, bool compilerGenerated) + { + if (linked == null) + { + yield return $"Field `{src}' should have been kept"; + yield break; + } + + + if (src.HasConstant) + throw new NotImplementedException("Constant value for a field is not yet supported by the test infra."); #if false if (!Equals (src.Constant, linked.Constant)) { yield return $"Field '{src}' value doesn's match. Expected {src.Constant}, actual {linked.Constant}"; @@ -594,30 +630,32 @@ private static IEnumerable VerifyFieldKept (FieldDefinition src, FieldDe foreach(var err in VerifyCustomAttributes (src, linked)) yield return err; #endif - } + } - private IEnumerable VerifyProperty (PropertyDefinition src, LinkedEntity? linkedEntity, TypeDesc linkedType) - { - PropertyPseudoDesc? linked = linkedEntity?.Entity as PropertyPseudoDesc; - VerifyMemberBackingField (src, linkedType); + private IEnumerable VerifyProperty(PropertyDefinition src, LinkedEntity? linkedEntity, TypeDesc linkedType) + { + PropertyPseudoDesc? linked = linkedEntity?.Entity as PropertyPseudoDesc; + VerifyMemberBackingField(src, linkedType); - bool compilerGenerated = IsCompilerGeneratedMember (src); - bool expectedKept = ShouldBeKept (src) || compilerGenerated; + bool compilerGenerated = IsCompilerGeneratedMember(src); + bool expectedKept = ShouldBeKept(src) || compilerGenerated; - if (!expectedKept) { - if (linked is not null) - yield return $"Property `{src}' should have been removed"; + if (!expectedKept) + { + if (linked is not null) + yield return $"Property `{src}' should have been removed"; - yield break; - } + yield break; + } - if (linked is null) { - yield return $"Property `{src}' should have been kept"; - yield break; - } + if (linked is null) + { + yield return $"Property `{src}' should have been kept"; + yield break; + } - if (src.HasConstant) - throw new NotSupportedException ("Constant value for a property is not yet supported by the test infra."); + if (src.HasConstant) + throw new NotSupportedException("Constant value for a property is not yet supported by the test infra."); #if false if (src.Constant != linked.Constant) { yield return $"Property '{src}' value doesn's match. Expected {src.Constant}, actual {linked.Constant}"; @@ -633,46 +671,50 @@ private IEnumerable VerifyProperty (PropertyDefinition src, LinkedEntity yield return err; } #endif - } - - private IEnumerable VerifyEvent (EventDefinition src, LinkedEntity? linkedEntity, TypeDesc linkedType) - { - EventPseudoDesc? linked = linkedEntity?.Entity as EventPseudoDesc; - foreach(var err in VerifyMemberBackingField (src, linkedType)) - yield return err; - - bool compilerGenerated = IsCompilerGeneratedMember (src); - bool expectedKept = ShouldBeKept (src) | compilerGenerated; - - if (!expectedKept) { - if (linked is not null) - yield return $"Event `{src}' should have been removed"; - - yield break; - } - - if (linked is null) { - yield return $"Event `{src}' should have been kept"; - yield break; - } - - if (src.CustomAttributes.Any (attr => attr.AttributeType.Name == nameof (KeptEventAddMethodAttribute))) { - // TODO: This is wrong - we can't validate that the method is present by looking at linked (as that is not actually linked) - // we need to look into linkedMembers to see if the method was actually preserved by the compiler (and has an entry point) - foreach(var err in VerifyMethodInternal (src.AddMethod, new LinkedMethodEntity(linked.AddMethod, false), true, compilerGenerated)) - yield return err; - verifiedEventMethods.Add (src.AddMethod.FullName); - linkedMembers.Remove (new AssemblyQualifiedToken (src.AddMethod)); - } - - if (src.CustomAttributes.Any (attr => attr.AttributeType.Name == nameof (KeptEventRemoveMethodAttribute))) { - // TODO: This is wrong - we can't validate that the method is present by looking at linked (as that is not actually linked) - // we need to look into linkedMembers to see if the method was actually preserved by the compiler (and has an entry point) - foreach(var err in VerifyMethodInternal (src.RemoveMethod, new LinkedMethodEntity(linked.RemoveMethod, false), true, compilerGenerated)) - yield return err; - verifiedEventMethods.Add (src.RemoveMethod.FullName); - linkedMembers.Remove (new AssemblyQualifiedToken (src.RemoveMethod)); - } + } + + private IEnumerable VerifyEvent(EventDefinition src, LinkedEntity? linkedEntity, TypeDesc linkedType) + { + EventPseudoDesc? linked = linkedEntity?.Entity as EventPseudoDesc; + foreach (var err in VerifyMemberBackingField(src, linkedType)) + yield return err; + + bool compilerGenerated = IsCompilerGeneratedMember(src); + bool expectedKept = ShouldBeKept(src) | compilerGenerated; + + if (!expectedKept) + { + if (linked is not null) + yield return $"Event `{src}' should have been removed"; + + yield break; + } + + if (linked is null) + { + yield return $"Event `{src}' should have been kept"; + yield break; + } + + if (src.CustomAttributes.Any(attr => attr.AttributeType.Name == nameof(KeptEventAddMethodAttribute))) + { + // TODO: This is wrong - we can't validate that the method is present by looking at linked (as that is not actually linked) + // we need to look into linkedMembers to see if the method was actually preserved by the compiler (and has an entry point) + foreach (var err in VerifyMethodInternal(src.AddMethod, new LinkedMethodEntity(linked.AddMethod, false), true, compilerGenerated)) + yield return err; + verifiedEventMethods.Add(src.AddMethod.FullName); + linkedMembers.Remove(new AssemblyQualifiedToken(src.AddMethod)); + } + + if (src.CustomAttributes.Any(attr => attr.AttributeType.Name == nameof(KeptEventRemoveMethodAttribute))) + { + // TODO: This is wrong - we can't validate that the method is present by looking at linked (as that is not actually linked) + // we need to look into linkedMembers to see if the method was actually preserved by the compiler (and has an entry point) + foreach (var err in VerifyMethodInternal(src.RemoveMethod, new LinkedMethodEntity(linked.RemoveMethod, false), true, compilerGenerated)) + yield return err; + verifiedEventMethods.Add(src.RemoveMethod.FullName); + linkedMembers.Remove(new AssemblyQualifiedToken(src.RemoveMethod)); + } #if false foreach(var err in VerifyPseudoAttributes (src, linked)) @@ -683,70 +725,74 @@ private IEnumerable VerifyEvent (EventDefinition src, LinkedEntity? link yield return err; } #endif - } - - private IEnumerable VerifyMethod (MethodDefinition src, LinkedEntity? linkedEntity) - { - LinkedMethodEntity? linked = linkedEntity as LinkedMethodEntity; - bool compilerGenerated = IsCompilerGeneratedMember (src); - bool expectedKept = ShouldMethodBeKept (src); - foreach(var err in VerifyMethodInternal (src, linked, expectedKept, compilerGenerated)) - yield return err; - } - - private IEnumerable VerifyMethodInternal (MethodDefinition src, LinkedMethodEntity? linked, bool expectedKept, bool compilerGenerated) - { - if (!expectedKept) { - if (linked == null) - yield break; - - // Similar to comment on types, compiler-generated methods can't be annotated with Kept attribute directly - // so we're not going to validate kept/remove on them. Note that we're still going to go validate "into" them - // to check for other properties (like parameter name presence/removal for example) - if (!compilerGenerated) - yield return $"Method `{NameUtils.GetExpectedOriginDisplayName (src)}' should have been removed"; - } - - foreach(var err in VerifyMethodKept (src, linked, compilerGenerated)) - yield return err; - } - - private IEnumerable VerifyMemberBackingField (IMemberDefinition src, TypeDesc? linkedType) - { - var keptBackingFieldAttribute = src.CustomAttributes.FirstOrDefault (attr => attr.AttributeType.Name == nameof (KeptBackingFieldAttribute)); - if (keptBackingFieldAttribute == null) - yield break; - - var backingFieldName = src.MetadataToken.TokenType == TokenType.Property - ? $"<{src.Name}>k__BackingField" : src.Name; - var srcField = src.DeclaringType.Fields.FirstOrDefault (f => f.Name == backingFieldName); - - if (srcField == null) { - // Can add more here if necessary - backingFieldName = backingFieldName.Replace ("System.Int32", "int"); - backingFieldName = backingFieldName.Replace ("System.String", "string"); - backingFieldName = backingFieldName.Replace ("System.Char", "char"); - - srcField = src.DeclaringType.Fields.FirstOrDefault (f => f.Name == backingFieldName); - } - - if (srcField == null) { - yield return $"{src.MetadataToken.TokenType} `{src}', could not locate the expected backing field {backingFieldName}"; - yield break; - } - - foreach(var err in VerifyFieldKept (srcField, linkedType?.GetFields ()?.FirstOrDefault (l => srcField.Name == l.Name), compilerGenerated: true)) - yield return err; - verifiedGeneratedFields.Add (srcField.FullName); - linkedMembers.Remove (new AssemblyQualifiedToken (srcField)); - } - - IEnumerable VerifyMethodKept (MethodDefinition src, LinkedMethodEntity? linked, bool compilerGenerated) - { - if (linked == null) { - yield return $"Method `{NameUtils.GetExpectedOriginDisplayName (src)}' should have been kept"; - yield break; - } + } + + private IEnumerable VerifyMethod(MethodDefinition src, LinkedEntity? linkedEntity) + { + LinkedMethodEntity? linked = linkedEntity as LinkedMethodEntity; + bool compilerGenerated = IsCompilerGeneratedMember(src); + bool expectedKept = ShouldMethodBeKept(src); + foreach (var err in VerifyMethodInternal(src, linked, expectedKept, compilerGenerated)) + yield return err; + } + + private IEnumerable VerifyMethodInternal(MethodDefinition src, LinkedMethodEntity? linked, bool expectedKept, bool compilerGenerated) + { + if (!expectedKept) + { + if (linked == null) + yield break; + + // Similar to comment on types, compiler-generated methods can't be annotated with Kept attribute directly + // so we're not going to validate kept/remove on them. Note that we're still going to go validate "into" them + // to check for other properties (like parameter name presence/removal for example) + if (!compilerGenerated) + yield return $"Method `{NameUtils.GetExpectedOriginDisplayName(src)}' should have been removed"; + } + + foreach (var err in VerifyMethodKept(src, linked, compilerGenerated)) + yield return err; + } + + private IEnumerable VerifyMemberBackingField(IMemberDefinition src, TypeDesc? linkedType) + { + var keptBackingFieldAttribute = src.CustomAttributes.FirstOrDefault(attr => attr.AttributeType.Name == nameof(KeptBackingFieldAttribute)); + if (keptBackingFieldAttribute == null) + yield break; + + var backingFieldName = src.MetadataToken.TokenType == TokenType.Property + ? $"<{src.Name}>k__BackingField" : src.Name; + var srcField = src.DeclaringType.Fields.FirstOrDefault(f => f.Name == backingFieldName); + + if (srcField == null) + { + // Can add more here if necessary + backingFieldName = backingFieldName.Replace("System.Int32", "int"); + backingFieldName = backingFieldName.Replace("System.String", "string"); + backingFieldName = backingFieldName.Replace("System.Char", "char"); + + srcField = src.DeclaringType.Fields.FirstOrDefault(f => f.Name == backingFieldName); + } + + if (srcField == null) + { + yield return $"{src.MetadataToken.TokenType} `{src}', could not locate the expected backing field {backingFieldName}"; + yield break; + } + + foreach (var err in VerifyFieldKept(srcField, linkedType?.GetFields()?.FirstOrDefault(l => srcField.Name == l.Name), compilerGenerated: true)) + yield return err; + verifiedGeneratedFields.Add(srcField.FullName); + linkedMembers.Remove(new AssemblyQualifiedToken(srcField)); + } + + IEnumerable VerifyMethodKept(MethodDefinition src, LinkedMethodEntity? linked, bool compilerGenerated) + { + if (linked == null) + { + yield return $"Method `{NameUtils.GetExpectedOriginDisplayName(src)}' should have been kept"; + yield break; + } #if false foreach(var err in VerifyPseudoAttributes (src, linked)) @@ -760,8 +806,8 @@ IEnumerable VerifyMethodKept (MethodDefinition src, LinkedMethodEntity? yield return err; } #endif - foreach(var err in VerifyParameters (src, linked)) - yield return err; + foreach (var err in VerifyParameters(src, linked)) + yield return err; #if false foreach(var err in VerifySecurityAttributes (src, linked)) yield return err; @@ -774,328 +820,343 @@ IEnumerable VerifyMethodKept (MethodDefinition src, LinkedMethodEntity? foreach(var err in VerifyKeptByAttributes (src, linked)) yield return err; #endif - } + } + + protected virtual IEnumerable VerifyMethodBody(MethodDefinition src, MethodDefinition linked) + { + if (!src.HasBody) + yield break; + + foreach (var err in VerifyInstructions(src, linked)) + yield return err; + foreach (var err in VerifyLocals(src, linked)) + yield return err; + } + + protected static IEnumerable VerifyInstructions(MethodDefinition src, MethodDefinition linked) + { + foreach (var err in VerifyBodyProperties( + src, + linked, + nameof(ExpectedInstructionSequenceAttribute), + nameof(ExpectBodyModifiedAttribute), + "instructions", + m => FormatMethodBody(m.Body), + attr => GetStringArrayAttributeValue(attr)!.ToArray())) + { + yield return err; + } + } + + public static string[] FormatMethodBody(MethodBody body) + { + List<(Instruction?, string)> result = new List<(Instruction?, string)>(body.Instructions.Count); + for (int index = 0; index < body.Instructions.Count; index++) + { + var instruction = body.Instructions[index]; + result.Add((instruction, FormatInstruction(instruction))); + } + + HashSet<(Instruction, Instruction)> existingTryBlocks = new HashSet<(Instruction, Instruction)>(); + foreach (var exHandler in body.ExceptionHandlers) + { + if (existingTryBlocks.Add((exHandler.TryStart, exHandler.TryEnd!))) + { + InsertBeforeInstruction(exHandler.TryStart, ".try"); + if (exHandler.TryEnd != null) + InsertBeforeInstruction(exHandler.TryEnd, ".endtry"); + else + Append(".endtry"); + } + + if (exHandler.HandlerStart != null) + InsertBeforeInstruction(exHandler.HandlerStart, ".catch"); + + if (exHandler.HandlerEnd != null) + InsertBeforeInstruction(exHandler.HandlerEnd, ".endcatch"); + else + Append(".endcatch"); + + if (exHandler.FilterStart != null) + InsertBeforeInstruction(exHandler.FilterStart, ".filter"); + } + + return result.Select(i => i.Item2).ToArray(); + + void InsertBeforeInstruction(Instruction instruction, string text) => + result.Insert(result.FindIndex(i => i.Item1 == instruction), (null, text)); + + void Append(string text) => + result.Add((null, text)); + } + + private static string FormatInstruction(Instruction instr) + { + switch (instr.OpCode.FlowControl) + { + case FlowControl.Branch: + case FlowControl.Cond_Branch: + if (instr.Operand is Instruction target) + return $"{instr.OpCode} il_{target.Offset:x}"; + + break; + } + + switch (instr.OpCode.Code) + { + case Code.Ldc_I4: + if (instr.Operand is int ivalue) + return $"{instr.OpCode} 0x{ivalue:x}"; + + throw new NotImplementedException(instr.Operand.GetType().ToString()); + case Code.Ldc_I4_S: + if (instr.Operand is sbyte bvalue) + return $"{instr.OpCode} 0x{bvalue:x}"; + + throw new NotImplementedException(instr.Operand.GetType().ToString()); + case Code.Ldc_I8: + if (instr.Operand is long lvalue) + return $"{instr.OpCode} 0x{lvalue:x}"; + + throw new NotImplementedException(instr.Operand.GetType().ToString()); + + case Code.Ldc_R4: + if (instr.Operand is float fvalue) + return $"{instr.OpCode} {fvalue}"; + + throw new NotImplementedException(instr.Operand.GetType().ToString()); + + case Code.Ldc_R8: + if (instr.Operand is double dvalue) + return $"{instr.OpCode} {dvalue}"; + + throw new NotImplementedException(instr.Operand.GetType().ToString()); + + case Code.Ldstr: + if (instr.Operand is string svalue) + return $"{instr.OpCode} '{svalue}'"; + + throw new NotImplementedException(instr.Operand.GetType().ToString()); + + default: + { + string? operandString = null; + switch (instr.OpCode.OperandType) + { + case OperandType.InlineField: + case OperandType.InlineMethod: + case OperandType.InlineType: + case OperandType.InlineTok: + operandString = instr.Operand switch + { + FieldReference fieldRef => fieldRef.FullName, + MethodReference methodRef => methodRef.FullName, + TypeReference typeRef => typeRef.FullName, + _ => null + }; + break; + } + + if (operandString != null) + return $"{instr.OpCode} {operandString}"; + else + return instr.OpCode.ToString(); + } + } + } + + private static IEnumerable VerifyLocals(MethodDefinition src, MethodDefinition linked) + { + foreach (var err in VerifyBodyProperties( + src, + linked, + nameof(ExpectedLocalsSequenceAttribute), + nameof(ExpectLocalsModifiedAttribute), + "locals", + m => m.Body.Variables.Select(v => v.VariableType.ToString()).ToArray(), + attr => GetStringOrTypeArrayAttributeValue(attr).ToArray())) + { + yield return err; + } + } + + public static IEnumerable VerifyBodyProperties(MethodDefinition src, MethodDefinition linked, string sequenceAttributeName, string expectModifiedAttributeName, + string propertyDescription, + Func valueCollector, + Func getExpectFromSequenceAttribute) + { + var expectedSequenceAttribute = src.CustomAttributes.FirstOrDefault(attr => attr.AttributeType.Name == sequenceAttributeName); + var linkedValues = valueCollector(linked); + var srcValues = valueCollector(src); + + if (src.CustomAttributes.Any(attr => attr.AttributeType.Name == expectModifiedAttributeName)) + { + if (linkedValues.SequenceEqual(srcValues)) + { + yield return $"Expected method `{src} to have {propertyDescription} modified, however, the {propertyDescription} were the same as the original\n{FormattingUtils.FormatSequenceCompareFailureMessage(linkedValues, srcValues)}"; + } + } + else if (expectedSequenceAttribute != null) + { + var expected = getExpectFromSequenceAttribute(expectedSequenceAttribute).ToArray(); + if (!linkedValues.SequenceEqual(expected)) + { + yield return $"Expected method `{src} to have it's {propertyDescription} modified, however, the sequence of {propertyDescription} does not match the expected value\n{FormattingUtils.FormatSequenceCompareFailureMessage2(linkedValues, expected, srcValues)}"; + } + } + else + { + if (!linkedValues.SequenceEqual(srcValues)) + { + yield return $"Expected method `{src} to have it's {propertyDescription} unchanged, however, the {propertyDescription} differ from the original\n{FormattingUtils.FormatSequenceCompareFailureMessage(linkedValues, srcValues)}"; + } + } + } + + private IEnumerable VerifyReferences(AssemblyDefinition original, AssemblyDefinition linked) + { + var expected = original.MainModule.AllDefinedTypes() + .SelectMany(t => GetCustomAttributeCtorValues(t, nameof(KeptReferenceAttribute))) + .Select(ReduceAssemblyFileNameOrNameToNameOnly) + .ToArray(); + + /* + - The test case will always need to have at least 1 reference. + - Forcing all tests to define their expected references seems tedious - protected virtual IEnumerable VerifyMethodBody (MethodDefinition src, MethodDefinition linked) - { - if (!src.HasBody) - yield break; + Given the above, let's assume that when no [KeptReference] attributes are present, + the test case does not want to make any assertions regarding references. - foreach(var err in VerifyInstructions (src, linked)) - yield return err; - foreach(var err in VerifyLocals (src, linked)) - yield return err; - } - - protected static IEnumerable VerifyInstructions (MethodDefinition src, MethodDefinition linked) - { - foreach (var err in VerifyBodyProperties ( - src, - linked, - nameof (ExpectedInstructionSequenceAttribute), - nameof (ExpectBodyModifiedAttribute), - "instructions", - m => FormatMethodBody (m.Body), - attr => GetStringArrayAttributeValue (attr)!.ToArray ())) - { - yield return err; - } - } - - public static string[] FormatMethodBody (MethodBody body) - { - List<(Instruction?, string)> result = new List<(Instruction?, string)> (body.Instructions.Count); - for (int index = 0; index < body.Instructions.Count; index++) { - var instruction = body.Instructions[index]; - result.Add ((instruction, FormatInstruction (instruction))); - } - - HashSet<(Instruction, Instruction)> existingTryBlocks = new HashSet<(Instruction, Instruction)> (); - foreach (var exHandler in body.ExceptionHandlers) { - if (existingTryBlocks.Add ((exHandler.TryStart, exHandler.TryEnd!))) { - InsertBeforeInstruction (exHandler.TryStart, ".try"); - if (exHandler.TryEnd != null) - InsertBeforeInstruction (exHandler.TryEnd, ".endtry"); - else - Append (".endtry"); - } - - if (exHandler.HandlerStart != null) - InsertBeforeInstruction (exHandler.HandlerStart, ".catch"); - - if (exHandler.HandlerEnd != null) - InsertBeforeInstruction (exHandler.HandlerEnd, ".endcatch"); - else - Append (".endcatch"); - - if (exHandler.FilterStart != null) - InsertBeforeInstruction (exHandler.FilterStart, ".filter"); - } - - return result.Select (i => i.Item2).ToArray (); - - void InsertBeforeInstruction (Instruction instruction, string text) => - result.Insert (result.FindIndex (i => i.Item1 == instruction), (null, text)); - - void Append (string text) => - result.Add ((null, text)); - } - - private static string FormatInstruction (Instruction instr) - { - switch (instr.OpCode.FlowControl) { - case FlowControl.Branch: - case FlowControl.Cond_Branch: - if (instr.Operand is Instruction target) - return $"{instr.OpCode} il_{target.Offset:x}"; - - break; - } - - switch (instr.OpCode.Code) { - case Code.Ldc_I4: - if (instr.Operand is int ivalue) - return $"{instr.OpCode} 0x{ivalue:x}"; - - throw new NotImplementedException (instr.Operand.GetType ().ToString ()); - case Code.Ldc_I4_S: - if (instr.Operand is sbyte bvalue) - return $"{instr.OpCode} 0x{bvalue:x}"; - - throw new NotImplementedException (instr.Operand.GetType ().ToString ()); - case Code.Ldc_I8: - if (instr.Operand is long lvalue) - return $"{instr.OpCode} 0x{lvalue:x}"; - - throw new NotImplementedException (instr.Operand.GetType ().ToString ()); - - case Code.Ldc_R4: - if (instr.Operand is float fvalue) - return $"{instr.OpCode} {fvalue}"; - - throw new NotImplementedException (instr.Operand.GetType ().ToString ()); - - case Code.Ldc_R8: - if (instr.Operand is double dvalue) - return $"{instr.OpCode} {dvalue}"; - - throw new NotImplementedException (instr.Operand.GetType ().ToString ()); - - case Code.Ldstr: - if (instr.Operand is string svalue) - return $"{instr.OpCode} '{svalue}'"; - - throw new NotImplementedException (instr.Operand.GetType ().ToString ()); - - default: { - string? operandString = null; - switch (instr.OpCode.OperandType) { - case OperandType.InlineField: - case OperandType.InlineMethod: - case OperandType.InlineType: - case OperandType.InlineTok: - operandString = instr.Operand switch { - FieldReference fieldRef => fieldRef.FullName, - MethodReference methodRef => methodRef.FullName, - TypeReference typeRef => typeRef.FullName, - _ => null - }; - break; - } - - if (operandString != null) - return $"{instr.OpCode} {operandString}"; - else - return instr.OpCode.ToString (); - } - } - } - - private static IEnumerable VerifyLocals (MethodDefinition src, MethodDefinition linked) - { - foreach(var err in VerifyBodyProperties ( - src, - linked, - nameof (ExpectedLocalsSequenceAttribute), - nameof (ExpectLocalsModifiedAttribute), - "locals", - m => m.Body.Variables.Select (v => v.VariableType.ToString ()).ToArray (), - attr => GetStringOrTypeArrayAttributeValue (attr).ToArray ())) - { - yield return err; - } - } - - public static IEnumerable VerifyBodyProperties (MethodDefinition src, MethodDefinition linked, string sequenceAttributeName, string expectModifiedAttributeName, - string propertyDescription, - Func valueCollector, - Func getExpectFromSequenceAttribute) - { - var expectedSequenceAttribute = src.CustomAttributes.FirstOrDefault (attr => attr.AttributeType.Name == sequenceAttributeName); - var linkedValues = valueCollector (linked); - var srcValues = valueCollector (src); - - if (src.CustomAttributes.Any (attr => attr.AttributeType.Name == expectModifiedAttributeName)) { - if (linkedValues.SequenceEqual(srcValues)) - { - yield return $"Expected method `{src} to have {propertyDescription} modified, however, the {propertyDescription} were the same as the original\n{FormattingUtils.FormatSequenceCompareFailureMessage (linkedValues, srcValues)}"; - } - } else if (expectedSequenceAttribute != null) { - var expected = getExpectFromSequenceAttribute (expectedSequenceAttribute).ToArray (); - if (!linkedValues.SequenceEqual(expected)) - { - yield return $"Expected method `{src} to have it's {propertyDescription} modified, however, the sequence of {propertyDescription} does not match the expected value\n{FormattingUtils.FormatSequenceCompareFailureMessage2 (linkedValues, expected, srcValues)}"; - } - } else { - if (!linkedValues.SequenceEqual(srcValues)) - { - yield return $"Expected method `{src} to have it's {propertyDescription} unchanged, however, the {propertyDescription} differ from the original\n{FormattingUtils.FormatSequenceCompareFailureMessage (linkedValues, srcValues)}"; - } - } - } - - private IEnumerable VerifyReferences (AssemblyDefinition original, AssemblyDefinition linked) - { - var expected = original.MainModule.AllDefinedTypes () - .SelectMany (t => GetCustomAttributeCtorValues (t, nameof (KeptReferenceAttribute))) - .Select (ReduceAssemblyFileNameOrNameToNameOnly) - .ToArray (); - - /* - - The test case will always need to have at least 1 reference. - - Forcing all tests to define their expected references seems tedious - - Given the above, let's assume that when no [KeptReference] attributes are present, - the test case does not want to make any assertions regarding references. - - Once 1 kept reference attribute is used, the test will need to define all of of it's expected references - */ - if (expected.Length == 0) - yield break; - - var actual = linked.MainModule.AssemblyReferences - .Select (name => name.Name) - .ToArray (); - - if (!actual!.SequenceEqual(expected)) - yield return $"Expected references do not match actual references:\n\tExpected: {string.Join(", ", expected)}\n\tActual: {string.Join(", ", actual)}"; - } - - private string? ReduceAssemblyFileNameOrNameToNameOnly (string? fileNameOrAssemblyName) - { - if (fileNameOrAssemblyName == null) - return null; - - if (fileNameOrAssemblyName.EndsWith (".dll") || fileNameOrAssemblyName.EndsWith (".exe") || fileNameOrAssemblyName.EndsWith (".winmd")) - return System.IO.Path.GetFileNameWithoutExtension (fileNameOrAssemblyName); - - // It must already be just the assembly name - return fileNameOrAssemblyName; - } - - private IEnumerable VerifyResources (AssemblyDefinition original, AssemblyDefinition linked) - { - List expectedResourceNames = original.MainModule.AllDefinedTypes () - .SelectMany (t => GetCustomAttributeCtorValues (t, nameof (KeptResourceAttribute))) - .ToList (); - - foreach (var resource in linked.MainModule.Resources) { - if (!expectedResourceNames.Remove (resource.Name)) - yield return $"Resource '{resource.Name}' should be removed."; - - EmbeddedResource embeddedResource = (EmbeddedResource) resource; - - var expectedResource = (EmbeddedResource) original.MainModule.Resources.First (r => r.Name == resource.Name); - - if (!embeddedResource.GetResourceData().SequenceEqual(expectedResource.GetResourceData())) - yield return $"Resource '{resource.Name}' data doesn't match."; - } - - if (expectedResourceNames.Count > 0) { - yield return $"Resource '{expectedResourceNames.First ()}' should be kept."; - } - } - - private IEnumerable VerifyExportedTypes (AssemblyDefinition original, AssemblyDefinition linked) - { - var expectedTypes = original.MainModule.AllDefinedTypes () - .SelectMany (t => GetCustomAttributeCtorValues (t, nameof (KeptExportedTypeAttribute)).Select (l => l?.FullName ?? "")).ToArray (); - - if (!linked.MainModule.ExportedTypes.Select (l => l.FullName).SequenceEqual(expectedTypes)) - yield return $"Exported types do not match expected values"; - } - - protected virtual IEnumerable VerifyPseudoAttributes (MethodDefinition src, MethodDefinition linked) - { - var expected = (MethodAttributes) GetExpectedPseudoAttributeValue (src, (uint) src.Attributes); - if (!linked.Attributes.Equals(expected)) - { - yield return $"Method `{src}' pseudo attributes did not match expected"; - } - } - - protected virtual IEnumerable VerifyPseudoAttributes (TypeDefinition src, TypeDefinition linked) - { - var expected = (TypeAttributes) GetExpectedPseudoAttributeValue (src, (uint) src.Attributes); - - if (!linked.Attributes.Equals(expected)) - { - yield return $"Type `{src}' pseudo attributes did not match expected"; - } - } - - protected virtual IEnumerable VerifyPseudoAttributes (FieldDefinition src, FieldDefinition linked) - { - var expected = (FieldAttributes) GetExpectedPseudoAttributeValue (src, (uint) src.Attributes); - if (!linked.Attributes.Equals(expected)) - { - yield return $"Field `{src}' pseudo attributes did not match expected"; - } - } - - protected virtual IEnumerable VerifyPseudoAttributes (PropertyDefinition src, PropertyDefinition linked) - { - var expected = (PropertyAttributes) GetExpectedPseudoAttributeValue (src, (uint) src.Attributes); - if (!linked.Attributes.Equals(expected)) - { - yield return $"Property `{src}' pseudo attributes did not match expected"; - } - - } - - protected virtual IEnumerable VerifyPseudoAttributes (EventDefinition src, EventDefinition linked) - { - var expected = (EventAttributes) GetExpectedPseudoAttributeValue (src, (uint) src.Attributes); - if (!linked.Attributes.Equals(expected)) - { - yield return $"Event `{src}' pseudo attributes did not match expected"; - } - } - - protected virtual IEnumerable VerifyCustomAttributes (ICustomAttributeProvider src, ICustomAttributeProvider linked) - { - var expectedAttrs = GetExpectedAttributes (src).ToList (); - var linkedAttrs = FilterLinkedAttributes (linked).ToList (); - - if (!linkedAttrs.SequenceEqual(expectedAttrs)) - { - yield return $"Custom attributes on `{src}' are not matching"; - } - } - - protected virtual IEnumerable VerifySecurityAttributes (ICustomAttributeProvider src, ISecurityDeclarationProvider linked) - { - var expectedAttrs = GetCustomAttributeCtorValues (src, nameof (KeptSecurityAttribute)) - .Select (attr => attr?.ToString () ?? "") - .ToList (); - - var linkedAttrs = FilterLinkedSecurityAttributes (linked).ToList (); - - if (!linkedAttrs.SequenceEqual(expectedAttrs)) - { - yield return $"Security attributes on `{src}' are not matching"; - } - } + Once 1 kept reference attribute is used, the test will need to define all of of it's expected references + */ + if (expected.Length == 0) + yield break; + + var actual = linked.MainModule.AssemblyReferences + .Select(name => name.Name) + .ToArray(); + + if (!actual!.SequenceEqual(expected)) + yield return $"Expected references do not match actual references:\n\tExpected: {string.Join(", ", expected)}\n\tActual: {string.Join(", ", actual)}"; + } + + private string? ReduceAssemblyFileNameOrNameToNameOnly(string? fileNameOrAssemblyName) + { + if (fileNameOrAssemblyName == null) + return null; + + if (fileNameOrAssemblyName.EndsWith(".dll") || fileNameOrAssemblyName.EndsWith(".exe") || fileNameOrAssemblyName.EndsWith(".winmd")) + return System.IO.Path.GetFileNameWithoutExtension(fileNameOrAssemblyName); + + // It must already be just the assembly name + return fileNameOrAssemblyName; + } + + private IEnumerable VerifyResources(AssemblyDefinition original, AssemblyDefinition linked) + { + List expectedResourceNames = original.MainModule.AllDefinedTypes() + .SelectMany(t => GetCustomAttributeCtorValues(t, nameof(KeptResourceAttribute))) + .ToList(); + + foreach (var resource in linked.MainModule.Resources) + { + if (!expectedResourceNames.Remove(resource.Name)) + yield return $"Resource '{resource.Name}' should be removed."; + + EmbeddedResource embeddedResource = (EmbeddedResource)resource; + + var expectedResource = (EmbeddedResource)original.MainModule.Resources.First(r => r.Name == resource.Name); + + if (!embeddedResource.GetResourceData().SequenceEqual(expectedResource.GetResourceData())) + yield return $"Resource '{resource.Name}' data doesn't match."; + } + + if (expectedResourceNames.Count > 0) + { + yield return $"Resource '{expectedResourceNames.First()}' should be kept."; + } + } + + private IEnumerable VerifyExportedTypes(AssemblyDefinition original, AssemblyDefinition linked) + { + var expectedTypes = original.MainModule.AllDefinedTypes() + .SelectMany(t => GetCustomAttributeCtorValues(t, nameof(KeptExportedTypeAttribute)).Select(l => l?.FullName ?? "")).ToArray(); + + if (!linked.MainModule.ExportedTypes.Select(l => l.FullName).SequenceEqual(expectedTypes)) + yield return $"Exported types do not match expected values"; + } + + protected virtual IEnumerable VerifyPseudoAttributes(MethodDefinition src, MethodDefinition linked) + { + var expected = (MethodAttributes)GetExpectedPseudoAttributeValue(src, (uint)src.Attributes); + if (!linked.Attributes.Equals(expected)) + { + yield return $"Method `{src}' pseudo attributes did not match expected"; + } + } + + protected virtual IEnumerable VerifyPseudoAttributes(TypeDefinition src, TypeDefinition linked) + { + var expected = (TypeAttributes)GetExpectedPseudoAttributeValue(src, (uint)src.Attributes); + + if (!linked.Attributes.Equals(expected)) + { + yield return $"Type `{src}' pseudo attributes did not match expected"; + } + } + + protected virtual IEnumerable VerifyPseudoAttributes(FieldDefinition src, FieldDefinition linked) + { + var expected = (FieldAttributes)GetExpectedPseudoAttributeValue(src, (uint)src.Attributes); + if (!linked.Attributes.Equals(expected)) + { + yield return $"Field `{src}' pseudo attributes did not match expected"; + } + } + + protected virtual IEnumerable VerifyPseudoAttributes(PropertyDefinition src, PropertyDefinition linked) + { + var expected = (PropertyAttributes)GetExpectedPseudoAttributeValue(src, (uint)src.Attributes); + if (!linked.Attributes.Equals(expected)) + { + yield return $"Property `{src}' pseudo attributes did not match expected"; + } + + } + + protected virtual IEnumerable VerifyPseudoAttributes(EventDefinition src, EventDefinition linked) + { + var expected = (EventAttributes)GetExpectedPseudoAttributeValue(src, (uint)src.Attributes); + if (!linked.Attributes.Equals(expected)) + { + yield return $"Event `{src}' pseudo attributes did not match expected"; + } + } + + protected virtual IEnumerable VerifyCustomAttributes(ICustomAttributeProvider src, ICustomAttributeProvider linked) + { + var expectedAttrs = GetExpectedAttributes(src).ToList(); + var linkedAttrs = FilterLinkedAttributes(linked).ToList(); + + if (!linkedAttrs.SequenceEqual(expectedAttrs)) + { + yield return $"Custom attributes on `{src}' are not matching"; + } + } + + protected virtual IEnumerable VerifySecurityAttributes(ICustomAttributeProvider src, ISecurityDeclarationProvider linked) + { + var expectedAttrs = GetCustomAttributeCtorValues(src, nameof(KeptSecurityAttribute)) + .Select(attr => attr?.ToString() ?? "") + .ToList(); + + var linkedAttrs = FilterLinkedSecurityAttributes(linked).ToList(); + + if (!linkedAttrs.SequenceEqual(expectedAttrs)) + { + yield return $"Security attributes on `{src}' are not matching"; + } + } #if false protected virtual IEnumerable VerifyArrayInitializers (MethodDefinition src, MethodDefinition linked) @@ -1168,72 +1229,76 @@ private IEnumerable VerifyInitializerField (FieldDefinition src, FieldDe } #endif - private static bool IsLdtokenOnPrivateImplementationDetails (TypeDefinition privateImplementationDetails, Instruction instruction) - { - if (instruction.OpCode.Code == Code.Ldtoken && instruction.Operand is FieldReference field) { - return field.DeclaringType.Resolve () == privateImplementationDetails; - } - - return false; - } - - protected static IEnumerable GetExpectedAttributes (ICustomAttributeProvider original) - { - foreach (var expectedAttrs in GetCustomAttributeCtorValues (original, nameof (KeptAttributeAttribute))) - yield return expectedAttrs?.ToString (); - - // The name of the generated fixed buffer type is a little tricky. - // Some versions of csc name it `e__FixedBuffer0` - // while mcs and other versions of csc name it `__FixedBuffer0` - if (original is TypeDefinition srcDefinition && srcDefinition.Name.Contains ("__FixedBuffer")) { - var name = srcDefinition.Name.Substring (1, srcDefinition.Name.IndexOf ('>') - 1); - var fixedField = srcDefinition.DeclaringType.Fields.FirstOrDefault (f => f.Name == name); - if (fixedField == null) - Assert.Fail($"Could not locate original fixed field for {srcDefinition}"); - - foreach (var additionalExpectedAttributesFromFixedField in GetCustomAttributeCtorValues (fixedField!, nameof (KeptAttributeOnFixedBufferTypeAttribute))) - yield return additionalExpectedAttributesFromFixedField?.ToString (); - - } - } - - /// - /// Filters out some attributes that should not be taken into consideration when checking the linked result against the expected result - /// - /// - /// - protected virtual IEnumerable FilterLinkedAttributes (ICustomAttributeProvider linked) - { - foreach (var attr in linked.CustomAttributes) { - switch (attr.AttributeType.FullName) { - case "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute": - case "System.Runtime.CompilerServices.CompilerGeneratedAttribute": - continue; - - // When mcs is used to compile the test cases, backing fields end up with this attribute on them - case "System.Diagnostics.DebuggerBrowsableAttribute": - continue; - - // When compiling with roslyn, assemblies get the DebuggableAttribute by default. - case "System.Diagnostics.DebuggableAttribute": - continue; - - case "System.Runtime.CompilerServices.CompilationRelaxationsAttribute": - if (linked is AssemblyDefinition) - continue; - break; - } - - yield return attr.AttributeType.FullName; - } - } - - protected virtual IEnumerable FilterLinkedSecurityAttributes (ISecurityDeclarationProvider linked) - { - return linked.SecurityDeclarations - .SelectMany (d => d.SecurityAttributes) - .Select (attr => attr.AttributeType.ToString ()); - } + private static bool IsLdtokenOnPrivateImplementationDetails(TypeDefinition privateImplementationDetails, Instruction instruction) + { + if (instruction.OpCode.Code == Code.Ldtoken && instruction.Operand is FieldReference field) + { + return field.DeclaringType.Resolve() == privateImplementationDetails; + } + + return false; + } + + protected static IEnumerable GetExpectedAttributes(ICustomAttributeProvider original) + { + foreach (var expectedAttrs in GetCustomAttributeCtorValues(original, nameof(KeptAttributeAttribute))) + yield return expectedAttrs?.ToString(); + + // The name of the generated fixed buffer type is a little tricky. + // Some versions of csc name it `e__FixedBuffer0` + // while mcs and other versions of csc name it `__FixedBuffer0` + if (original is TypeDefinition srcDefinition && srcDefinition.Name.Contains("__FixedBuffer")) + { + var name = srcDefinition.Name.Substring(1, srcDefinition.Name.IndexOf('>') - 1); + var fixedField = srcDefinition.DeclaringType.Fields.FirstOrDefault(f => f.Name == name); + if (fixedField == null) + Assert.Fail($"Could not locate original fixed field for {srcDefinition}"); + + foreach (var additionalExpectedAttributesFromFixedField in GetCustomAttributeCtorValues(fixedField!, nameof(KeptAttributeOnFixedBufferTypeAttribute))) + yield return additionalExpectedAttributesFromFixedField?.ToString(); + + } + } + + /// + /// Filters out some attributes that should not be taken into consideration when checking the linked result against the expected result + /// + /// + /// + protected virtual IEnumerable FilterLinkedAttributes(ICustomAttributeProvider linked) + { + foreach (var attr in linked.CustomAttributes) + { + switch (attr.AttributeType.FullName) + { + case "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute": + case "System.Runtime.CompilerServices.CompilerGeneratedAttribute": + continue; + + // When mcs is used to compile the test cases, backing fields end up with this attribute on them + case "System.Diagnostics.DebuggerBrowsableAttribute": + continue; + + // When compiling with roslyn, assemblies get the DebuggableAttribute by default. + case "System.Diagnostics.DebuggableAttribute": + continue; + + case "System.Runtime.CompilerServices.CompilationRelaxationsAttribute": + if (linked is AssemblyDefinition) + continue; + break; + } + + yield return attr.AttributeType.FullName; + } + } + + protected virtual IEnumerable FilterLinkedSecurityAttributes(ISecurityDeclarationProvider linked) + { + return linked.SecurityDeclarations + .SelectMany(d => d.SecurityAttributes) + .Select(attr => attr.AttributeType.ToString()); + } #if false private IEnumerable VerifyFixedBufferFields (TypeDefinition src, TypeDefinition linked) @@ -1297,185 +1362,204 @@ private IEnumerable VerifyDelegateBackingFields (TypeDefinition src, Typ } #endif - private IEnumerable VerifyGenericParameters (IGenericParameterProvider src, IGenericParameterProvider linked) - { - if (src.HasGenericParameters != linked.HasGenericParameters) - yield return $"Mismatch in having generic paramters. Expected {src.HasGenericParameters}, actual {linked.HasGenericParameters}"; - - if (src.HasGenericParameters) { - for (int i = 0; i < src.GenericParameters.Count; ++i) { - // TODO: Verify constraints - var srcp = src.GenericParameters[i]; - var lnkp = linked.GenericParameters[i]; - foreach(var err in VerifyCustomAttributes (srcp, lnkp)) - yield return err; - - if (checkNames) { - if (srcp.CustomAttributes.Any (attr => attr.AttributeType.Name == nameof (RemovedNameValueAttribute))) { - string name = (src.GenericParameterType == GenericParameterType.Method ? "!!" : "!") + srcp.Position; - if (lnkp.Name != name) - yield return "Expected empty generic parameter name"; - } else { - if (lnkp.Name != srcp.Name) - yield return "Mismatch in generic parameter name"; - } - } - } - } - } - - private IEnumerable VerifyParameters (IMethodSignature src, LinkedMethodEntity linked) - { - if (src.HasParameters != linked.Method.Signature.Length > 0) - yield return $"Mismatch in having parameters in {src as MethodDefinition}: Expected {src.HasParameters}, actual {linked.Method.Signature.Length > 0}"; - if (src.HasParameters) { - for (int i = 0; i < src.Parameters.Count; ++i) { - var srcp = src.Parameters[i]; - //var lnkp = linked.Parameters[i]; + private IEnumerable VerifyGenericParameters(IGenericParameterProvider src, IGenericParameterProvider linked) + { + if (src.HasGenericParameters != linked.HasGenericParameters) + yield return $"Mismatch in having generic paramters. Expected {src.HasGenericParameters}, actual {linked.HasGenericParameters}"; + + if (src.HasGenericParameters) + { + for (int i = 0; i < src.GenericParameters.Count; ++i) + { + // TODO: Verify constraints + var srcp = src.GenericParameters[i]; + var lnkp = linked.GenericParameters[i]; + foreach (var err in VerifyCustomAttributes(srcp, lnkp)) + yield return err; + + if (checkNames) + { + if (srcp.CustomAttributes.Any(attr => attr.AttributeType.Name == nameof(RemovedNameValueAttribute))) + { + string name = (src.GenericParameterType == GenericParameterType.Method ? "!!" : "!") + srcp.Position; + if (lnkp.Name != name) + yield return "Expected empty generic parameter name"; + } + else + { + if (lnkp.Name != srcp.Name) + yield return "Mismatch in generic parameter name"; + } + } + } + } + } + + private IEnumerable VerifyParameters(IMethodSignature src, LinkedMethodEntity linked) + { + if (src.HasParameters != linked.Method.Signature.Length > 0) + yield return $"Mismatch in having parameters in {src as MethodDefinition}: Expected {src.HasParameters}, actual {linked.Method.Signature.Length > 0}"; + if (src.HasParameters) + { + for (int i = 0; i < src.Parameters.Count; ++i) + { + var srcp = src.Parameters[i]; + //var lnkp = linked.Parameters[i]; #if false foreach(var err in VerifyCustomAttributes (srcp, lnkp)) yield return err; #endif - if (checkNames) { - if (srcp.CustomAttributes.Any (attr => attr.AttributeType.Name == nameof (RemovedNameValueAttribute))) - { - if (linked.IsReflected != false) - yield return $"Expected no parameter name (non-reflectable). Parameter {i} of {src as MethodDefinition}"; - } - else - { - if (linked.IsReflected != true) - yield return $"Expected accessible parameter name (reflectable). Parameter {i} of {(src as MethodDefinition)}"; - } - } - } - } - } - - protected virtual bool ShouldMethodBeKept (MethodDefinition method) - { - var srcSignature = method.GetSignature (); - return ShouldBeKept (method, srcSignature) || method.DeclaringType.Module.EntryPoint == method; - } - - protected virtual bool ShouldBeKept (T member, string? signature = null) where T : MemberReference, ICustomAttributeProvider - { - if (HasActiveKeptAttribute (member)) - return true; - - ICustomAttributeProvider cap = (ICustomAttributeProvider) member.DeclaringType; - if (cap == null) - return false; - - return GetActiveKeptAttributes (cap, nameof (KeptMemberAttribute)).Any (ca => { - if (ca.Constructor.Parameters.Count != 1 || - ca.ConstructorArguments[0].Value is not string a) - return false; - - return a == (signature ?? member.Name); - }); - } - - protected static uint GetExpectedPseudoAttributeValue (ICustomAttributeProvider provider, uint sourceValue) - { - var removals = provider.CustomAttributes.Where (attr => attr.AttributeType.Name == nameof (RemovedPseudoAttributeAttribute)).ToArray (); - var adds = provider.CustomAttributes.Where (attr => attr.AttributeType.Name == nameof (AddedPseudoAttributeAttribute)).ToArray (); - - return removals.Aggregate (sourceValue, (accum, item) => accum & ~(uint) item.ConstructorArguments[0].Value) | - adds.Aggregate ((uint) 0, (acum, item) => acum | (uint) item.ConstructorArguments[0].Value); - } - - protected static IEnumerable GetCustomAttributeCtorValues (ICustomAttributeProvider provider, string attributeName) where T : class - { - return provider.CustomAttributes. - Where (w => w.AttributeType.Name == attributeName && w.Constructor.Parameters.Count == 1). - Select (l => l.ConstructorArguments[0].Value as T); - } - - protected static IEnumerable GetStringOrTypeArrayAttributeValue (CustomAttribute attribute) - { - foreach (var arg in (CustomAttributeArgument[]) attribute.ConstructorArguments[0].Value) { - if (arg.Value is TypeReference tRef) - yield return tRef.ToString (); - else - yield return (string) arg.Value; - } - } - - protected static IEnumerable? GetStringArrayAttributeValue (CustomAttribute attribute) - { - return ((CustomAttributeArgument[]) attribute.ConstructorArguments[0].Value)?.Select (arg => arg.Value.ToString ()!); - } - - private static IEnumerable GetActiveKeptAttributes (ICustomAttributeProvider provider, string attributeName) - { - return provider.CustomAttributes.Where (ca => { - if (ca.AttributeType.Name != attributeName) { - return false; - } - - object? keptBy = ca.GetPropertyValue (nameof (KeptAttribute.By)); - return keptBy is null ? true : ((Tool) keptBy).HasFlag (Tool.NativeAot); - }); - } - - private static bool HasActiveKeptAttribute (ICustomAttributeProvider provider) - { - return GetActiveKeptAttributes (provider, nameof (KeptAttribute)).Any (); - } - - private static IEnumerable GetActiveKeptDerivedAttributes (ICustomAttributeProvider provider) - { - return provider.CustomAttributes.Where (ca => { - if (!ca.AttributeType.Resolve ().DerivesFrom (nameof (KeptAttribute))) { - return false; - } - - object? keptBy = ca.GetPropertyValue (nameof (KeptAttribute.By)); - return keptBy is null ? true : ((Tool) keptBy).HasFlag (Tool.NativeAot); - }); - } - - - private static bool HasActiveKeptDerivedAttribute (ICustomAttributeProvider provider) - { - return GetActiveKeptDerivedAttributes (provider).Any (); - } - - internal IEnumerable VerifyLinkingOfOtherAssemblies (AssemblyDefinition original) - { - var checks = BuildOtherAssemblyCheckTable (original); - List errs = []; - - try { - foreach (var assemblyName in checks.Keys) { - var linkedMembersInAssembly = ResolveLinkedMembersForAssembly (assemblyName); - var originalTargetAssembly = ResolveOriginalsAssembly(assemblyName); - foreach (var checkAttrInAssembly in checks[assemblyName]) { - var attributeTypeName = checkAttrInAssembly.AttributeType.Name; - - switch (attributeTypeName) { - case nameof (KeptAllTypesAndMembersInAssemblyAttribute): - errs.AddRange(VerifyKeptAllTypesAndMembersInAssembly (assemblyName, linkedMembersInAssembly)); - continue; - case nameof (KeptAttributeInAssemblyAttribute): - // errs.AddRange(VerifyKeptAttributeInAssembly (checkAttrInAssembly, linkedAssembly)) - continue; - case nameof (RemovedAttributeInAssembly): - // errs.AddRange(VerifyRemovedAttributeInAssembly (checkAttrInAssembly, linkedAssembly)) - continue; - default: - break; - } - - var expectedTypeName = checkAttrInAssembly.ConstructorArguments[1].Value.ToString ()!; - if (!originalsTypeNameResolver.TryResolveTypeName (originalTargetAssembly, expectedTypeName, out TypeReference? expectedTypeRef, out _)) - Assert.Fail($"Could not resolve original type `{expectedTypeName}' in assembly {assemblyName}"); - TypeDefinition expectedType = expectedTypeRef.Resolve (); - linkedMembersInAssembly.TryGetValue(new AssemblyQualifiedToken(expectedType), out LinkedEntity? linkedTypeEntity); - MetadataType? linkedType = linkedTypeEntity?.Entity as MetadataType; + if (checkNames) + { + if (srcp.CustomAttributes.Any(attr => attr.AttributeType.Name == nameof(RemovedNameValueAttribute))) + { + if (linked.IsReflected != false) + yield return $"Expected no parameter name (non-reflectable). Parameter {i} of {src as MethodDefinition}"; + } + else + { + if (linked.IsReflected != true) + yield return $"Expected accessible parameter name (reflectable). Parameter {i} of {(src as MethodDefinition)}"; + } + } + } + } + } + + protected virtual bool ShouldMethodBeKept(MethodDefinition method) + { + var srcSignature = method.GetSignature(); + return ShouldBeKept(method, srcSignature) || method.DeclaringType.Module.EntryPoint == method; + } + + protected virtual bool ShouldBeKept(T member, string? signature = null) where T : MemberReference, ICustomAttributeProvider + { + if (HasActiveKeptAttribute(member)) + return true; + + ICustomAttributeProvider cap = (ICustomAttributeProvider)member.DeclaringType; + if (cap == null) + return false; + + return GetActiveKeptAttributes(cap, nameof(KeptMemberAttribute)).Any(ca => + { + if (ca.Constructor.Parameters.Count != 1 || + ca.ConstructorArguments[0].Value is not string a) + return false; + + return a == (signature ?? member.Name); + }); + } + + protected static uint GetExpectedPseudoAttributeValue(ICustomAttributeProvider provider, uint sourceValue) + { + var removals = provider.CustomAttributes.Where(attr => attr.AttributeType.Name == nameof(RemovedPseudoAttributeAttribute)).ToArray(); + var adds = provider.CustomAttributes.Where(attr => attr.AttributeType.Name == nameof(AddedPseudoAttributeAttribute)).ToArray(); + + return removals.Aggregate(sourceValue, (accum, item) => accum & ~(uint)item.ConstructorArguments[0].Value) | + adds.Aggregate((uint)0, (acum, item) => acum | (uint)item.ConstructorArguments[0].Value); + } + + protected static IEnumerable GetCustomAttributeCtorValues(ICustomAttributeProvider provider, string attributeName) where T : class + { + return provider.CustomAttributes. + Where(w => w.AttributeType.Name == attributeName && w.Constructor.Parameters.Count == 1). + Select(l => l.ConstructorArguments[0].Value as T); + } + + protected static IEnumerable GetStringOrTypeArrayAttributeValue(CustomAttribute attribute) + { + foreach (var arg in (CustomAttributeArgument[])attribute.ConstructorArguments[0].Value) + { + if (arg.Value is TypeReference tRef) + yield return tRef.ToString(); + else + yield return (string)arg.Value; + } + } + + protected static IEnumerable? GetStringArrayAttributeValue(CustomAttribute attribute) + { + return ((CustomAttributeArgument[])attribute.ConstructorArguments[0].Value)?.Select(arg => arg.Value.ToString()!); + } + + private static IEnumerable GetActiveKeptAttributes(ICustomAttributeProvider provider, string attributeName) + { + return provider.CustomAttributes.Where(ca => + { + if (ca.AttributeType.Name != attributeName) + { + return false; + } + + object? keptBy = ca.GetPropertyValue(nameof(KeptAttribute.By)); + return keptBy is null ? true : ((Tool)keptBy).HasFlag(Tool.NativeAot); + }); + } + + private static bool HasActiveKeptAttribute(ICustomAttributeProvider provider) + { + return GetActiveKeptAttributes(provider, nameof(KeptAttribute)).Any(); + } + + private static IEnumerable GetActiveKeptDerivedAttributes(ICustomAttributeProvider provider) + { + return provider.CustomAttributes.Where(ca => + { + if (!ca.AttributeType.Resolve().DerivesFrom(nameof(KeptAttribute))) + { + return false; + } + + object? keptBy = ca.GetPropertyValue(nameof(KeptAttribute.By)); + return keptBy is null ? true : ((Tool)keptBy).HasFlag(Tool.NativeAot); + }); + } + + + private static bool HasActiveKeptDerivedAttribute(ICustomAttributeProvider provider) + { + return GetActiveKeptDerivedAttributes(provider).Any(); + } + + internal IEnumerable VerifyLinkingOfOtherAssemblies(AssemblyDefinition original) + { + var checks = BuildOtherAssemblyCheckTable(original); + List errs = []; + + try + { + foreach (var assemblyName in checks.Keys) + { + var linkedMembersInAssembly = ResolveLinkedMembersForAssembly(assemblyName); + var originalTargetAssembly = ResolveOriginalsAssembly(assemblyName); + foreach (var checkAttrInAssembly in checks[assemblyName]) + { + var attributeTypeName = checkAttrInAssembly.AttributeType.Name; + + switch (attributeTypeName) + { + case nameof(KeptAllTypesAndMembersInAssemblyAttribute): + errs.AddRange(VerifyKeptAllTypesAndMembersInAssembly(assemblyName, linkedMembersInAssembly)); + continue; + case nameof(KeptAttributeInAssemblyAttribute): + // errs.AddRange(VerifyKeptAttributeInAssembly (checkAttrInAssembly, linkedAssembly)) + continue; + case nameof(RemovedAttributeInAssembly): + // errs.AddRange(VerifyRemovedAttributeInAssembly (checkAttrInAssembly, linkedAssembly)) + continue; + default: + break; + } + + var expectedTypeName = checkAttrInAssembly.ConstructorArguments[1].Value.ToString()!; + if (!originalsTypeNameResolver.TryResolveTypeName(originalTargetAssembly, expectedTypeName, out TypeReference? expectedTypeRef, out _)) + Assert.Fail($"Could not resolve original type `{expectedTypeName}' in assembly {assemblyName}"); + TypeDefinition expectedType = expectedTypeRef.Resolve(); + linkedMembersInAssembly.TryGetValue(new AssemblyQualifiedToken(expectedType), out LinkedEntity? linkedTypeEntity); + MetadataType? linkedType = linkedTypeEntity?.Entity as MetadataType; #if false if (linkedType == null && linkedAssembly.MainModule.HasExportedTypes) { @@ -1492,16 +1576,17 @@ internal IEnumerable VerifyLinkingOfOtherAssemblies (AssemblyDefinition } #endif - switch (attributeTypeName) { - case nameof (RemovedTypeInAssemblyAttribute): - if (linkedType != null) - errs.Add($"Type `{expectedTypeName}' should have been removed from assembly {assemblyName}"); - GetOriginalTypeFromInAssemblyAttribute (checkAttrInAssembly); - break; - case nameof (KeptTypeInAssemblyAttribute): - if (linkedType == null) - errs.Add($"Type `{expectedTypeName}' should have been kept in assembly {assemblyName}"); - break; + switch (attributeTypeName) + { + case nameof(RemovedTypeInAssemblyAttribute): + if (linkedType != null) + errs.Add($"Type `{expectedTypeName}' should have been removed from assembly {assemblyName}"); + GetOriginalTypeFromInAssemblyAttribute(checkAttrInAssembly); + break; + case nameof(KeptTypeInAssemblyAttribute): + if (linkedType == null) + errs.Add($"Type `{expectedTypeName}' should have been kept in assembly {assemblyName}"); + break; #if false case nameof (RemovedInterfaceOnTypeInAssemblyAttribute): if (linkedType == null) @@ -1574,321 +1659,340 @@ internal IEnumerable VerifyLinkingOfOtherAssemblies (AssemblyDefinition UnhandledOtherAssemblyAssertion (expectedTypeName, checkAttrInAssembly, linkedType); break; #else - default: - break; + default: + break; #endif - } - } - } - } catch (AssemblyResolutionException e) { - errs.Add($"Failed to resolve linked assembly `{e.AssemblyReference.Name}`. It must not exist in the output."); - } - return errs; - } - - private IEnumerable VerifyKeptAttributeInAssembly (CustomAttribute inAssemblyAttribute, AssemblyDefinition linkedAssembly) - { - return VerifyAttributeInAssembly (inAssemblyAttribute, linkedAssembly, VerifyCustomAttributeKept); - } - - private IEnumerable VerifyRemovedAttributeInAssembly (CustomAttribute inAssemblyAttribute, AssemblyDefinition linkedAssembly) - { - return VerifyAttributeInAssembly (inAssemblyAttribute, linkedAssembly, VerifyCustomAttributeRemoved); - } - - private IEnumerable VerifyAttributeInAssembly (CustomAttribute inAssemblyAttribute, AssemblyDefinition linkedAssembly, Func> assertExpectedAttribute) - { - var assemblyName = (string) inAssemblyAttribute.ConstructorArguments[0].Value!; - string expectedAttributeTypeName; - var attributeTypeOrTypeName = inAssemblyAttribute.ConstructorArguments[1].Value!; - if (attributeTypeOrTypeName is TypeReference typeReference) { - expectedAttributeTypeName = typeReference.FullName; - } else { - expectedAttributeTypeName = attributeTypeOrTypeName.ToString ()!; - } - - if (inAssemblyAttribute.ConstructorArguments.Count == 2) { - // Assembly - foreach(var err in assertExpectedAttribute (linkedAssembly, expectedAttributeTypeName)) - yield return err; - yield break; - } - - // We are asserting on type or member - var typeOrTypeName = inAssemblyAttribute.ConstructorArguments[2].Value; - var originalType = GetOriginalTypeFromInAssemblyAttribute (inAssemblyAttribute.ConstructorArguments[0].Value.ToString ()!, typeOrTypeName); - if (originalType == null) - { - yield return $"Invalid test assertion. The original `{assemblyName}` does not contain a type `{typeOrTypeName}`"; - yield break; - } - - var linkedType = linkedAssembly.MainModule.GetType (originalType.FullName); - if (linkedType == null) - { - yield return $"Missing expected type `{typeOrTypeName}` in `{assemblyName}`"; - yield break; - } - - if (inAssemblyAttribute.ConstructorArguments.Count == 3) { - assertExpectedAttribute (linkedType, expectedAttributeTypeName); - yield break; - } - - // we are asserting on a member - string memberName = (string) inAssemblyAttribute.ConstructorArguments[3].Value; - - // We will find the matching type from the original assembly first that way we can confirm - // that the name defined in the attribute corresponds to a member that actually existed - var originalFieldMember = originalType.Fields.FirstOrDefault (m => m.Name == memberName); - if (originalFieldMember != null) { - var linkedField = linkedType.Fields.FirstOrDefault (m => m.Name == memberName); - if (linkedField == null) - { - yield return $"Field `{memberName}` on Type `{originalType}` should have been kept"; - yield break; - } - - assertExpectedAttribute (linkedField, expectedAttributeTypeName); - yield break; - } - - var originalPropertyMember = originalType.Properties.FirstOrDefault (m => m.Name == memberName); - if (originalPropertyMember != null) { - var linkedProperty = linkedType.Properties.FirstOrDefault (m => m.Name == memberName); - if (linkedProperty == null) - { - yield return $"Property `{memberName}` on Type `{originalType}` should have been kept"; - yield break; - } - - foreach(var err in assertExpectedAttribute (linkedProperty, expectedAttributeTypeName)) - yield return err; - yield break; - } - - var originalMethodMember = originalType.Methods.FirstOrDefault (m => m.GetSignature () == memberName); - if (originalMethodMember != null) { - var linkedMethod = linkedType.Methods.FirstOrDefault (m => m.GetSignature () == memberName); - if (linkedMethod == null) - { - yield return $"Method `{memberName}` on Type `{originalType}` should have been kept"; - yield break; - } - - assertExpectedAttribute (linkedMethod, expectedAttributeTypeName); - yield break; - } - - yield return $"Invalid test assertion. No member named `{memberName}` exists on the original type `{originalType}`"; - } - - private static IEnumerable VerifyCopyAssemblyIsKeptUnmodified (NPath outputDirectory, string assemblyName) - { - string inputAssemblyPath = Path.Combine (Directory.GetParent (outputDirectory)!.ToString (), "input", assemblyName); - string outputAssemblyPath = Path.Combine (outputDirectory, assemblyName); - if (true != File.ReadAllBytes (inputAssemblyPath).SequenceEqual (File.ReadAllBytes (outputAssemblyPath))) - yield return $"Expected assemblies\n" + - $"\t{inputAssemblyPath}\n" + - $"\t{outputAssemblyPath}\n" + - $"binaries to be equal, since the input assembly has copy action."; - } - - private IEnumerable VerifyCustomAttributeKept (ICustomAttributeProvider provider, string expectedAttributeTypeName) - { - var match = provider.CustomAttributes.FirstOrDefault (attr => attr.AttributeType.FullName == expectedAttributeTypeName); - if (match == null) - yield return $"Expected `{provider}` to have an attribute of type `{expectedAttributeTypeName}`"; - } - - private IEnumerable VerifyCustomAttributeRemoved (ICustomAttributeProvider provider, string expectedAttributeTypeName) - { - var match = provider.CustomAttributes.FirstOrDefault (attr => attr.AttributeType.FullName == expectedAttributeTypeName); - if (match != null) - yield return $"Expected `{provider}` to no longer have an attribute of type `{expectedAttributeTypeName}`"; - } - - private IEnumerable VerifyRemovedInterfaceOnTypeInAssembly (CustomAttribute inAssemblyAttribute, TypeDefinition linkedType) - { - var originalType = GetOriginalTypeFromInAssemblyAttribute (inAssemblyAttribute); - - var interfaceAssemblyName = inAssemblyAttribute.ConstructorArguments[2].Value.ToString ()!; - var interfaceType = inAssemblyAttribute.ConstructorArguments[3].Value; - - var originalInterface = GetOriginalTypeFromInAssemblyAttribute (interfaceAssemblyName, interfaceType); - if (!originalType.HasInterfaces) - yield return "Invalid assertion. Original type does not have any interfaces"; - - var originalInterfaceImpl = GetMatchingInterfaceImplementationOnType (originalType, originalInterface.FullName); - if (originalInterfaceImpl == null) - yield return $"Invalid assertion. Original type never had an interface of type `{originalInterface}`"; - - var linkedInterfaceImpl = GetMatchingInterfaceImplementationOnType (linkedType, originalInterface.FullName); - if (linkedInterfaceImpl != null) - yield return $"Expected `{linkedType}` to no longer have an interface of type {originalInterface.FullName}"; - } - - private IEnumerable VerifyKeptInterfaceOnTypeInAssembly (CustomAttribute inAssemblyAttribute, TypeDefinition linkedType) - { - var originalType = GetOriginalTypeFromInAssemblyAttribute (inAssemblyAttribute); - - var interfaceAssemblyName = inAssemblyAttribute.ConstructorArguments[2].Value.ToString ()!; - var interfaceType = inAssemblyAttribute.ConstructorArguments[3].Value; - - var originalInterface = GetOriginalTypeFromInAssemblyAttribute (interfaceAssemblyName, interfaceType); - if (!originalType.HasInterfaces) - yield return "Invalid assertion. Original type does not have any interfaces"; - - var originalInterfaceImpl = GetMatchingInterfaceImplementationOnType (originalType, originalInterface.FullName); - if (originalInterfaceImpl == null) - yield return $"Invalid assertion. Original type never had an interface of type `{originalInterface}`"; - - var linkedInterfaceImpl = GetMatchingInterfaceImplementationOnType (linkedType, originalInterface.FullName); - if (linkedInterfaceImpl == null) - yield return $"Expected `{linkedType}` to have interface of type {originalInterface.FullName}"; - } - - private IEnumerable VerifyKeptBaseOnTypeInAssembly (CustomAttribute inAssemblyAttribute, TypeDefinition linkedType) - { - var originalType = GetOriginalTypeFromInAssemblyAttribute (inAssemblyAttribute); - - var baseAssemblyName = inAssemblyAttribute.ConstructorArguments[2].Value.ToString ()!; - var baseType = inAssemblyAttribute.ConstructorArguments[3].Value; - - var originalBase = GetOriginalTypeFromInAssemblyAttribute (baseAssemblyName, baseType); - if (originalType.BaseType.Resolve () != originalBase) - yield return "Invalid assertion. Original type's base does not match the expected base"; - - if (originalBase.FullName != linkedType.BaseType.FullName) - yield return $"Incorrect base on `{linkedType.FullName}`. Expected `{originalBase.FullName}` but was `{linkedType.BaseType.FullName}`"; - } - - private static InterfaceImplementation? GetMatchingInterfaceImplementationOnType (TypeDefinition type, string expectedInterfaceTypeName) - { - return type.Interfaces.FirstOrDefault (impl => { - var resolvedImpl = impl.InterfaceType.Resolve (); - - if (resolvedImpl == null) - Assert.Fail ($"Failed to resolve interface : `{impl.InterfaceType}` on `{type}`"); - - return resolvedImpl.FullName == expectedInterfaceTypeName; - }); - } - - private IEnumerable VerifyRemovedMemberInAssembly (CustomAttribute inAssemblyAttribute, TypeDefinition linkedType) - { - var originalType = GetOriginalTypeFromInAssemblyAttribute (inAssemblyAttribute); - foreach (var memberNameAttr in (CustomAttributeArgument[]) inAssemblyAttribute.ConstructorArguments[2].Value) { - string memberName = (string) memberNameAttr.Value; - - // We will find the matching type from the original assembly first that way we can confirm - // that the name defined in the attribute corresponds to a member that actually existed - var originalFieldMember = originalType.Fields.FirstOrDefault (m => m.Name == memberName); - if (originalFieldMember != null) { - var linkedField = linkedType.Fields.FirstOrDefault (m => m.Name == memberName); - if (linkedField != null) - yield return $"Field `{memberName}` on Type `{originalType}` should have been removed"; - - continue; - } - - var originalPropertyMember = originalType.Properties.FirstOrDefault (m => m.Name == memberName); - if (originalPropertyMember != null) { - var linkedProperty = linkedType.Properties.FirstOrDefault (m => m.Name == memberName); - if (linkedProperty != null) - yield return $"Property `{memberName}` on Type `{originalType}` should have been removed"; - - continue; - } - - var originalMethodMember = originalType.Methods.FirstOrDefault (m => m.GetSignature () == memberName); - if (originalMethodMember != null) { - var linkedMethod = linkedType.Methods.FirstOrDefault (m => m.GetSignature () == memberName); - if (linkedMethod != null) - yield return $"Method `{memberName}` on Type `{originalType}` should have been removed"; - - continue; - } - - yield return $"Invalid test assertion. No member named `{memberName}` exists on the original type `{originalType}`"; - } - } - - private IEnumerable VerifyKeptMemberInAssembly (CustomAttribute inAssemblyAttribute, TypeDefinition linkedType) - { - var originalType = GetOriginalTypeFromInAssemblyAttribute (inAssemblyAttribute); - var memberNames = (CustomAttributeArgument[]) inAssemblyAttribute.ConstructorArguments[2].Value; - if (!(memberNames.Length > 0)) - yield return "Invalid KeptMemberInAssemblyAttribute. Expected member names."; - foreach (var memberNameAttr in memberNames) { - string memberName = (string) memberNameAttr.Value; - - // We will find the matching type from the original assembly first that way we can confirm - // that the name defined in the attribute corresponds to a member that actually existed - - if (TryVerifyKeptMemberInAssemblyAsField (memberName, originalType, linkedType)) - continue; - - if (TryVerifyKeptMemberInAssemblyAsProperty (memberName, originalType, linkedType)) - continue; - - if (TryVerifyKeptMemberInAssemblyAsMethod (memberName, originalType, linkedType)) - continue; - - yield return $"Invalid test assertion. No member named `{memberName}` exists on the original type `{originalType}`"; - } - } - - protected virtual bool TryVerifyKeptMemberInAssemblyAsField (string memberName, TypeDefinition originalType, TypeDefinition linkedType) - { - var originalFieldMember = originalType.Fields.FirstOrDefault (m => m.Name == memberName); - if (originalFieldMember != null) { - var linkedField = linkedType.Fields.FirstOrDefault (m => m.Name == memberName); - if (linkedField == null) - Assert.Fail ($"Field `{memberName}` on Type `{originalType}` should have been kept"); - - return true; - } - - return false; - } - - protected virtual bool TryVerifyKeptMemberInAssemblyAsProperty (string memberName, TypeDefinition originalType, TypeDefinition linkedType) - { - var originalPropertyMember = originalType.Properties.FirstOrDefault (m => m.Name == memberName); - if (originalPropertyMember != null) { - var linkedProperty = linkedType.Properties.FirstOrDefault (m => m.Name == memberName); - if (linkedProperty == null) - Assert.Fail ($"Property `{memberName}` on Type `{originalType}` should have been kept"); - - return true; - } - - return false; - } - - protected virtual bool TryVerifyKeptMemberInAssemblyAsMethod (string memberName, TypeDefinition originalType, TypeDefinition linkedType) - { - return TryVerifyKeptMemberInAssemblyAsMethod (memberName, originalType, linkedType, out _, out _); - } - - protected virtual bool TryVerifyKeptMemberInAssemblyAsMethod (string memberName, TypeDefinition originalType, TypeDefinition linkedType, out MethodDefinition? originalMethod, out MethodDefinition? linkedMethod) - { - originalMethod = originalType.Methods.FirstOrDefault (m => m.GetSignature () == memberName); - if (originalMethod != null) { - linkedMethod = linkedType.Methods.FirstOrDefault (m => m.GetSignature () == memberName); - if (linkedMethod == null) - Assert.Fail ($"Method `{memberName}` on Type `{originalType}` should have been kept"); - - return true; - } - - linkedMethod = null; - return false; - } - - private IEnumerable VerifyKeptReferencesInAssembly (CustomAttribute inAssemblyAttribute) - { + } + } + } + } + catch (AssemblyResolutionException e) + { + errs.Add($"Failed to resolve linked assembly `{e.AssemblyReference.Name}`. It must not exist in the output."); + } + return errs; + } + + private IEnumerable VerifyKeptAttributeInAssembly(CustomAttribute inAssemblyAttribute, AssemblyDefinition linkedAssembly) + { + return VerifyAttributeInAssembly(inAssemblyAttribute, linkedAssembly, VerifyCustomAttributeKept); + } + + private IEnumerable VerifyRemovedAttributeInAssembly(CustomAttribute inAssemblyAttribute, AssemblyDefinition linkedAssembly) + { + return VerifyAttributeInAssembly(inAssemblyAttribute, linkedAssembly, VerifyCustomAttributeRemoved); + } + + private IEnumerable VerifyAttributeInAssembly(CustomAttribute inAssemblyAttribute, AssemblyDefinition linkedAssembly, Func> assertExpectedAttribute) + { + var assemblyName = (string)inAssemblyAttribute.ConstructorArguments[0].Value!; + string expectedAttributeTypeName; + var attributeTypeOrTypeName = inAssemblyAttribute.ConstructorArguments[1].Value!; + if (attributeTypeOrTypeName is TypeReference typeReference) + { + expectedAttributeTypeName = typeReference.FullName; + } + else + { + expectedAttributeTypeName = attributeTypeOrTypeName.ToString()!; + } + + if (inAssemblyAttribute.ConstructorArguments.Count == 2) + { + // Assembly + foreach (var err in assertExpectedAttribute(linkedAssembly, expectedAttributeTypeName)) + yield return err; + yield break; + } + + // We are asserting on type or member + var typeOrTypeName = inAssemblyAttribute.ConstructorArguments[2].Value; + var originalType = GetOriginalTypeFromInAssemblyAttribute(inAssemblyAttribute.ConstructorArguments[0].Value.ToString()!, typeOrTypeName); + if (originalType == null) + { + yield return $"Invalid test assertion. The original `{assemblyName}` does not contain a type `{typeOrTypeName}`"; + yield break; + } + + var linkedType = linkedAssembly.MainModule.GetType(originalType.FullName); + if (linkedType == null) + { + yield return $"Missing expected type `{typeOrTypeName}` in `{assemblyName}`"; + yield break; + } + + if (inAssemblyAttribute.ConstructorArguments.Count == 3) + { + assertExpectedAttribute(linkedType, expectedAttributeTypeName); + yield break; + } + + // we are asserting on a member + string memberName = (string)inAssemblyAttribute.ConstructorArguments[3].Value; + + // We will find the matching type from the original assembly first that way we can confirm + // that the name defined in the attribute corresponds to a member that actually existed + var originalFieldMember = originalType.Fields.FirstOrDefault(m => m.Name == memberName); + if (originalFieldMember != null) + { + var linkedField = linkedType.Fields.FirstOrDefault(m => m.Name == memberName); + if (linkedField == null) + { + yield return $"Field `{memberName}` on Type `{originalType}` should have been kept"; + yield break; + } + + assertExpectedAttribute(linkedField, expectedAttributeTypeName); + yield break; + } + + var originalPropertyMember = originalType.Properties.FirstOrDefault(m => m.Name == memberName); + if (originalPropertyMember != null) + { + var linkedProperty = linkedType.Properties.FirstOrDefault(m => m.Name == memberName); + if (linkedProperty == null) + { + yield return $"Property `{memberName}` on Type `{originalType}` should have been kept"; + yield break; + } + + foreach (var err in assertExpectedAttribute(linkedProperty, expectedAttributeTypeName)) + yield return err; + yield break; + } + + var originalMethodMember = originalType.Methods.FirstOrDefault(m => m.GetSignature() == memberName); + if (originalMethodMember != null) + { + var linkedMethod = linkedType.Methods.FirstOrDefault(m => m.GetSignature() == memberName); + if (linkedMethod == null) + { + yield return $"Method `{memberName}` on Type `{originalType}` should have been kept"; + yield break; + } + + assertExpectedAttribute(linkedMethod, expectedAttributeTypeName); + yield break; + } + + yield return $"Invalid test assertion. No member named `{memberName}` exists on the original type `{originalType}`"; + } + + private static IEnumerable VerifyCopyAssemblyIsKeptUnmodified(NPath outputDirectory, string assemblyName) + { + string inputAssemblyPath = Path.Combine(Directory.GetParent(outputDirectory)!.ToString(), "input", assemblyName); + string outputAssemblyPath = Path.Combine(outputDirectory, assemblyName); + if (true != File.ReadAllBytes(inputAssemblyPath).SequenceEqual(File.ReadAllBytes(outputAssemblyPath))) + yield return $"Expected assemblies\n" + + $"\t{inputAssemblyPath}\n" + + $"\t{outputAssemblyPath}\n" + + $"binaries to be equal, since the input assembly has copy action."; + } + + private IEnumerable VerifyCustomAttributeKept(ICustomAttributeProvider provider, string expectedAttributeTypeName) + { + var match = provider.CustomAttributes.FirstOrDefault(attr => attr.AttributeType.FullName == expectedAttributeTypeName); + if (match == null) + yield return $"Expected `{provider}` to have an attribute of type `{expectedAttributeTypeName}`"; + } + + private IEnumerable VerifyCustomAttributeRemoved(ICustomAttributeProvider provider, string expectedAttributeTypeName) + { + var match = provider.CustomAttributes.FirstOrDefault(attr => attr.AttributeType.FullName == expectedAttributeTypeName); + if (match != null) + yield return $"Expected `{provider}` to no longer have an attribute of type `{expectedAttributeTypeName}`"; + } + + private IEnumerable VerifyRemovedInterfaceOnTypeInAssembly(CustomAttribute inAssemblyAttribute, TypeDefinition linkedType) + { + var originalType = GetOriginalTypeFromInAssemblyAttribute(inAssemblyAttribute); + + var interfaceAssemblyName = inAssemblyAttribute.ConstructorArguments[2].Value.ToString()!; + var interfaceType = inAssemblyAttribute.ConstructorArguments[3].Value; + + var originalInterface = GetOriginalTypeFromInAssemblyAttribute(interfaceAssemblyName, interfaceType); + if (!originalType.HasInterfaces) + yield return "Invalid assertion. Original type does not have any interfaces"; + + var originalInterfaceImpl = GetMatchingInterfaceImplementationOnType(originalType, originalInterface.FullName); + if (originalInterfaceImpl == null) + yield return $"Invalid assertion. Original type never had an interface of type `{originalInterface}`"; + + var linkedInterfaceImpl = GetMatchingInterfaceImplementationOnType(linkedType, originalInterface.FullName); + if (linkedInterfaceImpl != null) + yield return $"Expected `{linkedType}` to no longer have an interface of type {originalInterface.FullName}"; + } + + private IEnumerable VerifyKeptInterfaceOnTypeInAssembly(CustomAttribute inAssemblyAttribute, TypeDefinition linkedType) + { + var originalType = GetOriginalTypeFromInAssemblyAttribute(inAssemblyAttribute); + + var interfaceAssemblyName = inAssemblyAttribute.ConstructorArguments[2].Value.ToString()!; + var interfaceType = inAssemblyAttribute.ConstructorArguments[3].Value; + + var originalInterface = GetOriginalTypeFromInAssemblyAttribute(interfaceAssemblyName, interfaceType); + if (!originalType.HasInterfaces) + yield return "Invalid assertion. Original type does not have any interfaces"; + + var originalInterfaceImpl = GetMatchingInterfaceImplementationOnType(originalType, originalInterface.FullName); + if (originalInterfaceImpl == null) + yield return $"Invalid assertion. Original type never had an interface of type `{originalInterface}`"; + + var linkedInterfaceImpl = GetMatchingInterfaceImplementationOnType(linkedType, originalInterface.FullName); + if (linkedInterfaceImpl == null) + yield return $"Expected `{linkedType}` to have interface of type {originalInterface.FullName}"; + } + + private IEnumerable VerifyKeptBaseOnTypeInAssembly(CustomAttribute inAssemblyAttribute, TypeDefinition linkedType) + { + var originalType = GetOriginalTypeFromInAssemblyAttribute(inAssemblyAttribute); + + var baseAssemblyName = inAssemblyAttribute.ConstructorArguments[2].Value.ToString()!; + var baseType = inAssemblyAttribute.ConstructorArguments[3].Value; + + var originalBase = GetOriginalTypeFromInAssemblyAttribute(baseAssemblyName, baseType); + if (originalType.BaseType.Resolve() != originalBase) + yield return "Invalid assertion. Original type's base does not match the expected base"; + + if (originalBase.FullName != linkedType.BaseType.FullName) + yield return $"Incorrect base on `{linkedType.FullName}`. Expected `{originalBase.FullName}` but was `{linkedType.BaseType.FullName}`"; + } + + private static InterfaceImplementation? GetMatchingInterfaceImplementationOnType(TypeDefinition type, string expectedInterfaceTypeName) + { + return type.Interfaces.FirstOrDefault(impl => + { + var resolvedImpl = impl.InterfaceType.Resolve(); + + if (resolvedImpl == null) + Assert.Fail($"Failed to resolve interface : `{impl.InterfaceType}` on `{type}`"); + + return resolvedImpl.FullName == expectedInterfaceTypeName; + }); + } + + private IEnumerable VerifyRemovedMemberInAssembly(CustomAttribute inAssemblyAttribute, TypeDefinition linkedType) + { + var originalType = GetOriginalTypeFromInAssemblyAttribute(inAssemblyAttribute); + foreach (var memberNameAttr in (CustomAttributeArgument[])inAssemblyAttribute.ConstructorArguments[2].Value) + { + string memberName = (string)memberNameAttr.Value; + + // We will find the matching type from the original assembly first that way we can confirm + // that the name defined in the attribute corresponds to a member that actually existed + var originalFieldMember = originalType.Fields.FirstOrDefault(m => m.Name == memberName); + if (originalFieldMember != null) + { + var linkedField = linkedType.Fields.FirstOrDefault(m => m.Name == memberName); + if (linkedField != null) + yield return $"Field `{memberName}` on Type `{originalType}` should have been removed"; + + continue; + } + + var originalPropertyMember = originalType.Properties.FirstOrDefault(m => m.Name == memberName); + if (originalPropertyMember != null) + { + var linkedProperty = linkedType.Properties.FirstOrDefault(m => m.Name == memberName); + if (linkedProperty != null) + yield return $"Property `{memberName}` on Type `{originalType}` should have been removed"; + + continue; + } + + var originalMethodMember = originalType.Methods.FirstOrDefault(m => m.GetSignature() == memberName); + if (originalMethodMember != null) + { + var linkedMethod = linkedType.Methods.FirstOrDefault(m => m.GetSignature() == memberName); + if (linkedMethod != null) + yield return $"Method `{memberName}` on Type `{originalType}` should have been removed"; + + continue; + } + + yield return $"Invalid test assertion. No member named `{memberName}` exists on the original type `{originalType}`"; + } + } + + private IEnumerable VerifyKeptMemberInAssembly(CustomAttribute inAssemblyAttribute, TypeDefinition linkedType) + { + var originalType = GetOriginalTypeFromInAssemblyAttribute(inAssemblyAttribute); + var memberNames = (CustomAttributeArgument[])inAssemblyAttribute.ConstructorArguments[2].Value; + if (!(memberNames.Length > 0)) + yield return "Invalid KeptMemberInAssemblyAttribute. Expected member names."; + foreach (var memberNameAttr in memberNames) + { + string memberName = (string)memberNameAttr.Value; + + // We will find the matching type from the original assembly first that way we can confirm + // that the name defined in the attribute corresponds to a member that actually existed + + if (TryVerifyKeptMemberInAssemblyAsField(memberName, originalType, linkedType)) + continue; + + if (TryVerifyKeptMemberInAssemblyAsProperty(memberName, originalType, linkedType)) + continue; + + if (TryVerifyKeptMemberInAssemblyAsMethod(memberName, originalType, linkedType)) + continue; + + yield return $"Invalid test assertion. No member named `{memberName}` exists on the original type `{originalType}`"; + } + } + + protected virtual bool TryVerifyKeptMemberInAssemblyAsField(string memberName, TypeDefinition originalType, TypeDefinition linkedType) + { + var originalFieldMember = originalType.Fields.FirstOrDefault(m => m.Name == memberName); + if (originalFieldMember != null) + { + var linkedField = linkedType.Fields.FirstOrDefault(m => m.Name == memberName); + if (linkedField == null) + Assert.Fail($"Field `{memberName}` on Type `{originalType}` should have been kept"); + + return true; + } + + return false; + } + + protected virtual bool TryVerifyKeptMemberInAssemblyAsProperty(string memberName, TypeDefinition originalType, TypeDefinition linkedType) + { + var originalPropertyMember = originalType.Properties.FirstOrDefault(m => m.Name == memberName); + if (originalPropertyMember != null) + { + var linkedProperty = linkedType.Properties.FirstOrDefault(m => m.Name == memberName); + if (linkedProperty == null) + Assert.Fail($"Property `{memberName}` on Type `{originalType}` should have been kept"); + + return true; + } + + return false; + } + + protected virtual bool TryVerifyKeptMemberInAssemblyAsMethod(string memberName, TypeDefinition originalType, TypeDefinition linkedType) + { + return TryVerifyKeptMemberInAssemblyAsMethod(memberName, originalType, linkedType, out _, out _); + } + + protected virtual bool TryVerifyKeptMemberInAssemblyAsMethod(string memberName, TypeDefinition originalType, TypeDefinition linkedType, out MethodDefinition? originalMethod, out MethodDefinition? linkedMethod) + { + originalMethod = originalType.Methods.FirstOrDefault(m => m.GetSignature() == memberName); + if (originalMethod != null) + { + linkedMethod = linkedType.Methods.FirstOrDefault(m => m.GetSignature() == memberName); + if (linkedMethod == null) + Assert.Fail($"Method `{memberName}` on Type `{originalType}` should have been kept"); + + return true; + } + + linkedMethod = null; + return false; + } + + private IEnumerable VerifyKeptReferencesInAssembly(CustomAttribute inAssemblyAttribute) + { #if false var assembly = ResolveLinkedAssembly (inAssemblyAttribute.ConstructorArguments[0].Value.ToString ()!); var expectedReferenceNames = ((CustomAttributeArgument[]) inAssemblyAttribute.ConstructorArguments[1].Value).Select (attr => (string) attr.Value).ToList (); @@ -1898,156 +2002,160 @@ private IEnumerable VerifyKeptReferencesInAssembly (CustomAttribute inAs Assert.Equal (assembly.MainModule.AssemblyReferences.Select (asm => asm.Name), expectedReferenceNames); #endif - yield break; - } + yield break; + } - private IEnumerable VerifyKeptResourceInAssembly (CustomAttribute inAssemblyAttribute) - { + private IEnumerable VerifyKeptResourceInAssembly(CustomAttribute inAssemblyAttribute) + { #if false var assembly = ResolveLinkedAssembly (inAssemblyAttribute.ConstructorArguments[0].Value.ToString ()!); var resourceName = inAssemblyAttribute.ConstructorArguments[1].Value.ToString (); Assert.Contains (resourceName, assembly.MainModule.Resources.Select (r => r.Name)); #endif - yield break; - } + yield break; + } - private IEnumerable VerifyRemovedResourceInAssembly (CustomAttribute inAssemblyAttribute) - { + private IEnumerable VerifyRemovedResourceInAssembly(CustomAttribute inAssemblyAttribute) + { #if false var assembly = ResolveLinkedAssembly (inAssemblyAttribute.ConstructorArguments[0].Value.ToString ()!); var resourceName = inAssemblyAttribute.ConstructorArguments[1].Value.ToString (); Assert.DoesNotContain (resourceName, assembly.MainModule.Resources.Select (r => r.Name)); #endif - yield break; - } - - private IEnumerable VerifyKeptAllTypesAndMembersInAssembly (string assemblyName, Dictionary linkedMembers) - { - var original = ResolveOriginalsAssembly (assemblyName); - - if (original == null) - { - yield return $"Failed to resolve original assembly {assemblyName}"; - yield break; - } - - var originalTypes = original.AllDefinedTypes ().ToDictionary (t => new AssemblyQualifiedToken(t)); - var linkedTypes = linkedMembers.Where(t => t.Value.Entity is TypeDesc).ToDictionary(); - - var missingInLinked = originalTypes.Keys.Except (linkedTypes.Keys); - - if (missingInLinked.Any ()) - yield return $"Expected all types to exist in the linked assembly {assemblyName}, but one or more were missing"; - - foreach (var originalKvp in originalTypes) { - var linkedType = linkedTypes[originalKvp.Key]; - TypeDesc linkedTypeDesc = (TypeDesc)linkedType.Entity; - - // NativeAOT field trimming is very different (it basically doesn't trim fields, not in the same way trimmer does) - var originalMembers = originalKvp.Value.AllMembers ().Where(m => m is not FieldDefinition).Select (m => new AssemblyQualifiedToken(m)); - var linkedMembersOnType = linkedMembers.Where(t => GetOwningType(t.Value.Entity) == linkedTypeDesc).Select(t => t.Key); - - var missingMembersInLinked = originalMembers.Except (linkedMembersOnType); - - if (missingMembersInLinked.Any ()) - yield return $"Expected all members of `{linkedTypeDesc.GetDisplayName()}`to exist in the linked assembly, but one or more were missing"; - } - } - - private TypeDefinition GetOriginalTypeFromInAssemblyAttribute (CustomAttribute inAssemblyAttribute) - { - string assemblyName; - if (inAssemblyAttribute.HasProperties && inAssemblyAttribute.Properties[0].Name == "ExpectationAssemblyName") - assemblyName = inAssemblyAttribute.Properties[0].Argument.Value.ToString ()!; - else - assemblyName = inAssemblyAttribute.ConstructorArguments[0].Value.ToString ()!; - - return GetOriginalTypeFromInAssemblyAttribute (assemblyName, inAssemblyAttribute.ConstructorArguments[1].Value); - } - - private TypeDefinition GetOriginalTypeFromInAssemblyAttribute (string assemblyName, object typeOrTypeName) - { - if (typeOrTypeName is TypeReference attributeValueAsTypeReference) - return attributeValueAsTypeReference.Resolve (); - - var assembly = ResolveOriginalsAssembly (assemblyName); - - var expectedTypeName = typeOrTypeName.ToString (); - var originalType = assembly.MainModule.GetType (expectedTypeName); - if (originalType == null) - Assert.Fail ($"Invalid test assertion. Unable to locate the original type `{expectedTypeName}.`"); - return originalType; - } - - private static Dictionary> BuildOtherAssemblyCheckTable (AssemblyDefinition original) - { - var checks = new Dictionary> (); - - foreach (var typeWithRemoveInAssembly in original.AllDefinedTypes ()) { - foreach (var attr in typeWithRemoveInAssembly.CustomAttributes.Where (IsTypeInOtherAssemblyAssertion)) { - var assemblyName = (string) attr.ConstructorArguments[0].Value; - - Tool? toolTarget = (Tool?)(int?)attr.GetPropertyValue("Tool"); - if (toolTarget is not null && !toolTarget.Value.HasFlag(Tool.NativeAot)) - continue; - - if (!checks.TryGetValue (assemblyName, out List? checksForAssembly)) - checks[assemblyName] = checksForAssembly = new List (); - - checksForAssembly.Add (attr); - } - } - - return checks; - } - - private Dictionary ResolveLinkedMembersForAssembly (string assemblyName) - { - var cleanAssemblyName = assemblyName; - if (assemblyName.EndsWith(".exe") || assemblyName.EndsWith(".dll")) - cleanAssemblyName = System.IO.Path.GetFileNameWithoutExtension(assemblyName); - - return this.linkedMembers.Where(e => GetModuleName(e.Value.Entity) == cleanAssemblyName).ToDictionary(); - } - - protected AssemblyDefinition ResolveOriginalsAssembly (string assemblyName) - { - var cleanAssemblyName = assemblyName; - if (assemblyName.EndsWith (".exe") || assemblyName.EndsWith (".dll")) - cleanAssemblyName = Path.GetFileNameWithoutExtension (assemblyName); - return originalsResolver.Resolve (new AssemblyNameReference (cleanAssemblyName, null), originalReaderParameters); - } - - private static bool IsTypeInOtherAssemblyAssertion (CustomAttribute attr) - { - return attr.AttributeType.Resolve ()?.DerivesFrom (nameof (BaseInAssemblyAttribute)) ?? false; - } - - private IEnumerable VerifyExpectedInstructionSequenceOnMemberInAssembly (CustomAttribute inAssemblyAttribute, TypeDefinition linkedType) - { - var originalType = GetOriginalTypeFromInAssemblyAttribute (inAssemblyAttribute); - var memberName = (string) inAssemblyAttribute.ConstructorArguments[2].Value; - - if (TryVerifyKeptMemberInAssemblyAsMethod (memberName, originalType, linkedType, out MethodDefinition? originalMethod, out MethodDefinition? linkedMethod)) { - static string[] valueCollector (MethodDefinition m) => AssemblyChecker.FormatMethodBody (m.Body); - var linkedValues = valueCollector (linkedMethod!); - var srcValues = valueCollector (originalMethod!); - - var expected = ((CustomAttributeArgument[]) inAssemblyAttribute.ConstructorArguments[3].Value)?.Select (arg => arg.Value.ToString ()).ToArray (); - if (!linkedValues.Equals(expected)) - yield return "Expected instruction sequence does not match"; - - yield break; - } - - yield return $"Invalid test assertion. No method named `{memberName}` exists on the original type `{originalType}`"; - } - - protected virtual void UnhandledOtherAssemblyAssertion (string expectedTypeName, CustomAttribute checkAttrInAssembly, TypeDefinition? linkedType) - { - throw new NotImplementedException ($"Type {expectedTypeName}, has an unknown other assembly attribute of type {checkAttrInAssembly.AttributeType}"); - } - } + yield break; + } + + private IEnumerable VerifyKeptAllTypesAndMembersInAssembly(string assemblyName, Dictionary linkedMembers) + { + var original = ResolveOriginalsAssembly(assemblyName); + + if (original == null) + { + yield return $"Failed to resolve original assembly {assemblyName}"; + yield break; + } + + var originalTypes = original.AllDefinedTypes().ToDictionary(t => new AssemblyQualifiedToken(t)); + var linkedTypes = linkedMembers.Where(t => t.Value.Entity is TypeDesc).ToDictionary(); + + var missingInLinked = originalTypes.Keys.Except(linkedTypes.Keys); + + if (missingInLinked.Any()) + yield return $"Expected all types to exist in the linked assembly {assemblyName}, but one or more were missing"; + + foreach (var originalKvp in originalTypes) + { + var linkedType = linkedTypes[originalKvp.Key]; + TypeDesc linkedTypeDesc = (TypeDesc)linkedType.Entity; + + // NativeAOT field trimming is very different (it basically doesn't trim fields, not in the same way trimmer does) + var originalMembers = originalKvp.Value.AllMembers().Where(m => m is not FieldDefinition).Select(m => new AssemblyQualifiedToken(m)); + var linkedMembersOnType = linkedMembers.Where(t => GetOwningType(t.Value.Entity) == linkedTypeDesc).Select(t => t.Key); + + var missingMembersInLinked = originalMembers.Except(linkedMembersOnType); + + if (missingMembersInLinked.Any()) + yield return $"Expected all members of `{linkedTypeDesc.GetDisplayName()}`to exist in the linked assembly, but one or more were missing"; + } + } + + private TypeDefinition GetOriginalTypeFromInAssemblyAttribute(CustomAttribute inAssemblyAttribute) + { + string assemblyName; + if (inAssemblyAttribute.HasProperties && inAssemblyAttribute.Properties[0].Name == "ExpectationAssemblyName") + assemblyName = inAssemblyAttribute.Properties[0].Argument.Value.ToString()!; + else + assemblyName = inAssemblyAttribute.ConstructorArguments[0].Value.ToString()!; + + return GetOriginalTypeFromInAssemblyAttribute(assemblyName, inAssemblyAttribute.ConstructorArguments[1].Value); + } + + private TypeDefinition GetOriginalTypeFromInAssemblyAttribute(string assemblyName, object typeOrTypeName) + { + if (typeOrTypeName is TypeReference attributeValueAsTypeReference) + return attributeValueAsTypeReference.Resolve(); + + var assembly = ResolveOriginalsAssembly(assemblyName); + + var expectedTypeName = typeOrTypeName.ToString(); + var originalType = assembly.MainModule.GetType(expectedTypeName); + if (originalType == null) + Assert.Fail($"Invalid test assertion. Unable to locate the original type `{expectedTypeName}.`"); + return originalType; + } + + private static Dictionary> BuildOtherAssemblyCheckTable(AssemblyDefinition original) + { + var checks = new Dictionary>(); + + foreach (var typeWithRemoveInAssembly in original.AllDefinedTypes()) + { + foreach (var attr in typeWithRemoveInAssembly.CustomAttributes.Where(IsTypeInOtherAssemblyAssertion)) + { + var assemblyName = (string)attr.ConstructorArguments[0].Value; + + Tool? toolTarget = (Tool?)(int?)attr.GetPropertyValue("Tool"); + if (toolTarget is not null && !toolTarget.Value.HasFlag(Tool.NativeAot)) + continue; + + if (!checks.TryGetValue(assemblyName, out List? checksForAssembly)) + checks[assemblyName] = checksForAssembly = new List(); + + checksForAssembly.Add(attr); + } + } + + return checks; + } + + private Dictionary ResolveLinkedMembersForAssembly(string assemblyName) + { + var cleanAssemblyName = assemblyName; + if (assemblyName.EndsWith(".exe") || assemblyName.EndsWith(".dll")) + cleanAssemblyName = System.IO.Path.GetFileNameWithoutExtension(assemblyName); + + return this.linkedMembers.Where(e => GetModuleName(e.Value.Entity) == cleanAssemblyName).ToDictionary(); + } + + protected AssemblyDefinition ResolveOriginalsAssembly(string assemblyName) + { + var cleanAssemblyName = assemblyName; + if (assemblyName.EndsWith(".exe") || assemblyName.EndsWith(".dll")) + cleanAssemblyName = Path.GetFileNameWithoutExtension(assemblyName); + return originalsResolver.Resolve(new AssemblyNameReference(cleanAssemblyName, null), originalReaderParameters); + } + + private static bool IsTypeInOtherAssemblyAssertion(CustomAttribute attr) + { + return attr.AttributeType.Resolve()?.DerivesFrom(nameof(BaseInAssemblyAttribute)) ?? false; + } + + private IEnumerable VerifyExpectedInstructionSequenceOnMemberInAssembly(CustomAttribute inAssemblyAttribute, TypeDefinition linkedType) + { + var originalType = GetOriginalTypeFromInAssemblyAttribute(inAssemblyAttribute); + var memberName = (string)inAssemblyAttribute.ConstructorArguments[2].Value; + + if (TryVerifyKeptMemberInAssemblyAsMethod(memberName, originalType, linkedType, out MethodDefinition? originalMethod, out MethodDefinition? linkedMethod)) + { + static string[] valueCollector(MethodDefinition m) => AssemblyChecker.FormatMethodBody(m.Body); + var linkedValues = valueCollector(linkedMethod!); + var srcValues = valueCollector(originalMethod!); + + var expected = ((CustomAttributeArgument[])inAssemblyAttribute.ConstructorArguments[3].Value)?.Select(arg => arg.Value.ToString()).ToArray(); + if (!linkedValues.Equals(expected)) + yield return "Expected instruction sequence does not match"; + + yield break; + } + + yield return $"Invalid test assertion. No method named `{memberName}` exists on the original type `{originalType}`"; + } + + protected virtual void UnhandledOtherAssemblyAssertion(string expectedTypeName, CustomAttribute checkAttrInAssembly, TypeDefinition? linkedType) + { + throw new NotImplementedException($"Type {expectedTypeName}, has an unknown other assembly attribute of type {checkAttrInAssembly.AttributeType}"); + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyQualifiedToken.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyQualifiedToken.cs index 2e0ecaa9a5b7ac..01bf36d8e936d2 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyQualifiedToken.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyQualifiedToken.cs @@ -6,51 +6,54 @@ using System.Reflection.Metadata.Ecma335; using ILCompiler; using Internal.IL.Stubs; -using Internal.TypeSystem.Ecma; using Internal.TypeSystem; +using Internal.TypeSystem.Ecma; using Mono.Cecil; using MetadataType = Internal.TypeSystem.MetadataType; namespace Mono.Linker.Tests.TestCasesRunner { - internal readonly struct AssemblyQualifiedToken : IEquatable - { - public string? AssemblyName { get; } - public int Token { get; } + internal readonly struct AssemblyQualifiedToken : IEquatable + { + public string? AssemblyName { get; } + public int Token { get; } - public AssemblyQualifiedToken (string? assemblyName, int token) => (AssemblyName, Token) = (assemblyName, token); + public AssemblyQualifiedToken(string? assemblyName, int token) => (AssemblyName, Token) = (assemblyName, token); - public AssemblyQualifiedToken (TypeSystemEntity entity) { - if (entity is MethodForInstantiatedType instantiatedMethod) - entity = instantiatedMethod.GetTypicalMethodDefinition (); - (AssemblyName, Token) = entity switch { - EcmaType type => (type.Module.Assembly.GetName ().Name, MetadataTokens.GetToken (type.Handle)), - EcmaMethod method => (method.Module.Assembly.GetName ().Name, MetadataTokens.GetToken (method.Handle)), - EcmaField field => (field.Module.Assembly.GetName ().Name, MetadataTokens.GetToken (field.Handle)), - PropertyPseudoDesc property => (((EcmaType) property.OwningType).Module.Assembly.GetName ().Name, MetadataTokens.GetToken (property.Handle)), - EventPseudoDesc @event => (((EcmaType) @event.OwningType).Module.Assembly.GetName ().Name, MetadataTokens.GetToken (@event.Handle)), - ILStubMethod => (null, 0), // Ignore compiler generated methods - MetadataType mt when mt.GetType().Name == "BoxedValueType" => (null, 0), - _ => throw new NotSupportedException ($"The infra doesn't support getting a token for {entity} yet.") - }; - } + public AssemblyQualifiedToken(TypeSystemEntity entity) + { + if (entity is MethodForInstantiatedType instantiatedMethod) + entity = instantiatedMethod.GetTypicalMethodDefinition(); + (AssemblyName, Token) = entity switch + { + EcmaType type => (type.Module.Assembly.GetName().Name, MetadataTokens.GetToken(type.Handle)), + EcmaMethod method => (method.Module.Assembly.GetName().Name, MetadataTokens.GetToken(method.Handle)), + EcmaField field => (field.Module.Assembly.GetName().Name, MetadataTokens.GetToken(field.Handle)), + PropertyPseudoDesc property => (((EcmaType)property.OwningType).Module.Assembly.GetName().Name, MetadataTokens.GetToken(property.Handle)), + EventPseudoDesc @event => (((EcmaType)@event.OwningType).Module.Assembly.GetName().Name, MetadataTokens.GetToken(@event.Handle)), + ILStubMethod => (null, 0), // Ignore compiler generated methods + MetadataType mt when mt.GetType().Name == "BoxedValueType" => (null, 0), + _ => throw new NotSupportedException($"The infra doesn't support getting a token for {entity} yet.") + }; + } - public AssemblyQualifiedToken (IMemberDefinition member) => - (AssemblyName, Token) = member switch { - TypeDefinition type => (type.Module.Assembly.Name.Name, type.MetadataToken.ToInt32 ()), - MethodDefinition method => (method.Module.Assembly.Name.Name, method.MetadataToken.ToInt32 ()), - PropertyDefinition property => (property.Module.Assembly.Name.Name, property.MetadataToken.ToInt32 ()), - EventDefinition @event => (@event.Module.Assembly.Name.Name, @event.MetadataToken.ToInt32 ()), - FieldDefinition field => (field.Module.Assembly.Name.Name, field.MetadataToken.ToInt32 ()), - _ => throw new NotSupportedException ($"The infra doesn't support getting a token for {member} yet.") - }; + public AssemblyQualifiedToken(IMemberDefinition member) => + (AssemblyName, Token) = member switch + { + TypeDefinition type => (type.Module.Assembly.Name.Name, type.MetadataToken.ToInt32()), + MethodDefinition method => (method.Module.Assembly.Name.Name, method.MetadataToken.ToInt32()), + PropertyDefinition property => (property.Module.Assembly.Name.Name, property.MetadataToken.ToInt32()), + EventDefinition @event => (@event.Module.Assembly.Name.Name, @event.MetadataToken.ToInt32()), + FieldDefinition field => (field.Module.Assembly.Name.Name, field.MetadataToken.ToInt32()), + _ => throw new NotSupportedException($"The infra doesn't support getting a token for {member} yet.") + }; - public override int GetHashCode () => AssemblyName == null ? 0 : AssemblyName.GetHashCode () ^ Token.GetHashCode (); - public override string ToString () => $"{AssemblyName}: {Token}"; - public bool Equals (AssemblyQualifiedToken other) => - string.CompareOrdinal (AssemblyName, other.AssemblyName) == 0 && Token == other.Token; - public override bool Equals ([NotNullWhen (true)] object? obj) => ((AssemblyQualifiedToken?) obj)?.Equals (this) == true; + public override int GetHashCode() => AssemblyName == null ? 0 : AssemblyName.GetHashCode() ^ Token.GetHashCode(); + public override string ToString() => $"{AssemblyName}: {Token}"; + public bool Equals(AssemblyQualifiedToken other) => + string.CompareOrdinal(AssemblyName, other.AssemblyName) == 0 && Token == other.Token; + public override bool Equals([NotNullWhen(true)] object? obj) => ((AssemblyQualifiedToken?)obj)?.Equals(this) == true; - public bool IsNil => AssemblyName == null; - } + public bool IsNil => AssemblyName == null; + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILCompilerOptions.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILCompilerOptions.cs index 926f3e593b8c70..e9a6db92c2bf86 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILCompilerOptions.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILCompilerOptions.cs @@ -5,20 +5,20 @@ namespace Mono.Linker.Tests.TestCasesRunner { - public class ILCompilerOptions - { - public Dictionary InputFilePaths = new Dictionary (); - public Dictionary ReferenceFilePaths = new Dictionary (); - public List InitAssemblies = new List (); - public List TrimAssemblies = new List (); - public List AdditionalRootAssemblies = new List (); - public Dictionary FeatureSwitches = new Dictionary (); - public List Descriptors = new List (); - public bool FrameworkCompilation; - public bool SingleWarn; - public List SubstitutionFiles = new List (); - public bool TreatWarningsAsErrors; - public Dictionary WarningsAsErrors = new Dictionary (); - public List SuppressedWarningCategories = new List (); - } + public class ILCompilerOptions + { + public Dictionary InputFilePaths = new Dictionary(); + public Dictionary ReferenceFilePaths = new Dictionary(); + public List InitAssemblies = new List(); + public List TrimAssemblies = new List(); + public List AdditionalRootAssemblies = new List(); + public Dictionary FeatureSwitches = new Dictionary(); + public List Descriptors = new List(); + public bool FrameworkCompilation; + public bool SingleWarn; + public List SubstitutionFiles = new List(); + public bool TreatWarningsAsErrors; + public Dictionary WarningsAsErrors = new Dictionary(); + public List SuppressedWarningCategories = new List(); + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILCompilerTestPInvokePolicy.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILCompilerTestPInvokePolicy.cs index 4d2aebdcd269c1..5719ee5677b888 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILCompilerTestPInvokePolicy.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILCompilerTestPInvokePolicy.cs @@ -6,12 +6,12 @@ namespace Mono.Linker.Tests.TestCasesRunner { - internal sealed class ILCompilerTestPInvokePolicy : PInvokeILEmitterConfiguration - { - public override bool GenerateDirectCall (MethodDesc method, out string? externName) - { - externName = method.Name; - return true; - } - } + internal sealed class ILCompilerTestPInvokePolicy : PInvokeILEmitterConfiguration + { + public override bool GenerateDirectCall(MethodDesc method, out string? externName) + { + externName = method.Name; + return true; + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILInputCompiler.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILInputCompiler.cs index 80a48c2da1695e..86b93e02b5ad34 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILInputCompiler.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILInputCompiler.cs @@ -13,80 +13,81 @@ namespace Mono.Linker.Tests.TestCasesRunner { - public class ILInputCompiler - { - public NPath Compile (CompilerOptions options) - { - var capturedOutput = new List (); - var process = new Process (); - SetupProcess (process, options); - process.StartInfo.RedirectStandardOutput = true; - process.OutputDataReceived += (sender, args) => capturedOutput.Add (args.Data!); - process.Start (); - process.BeginOutputReadLine (); - process.WaitForExit (); + public class ILInputCompiler + { + public NPath Compile(CompilerOptions options) + { + var capturedOutput = new List(); + var process = new Process(); + SetupProcess(process, options); + process.StartInfo.RedirectStandardOutput = true; + process.OutputDataReceived += (sender, args) => capturedOutput.Add(args.Data!); + process.Start(); + process.BeginOutputReadLine(); + process.WaitForExit(); - if (process.ExitCode != 0) { - Assert.Fail($"Failed to compile IL assembly : {options.OutputPath}\n{capturedOutput.Aggregate ((buff, s) => buff + Environment.NewLine + s)}"); - } + if (process.ExitCode != 0) + { + Assert.Fail($"Failed to compile IL assembly : {options.OutputPath}\n{capturedOutput.Aggregate((buff, s) => buff + Environment.NewLine + s)}"); + } - return options.OutputPath; - } + return options.OutputPath; + } - protected virtual void SetupProcess (Process process, CompilerOptions options) - { - process.StartInfo.FileName = LocateIlasm ().ToString (); - process.StartInfo.Arguments = BuildArguments (options); - process.StartInfo.UseShellExecute = false; - process.StartInfo.CreateNoWindow = true; - process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; - } + protected virtual void SetupProcess(Process process, CompilerOptions options) + { + process.StartInfo.FileName = LocateIlasm().ToString(); + process.StartInfo.Arguments = BuildArguments(options); + process.StartInfo.UseShellExecute = false; + process.StartInfo.CreateNoWindow = true; + process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; + } - private static string BuildArguments (CompilerOptions options) - { - var args = new StringBuilder (); + private static string BuildArguments(CompilerOptions options) + { + var args = new StringBuilder(); #if NET - args.Append (options.OutputPath.ExtensionWithDot == ".dll" ? "-dll" : "-exe"); - args.Append ($" -out:{options.OutputPath.InQuotes ()}"); + args.Append(options.OutputPath.ExtensionWithDot == ".dll" ? "-dll" : "-exe"); + args.Append($" -out:{options.OutputPath.InQuotes()}"); #else - args.Append (options.OutputPath.ExtensionWithDot == ".dll" ? "/dll" : "/exe"); - args.Append ($" /out:{options.OutputPath.InQuotes ()}"); + args.Append (options.OutputPath.ExtensionWithDot == ".dll" ? "/dll" : "/exe"); + args.Append ($" /out:{options.OutputPath.InQuotes ()}"); #endif - args.Append ($" {options.SourceFiles.Aggregate (string.Empty, (buff, file) => $"{buff} {file.InQuotes ()}")}"); - return args.ToString (); - } + args.Append($" {options.SourceFiles.Aggregate(string.Empty, (buff, file) => $"{buff} {file.InQuotes()}")}"); + return args.ToString(); + } - protected virtual NPath LocateIlasm () - { + protected virtual NPath LocateIlasm() + { #if NET - var extension = RuntimeInformation.IsOSPlatform (OSPlatform.Windows) ? ".exe" : ""; + var extension = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".exe" : ""; - var toolsDir = (string) AppContext.GetData ("Mono.Linker.Tests.ILToolsDir")!; + var toolsDir = (string)AppContext.GetData("Mono.Linker.Tests.ILToolsDir")!; - var ilasmPath = Path.GetFullPath (Path.Combine (toolsDir, $"ilasm{extension}")).ToNPath (); - if (ilasmPath.FileExists ()) - return ilasmPath; + var ilasmPath = Path.GetFullPath(Path.Combine(toolsDir, $"ilasm{extension}")).ToNPath(); + if (ilasmPath.FileExists()) + return ilasmPath; - throw new InvalidOperationException ("ilasm not found at " + ilasmPath); + throw new InvalidOperationException("ilasm not found at " + ilasmPath); #else - return Environment.OSVersion.Platform == PlatformID.Win32NT ? LocateIlasmOnWindows () : "ilasm".ToNPath (); + return Environment.OSVersion.Platform == PlatformID.Win32NT ? LocateIlasmOnWindows () : "ilasm".ToNPath (); #endif - } + } - public static NPath LocateIlasmOnWindows () - { - if (Environment.OSVersion.Platform != PlatformID.Win32NT) - throw new InvalidOperationException ("This method should only be called on windows"); + public static NPath LocateIlasmOnWindows() + { + if (Environment.OSVersion.Platform != PlatformID.Win32NT) + throw new InvalidOperationException("This method should only be called on windows"); - var possiblePath = RuntimeEnvironment.GetRuntimeDirectory ().ToNPath ().Combine ("ilasm.exe"); - if (possiblePath.FileExists ()) - return possiblePath; + var possiblePath = RuntimeEnvironment.GetRuntimeDirectory().ToNPath().Combine("ilasm.exe"); + if (possiblePath.FileExists()) + return possiblePath; - possiblePath = Environment.CurrentDirectory.ToNPath ().Combine ("ilasm.exe"); - if (possiblePath.FileExists ()) - return possiblePath; + possiblePath = Environment.CurrentDirectory.ToNPath().Combine("ilasm.exe"); + if (possiblePath.FileExists()) + return possiblePath; - throw new InvalidOperationException ("Could not locate a ilasm.exe executable"); - } - } + throw new InvalidOperationException("Could not locate a ilasm.exe executable"); + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/MemberAssertionsCollector.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/MemberAssertionsCollector.cs index 6b7958c92c4d89..425ad3d1dbce5c 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/MemberAssertionsCollector.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/MemberAssertionsCollector.cs @@ -16,181 +16,195 @@ namespace Mono.Linker.Tests.TestCasesRunner { - public class MemberAssertionsCollector : IEnumerable - { - public struct CustomAttribute - { - public MetadataType AttributeType; - public CustomAttributeValue Value; - - public override string ToString () => AttributeType.ToString (); - } - - public MemberAssertionsCollector(Type type) - { - this.type = type; - TypeSystemContext = CreateTypeSystemContext(); - } - - private CompilerTypeSystemContext TypeSystemContext; - private readonly Type type; - - private CompilerTypeSystemContext CreateTypeSystemContext () - { - TrimmingDriver.ComputeDefaultOptions (out var targetOS, out var targetArchitecture); - var targetDetails = new TargetDetails (targetArchitecture, targetOS, TargetAbi.NativeAot); - CompilerTypeSystemContext typeSystemContext = - new CompilerTypeSystemContext (targetDetails, SharedGenericsMode.CanonicalReferenceTypes, DelegateFeature.All); - typeSystemContext.InputFilePaths = new Dictionary () { - { type.Assembly.GetName().Name!, type.Assembly.Location } - }; - Dictionary references = new Dictionary (); - foreach (Assembly assembly in AssemblyLoadContext.Default.Assemblies) { - references.Add (assembly.GetName ().Name!, assembly.Location!); - } - typeSystemContext.ReferenceFilePaths = references; - typeSystemContext.SetSystemModule (typeSystemContext.GetModuleForSimpleName (TrimmingDriver.DefaultSystemModule)); - - return typeSystemContext; - } - - internal IEnumerable<(TypeSystemEntity member, CustomAttribute ca)> GetMemberAssertions (Type type) - { - var module = TypeSystemContext.GetModuleFromPath (type.Assembly.Location); - var t = module.GetType (type.Namespace, type.Name, throwIfNotFound: false); - if (t == null) - throw new InvalidOperationException ($"type {type} not found in {module}"); - var results = new List<(TypeSystemEntity, CustomAttribute)> (); - CollectMemberAssertions (t, results); - return results; - } - - public IEnumerable GetMemberAssertionsData () - { - return GetMemberAssertions (type).Select (v => new object[] { v.member, v.ca }); - } - - public IEnumerator GetEnumerator () => GetMemberAssertionsData ().GetEnumerator (); - IEnumerator IEnumerable.GetEnumerator () => throw new NotImplementedException (); - - private static bool IsMemberAssertion (MetadataType attributeType) - { - if (attributeType == null) - return false; - - if (attributeType.Namespace != "Mono.Linker.Tests.Cases.Expectations.Assertions") - return false; - - MetadataType t = attributeType; - while (t != null) { - if (t.Name == nameof (BaseMemberAssertionAttribute)) - return true; - - t = t.MetadataBaseType; - } - - return false; - } - - private static void CollectMemberAssertions (MetadataType metadataType, List<(TypeSystemEntity, CustomAttribute)> results) - { - if (metadataType is not EcmaType type) - return; - - foreach (var ca in GetCustomAttributes (type)) { - if (!IsMemberAssertion (ca.AttributeType)) - continue; - results.Add ((type, ca)); - } - - foreach (var md in type.GetMethods ()) { - if (md is not EcmaMethod m) - continue; - - foreach (var ca in GetCustomAttributes(m)) { - if (!IsMemberAssertion (ca.AttributeType)) - continue; - results.Add ((m, ca)); - } - } - - foreach (var fd in type.GetFields()) { - if (fd is not EcmaField f) - continue; - - foreach (var ca in GetCustomAttributes(f)) { - if (!IsMemberAssertion (ca.AttributeType)) - continue; - results.Add ((f, ca)); - } - } - - foreach (var propertyHandle in type.MetadataReader.GetTypeDefinition (type.Handle).GetProperties ()) { - var p = new PropertyPseudoDesc (type, propertyHandle); - foreach (var ca in GetCustomAttributes(type, p)) { - if (!IsMemberAssertion (ca.AttributeType)) - continue; - results.Add ((p, ca)); - } - } - - foreach (var eventHandle in type.MetadataReader.GetTypeDefinition (type.Handle).GetEvents ()) { - var e = new EventPseudoDesc (type, eventHandle); - foreach (var ca in GetCustomAttributes(type, e)) { - if (!IsMemberAssertion (ca.AttributeType)) - continue; - results.Add ((e, ca)); - } - } - - foreach (var nested in type.GetNestedTypes()) { - CollectMemberAssertions (nested, results); - } - } - - private static IEnumerable GetCustomAttributes (EcmaType type) - { - var metadataReader = type.MetadataReader; - return GetCustomAttributes (metadataReader.GetTypeDefinition (type.Handle).GetCustomAttributes (), metadataReader, type.EcmaModule); - } - - private static IEnumerable GetCustomAttributes (EcmaMethod method) - { - var metadataReader = method.MetadataReader; - return GetCustomAttributes (metadataReader.GetMethodDefinition (method.Handle).GetCustomAttributes (), metadataReader, method.Module); - } - - private static IEnumerable GetCustomAttributes (EcmaField field) - { - var metadataReader = field.MetadataReader; - return GetCustomAttributes (metadataReader.GetFieldDefinition (field.Handle).GetCustomAttributes (), metadataReader, field.Module); - } - - private static IEnumerable GetCustomAttributes (EcmaType type, PropertyPseudoDesc prop) - { - return GetCustomAttributes (prop.GetCustomAttributes, type.MetadataReader, type.EcmaModule); - } - - private static IEnumerable GetCustomAttributes (EcmaType type, EventPseudoDesc @event) - { - return GetCustomAttributes (@event.GetCustomAttributes, type.MetadataReader, type.EcmaModule); - } - - private static IEnumerable GetCustomAttributes(CustomAttributeHandleCollection attributeHandles, MetadataReader metadataReader, EcmaModule module) - { - foreach (var attributeHandle in attributeHandles) { - if (!metadataReader.GetAttributeTypeAndConstructor (attributeHandle, out var attributeType, out _)) - continue; - - if (module.GetType (attributeType) is not MetadataType attributeMetadataType) - continue; - - yield return - new CustomAttribute () { - AttributeType = attributeMetadataType, - Value = metadataReader.GetCustomAttribute (attributeHandle).DecodeValue (new CustomAttributeTypeProvider (module)) - }; - } - } - } + public class MemberAssertionsCollector : IEnumerable + { + public struct CustomAttribute + { + public MetadataType AttributeType; + public CustomAttributeValue Value; + + public override string ToString() => AttributeType.ToString(); + } + + public MemberAssertionsCollector(Type type) + { + this.type = type; + TypeSystemContext = CreateTypeSystemContext(); + } + + private CompilerTypeSystemContext TypeSystemContext; + private readonly Type type; + + private CompilerTypeSystemContext CreateTypeSystemContext() + { + TrimmingDriver.ComputeDefaultOptions(out var targetOS, out var targetArchitecture); + var targetDetails = new TargetDetails(targetArchitecture, targetOS, TargetAbi.NativeAot); + CompilerTypeSystemContext typeSystemContext = + new CompilerTypeSystemContext(targetDetails, SharedGenericsMode.CanonicalReferenceTypes, DelegateFeature.All); + typeSystemContext.InputFilePaths = new Dictionary() { + { type.Assembly.GetName().Name!, type.Assembly.Location } + }; + Dictionary references = new Dictionary(); + foreach (Assembly assembly in AssemblyLoadContext.Default.Assemblies) + { + references.Add(assembly.GetName().Name!, assembly.Location!); + } + typeSystemContext.ReferenceFilePaths = references; + typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(TrimmingDriver.DefaultSystemModule)); + + return typeSystemContext; + } + + internal IEnumerable<(TypeSystemEntity member, CustomAttribute ca)> GetMemberAssertions(Type type) + { + var module = TypeSystemContext.GetModuleFromPath(type.Assembly.Location); + var t = module.GetType(type.Namespace, type.Name, throwIfNotFound: false); + if (t == null) + throw new InvalidOperationException($"type {type} not found in {module}"); + var results = new List<(TypeSystemEntity, CustomAttribute)>(); + CollectMemberAssertions(t, results); + return results; + } + + public IEnumerable GetMemberAssertionsData() + { + return GetMemberAssertions(type).Select(v => new object[] { v.member, v.ca }); + } + + public IEnumerator GetEnumerator() => GetMemberAssertionsData().GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); + + private static bool IsMemberAssertion(MetadataType attributeType) + { + if (attributeType == null) + return false; + + if (attributeType.Namespace != "Mono.Linker.Tests.Cases.Expectations.Assertions") + return false; + + MetadataType t = attributeType; + while (t != null) + { + if (t.Name == nameof(BaseMemberAssertionAttribute)) + return true; + + t = t.MetadataBaseType; + } + + return false; + } + + private static void CollectMemberAssertions(MetadataType metadataType, List<(TypeSystemEntity, CustomAttribute)> results) + { + if (metadataType is not EcmaType type) + return; + + foreach (var ca in GetCustomAttributes(type)) + { + if (!IsMemberAssertion(ca.AttributeType)) + continue; + results.Add((type, ca)); + } + + foreach (var md in type.GetMethods()) + { + if (md is not EcmaMethod m) + continue; + + foreach (var ca in GetCustomAttributes(m)) + { + if (!IsMemberAssertion(ca.AttributeType)) + continue; + results.Add((m, ca)); + } + } + + foreach (var fd in type.GetFields()) + { + if (fd is not EcmaField f) + continue; + + foreach (var ca in GetCustomAttributes(f)) + { + if (!IsMemberAssertion(ca.AttributeType)) + continue; + results.Add((f, ca)); + } + } + + foreach (var propertyHandle in type.MetadataReader.GetTypeDefinition(type.Handle).GetProperties()) + { + var p = new PropertyPseudoDesc(type, propertyHandle); + foreach (var ca in GetCustomAttributes(type, p)) + { + if (!IsMemberAssertion(ca.AttributeType)) + continue; + results.Add((p, ca)); + } + } + + foreach (var eventHandle in type.MetadataReader.GetTypeDefinition(type.Handle).GetEvents()) + { + var e = new EventPseudoDesc(type, eventHandle); + foreach (var ca in GetCustomAttributes(type, e)) + { + if (!IsMemberAssertion(ca.AttributeType)) + continue; + results.Add((e, ca)); + } + } + + foreach (var nested in type.GetNestedTypes()) + { + CollectMemberAssertions(nested, results); + } + } + + private static IEnumerable GetCustomAttributes(EcmaType type) + { + var metadataReader = type.MetadataReader; + return GetCustomAttributes(metadataReader.GetTypeDefinition(type.Handle).GetCustomAttributes(), metadataReader, type.EcmaModule); + } + + private static IEnumerable GetCustomAttributes(EcmaMethod method) + { + var metadataReader = method.MetadataReader; + return GetCustomAttributes(metadataReader.GetMethodDefinition(method.Handle).GetCustomAttributes(), metadataReader, method.Module); + } + + private static IEnumerable GetCustomAttributes(EcmaField field) + { + var metadataReader = field.MetadataReader; + return GetCustomAttributes(metadataReader.GetFieldDefinition(field.Handle).GetCustomAttributes(), metadataReader, field.Module); + } + + private static IEnumerable GetCustomAttributes(EcmaType type, PropertyPseudoDesc prop) + { + return GetCustomAttributes(prop.GetCustomAttributes, type.MetadataReader, type.EcmaModule); + } + + private static IEnumerable GetCustomAttributes(EcmaType type, EventPseudoDesc @event) + { + return GetCustomAttributes(@event.GetCustomAttributes, type.MetadataReader, type.EcmaModule); + } + + private static IEnumerable GetCustomAttributes(CustomAttributeHandleCollection attributeHandles, MetadataReader metadataReader, EcmaModule module) + { + foreach (var attributeHandle in attributeHandles) + { + if (!metadataReader.GetAttributeTypeAndConstructor(attributeHandle, out var attributeType, out _)) + continue; + + if (module.GetType(attributeType) is not MetadataType attributeMetadataType) + continue; + + yield return + new CustomAttribute() + { + AttributeType = attributeMetadataType, + Value = metadataReader.GetCustomAttribute(attributeHandle).DecodeValue(new CustomAttributeTypeProvider(module)) + }; + } + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/NameUtils.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/NameUtils.cs index 68c4006eb65303..53a13f821c8faa 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/NameUtils.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/NameUtils.cs @@ -11,74 +11,83 @@ namespace Mono.Linker.Tests.TestCasesRunner { - internal static class NameUtils - { - internal static string? GetActualOriginDisplayName (TypeSystemEntity? entity) => entity switch { - DefType defType => TrimAssemblyNamePrefix (defType.GetDisplayName ()), - MethodDesc method => TrimAssemblyNamePrefix (method.GetDisplayName ()), - FieldDesc field => TrimAssemblyNamePrefix (field.ToString ()), - ModuleDesc module => module.Assembly.GetName ().Name, - _ => null - }; + internal static class NameUtils + { + internal static string? GetActualOriginDisplayName(TypeSystemEntity? entity) => entity switch + { + DefType defType => TrimAssemblyNamePrefix(defType.GetDisplayName()), + MethodDesc method => TrimAssemblyNamePrefix(method.GetDisplayName()), + FieldDesc field => TrimAssemblyNamePrefix(field.ToString()), + ModuleDesc module => module.Assembly.GetName().Name, + _ => null + }; - private static string? TrimAssemblyNamePrefix (string? name) - { - if (name == null) - return null; + private static string? TrimAssemblyNamePrefix(string? name) + { + if (name == null) + return null; - if (name.StartsWith ('[')) { - int i = name.IndexOf (']'); - if (i > 0) { - return name.Substring (i + 1); - } - } + if (name.StartsWith('[')) + { + int i = name.IndexOf(']'); + if (i > 0) + { + return name.Substring(i + 1); + } + } - return name; - } + return name; + } - internal static string GetExpectedOriginDisplayName (ICustomAttributeProvider provider) => - ConvertSignatureToIlcFormat (provider switch { - MethodDefinition method => method.GetDisplayName (), - FieldDefinition field => field.GetDisplayName (), - TypeDefinition type => type.GetDisplayName (), - IMemberDefinition member => member.FullName, - AssemblyDefinition asm => asm.Name.Name, - _ => throw new NotImplementedException () - }); + internal static string GetExpectedOriginDisplayName(ICustomAttributeProvider provider) => + ConvertSignatureToIlcFormat(provider switch + { + MethodDefinition method => method.GetDisplayName(), + FieldDefinition field => field.GetDisplayName(), + TypeDefinition type => type.GetDisplayName(), + IMemberDefinition member => member.FullName, + AssemblyDefinition asm => asm.Name.Name, + _ => throw new NotImplementedException() + }); - internal static string ConvertSignatureToIlcFormat (string value) - { - if (value.Contains ('(') || value.Contains ('<')) { - value = value.Replace (", ", ","); - } + internal static string ConvertSignatureToIlcFormat(string value) + { + if (value.Contains('(') || value.Contains('<')) + { + value = value.Replace(", ", ","); + } - if (value.Contains ('/')) { - value = value.Replace ('/', '+'); - } + if (value.Contains('/')) + { + value = value.Replace('/', '+'); + } - // Split it into . separated parts and if one is ending with > rewrite it to `1 format - // ILC folows the reflection format which doesn't actually use generic instantiations on anything but the last type - // in nested hierarchy - it's difficult to replicate this with Cecil as it has different representation so just strip that info - var parts = value.Split ('.'); - StringBuilder sb = new StringBuilder (); - foreach (var part in parts) { - if (sb.Length > 0) - sb.Append ('.'); + // Split it into . separated parts and if one is ending with > rewrite it to `1 format + // ILC folows the reflection format which doesn't actually use generic instantiations on anything but the last type + // in nested hierarchy - it's difficult to replicate this with Cecil as it has different representation so just strip that info + var parts = value.Split('.'); + StringBuilder sb = new StringBuilder(); + foreach (var part in parts) + { + if (sb.Length > 0) + sb.Append('.'); - if (part.EndsWith ('>')) { - int i = part.LastIndexOf ('<'); - if (i >= 0) { - sb.Append (part.AsSpan (0, i)); - sb.Append ('`'); - sb.Append (part.Substring (i + 1).Where (c => c == ',').Count () + 1); - continue; - } - } + if (part.EndsWith('>')) + { + int i = part.LastIndexOf('<'); + if (i >= 0) + { + sb.Append(part.AsSpan(0, i)); + sb.Append('`'); + sb.Append(part.Substring(i + 1).Where(c => c == ',').Count() + 1); + continue; + } + } - sb.Append (part); - } + sb.Append(part); + } - return sb.ToString (); - } - } + return sb.ToString(); + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ResultChecker.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ResultChecker.cs index a6eb6007661f62..06411420c5fddd 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ResultChecker.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ResultChecker.cs @@ -18,485 +18,534 @@ namespace Mono.Linker.Tests.TestCasesRunner { - public class ResultChecker - { - private readonly BaseAssemblyResolver _originalsResolver; - private readonly ReaderParameters _originalReaderParameters; - private readonly ReaderParameters _linkedReaderParameters; - - public ResultChecker () - : this (new TestCaseAssemblyResolver (), - new ReaderParameters { - SymbolReaderProvider = new DefaultSymbolReaderProvider (false) - }, - new ReaderParameters { - SymbolReaderProvider = new DefaultSymbolReaderProvider (false) - }) - { - } - - public ResultChecker (BaseAssemblyResolver originalsResolver, - ReaderParameters originalReaderParameters, ReaderParameters linkedReaderParameters) - { - _originalsResolver = originalsResolver; - _originalReaderParameters = originalReaderParameters; - _linkedReaderParameters = linkedReaderParameters; - } - - public virtual void Check (TrimmedTestCaseResult testResult) - { - InitializeResolvers (testResult); - - try { - var original = ResolveOriginalsAssembly (testResult.ExpectationsAssemblyPath.FileNameWithoutExtension); - - if (!HasAttribute (original, nameof (NoLinkedOutputAttribute))) { - // TODO Validate presence of the main assembly - if it makes sense (reflection only somehow) - - // IL verification is impossible for NativeAOT since there's no IL output - // if (ShouldValidateIL (original)) - // VerifyIL (); - - InitialChecking (testResult, original); - - PerformOutputAssemblyChecks (original, testResult); - PerformOutputSymbolChecks (original, testResult); - - if (!HasActiveSkipKeptItemsValidationAttribute (testResult.TestCase.FindTypeDefinition (original))) { - CreateAssemblyChecker (original, testResult).Verify (); - } - } - - AdditionalChecking (testResult, original); - } finally { - _originalsResolver.Dispose (); - } - - bool HasActiveSkipKeptItemsValidationAttribute(ICustomAttributeProvider provider) - { - if (TryGetCustomAttribute(provider, nameof(SkipKeptItemsValidationAttribute), out var attribute)) { - object? by = attribute.GetPropertyValue (nameof (SkipKeptItemsValidationAttribute.By)); - return by is null ? true : ((Tool) by).HasFlag (Tool.NativeAot); - } - - return false; - } - } - - protected virtual AssemblyChecker CreateAssemblyChecker (AssemblyDefinition original, TrimmedTestCaseResult testResult) - { - return new AssemblyChecker (_originalsResolver, _originalReaderParameters, original, testResult); - } - - private void InitializeResolvers (TrimmedTestCaseResult linkedResult) - { - _originalsResolver.AddSearchDirectory (linkedResult.ExpectationsAssemblyPath.Parent.ToString ()); - } - - protected AssemblyDefinition ResolveOriginalsAssembly (string assemblyName) - { - var cleanAssemblyName = assemblyName; - if (assemblyName.EndsWith (".exe") || assemblyName.EndsWith (".dll")) - cleanAssemblyName = Path.GetFileNameWithoutExtension (assemblyName); - return _originalsResolver.Resolve (new AssemblyNameReference (cleanAssemblyName, null), _originalReaderParameters); - } - - private static void PerformOutputAssemblyChecks (AssemblyDefinition original, TrimmedTestCaseResult testResult) - { - var assembliesToCheck = original.MainModule.Types.SelectMany (t => t.CustomAttributes).Where (ExpectationsProvider.IsAssemblyAssertion); - var actionAssemblies = new HashSet (); - //bool trimModeIsCopy = false; - - foreach (var assemblyAttr in assembliesToCheck) { - var name = (string) assemblyAttr.ConstructorArguments.First ().Value; - name = Path.GetFileNameWithoutExtension (name); + public class ResultChecker + { + private readonly BaseAssemblyResolver _originalsResolver; + private readonly ReaderParameters _originalReaderParameters; + private readonly ReaderParameters _linkedReaderParameters; + + public ResultChecker() + : this(new TestCaseAssemblyResolver(), + new ReaderParameters + { + SymbolReaderProvider = new DefaultSymbolReaderProvider(false) + }, + new ReaderParameters + { + SymbolReaderProvider = new DefaultSymbolReaderProvider(false) + }) + { + } + + public ResultChecker(BaseAssemblyResolver originalsResolver, + ReaderParameters originalReaderParameters, ReaderParameters linkedReaderParameters) + { + _originalsResolver = originalsResolver; + _originalReaderParameters = originalReaderParameters; + _linkedReaderParameters = linkedReaderParameters; + } + + public virtual void Check(TrimmedTestCaseResult testResult) + { + InitializeResolvers(testResult); + + try + { + var original = ResolveOriginalsAssembly(testResult.ExpectationsAssemblyPath.FileNameWithoutExtension); + + if (!HasAttribute(original, nameof(NoLinkedOutputAttribute))) + { + // TODO Validate presence of the main assembly - if it makes sense (reflection only somehow) + + // IL verification is impossible for NativeAOT since there's no IL output + // if (ShouldValidateIL (original)) + // VerifyIL (); + + InitialChecking(testResult, original); + + PerformOutputAssemblyChecks(original, testResult); + PerformOutputSymbolChecks(original, testResult); + + if (!HasActiveSkipKeptItemsValidationAttribute(testResult.TestCase.FindTypeDefinition(original))) + { + CreateAssemblyChecker(original, testResult).Verify(); + } + } + + AdditionalChecking(testResult, original); + } + finally + { + _originalsResolver.Dispose(); + } + + bool HasActiveSkipKeptItemsValidationAttribute(ICustomAttributeProvider provider) + { + if (TryGetCustomAttribute(provider, nameof(SkipKeptItemsValidationAttribute), out var attribute)) + { + object? by = attribute.GetPropertyValue(nameof(SkipKeptItemsValidationAttribute.By)); + return by is null ? true : ((Tool)by).HasFlag(Tool.NativeAot); + } + + return false; + } + } + + protected virtual AssemblyChecker CreateAssemblyChecker(AssemblyDefinition original, TrimmedTestCaseResult testResult) + { + return new AssemblyChecker(_originalsResolver, _originalReaderParameters, original, testResult); + } + + private void InitializeResolvers(TrimmedTestCaseResult linkedResult) + { + _originalsResolver.AddSearchDirectory(linkedResult.ExpectationsAssemblyPath.Parent.ToString()); + } + + protected AssemblyDefinition ResolveOriginalsAssembly(string assemblyName) + { + var cleanAssemblyName = assemblyName; + if (assemblyName.EndsWith(".exe") || assemblyName.EndsWith(".dll")) + cleanAssemblyName = Path.GetFileNameWithoutExtension(assemblyName); + return _originalsResolver.Resolve(new AssemblyNameReference(cleanAssemblyName, null), _originalReaderParameters); + } + + private static void PerformOutputAssemblyChecks(AssemblyDefinition original, TrimmedTestCaseResult testResult) + { + var assembliesToCheck = original.MainModule.Types.SelectMany(t => t.CustomAttributes).Where(ExpectationsProvider.IsAssemblyAssertion); + var actionAssemblies = new HashSet(); + //bool trimModeIsCopy = false; + + foreach (var assemblyAttr in assembliesToCheck) + { + var name = (string)assemblyAttr.ConstructorArguments.First().Value; + name = Path.GetFileNameWithoutExtension(name); #if false - if (assemblyAttr.AttributeType.Name == nameof (RemovedAssemblyAttribute)) - Assert.IsFalse (expectedPath.FileExists (), $"Expected the assembly {name} to not exist in {outputDirectory}, but it did"); - else if (assemblyAttr.AttributeType.Name == nameof (KeptAssemblyAttribute)) - Assert.IsTrue (expectedPath.FileExists (), $"Expected the assembly {name} to exist in {outputDirectory}, but it did not"); - else if (assemblyAttr.AttributeType.Name == nameof (SetupLinkerActionAttribute)) { - string assemblyName = (string) assemblyAttr.ConstructorArguments[1].Value; - if ((string) assemblyAttr.ConstructorArguments[0].Value == "copy") { - VerifyCopyAssemblyIsKeptUnmodified (outputDirectory, assemblyName + (assemblyName == "test" ? ".exe" : ".dll")); - } - - actionAssemblies.Add (assemblyName); - } else if (assemblyAttr.AttributeType.Name == nameof (SetupLinkerTrimModeAttribute)) { - // We delay checking that everything was copied after processing all assemblies - // with a specific action, since assembly action wins over trim mode. - if ((string) assemblyAttr.ConstructorArguments[0].Value == "copy") - trimModeIsCopy = true; - } else - throw new NotImplementedException ($"Unknown assembly assertion of type {assemblyAttr.AttributeType}"); + if (assemblyAttr.AttributeType.Name == nameof (RemovedAssemblyAttribute)) + Assert.IsFalse (expectedPath.FileExists (), $"Expected the assembly {name} to not exist in {outputDirectory}, but it did"); + else if (assemblyAttr.AttributeType.Name == nameof (KeptAssemblyAttribute)) + Assert.IsTrue (expectedPath.FileExists (), $"Expected the assembly {name} to exist in {outputDirectory}, but it did not"); + else if (assemblyAttr.AttributeType.Name == nameof (SetupLinkerActionAttribute)) { + string assemblyName = (string) assemblyAttr.ConstructorArguments[1].Value; + if ((string) assemblyAttr.ConstructorArguments[0].Value == "copy") { + VerifyCopyAssemblyIsKeptUnmodified (outputDirectory, assemblyName + (assemblyName == "test" ? ".exe" : ".dll")); + } + + actionAssemblies.Add (assemblyName); + } else if (assemblyAttr.AttributeType.Name == nameof (SetupLinkerTrimModeAttribute)) { + // We delay checking that everything was copied after processing all assemblies + // with a specific action, since assembly action wins over trim mode. + if ((string) assemblyAttr.ConstructorArguments[0].Value == "copy") + trimModeIsCopy = true; + } else + throw new NotImplementedException ($"Unknown assembly assertion of type {assemblyAttr.AttributeType}"); #endif - } + } #if false - if (trimModeIsCopy) { - foreach (string assemblyName in Directory.GetFiles (Directory.GetParent (outputDirectory).ToString (), "input")) { - var fileInfo = new FileInfo (assemblyName); - if (fileInfo.Extension == ".dll" && !actionAssemblies.Contains (assemblyName)) - VerifyCopyAssemblyIsKeptUnmodified (outputDirectory, assemblyName + (assemblyName == "test" ? ".exe" : ".dll")); - } - } + if (trimModeIsCopy) { + foreach (string assemblyName in Directory.GetFiles (Directory.GetParent (outputDirectory).ToString (), "input")) { + var fileInfo = new FileInfo (assemblyName); + if (fileInfo.Extension == ".dll" && !actionAssemblies.Contains (assemblyName)) + VerifyCopyAssemblyIsKeptUnmodified (outputDirectory, assemblyName + (assemblyName == "test" ? ".exe" : ".dll")); + } + } #endif - } + } #pragma warning disable IDE0060 // Remove unused parameter - private static void PerformOutputSymbolChecks (AssemblyDefinition original, TrimmedTestCaseResult testResult) + private static void PerformOutputSymbolChecks(AssemblyDefinition original, TrimmedTestCaseResult testResult) #pragma warning restore IDE0060 // Remove unused parameter - { - // While NativeAOT has symbols, verifying them is rather difficult - } - - protected virtual void AdditionalChecking (TrimmedTestCaseResult linkResult, AssemblyDefinition original) - { - bool checkRemainingErrors = !HasAttribute (linkResult.TestCase.FindTypeDefinition (original), nameof (SkipRemainingErrorsValidationAttribute)); - VerifyLoggedMessages (original, linkResult.Logger, checkRemainingErrors); - } - - private static bool IsProducedByNativeAOT (CustomAttribute attr) - { - if (attr.ConstructorArguments.Count > 2 && attr.ConstructorArguments[^2].Type.Name == "Tool") - return ((Tool)attr.ConstructorArguments[^2].Value).HasFlag(Tool.NativeAot); - var producedBy = attr.GetPropertyValue ("ProducedBy"); - return producedBy is null ? true : ((Tool) producedBy).HasFlag (Tool.NativeAot); - } - - private static IEnumerable GetAttributeProviders (AssemblyDefinition assembly) - { - foreach (var testType in assembly.AllDefinedTypes ()) { - foreach (var provider in testType.AllMembers ()) - yield return provider; - - yield return testType; - } - - foreach (var module in assembly.Modules) - yield return module; - - yield return assembly; - } - - protected virtual void InitialChecking (TrimmedTestCaseResult testResult, AssemblyDefinition original) - { - // PE verifier is done here in ILLinker, but that's not possible with NativeAOT - } - - private void VerifyLoggedMessages (AssemblyDefinition original, TrimmingTestLogger logger, bool checkRemainingErrors) - { - List loggedMessages = logger.GetLoggedMessages (); - List<(ICustomAttributeProvider, CustomAttribute)> expectedNoWarningsAttributes = new (); - foreach (var attrProvider in GetAttributeProviders (original)) { - foreach (var attr in attrProvider.CustomAttributes) { - if (!IsProducedByNativeAOT (attr)) - continue; - - switch (attr.AttributeType.Name) { - - case nameof (LogContainsAttribute): { - var expectedMessage = (string) attr.ConstructorArguments[0].Value; - - List matchedMessages; - if ((bool) attr.ConstructorArguments[1].Value) - matchedMessages = loggedMessages.Where (m => Regex.IsMatch (m.ToString (), expectedMessage)).ToList (); - else - matchedMessages = loggedMessages.Where (m => MessageTextContains (m.ToString (), expectedMessage)).ToList (); - Assert.True ( - matchedMessages.Count > 0, - $"Expected to find logged message matching `{expectedMessage}`, but no such message was found.{Environment.NewLine}Logged messages:{Environment.NewLine}{string.Join (Environment.NewLine, loggedMessages)}"); - - foreach (var matchedMessage in matchedMessages) - loggedMessages.Remove (matchedMessage); - } - break; - - case nameof (LogDoesNotContainAttribute): { - var unexpectedMessage = (string) attr.ConstructorArguments[0].Value; - foreach (var loggedMessage in loggedMessages) { - var isLogged = () => { - if ((bool) attr.ConstructorArguments[1].Value) - return !Regex.IsMatch (loggedMessage.ToString (), unexpectedMessage); - return !MessageTextContains (loggedMessage.ToString (), unexpectedMessage); - }; - - Assert.True ( - isLogged (), - $"Expected to not find logged message matching `{unexpectedMessage}`, but found:{Environment.NewLine}{loggedMessage}{Environment.NewLine}Logged messages:{Environment.NewLine}{string.Join (Environment.NewLine, loggedMessages)}"); - } - } - break; - - case nameof (ExpectedWarningAttribute) or nameof(UnexpectedWarningAttribute): { - var expectedWarningCode = (string) attr.GetConstructorArgumentValue (0); - if (!expectedWarningCode.StartsWith ("IL")) { - Assert.Fail ($"The warning code specified in {attr.AttributeType.Name} must start with the 'IL' prefix. Specified value: '{expectedWarningCode}'."); - } - IEnumerable expectedMessageContains = attr.Constructor.Parameters switch - { - // ExpectedWarningAttribute(string warningCode, params string[] expectedMessages) - // ExpectedWarningAttribute(string warningCode, string[] expectedMessages, Tool producedBy, string issueLink) - [_, { ParameterType.IsArray: true }, ..] - => ((CustomAttributeArgument[])attr.ConstructorArguments[1].Value) - .Select(caa => (string)caa.Value), - // ExpectedWarningAttribute(string warningCode, string expectedMessage1, string expectedMessage2, Tool producedBy, string issueLink) - [_, { ParameterType.Name: "String" }, { ParameterType.Name: "String" }, { ParameterType.Name: "Tool" }, _] - => [(string)attr.GetConstructorArgumentValue(1), (string)attr.GetConstructorArgumentValue(2)], - // ExpectedWarningAttribute(string warningCode, string expectedMessage, Tool producedBy, string issueLink) - [_, { ParameterType.Name: "String" }, { ParameterType.Name: "Tool" }, _] - => [(string)attr.GetConstructorArgumentValue(1)], - // ExpectedWarningAttribute(string warningCode, Tool producedBy, string issueLink) - [_, { ParameterType.Name: "Tool" }, _] - => [], - _ => throw new UnreachableException(), - }; - string fileName = (string) attr.GetPropertyValue ("FileName")!; - int? sourceLine = (int?) attr.GetPropertyValue ("SourceLine"); - int? sourceColumn = (int?) attr.GetPropertyValue ("SourceColumn"); - bool? isCompilerGeneratedCode = (bool?) attr.GetPropertyValue ("CompilerGeneratedCode"); - - int expectedWarningCodeNumber = int.Parse (expectedWarningCode.Substring (2)); - string? expectedOrigin = null; - bool expectedWarningFound = false; - - foreach (var loggedMessage in loggedMessages) { - if (loggedMessage.Category != MessageCategory.Warning || loggedMessage.Code != expectedWarningCodeNumber) - continue; - - bool messageNotFound = false; - foreach (var expectedMessage in expectedMessageContains) { - if (!MessageTextContains (loggedMessage.Text, expectedMessage)) { - messageNotFound = true; - break; - } - } - if (messageNotFound) - continue; - - if (fileName != null) { - if (loggedMessage.Origin == null) - continue; - - var actualOrigin = loggedMessage.Origin.Value; - if (actualOrigin.FileName != null) { - // Note: string.Compare(string, StringComparison) doesn't exist in .NET Framework API set - if (actualOrigin.FileName.IndexOf (fileName, StringComparison.OrdinalIgnoreCase) < 0) - continue; - - if (sourceLine != null && loggedMessage.Origin?.SourceLine != sourceLine.Value) - continue; - - if (sourceColumn != null && loggedMessage.Origin?.SourceColumn != sourceColumn.Value) - continue; - } else { - // The warning was logged with member/ILoffset, so it didn't have line/column info filled - // but it will be computed from PDBs, so instead compare it in a string representation - if (expectedOrigin == null) { - expectedOrigin = fileName; - if (sourceLine.HasValue) { - expectedOrigin += "(" + sourceLine.Value; - if (sourceColumn.HasValue) - expectedOrigin += "," + sourceColumn.Value; - expectedOrigin += ")"; - } - } - - string actualOriginString = actualOrigin.ToString () ?? ""; - if (!actualOriginString.EndsWith (expectedOrigin, StringComparison.OrdinalIgnoreCase)) - continue; - } - } else if (isCompilerGeneratedCode == true) { - if (loggedMessage.Origin?.MemberDefinition is not MethodDesc methodDesc) - continue; - - if (attrProvider is IMemberDefinition expectedMember) { - string? actualName = NameUtils.GetActualOriginDisplayName (methodDesc); - string expectedTypeName = NameUtils.GetExpectedOriginDisplayName (expectedMember.DeclaringType); - if (actualName?.Contains (expectedTypeName) == true && - actualName?.Contains ("<" + expectedMember.Name + ">") == true) { - expectedWarningFound = true; - loggedMessages.Remove (loggedMessage); - break; - } - if (actualName?.StartsWith (expectedTypeName) == true) { - if (actualName?.Contains (".cctor") == true && - (expectedMember is FieldDefinition || expectedMember is PropertyDefinition)) { - expectedWarningFound = true; - loggedMessages.Remove (loggedMessage); - break; - } - if (methodDesc.IsConstructor && - (expectedMember is FieldDefinition || expectedMember is PropertyDefinition || new AssemblyQualifiedToken (methodDesc.OwningType).Equals(new AssemblyQualifiedToken (expectedMember)))) { - expectedWarningFound = true; - loggedMessages.Remove (loggedMessage); - break; - } - } - } else if (attrProvider is AssemblyDefinition expectedAssembly) { - // Allow assembly-level attributes to match warnings from compiler-generated Main - if (NameUtils.GetActualOriginDisplayName (methodDesc) == "Program.
$(String[])") { - expectedWarningFound = true; - loggedMessages.Remove (loggedMessage); - break; - } - } - continue; - } else { - if (LogMessageHasSameOriginMember (loggedMessage, attrProvider)) { - expectedWarningFound = true; - loggedMessages.Remove (loggedMessage); - break; - } - continue; - } - - expectedWarningFound = true; - loggedMessages.Remove (loggedMessage); - break; - } - - var expectedOriginString = fileName == null - ? NameUtils.GetExpectedOriginDisplayName (attrProvider) + ": " - : ""; - - Assert.True (expectedWarningFound, - $"Expected to find warning: {(fileName != null ? fileName + (sourceLine != null ? $"({sourceLine},{sourceColumn})" : "") + ": " : "")}" + - $"warning {expectedWarningCode}: {expectedOriginString}" + - $"and message containing {string.Join (" ", expectedMessageContains.Select (m => "'" + m + "'"))}, " + - $"but no such message was found.{Environment.NewLine}Logged messages:{Environment.NewLine}{string.Join (Environment.NewLine, loggedMessages)}"); - } - break; - - case nameof (ExpectedNoWarningsAttribute): - // Postpone processing of negative checks, to make it possible to mark some warnings as expected (will be removed from the list above) - // and then do the negative check on the rest. - expectedNoWarningsAttributes.Add ((attrProvider, attr)); - break; - } - } - } - - foreach ((var attrProvider, var attr) in expectedNoWarningsAttributes) { - var unexpectedWarningCode = attr.ConstructorArguments.Count == 0 ? null : (string) attr.GetConstructorArgumentValue (0); - if (unexpectedWarningCode != null && !unexpectedWarningCode.StartsWith ("IL")) { - Assert.Fail ($"The warning code specified in ExpectedNoWarnings attribute must start with the 'IL' prefix. Specified value: '{unexpectedWarningCode}'."); - } - - int? unexpectedWarningCodeNumber = unexpectedWarningCode == null ? null : int.Parse (unexpectedWarningCode.Substring (2)); - - MessageContainer? unexpectedWarningMessage = null; - foreach (var mc in logger.GetLoggedMessages ()) { - if (mc.Category != MessageCategory.Warning) - continue; - - if (unexpectedWarningCodeNumber != null && unexpectedWarningCodeNumber.Value != mc.Code) - continue; - - // This is a hacky way to say anything in the "subtree" of the attrProvider - if (attrProvider is IMemberDefinition attrMember && (mc.Origin?.MemberDefinition is TypeSystemEntity member) && member.ToString ()?.Contains (attrMember.FullName) != true) - continue; - - unexpectedWarningMessage = mc; - break; - } - - Assert.False (unexpectedWarningMessage.HasValue, - $"Unexpected warning found: {unexpectedWarningMessage}"); - } - - if (checkRemainingErrors) { - var remainingErrors = loggedMessages.Where (m => Regex.IsMatch (m.ToString (), @".*(error | warning): \d{4}.*")); - Assert.False (remainingErrors.Any (), $"Found unexpected errors:{Environment.NewLine}{string.Join (Environment.NewLine, remainingErrors)}"); - } - - static bool LogMessageHasSameOriginMember (MessageContainer mc, ICustomAttributeProvider expectedOriginProvider) - { - var origin = mc.Origin; - Debug.Assert (origin != null); - if (origin?.MemberDefinition == null) - return false; - if (origin?.MemberDefinition is IAssemblyDesc asm) - return expectedOriginProvider is AssemblyDefinition expectedAsm && asm.GetName().Name == expectedAsm.Name.Name; - - if (expectedOriginProvider is not IMemberDefinition expectedOriginMember) - return false; - - var actualOriginToken = new AssemblyQualifiedToken (origin!.Value.MemberDefinition); - var expectedOriginToken = new AssemblyQualifiedToken (expectedOriginMember); - if (actualOriginToken.Equals (expectedOriginToken)) - return true; - - var actualMember = origin.Value.MemberDefinition; - // Compensate for cases where for some reason the OM doesn't preserve the declaring types - // on certain things after trimming. - if (actualMember != null && GetOwningType (actualMember) == null && - GetMemberName (actualMember) == (expectedOriginProvider as IMemberDefinition)?.Name) - return true; - - return false; - } - - static TypeDesc? GetOwningType (TypeSystemEntity entity) => entity switch { - DefType defType => defType.ContainingType, - MethodDesc method => method.OwningType, - FieldDesc field => field.OwningType, - _ => null - }; - - static string? GetMemberName (TypeSystemEntity? entity) => entity switch { - DefType defType => defType.Name, - MethodDesc method => method.Name, - FieldDesc field => field.Name, - _ => null - }; - - static bool MessageTextContains (string message, string value) - { - // This is a workaround for different formatting of methods between ilc and illink/analyzer - // Sometimes they're written with a space after comma and sometimes without - // Method(String,String) - ilc - // Method(String, String) - illink/analyzer - return message.Contains (value) || message.Contains (NameUtils.ConvertSignatureToIlcFormat (value)); - } - } - - private static bool HasAttribute (ICustomAttributeProvider caProvider, string attributeName) - { - return TryGetCustomAttribute (caProvider, attributeName, out var _); - } + { + // While NativeAOT has symbols, verifying them is rather difficult + } + + protected virtual void AdditionalChecking(TrimmedTestCaseResult linkResult, AssemblyDefinition original) + { + bool checkRemainingErrors = !HasAttribute(linkResult.TestCase.FindTypeDefinition(original), nameof(SkipRemainingErrorsValidationAttribute)); + VerifyLoggedMessages(original, linkResult.Logger, checkRemainingErrors); + } + + private static bool IsProducedByNativeAOT(CustomAttribute attr) + { + if (attr.ConstructorArguments.Count > 2 && attr.ConstructorArguments[^2].Type.Name == "Tool") + return ((Tool)attr.ConstructorArguments[^2].Value).HasFlag(Tool.NativeAot); + var producedBy = attr.GetPropertyValue("ProducedBy"); + return producedBy is null ? true : ((Tool)producedBy).HasFlag(Tool.NativeAot); + } + + private static IEnumerable GetAttributeProviders(AssemblyDefinition assembly) + { + foreach (var testType in assembly.AllDefinedTypes()) + { + foreach (var provider in testType.AllMembers()) + yield return provider; + + yield return testType; + } + + foreach (var module in assembly.Modules) + yield return module; + + yield return assembly; + } + + protected virtual void InitialChecking(TrimmedTestCaseResult testResult, AssemblyDefinition original) + { + // PE verifier is done here in ILLinker, but that's not possible with NativeAOT + } + + private void VerifyLoggedMessages(AssemblyDefinition original, TrimmingTestLogger logger, bool checkRemainingErrors) + { + List loggedMessages = logger.GetLoggedMessages(); + List<(ICustomAttributeProvider, CustomAttribute)> expectedNoWarningsAttributes = new(); + foreach (var attrProvider in GetAttributeProviders(original)) + { + foreach (var attr in attrProvider.CustomAttributes) + { + if (!IsProducedByNativeAOT(attr)) + continue; + + switch (attr.AttributeType.Name) + { + + case nameof(LogContainsAttribute): + { + var expectedMessage = (string)attr.ConstructorArguments[0].Value; + + List matchedMessages; + if ((bool)attr.ConstructorArguments[1].Value) + matchedMessages = loggedMessages.Where(m => Regex.IsMatch(m.ToString(), expectedMessage)).ToList(); + else + matchedMessages = loggedMessages.Where(m => MessageTextContains(m.ToString(), expectedMessage)).ToList(); + Assert.True( + matchedMessages.Count > 0, + $"Expected to find logged message matching `{expectedMessage}`, but no such message was found.{Environment.NewLine}Logged messages:{Environment.NewLine}{string.Join(Environment.NewLine, loggedMessages)}"); + + foreach (var matchedMessage in matchedMessages) + loggedMessages.Remove(matchedMessage); + } + break; + + case nameof(LogDoesNotContainAttribute): + { + var unexpectedMessage = (string)attr.ConstructorArguments[0].Value; + foreach (var loggedMessage in loggedMessages) + { + var isLogged = () => + { + if ((bool)attr.ConstructorArguments[1].Value) + return !Regex.IsMatch(loggedMessage.ToString(), unexpectedMessage); + return !MessageTextContains(loggedMessage.ToString(), unexpectedMessage); + }; + + Assert.True( + isLogged(), + $"Expected to not find logged message matching `{unexpectedMessage}`, but found:{Environment.NewLine}{loggedMessage}{Environment.NewLine}Logged messages:{Environment.NewLine}{string.Join(Environment.NewLine, loggedMessages)}"); + } + } + break; + + case nameof(ExpectedWarningAttribute) or nameof(UnexpectedWarningAttribute): + { + var expectedWarningCode = (string)attr.GetConstructorArgumentValue(0); + if (!expectedWarningCode.StartsWith("IL")) + { + Assert.Fail($"The warning code specified in {attr.AttributeType.Name} must start with the 'IL' prefix. Specified value: '{expectedWarningCode}'."); + } + IEnumerable expectedMessageContains = attr.Constructor.Parameters switch + { + // ExpectedWarningAttribute(string warningCode, params string[] expectedMessages) + // ExpectedWarningAttribute(string warningCode, string[] expectedMessages, Tool producedBy, string issueLink) + [_, { ParameterType.IsArray: true }, ..] + => ((CustomAttributeArgument[])attr.ConstructorArguments[1].Value) + .Select(caa => (string)caa.Value), + // ExpectedWarningAttribute(string warningCode, string expectedMessage1, string expectedMessage2, Tool producedBy, string issueLink) + [_, { ParameterType.Name: "String" }, { ParameterType.Name: "String" }, { ParameterType.Name: "Tool" }, _] + => [(string)attr.GetConstructorArgumentValue(1), (string)attr.GetConstructorArgumentValue(2)], + // ExpectedWarningAttribute(string warningCode, string expectedMessage, Tool producedBy, string issueLink) + [_, { ParameterType.Name: "String" }, { ParameterType.Name: "Tool" }, _] + => [(string)attr.GetConstructorArgumentValue(1)], + // ExpectedWarningAttribute(string warningCode, Tool producedBy, string issueLink) + [_, { ParameterType.Name: "Tool" }, _] + => [], + _ => throw new UnreachableException(), + }; + string fileName = (string)attr.GetPropertyValue("FileName")!; + int? sourceLine = (int?)attr.GetPropertyValue("SourceLine"); + int? sourceColumn = (int?)attr.GetPropertyValue("SourceColumn"); + bool? isCompilerGeneratedCode = (bool?)attr.GetPropertyValue("CompilerGeneratedCode"); + + int expectedWarningCodeNumber = int.Parse(expectedWarningCode.Substring(2)); + string? expectedOrigin = null; + bool expectedWarningFound = false; + + foreach (var loggedMessage in loggedMessages) + { + if (loggedMessage.Category != MessageCategory.Warning || loggedMessage.Code != expectedWarningCodeNumber) + continue; + + bool messageNotFound = false; + foreach (var expectedMessage in expectedMessageContains) + { + if (!MessageTextContains(loggedMessage.Text, expectedMessage)) + { + messageNotFound = true; + break; + } + } + if (messageNotFound) + continue; + + if (fileName != null) + { + if (loggedMessage.Origin == null) + continue; + + var actualOrigin = loggedMessage.Origin.Value; + if (actualOrigin.FileName != null) + { + // Note: string.Compare(string, StringComparison) doesn't exist in .NET Framework API set + if (actualOrigin.FileName.IndexOf(fileName, StringComparison.OrdinalIgnoreCase) < 0) + continue; + + if (sourceLine != null && loggedMessage.Origin?.SourceLine != sourceLine.Value) + continue; + + if (sourceColumn != null && loggedMessage.Origin?.SourceColumn != sourceColumn.Value) + continue; + } + else + { + // The warning was logged with member/ILoffset, so it didn't have line/column info filled + // but it will be computed from PDBs, so instead compare it in a string representation + if (expectedOrigin == null) + { + expectedOrigin = fileName; + if (sourceLine.HasValue) + { + expectedOrigin += "(" + sourceLine.Value; + if (sourceColumn.HasValue) + expectedOrigin += "," + sourceColumn.Value; + expectedOrigin += ")"; + } + } + + string actualOriginString = actualOrigin.ToString() ?? ""; + if (!actualOriginString.EndsWith(expectedOrigin, StringComparison.OrdinalIgnoreCase)) + continue; + } + } + else if (isCompilerGeneratedCode == true) + { + if (loggedMessage.Origin?.MemberDefinition is not MethodDesc methodDesc) + continue; + + if (attrProvider is IMemberDefinition expectedMember) + { + string? actualName = NameUtils.GetActualOriginDisplayName(methodDesc); + string expectedTypeName = NameUtils.GetExpectedOriginDisplayName(expectedMember.DeclaringType); + if (actualName?.Contains(expectedTypeName) == true && + actualName?.Contains("<" + expectedMember.Name + ">") == true) + { + expectedWarningFound = true; + loggedMessages.Remove(loggedMessage); + break; + } + if (actualName?.StartsWith(expectedTypeName) == true) + { + if (actualName?.Contains(".cctor") == true && + (expectedMember is FieldDefinition || expectedMember is PropertyDefinition)) + { + expectedWarningFound = true; + loggedMessages.Remove(loggedMessage); + break; + } + if (methodDesc.IsConstructor && + (expectedMember is FieldDefinition || expectedMember is PropertyDefinition || new AssemblyQualifiedToken(methodDesc.OwningType).Equals(new AssemblyQualifiedToken(expectedMember)))) + { + expectedWarningFound = true; + loggedMessages.Remove(loggedMessage); + break; + } + } + } + else if (attrProvider is AssemblyDefinition expectedAssembly) + { + // Allow assembly-level attributes to match warnings from compiler-generated Main + if (NameUtils.GetActualOriginDisplayName(methodDesc) == "Program.
$(String[])") + { + expectedWarningFound = true; + loggedMessages.Remove(loggedMessage); + break; + } + } + continue; + } + else + { + if (LogMessageHasSameOriginMember(loggedMessage, attrProvider)) + { + expectedWarningFound = true; + loggedMessages.Remove(loggedMessage); + break; + } + continue; + } + + expectedWarningFound = true; + loggedMessages.Remove(loggedMessage); + break; + } + + var expectedOriginString = fileName == null + ? NameUtils.GetExpectedOriginDisplayName(attrProvider) + ": " + : ""; + + Assert.True(expectedWarningFound, + $"Expected to find warning: {(fileName != null ? fileName + (sourceLine != null ? $"({sourceLine},{sourceColumn})" : "") + ": " : "")}" + + $"warning {expectedWarningCode}: {expectedOriginString}" + + $"and message containing {string.Join(" ", expectedMessageContains.Select(m => "'" + m + "'"))}, " + + $"but no such message was found.{Environment.NewLine}Logged messages:{Environment.NewLine}{string.Join(Environment.NewLine, loggedMessages)}"); + } + break; + + case nameof(ExpectedNoWarningsAttribute): + // Postpone processing of negative checks, to make it possible to mark some warnings as expected (will be removed from the list above) + // and then do the negative check on the rest. + expectedNoWarningsAttributes.Add((attrProvider, attr)); + break; + } + } + } + + foreach ((var attrProvider, var attr) in expectedNoWarningsAttributes) + { + var unexpectedWarningCode = attr.ConstructorArguments.Count == 0 ? null : (string)attr.GetConstructorArgumentValue(0); + if (unexpectedWarningCode != null && !unexpectedWarningCode.StartsWith("IL")) + { + Assert.Fail($"The warning code specified in ExpectedNoWarnings attribute must start with the 'IL' prefix. Specified value: '{unexpectedWarningCode}'."); + } + + int? unexpectedWarningCodeNumber = unexpectedWarningCode == null ? null : int.Parse(unexpectedWarningCode.Substring(2)); + + MessageContainer? unexpectedWarningMessage = null; + foreach (var mc in logger.GetLoggedMessages()) + { + if (mc.Category != MessageCategory.Warning) + continue; + + if (unexpectedWarningCodeNumber != null && unexpectedWarningCodeNumber.Value != mc.Code) + continue; + + // This is a hacky way to say anything in the "subtree" of the attrProvider + if (attrProvider is IMemberDefinition attrMember && (mc.Origin?.MemberDefinition is TypeSystemEntity member) && member.ToString()?.Contains(attrMember.FullName) != true) + continue; + + unexpectedWarningMessage = mc; + break; + } + + Assert.False(unexpectedWarningMessage.HasValue, + $"Unexpected warning found: {unexpectedWarningMessage}"); + } + + if (checkRemainingErrors) + { + var remainingErrors = loggedMessages.Where(m => Regex.IsMatch(m.ToString(), @".*(error | warning): \d{4}.*")); + Assert.False(remainingErrors.Any(), $"Found unexpected errors:{Environment.NewLine}{string.Join(Environment.NewLine, remainingErrors)}"); + } + + static bool LogMessageHasSameOriginMember(MessageContainer mc, ICustomAttributeProvider expectedOriginProvider) + { + var origin = mc.Origin; + Debug.Assert(origin != null); + if (origin?.MemberDefinition == null) + return false; + if (origin?.MemberDefinition is IAssemblyDesc asm) + return expectedOriginProvider is AssemblyDefinition expectedAsm && asm.GetName().Name == expectedAsm.Name.Name; + + if (expectedOriginProvider is not IMemberDefinition expectedOriginMember) + return false; + + var actualOriginToken = new AssemblyQualifiedToken(origin!.Value.MemberDefinition); + var expectedOriginToken = new AssemblyQualifiedToken(expectedOriginMember); + if (actualOriginToken.Equals(expectedOriginToken)) + return true; + + var actualMember = origin.Value.MemberDefinition; + // Compensate for cases where for some reason the OM doesn't preserve the declaring types + // on certain things after trimming. + if (actualMember != null && GetOwningType(actualMember) == null && + GetMemberName(actualMember) == (expectedOriginProvider as IMemberDefinition)?.Name) + return true; + + return false; + } + + static TypeDesc? GetOwningType(TypeSystemEntity entity) => entity switch + { + DefType defType => defType.ContainingType, + MethodDesc method => method.OwningType, + FieldDesc field => field.OwningType, + _ => null + }; + + static string? GetMemberName(TypeSystemEntity? entity) => entity switch + { + DefType defType => defType.Name, + MethodDesc method => method.Name, + FieldDesc field => field.Name, + _ => null + }; + + static bool MessageTextContains(string message, string value) + { + // This is a workaround for different formatting of methods between ilc and illink/analyzer + // Sometimes they're written with a space after comma and sometimes without + // Method(String,String) - ilc + // Method(String, String) - illink/analyzer + return message.Contains(value) || message.Contains(NameUtils.ConvertSignatureToIlcFormat(value)); + } + } + + private static bool HasAttribute(ICustomAttributeProvider caProvider, string attributeName) + { + return TryGetCustomAttribute(caProvider, attributeName, out var _); + } #nullable enable - private static bool TryGetCustomAttribute (ICustomAttributeProvider caProvider, string attributeName, [NotNullWhen (true)] out CustomAttribute? customAttribute) - { - if (caProvider is AssemblyDefinition assembly && assembly.EntryPoint != null) { - customAttribute = assembly.EntryPoint.DeclaringType.CustomAttributes - .FirstOrDefault (attr => attr!.AttributeType.Name == attributeName, null); - return customAttribute is not null; - } - - if (caProvider is TypeDefinition type) { - customAttribute = type.CustomAttributes - .FirstOrDefault (attr => attr!.AttributeType.Name == attributeName, null); - return customAttribute is not null; - } - customAttribute = null; - return false; - } - - private static IEnumerable GetCustomAttributes (ICustomAttributeProvider caProvider, string attributeName) - { - if (caProvider is AssemblyDefinition assembly && assembly.EntryPoint != null) - return assembly.EntryPoint.DeclaringType.CustomAttributes - .Where (attr => attr!.AttributeType.Name == attributeName); - - if (caProvider is TypeDefinition type) - return type.CustomAttributes - .Where (attr => attr!.AttributeType.Name == attributeName); - - return Enumerable.Empty (); - } + private static bool TryGetCustomAttribute(ICustomAttributeProvider caProvider, string attributeName, [NotNullWhen(true)] out CustomAttribute? customAttribute) + { + if (caProvider is AssemblyDefinition assembly && assembly.EntryPoint != null) + { + customAttribute = assembly.EntryPoint.DeclaringType.CustomAttributes + .FirstOrDefault(attr => attr!.AttributeType.Name == attributeName, null); + return customAttribute is not null; + } + + if (caProvider is TypeDefinition type) + { + customAttribute = type.CustomAttributes + .FirstOrDefault(attr => attr!.AttributeType.Name == attributeName, null); + return customAttribute is not null; + } + customAttribute = null; + return false; + } + + private static IEnumerable GetCustomAttributes(ICustomAttributeProvider caProvider, string attributeName) + { + if (caProvider is AssemblyDefinition assembly && assembly.EntryPoint != null) + return assembly.EntryPoint.DeclaringType.CustomAttributes + .Where(attr => attr!.AttributeType.Name == attributeName); + + if (caProvider is TypeDefinition type) + return type.CustomAttributes + .Where(attr => attr!.AttributeType.Name == attributeName); + + return Enumerable.Empty(); + } #nullable restore - } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCollector.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCollector.cs index 1a301af17577e8..42c7bf7a44a6c8 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCollector.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCollector.cs @@ -13,145 +13,155 @@ namespace Mono.Linker.Tests.TestCasesRunner { - public class TestCaseCollector - { - private readonly NPath _rootDirectory; - private readonly NPath _testCaseAssemblyRoot; - - public TestCaseCollector (string rootDirectory, string testCaseAssemblyPath) - : this (rootDirectory.ToNPath (), testCaseAssemblyPath.ToNPath ()) - { - } - - public TestCaseCollector (NPath rootDirectory, NPath testCaseAssemblyRoot) - { - _rootDirectory = rootDirectory; - _testCaseAssemblyRoot = testCaseAssemblyRoot; - } - - public IEnumerable Collect () - { - return Collect (AllSourceFiles ()); - } - - public TestCase? Collect (NPath sourceFile) - { - return Collect (new[] { sourceFile }).FirstOrDefault (); - } - - public IEnumerable Collect (IEnumerable sourceFiles) - { - _rootDirectory.DirectoryMustExist (); - _testCaseAssemblyRoot.DirectoryMustExist (); - - foreach (var file in sourceFiles) { - var testCaseAssemblyPath = FindTestCaseAssembly (file); - testCaseAssemblyPath.FileMustExist (); - if (CreateCase (testCaseAssemblyPath, file, out TestCase? testCase)) - yield return testCase; - } - } - - NPath FindTestCaseAssembly (NPath sourceFile) - { - if (!sourceFile.IsChildOf (_rootDirectory)) - throw new ArgumentException ($"{sourceFile} is not a child of {_rootDirectory}"); - - var current = sourceFile; - do { - if (current.Parent.Files ("*.csproj").FirstOrDefault () is NPath csproj) { - var relative = csproj.Parent.RelativeTo (_rootDirectory); - return _testCaseAssemblyRoot.Combine (relative).Combine (csproj.ChangeExtension ("dll").FileName); - } - - current = current.Parent; - } while (current != _rootDirectory); - - throw new InvalidOperationException ($"Could not find a .csproj file for {sourceFile}"); - } - - public IEnumerable AllSourceFiles () - { - _rootDirectory.DirectoryMustExist (); - - foreach (var file in _rootDirectory.Files ("*.cs")) { - yield return file; - } - - foreach (var subDir in _rootDirectory.Directories ()) { - if (subDir.FileName == "bin" || subDir.FileName == "obj" || subDir.FileName == "Properties") - continue; - - foreach (var file in subDir.Files ("*.cs", true)) { - - var relativeParents = file.RelativeTo (_rootDirectory); - // Magic : Anything in a directory named Dependencies is assumed to be a dependency to a test case - // and never a test itself - // This makes life a little easier when writing these supporting files as it removes some constraints you would previously have - // had to follow such as ensuring a class exists that matches the file name and putting [NotATestCase] on that class - if (relativeParents.RecursiveParents.Any (p => p.Elements.Any () && p.FileName == "Dependencies")) - continue; - - // Magic: Anything in a directory named Individual is expected to be ran by it's own [Test] rather than as part of [TestCaseSource] - if (relativeParents.RecursiveParents.Any (p => p.Elements.Any () && p.FileName == "Individual")) - continue; - - yield return file; - } - } - } - - public TestCase? CreateIndividualCase (Type testCaseType) - { - _rootDirectory.DirectoryMustExist (); - _testCaseAssemblyRoot.FileMustExist (); - - var pathRelativeToAssembly = $"{testCaseType.FullName?.Substring (testCaseType.Module.Name.Length - 3).Replace ('.', '/')}.cs"; - var fullSourcePath = _rootDirectory.Combine (pathRelativeToAssembly).FileMustExist (); - var testCaseAssemblyPath = FindTestCaseAssembly (fullSourcePath); - - if (!CreateCase (testCaseAssemblyPath, fullSourcePath, out TestCase? testCase)) - throw new ArgumentException ($"Could not create a test case for `{testCaseType}`. Ensure the namespace matches it's location on disk"); - - return testCase; - } - - private bool CreateCase (NPath caseAssemblyPath, NPath sourceFile, [NotNullWhen (true)] out TestCase? testCase) - { - using AssemblyDefinition caseAssemblyDefinition = AssemblyDefinition.ReadAssembly (caseAssemblyPath.ToString ()); - - var potentialCase = new TestCase (sourceFile, _rootDirectory, caseAssemblyPath); - var typeDefinition = potentialCase.TryFindTypeDefinition (caseAssemblyDefinition); - - testCase = null; - - if (typeDefinition == null) { - Console.WriteLine ($"Could not find the matching type for test case {sourceFile}. Ensure the file name and class name match"); - return false; - } - - if (typeDefinition.HasAttribute (nameof (NotATestCaseAttribute))) { - return false; - } - - // Verify the class as a static main method - var mainMethod = typeDefinition.Methods.FirstOrDefault (m => m.Name == - (typeDefinition.FullName == "Program" - ? "
$" // Compiler-generated Main for top-level statements - : "Main")); - - if (mainMethod == null) { - Console.WriteLine ($"{typeDefinition} in {sourceFile} is missing a Main() method"); - return false; - } - - if (!mainMethod.IsStatic) { - Console.WriteLine ($"The Main() method for {typeDefinition} in {sourceFile} should be static"); - return false; - } - - testCase = potentialCase; - return true; - } - } + public class TestCaseCollector + { + private readonly NPath _rootDirectory; + private readonly NPath _testCaseAssemblyRoot; + + public TestCaseCollector(string rootDirectory, string testCaseAssemblyPath) + : this(rootDirectory.ToNPath(), testCaseAssemblyPath.ToNPath()) + { + } + + public TestCaseCollector(NPath rootDirectory, NPath testCaseAssemblyRoot) + { + _rootDirectory = rootDirectory; + _testCaseAssemblyRoot = testCaseAssemblyRoot; + } + + public IEnumerable Collect() + { + return Collect(AllSourceFiles()); + } + + public TestCase? Collect(NPath sourceFile) + { + return Collect(new[] { sourceFile }).FirstOrDefault(); + } + + public IEnumerable Collect(IEnumerable sourceFiles) + { + _rootDirectory.DirectoryMustExist(); + _testCaseAssemblyRoot.DirectoryMustExist(); + + foreach (var file in sourceFiles) + { + var testCaseAssemblyPath = FindTestCaseAssembly(file); + testCaseAssemblyPath.FileMustExist(); + if (CreateCase(testCaseAssemblyPath, file, out TestCase? testCase)) + yield return testCase; + } + } + + NPath FindTestCaseAssembly(NPath sourceFile) + { + if (!sourceFile.IsChildOf(_rootDirectory)) + throw new ArgumentException($"{sourceFile} is not a child of {_rootDirectory}"); + + var current = sourceFile; + do + { + if (current.Parent.Files("*.csproj").FirstOrDefault() is NPath csproj) + { + var relative = csproj.Parent.RelativeTo(_rootDirectory); + return _testCaseAssemblyRoot.Combine(relative).Combine(csproj.ChangeExtension("dll").FileName); + } + + current = current.Parent; + } while (current != _rootDirectory); + + throw new InvalidOperationException($"Could not find a .csproj file for {sourceFile}"); + } + + public IEnumerable AllSourceFiles() + { + _rootDirectory.DirectoryMustExist(); + + foreach (var file in _rootDirectory.Files("*.cs")) + { + yield return file; + } + + foreach (var subDir in _rootDirectory.Directories()) + { + if (subDir.FileName == "bin" || subDir.FileName == "obj" || subDir.FileName == "Properties") + continue; + + foreach (var file in subDir.Files("*.cs", true)) + { + + var relativeParents = file.RelativeTo(_rootDirectory); + // Magic : Anything in a directory named Dependencies is assumed to be a dependency to a test case + // and never a test itself + // This makes life a little easier when writing these supporting files as it removes some constraints you would previously have + // had to follow such as ensuring a class exists that matches the file name and putting [NotATestCase] on that class + if (relativeParents.RecursiveParents.Any(p => p.Elements.Any() && p.FileName == "Dependencies")) + continue; + + // Magic: Anything in a directory named Individual is expected to be ran by it's own [Test] rather than as part of [TestCaseSource] + if (relativeParents.RecursiveParents.Any(p => p.Elements.Any() && p.FileName == "Individual")) + continue; + + yield return file; + } + } + } + + public TestCase? CreateIndividualCase(Type testCaseType) + { + _rootDirectory.DirectoryMustExist(); + _testCaseAssemblyRoot.FileMustExist(); + + var pathRelativeToAssembly = $"{testCaseType.FullName?.Substring(testCaseType.Module.Name.Length - 3).Replace('.', '/')}.cs"; + var fullSourcePath = _rootDirectory.Combine(pathRelativeToAssembly).FileMustExist(); + var testCaseAssemblyPath = FindTestCaseAssembly(fullSourcePath); + + if (!CreateCase(testCaseAssemblyPath, fullSourcePath, out TestCase? testCase)) + throw new ArgumentException($"Could not create a test case for `{testCaseType}`. Ensure the namespace matches it's location on disk"); + + return testCase; + } + + private bool CreateCase(NPath caseAssemblyPath, NPath sourceFile, [NotNullWhen(true)] out TestCase? testCase) + { + using AssemblyDefinition caseAssemblyDefinition = AssemblyDefinition.ReadAssembly(caseAssemblyPath.ToString()); + + var potentialCase = new TestCase(sourceFile, _rootDirectory, caseAssemblyPath); + var typeDefinition = potentialCase.TryFindTypeDefinition(caseAssemblyDefinition); + + testCase = null; + + if (typeDefinition == null) + { + Console.WriteLine($"Could not find the matching type for test case {sourceFile}. Ensure the file name and class name match"); + return false; + } + + if (typeDefinition.HasAttribute(nameof(NotATestCaseAttribute))) + { + return false; + } + + // Verify the class as a static main method + var mainMethod = typeDefinition.Methods.FirstOrDefault(m => m.Name == + (typeDefinition.FullName == "Program" + ? "
$" // Compiler-generated Main for top-level statements + : "Main")); + + if (mainMethod == null) + { + Console.WriteLine($"{typeDefinition} in {sourceFile} is missing a Main() method"); + return false; + } + + if (!mainMethod.IsStatic) + { + Console.WriteLine($"The Main() method for {typeDefinition} in {sourceFile} should be static"); + return false; + } + + testCase = potentialCase; + return true; + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCompilationMetadataProvider.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCompilationMetadataProvider.cs index 825663ac8bdae1..4dbdaf53bd47b0 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCompilationMetadataProvider.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCompilationMetadataProvider.cs @@ -14,237 +14,265 @@ namespace Mono.Linker.Tests.TestCasesRunner { - public class TestCaseCompilationMetadataProvider : BaseMetadataProvider - { - - public TestCaseCompilationMetadataProvider (TestCase testCase, AssemblyDefinition fullTestCaseAssemblyDefinition) - : base (testCase, fullTestCaseAssemblyDefinition) - { - - } - - public virtual TestRunCharacteristics Characteristics => - TestRunCharacteristics.TargetingNetCore | TestRunCharacteristics.SupportsDefaultInterfaceMethods | TestRunCharacteristics.SupportsStaticInterfaceMethods; - - private static bool IsIgnoredByNativeAOT (CustomAttribute attr) - { - var ignoredBy = attr.GetPropertyValue ("IgnoredBy"); - return ignoredBy is null ? true : ((Tool) ignoredBy).HasFlag (Tool.NativeAot); - } - - public virtual bool IsIgnored ([NotNullWhen (true)] out string? reason) - { - var ignoreAttribute = _testCaseTypeDefinition.CustomAttributes.FirstOrDefault (attr => attr.AttributeType.Name == nameof (IgnoreTestCaseAttribute)); - if (ignoreAttribute != null && IsIgnoredByNativeAOT (ignoreAttribute)) { - if (ignoreAttribute.ConstructorArguments.Count == 1) { - reason = (string) ignoreAttribute.ConstructorArguments.First ().Value; - return true; - } else { - throw new ArgumentException ($"Unhandled {nameof (IgnoreTestCaseAttribute)} constructor with {ignoreAttribute.ConstructorArguments} arguments"); - } - } - - var requirementsAttribute = _testCaseTypeDefinition.CustomAttributes.FirstOrDefault (attr => attr.AttributeType.Name == nameof (TestCaseRequirementsAttribute)); - if (requirementsAttribute != null) { - if (requirementsAttribute.ConstructorArguments.Count == 2) { - var testCaseRequirements = (TestRunCharacteristics) requirementsAttribute.ConstructorArguments[0].Value; - - foreach (var value in Enum.GetValues (typeof (TestRunCharacteristics))) { - if (IsRequirementMissing ((TestRunCharacteristics) value, testCaseRequirements)) { - reason = (string) requirementsAttribute.ConstructorArguments[1].Value; - return true; - } - } - } else { - throw new ArgumentException ($"Unhandled {nameof (TestCaseRequirementsAttribute)} constructor with {requirementsAttribute.ConstructorArguments} arguments"); - } - } - - reason = null; - return false; - } - - private bool IsRequirementMissing (TestRunCharacteristics requirement, TestRunCharacteristics testCaseRequirements) - { - return testCaseRequirements.HasFlag (requirement) && !Characteristics.HasFlag (requirement); - } - - public virtual IEnumerable GetDefines () - { - // There are a few tests related to native pdbs where the assertions are different between windows and non-windows - // To enable test cases to define different expected behavior we set this special define - if (Environment.OSVersion.Platform == PlatformID.Win32NT) - yield return "WIN32"; - - if (Characteristics.HasFlag (TestRunCharacteristics.TargetingNetCore)) - yield return "NET"; - - if (Characteristics.HasFlag (TestRunCharacteristics.SupportsDefaultInterfaceMethods)) - yield return "SUPPORTS_DEFAULT_INTERFACE_METHODS"; - - foreach (var attr in _testCaseTypeDefinition.CustomAttributes.Where (attr => attr.AttributeType.Name == nameof (DefineAttribute))) - yield return (string) attr.ConstructorArguments.First ().Value; - } - - public virtual string GetAssemblyName () - { - var asLibraryAttribute = _testCaseTypeDefinition.CustomAttributes - .FirstOrDefault (attr => attr.AttributeType.Name == nameof (SetupCompileAsLibraryAttribute)); - var defaultName = asLibraryAttribute == null ? "test.exe" : "test.dll"; - return GetOptionAttributeValue (nameof (SetupCompileAssemblyNameAttribute), defaultName)!; - } - - public virtual string GetCSharpCompilerToUse () - { - return GetOptionAttributeValue (nameof (SetupCSharpCompilerToUseAttribute), string.Empty)!.ToLowerInvariant (); - } - - public virtual IEnumerable GetSetupCompilerArguments () - { - return _testCaseTypeDefinition.CustomAttributes - .Where (attr => attr.AttributeType.Name == nameof (SetupCompileArgumentAttribute)) - .Select (attr => (string) attr.ConstructorArguments.First ().Value); - } - - public virtual IEnumerable AdditionalFilesToSandbox () - { - return _testCaseTypeDefinition.CustomAttributes - .Where (attr => attr.AttributeType.Name == nameof (SandboxDependencyAttribute)) - .Select (GetSourceAndRelativeDestinationValue); - } - - private static string GetReferenceDir () - { - string runtimeDir = Path.GetDirectoryName (typeof (object).Assembly.Location)!; - string ncaVersion = Path.GetFileName (runtimeDir); - string dotnetDir = Path.GetDirectoryName (Path.GetDirectoryName (Path.GetDirectoryName (runtimeDir)))!; - return Path.Combine (dotnetDir, "packs", "Microsoft.NETCore.App.Ref", ncaVersion, "ref", PathUtilities.TFMDirectoryName); - } - - public virtual IEnumerable GetCommonReferencedAssemblies (NPath workingDirectory) - { - yield return workingDirectory.Combine ("Mono.Linker.Tests.Cases.Expectations.dll").ToString (); - if (Characteristics.HasFlag (TestRunCharacteristics.TargetingNetCore)) { - string referenceDir = GetReferenceDir (); - - yield return Path.Combine (referenceDir, "mscorlib.dll"); - yield return Path.Combine (referenceDir, "System.Collections.dll"); - yield return Path.Combine (referenceDir, "System.Collections.Immutable.dll"); - yield return Path.Combine (referenceDir, "System.ComponentModel.TypeConverter.dll"); - yield return Path.Combine (referenceDir, "System.Console.dll"); - yield return Path.Combine (referenceDir, "System.Linq.Expressions.dll"); - yield return Path.Combine (referenceDir, "System.Memory.dll"); - yield return Path.Combine (referenceDir, "System.ObjectModel.dll"); - yield return Path.Combine (referenceDir, "System.Runtime.dll"); - yield return Path.Combine (referenceDir, "System.Runtime.Extensions.dll"); - yield return Path.Combine (referenceDir, "System.Runtime.InteropServices.dll"); - } else { - yield return "mscorlib.dll"; - } - } - - public virtual IEnumerable GetReferencedAssemblies (NPath workingDirectory) - { - foreach (var fileName in GetReferenceValues ()) { - - if (fileName.StartsWith ("System.", StringComparison.Ordinal) || fileName.StartsWith ("Mono.", StringComparison.Ordinal) || fileName.StartsWith ("Microsoft.", StringComparison.Ordinal)) { - if (Characteristics.HasFlag (TestRunCharacteristics.TargetingNetCore)) { - var referenceDir = GetReferenceDir (); - var filePath = Path.Combine (referenceDir, fileName); - - if (File.Exists (filePath)) { - yield return filePath; - } else { - yield return fileName; - } - } else { - yield return fileName; - } - } else { - // Drop any relative path information. Sandboxing will have taken care of copying the reference to the directory - yield return workingDirectory.Combine (Path.GetFileName (fileName)); - } - } - } - - public virtual IEnumerable GetReferenceDependencies () - { - return _testCaseTypeDefinition.CustomAttributes - .Where (attr => attr.AttributeType.Name == nameof (ReferenceDependencyAttribute)) - .Select (attr => (string) attr.ConstructorArguments[0].Value); - } - - public virtual IEnumerable GetReferenceValues () - { - foreach (var referenceAttr in _testCaseTypeDefinition.CustomAttributes.Where (attr => attr.AttributeType.Name == nameof (ReferenceAttribute))) - yield return (string) referenceAttr.ConstructorArguments.First ().Value; - } - - public virtual IEnumerable GetResources () - { - return _testCaseTypeDefinition.CustomAttributes - .Where (attr => attr.AttributeType.Name == nameof (SetupCompileResourceAttribute)) - .Select (GetSourceAndRelativeDestinationValue); - } - - public virtual IEnumerable GetSetupCompileAssembliesBefore () - { - return _testCaseTypeDefinition.CustomAttributes - .Where (attr => attr.AttributeType.Name == nameof (SetupCompileBeforeAttribute)) - .Select (CreateSetupCompileAssemblyInfo); - } - - public virtual IEnumerable GetSetupCompileAssembliesAfter () - { - return _testCaseTypeDefinition.CustomAttributes - .Where (attr => attr.AttributeType.Name == nameof (SetupCompileAfterAttribute)) - .Select (CreateSetupCompileAssemblyInfo); - } - - private SetupCompileInfo CreateSetupCompileAssemblyInfo (CustomAttribute attribute) - { - var ctorArguments = attribute.ConstructorArguments; - return new SetupCompileInfo { - OutputName = (string) ctorArguments[0].Value, - SourceFiles = SourceFilesForAttributeArgument (ctorArguments[1]), - References = ((CustomAttributeArgument[]) ctorArguments[2].Value)?.Select (arg => arg.Value.ToString ()).ToArray (), - Defines = ((CustomAttributeArgument[]) ctorArguments[3].Value)?.Select (arg => arg.Value.ToString ()).ToArray (), - Resources = ResourcesForAttributeArgument (ctorArguments[4]), - AdditionalArguments = ((CustomAttributeArgument[]) ctorArguments[5].Value)?.Select (arg => arg.Value.ToString ()).ToArray (), - CompilerToUse = (string) ctorArguments[6].Value, - AddAsReference = ctorArguments.Count >= 8 ? (bool) ctorArguments[7].Value : true, - RemoveFromLinkerInput = ctorArguments.Count >= 9 ? (bool) ctorArguments[8].Value : false, - OutputSubFolder = ctorArguments.Count >= 10 ? (string) ctorArguments[9].Value : null - }; - } - - protected NPath[] SourceFilesForAttributeArgument (CustomAttributeArgument attributeArgument) - { - return ((CustomAttributeArgument[]) attributeArgument.Value) - .Select (attributeArg => SourceFileForAttributeArgumentValue (attributeArg.Value)) - .Distinct () - .ToArray (); - } - - protected SourceAndDestinationPair[]? ResourcesForAttributeArgument (CustomAttributeArgument attributeArgument) - { - return ((CustomAttributeArgument[]) attributeArgument.Value) - ?.Select (arg => { - var referenceArg = (CustomAttributeArgument) arg.Value; - if (referenceArg.Value is string source) { - var fullSource = MakeSourceTreeFilePathAbsolute (source); - return new SourceAndDestinationPair { - Source = fullSource, - DestinationFileName = fullSource.FileName - }; - } - var sourceAndDestination = (CustomAttributeArgument[]) referenceArg.Value; - return new SourceAndDestinationPair { - Source = MakeSourceTreeFilePathAbsolute (sourceAndDestination[0].Value!.ToString ()!), - DestinationFileName = sourceAndDestination[1].Value!.ToString ()! - }; - }) - ?.ToArray (); - } - } + public class TestCaseCompilationMetadataProvider : BaseMetadataProvider + { + + public TestCaseCompilationMetadataProvider(TestCase testCase, AssemblyDefinition fullTestCaseAssemblyDefinition) + : base(testCase, fullTestCaseAssemblyDefinition) + { + + } + + public virtual TestRunCharacteristics Characteristics => + TestRunCharacteristics.TargetingNetCore | TestRunCharacteristics.SupportsDefaultInterfaceMethods | TestRunCharacteristics.SupportsStaticInterfaceMethods; + + private static bool IsIgnoredByNativeAOT(CustomAttribute attr) + { + var ignoredBy = attr.GetPropertyValue("IgnoredBy"); + return ignoredBy is null ? true : ((Tool)ignoredBy).HasFlag(Tool.NativeAot); + } + + public virtual bool IsIgnored([NotNullWhen(true)] out string? reason) + { + var ignoreAttribute = _testCaseTypeDefinition.CustomAttributes.FirstOrDefault(attr => attr.AttributeType.Name == nameof(IgnoreTestCaseAttribute)); + if (ignoreAttribute != null && IsIgnoredByNativeAOT(ignoreAttribute)) + { + if (ignoreAttribute.ConstructorArguments.Count == 1) + { + reason = (string)ignoreAttribute.ConstructorArguments.First().Value; + return true; + } + else + { + throw new ArgumentException($"Unhandled {nameof(IgnoreTestCaseAttribute)} constructor with {ignoreAttribute.ConstructorArguments} arguments"); + } + } + + var requirementsAttribute = _testCaseTypeDefinition.CustomAttributes.FirstOrDefault(attr => attr.AttributeType.Name == nameof(TestCaseRequirementsAttribute)); + if (requirementsAttribute != null) + { + if (requirementsAttribute.ConstructorArguments.Count == 2) + { + var testCaseRequirements = (TestRunCharacteristics)requirementsAttribute.ConstructorArguments[0].Value; + + foreach (var value in Enum.GetValues(typeof(TestRunCharacteristics))) + { + if (IsRequirementMissing((TestRunCharacteristics)value, testCaseRequirements)) + { + reason = (string)requirementsAttribute.ConstructorArguments[1].Value; + return true; + } + } + } + else + { + throw new ArgumentException($"Unhandled {nameof(TestCaseRequirementsAttribute)} constructor with {requirementsAttribute.ConstructorArguments} arguments"); + } + } + + reason = null; + return false; + } + + private bool IsRequirementMissing(TestRunCharacteristics requirement, TestRunCharacteristics testCaseRequirements) + { + return testCaseRequirements.HasFlag(requirement) && !Characteristics.HasFlag(requirement); + } + + public virtual IEnumerable GetDefines() + { + // There are a few tests related to native pdbs where the assertions are different between windows and non-windows + // To enable test cases to define different expected behavior we set this special define + if (Environment.OSVersion.Platform == PlatformID.Win32NT) + yield return "WIN32"; + + if (Characteristics.HasFlag(TestRunCharacteristics.TargetingNetCore)) + yield return "NET"; + + if (Characteristics.HasFlag(TestRunCharacteristics.SupportsDefaultInterfaceMethods)) + yield return "SUPPORTS_DEFAULT_INTERFACE_METHODS"; + + foreach (var attr in _testCaseTypeDefinition.CustomAttributes.Where(attr => attr.AttributeType.Name == nameof(DefineAttribute))) + yield return (string)attr.ConstructorArguments.First().Value; + } + + public virtual string GetAssemblyName() + { + var asLibraryAttribute = _testCaseTypeDefinition.CustomAttributes + .FirstOrDefault(attr => attr.AttributeType.Name == nameof(SetupCompileAsLibraryAttribute)); + var defaultName = asLibraryAttribute == null ? "test.exe" : "test.dll"; + return GetOptionAttributeValue(nameof(SetupCompileAssemblyNameAttribute), defaultName)!; + } + + public virtual string GetCSharpCompilerToUse() + { + return GetOptionAttributeValue(nameof(SetupCSharpCompilerToUseAttribute), string.Empty)!.ToLowerInvariant(); + } + + public virtual IEnumerable GetSetupCompilerArguments() + { + return _testCaseTypeDefinition.CustomAttributes + .Where(attr => attr.AttributeType.Name == nameof(SetupCompileArgumentAttribute)) + .Select(attr => (string)attr.ConstructorArguments.First().Value); + } + + public virtual IEnumerable AdditionalFilesToSandbox() + { + return _testCaseTypeDefinition.CustomAttributes + .Where(attr => attr.AttributeType.Name == nameof(SandboxDependencyAttribute)) + .Select(GetSourceAndRelativeDestinationValue); + } + + private static string GetReferenceDir() + { + string runtimeDir = Path.GetDirectoryName(typeof(object).Assembly.Location)!; + string ncaVersion = Path.GetFileName(runtimeDir); + string dotnetDir = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(runtimeDir)))!; + return Path.Combine(dotnetDir, "packs", "Microsoft.NETCore.App.Ref", ncaVersion, "ref", PathUtilities.TFMDirectoryName); + } + + public virtual IEnumerable GetCommonReferencedAssemblies(NPath workingDirectory) + { + yield return workingDirectory.Combine("Mono.Linker.Tests.Cases.Expectations.dll").ToString(); + if (Characteristics.HasFlag(TestRunCharacteristics.TargetingNetCore)) + { + string referenceDir = GetReferenceDir(); + + yield return Path.Combine(referenceDir, "mscorlib.dll"); + yield return Path.Combine(referenceDir, "System.Collections.dll"); + yield return Path.Combine(referenceDir, "System.Collections.Immutable.dll"); + yield return Path.Combine(referenceDir, "System.ComponentModel.TypeConverter.dll"); + yield return Path.Combine(referenceDir, "System.Console.dll"); + yield return Path.Combine(referenceDir, "System.Linq.Expressions.dll"); + yield return Path.Combine(referenceDir, "System.Memory.dll"); + yield return Path.Combine(referenceDir, "System.ObjectModel.dll"); + yield return Path.Combine(referenceDir, "System.Runtime.dll"); + yield return Path.Combine(referenceDir, "System.Runtime.Extensions.dll"); + yield return Path.Combine(referenceDir, "System.Runtime.InteropServices.dll"); + } + else + { + yield return "mscorlib.dll"; + } + } + + public virtual IEnumerable GetReferencedAssemblies(NPath workingDirectory) + { + foreach (var fileName in GetReferenceValues()) + { + + if (fileName.StartsWith("System.", StringComparison.Ordinal) || fileName.StartsWith("Mono.", StringComparison.Ordinal) || fileName.StartsWith("Microsoft.", StringComparison.Ordinal)) + { + if (Characteristics.HasFlag(TestRunCharacteristics.TargetingNetCore)) + { + var referenceDir = GetReferenceDir(); + var filePath = Path.Combine(referenceDir, fileName); + + if (File.Exists(filePath)) + { + yield return filePath; + } + else + { + yield return fileName; + } + } + else + { + yield return fileName; + } + } + else + { + // Drop any relative path information. Sandboxing will have taken care of copying the reference to the directory + yield return workingDirectory.Combine(Path.GetFileName(fileName)); + } + } + } + + public virtual IEnumerable GetReferenceDependencies() + { + return _testCaseTypeDefinition.CustomAttributes + .Where(attr => attr.AttributeType.Name == nameof(ReferenceDependencyAttribute)) + .Select(attr => (string)attr.ConstructorArguments[0].Value); + } + + public virtual IEnumerable GetReferenceValues() + { + foreach (var referenceAttr in _testCaseTypeDefinition.CustomAttributes.Where(attr => attr.AttributeType.Name == nameof(ReferenceAttribute))) + yield return (string)referenceAttr.ConstructorArguments.First().Value; + } + + public virtual IEnumerable GetResources() + { + return _testCaseTypeDefinition.CustomAttributes + .Where(attr => attr.AttributeType.Name == nameof(SetupCompileResourceAttribute)) + .Select(GetSourceAndRelativeDestinationValue); + } + + public virtual IEnumerable GetSetupCompileAssembliesBefore() + { + return _testCaseTypeDefinition.CustomAttributes + .Where(attr => attr.AttributeType.Name == nameof(SetupCompileBeforeAttribute)) + .Select(CreateSetupCompileAssemblyInfo); + } + + public virtual IEnumerable GetSetupCompileAssembliesAfter() + { + return _testCaseTypeDefinition.CustomAttributes + .Where(attr => attr.AttributeType.Name == nameof(SetupCompileAfterAttribute)) + .Select(CreateSetupCompileAssemblyInfo); + } + + private SetupCompileInfo CreateSetupCompileAssemblyInfo(CustomAttribute attribute) + { + var ctorArguments = attribute.ConstructorArguments; + return new SetupCompileInfo + { + OutputName = (string)ctorArguments[0].Value, + SourceFiles = SourceFilesForAttributeArgument(ctorArguments[1]), + References = ((CustomAttributeArgument[])ctorArguments[2].Value)?.Select(arg => arg.Value.ToString()).ToArray(), + Defines = ((CustomAttributeArgument[])ctorArguments[3].Value)?.Select(arg => arg.Value.ToString()).ToArray(), + Resources = ResourcesForAttributeArgument(ctorArguments[4]), + AdditionalArguments = ((CustomAttributeArgument[])ctorArguments[5].Value)?.Select(arg => arg.Value.ToString()).ToArray(), + CompilerToUse = (string)ctorArguments[6].Value, + AddAsReference = ctorArguments.Count >= 8 ? (bool)ctorArguments[7].Value : true, + RemoveFromLinkerInput = ctorArguments.Count >= 9 ? (bool)ctorArguments[8].Value : false, + OutputSubFolder = ctorArguments.Count >= 10 ? (string)ctorArguments[9].Value : null + }; + } + + protected NPath[] SourceFilesForAttributeArgument(CustomAttributeArgument attributeArgument) + { + return ((CustomAttributeArgument[])attributeArgument.Value) + .Select(attributeArg => SourceFileForAttributeArgumentValue(attributeArg.Value)) + .Distinct() + .ToArray(); + } + + protected SourceAndDestinationPair[]? ResourcesForAttributeArgument(CustomAttributeArgument attributeArgument) + { + return ((CustomAttributeArgument[])attributeArgument.Value) + ?.Select(arg => + { + var referenceArg = (CustomAttributeArgument)arg.Value; + if (referenceArg.Value is string source) + { + var fullSource = MakeSourceTreeFilePathAbsolute(source); + return new SourceAndDestinationPair + { + Source = fullSource, + DestinationFileName = fullSource.FileName + }; + } + var sourceAndDestination = (CustomAttributeArgument[])referenceArg.Value; + return new SourceAndDestinationPair + { + Source = MakeSourceTreeFilePathAbsolute(sourceAndDestination[0].Value!.ToString()!), + DestinationFileName = sourceAndDestination[1].Value!.ToString()! + }; + }) + ?.ToArray(); + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCompiler.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCompiler.cs index b20c16631302c2..feaed7f0f69c9d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCompiler.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCompiler.cs @@ -18,404 +18,419 @@ namespace Mono.Linker.Tests.TestCasesRunner { - public class TestCaseCompiler - { - protected readonly TestCaseCompilationMetadataProvider _metadataProvider; - protected readonly TestCaseSandbox _sandbox; - protected readonly ILInputCompiler _ilCompiler; - - public TestCaseCompiler (TestCaseSandbox sandbox, TestCaseCompilationMetadataProvider metadataProvider) - : this (sandbox, metadataProvider, new ILInputCompiler ()) - { - } - - public TestCaseCompiler (TestCaseSandbox sandbox, TestCaseCompilationMetadataProvider metadataProvider, ILInputCompiler ilCompiler) - { - _ilCompiler = ilCompiler; - _sandbox = sandbox; - _metadataProvider = metadataProvider; - } - - public NPath CompileTestIn (NPath outputDirectory, string outputName, IEnumerable sourceFiles, string[] commonReferences, string[] mainAssemblyReferences, IEnumerable? defines, NPath[] resources, string[] additionalArguments) - { - var originalCommonReferences = commonReferences.Select (r => r.ToNPath ()).ToArray (); - var originalDefines = defines?.ToArray () ?? Array.Empty (); - - Prepare (outputDirectory); - - var removeFromLinkerInputAssemblies = new List (); - var compiledReferences = CompileBeforeTestCaseAssemblies (outputDirectory, originalCommonReferences, originalDefines, removeFromLinkerInputAssemblies).ToArray (); - var allTestCaseReferences = originalCommonReferences - .Concat (compiledReferences) - .Concat (mainAssemblyReferences.Select (r => r.ToNPath ())) - .ToArray (); - - var options = CreateOptionsForTestCase ( - outputDirectory.Combine (outputName), - sourceFiles.Select (s => s.ToNPath ()).ToArray (), - allTestCaseReferences, - originalDefines, - resources, - additionalArguments); - var testAssembly = CompileAssembly (options); - - - // The compile after step is used by tests to mess around with the input to the illink tool. Generally speaking, it doesn't seem like we would ever want to mess with the - // expectations assemblies because this would undermine our ability to inspect them for expected results during ResultChecking. The UnityLinker UnresolvedHandling tests depend on this - // behavior of skipping the after test compile - if (outputDirectory != _sandbox.ExpectationsDirectory) { - CompileAfterTestCaseAssemblies (outputDirectory, originalCommonReferences, originalDefines, removeFromLinkerInputAssemblies); - - foreach (var assemblyToRemove in removeFromLinkerInputAssemblies) - assemblyToRemove.DeleteIfExists (); - } - - return testAssembly; - } - - protected virtual void Prepare (NPath outputDirectory) - { - } - - protected virtual CompilerOptions CreateOptionsForTestCase (NPath outputPath, NPath[] sourceFiles, NPath[] references, string[] defines, NPath[] resources, string[] additionalArguments) - { - return new CompilerOptions { - OutputPath = outputPath, - SourceFiles = sourceFiles, - References = references, - Defines = defines.Concat (_metadataProvider.GetDefines ()).ToArray (), - Resources = resources, - AdditionalArguments = additionalArguments, - CompilerToUse = _metadataProvider.GetCSharpCompilerToUse () - }; - } - - protected virtual CompilerOptions CreateOptionsForSupportingAssembly (SetupCompileInfo setupCompileInfo, NPath outputDirectory, NPath[] sourceFiles, NPath[] references, string[] defines, NPath[] resources) - { - var allDefines = defines.Concat (setupCompileInfo.Defines ?? Array.Empty ()).ToArray (); - var allReferences = references.Concat (setupCompileInfo.References?.Select (p => MakeSupportingAssemblyReferencePathAbsolute (outputDirectory, p)) ?? Array.Empty ()).ToArray (); - string[]? additionalArguments = setupCompileInfo.AdditionalArguments; - return new CompilerOptions { - OutputPath = outputDirectory.Combine (setupCompileInfo.OutputName), - SourceFiles = sourceFiles, - References = allReferences, - Defines = allDefines, - Resources = resources, - AdditionalArguments = additionalArguments, - CompilerToUse = setupCompileInfo.CompilerToUse?.ToLowerInvariant () - }; - } - - private IEnumerable CompileBeforeTestCaseAssemblies (NPath outputDirectory, NPath[] references, string[] defines, IList removeFromLinkerInputAssemblies) - { - foreach (var setupCompileInfo in _metadataProvider.GetSetupCompileAssembliesBefore ()) { - NPath outputFolder; - if (setupCompileInfo.OutputSubFolder == null) { - outputFolder = outputDirectory; - } else { - outputFolder = outputDirectory.Combine (setupCompileInfo.OutputSubFolder); - Directory.CreateDirectory (outputFolder.ToString ()); - } - - var options = CreateOptionsForSupportingAssembly ( - setupCompileInfo, - outputFolder, - CollectSetupBeforeSourcesFiles (setupCompileInfo), - references, - defines, - CollectSetupBeforeResourcesFiles (setupCompileInfo)); - var output = CompileAssembly (options); - - if (setupCompileInfo.RemoveFromLinkerInput) - removeFromLinkerInputAssemblies.Add (output); - - if (setupCompileInfo.AddAsReference) - yield return output; - } - } - - private void CompileAfterTestCaseAssemblies (NPath outputDirectory, NPath[] references, string[] defines, IList removeFromLinkerInputAssemblies) - { - foreach (var setupCompileInfo in _metadataProvider.GetSetupCompileAssembliesAfter ()) { - var options = CreateOptionsForSupportingAssembly ( - setupCompileInfo, - outputDirectory, - CollectSetupAfterSourcesFiles (setupCompileInfo), - references, - defines, - CollectSetupAfterResourcesFiles (setupCompileInfo)); - var output = CompileAssembly (options); - - if (setupCompileInfo.RemoveFromLinkerInput) - removeFromLinkerInputAssemblies.Add (output); - } - } - - private NPath[] CollectSetupBeforeSourcesFiles (SetupCompileInfo info) - { - return CollectSourceFilesFrom (_sandbox.BeforeReferenceSourceDirectoryFor (info.OutputName)); - } - - private NPath[] CollectSetupAfterSourcesFiles (SetupCompileInfo info) - { - return CollectSourceFilesFrom (_sandbox.AfterReferenceSourceDirectoryFor (info.OutputName)); - } - - private NPath[] CollectSetupBeforeResourcesFiles (SetupCompileInfo info) - { - return _sandbox.BeforeReferenceResourceDirectoryFor (info.OutputName).Files ().ToArray (); - } - - private NPath[] CollectSetupAfterResourcesFiles (SetupCompileInfo info) - { - return _sandbox.AfterReferenceResourceDirectoryFor (info.OutputName).Files ().ToArray (); - } - - private static NPath[] CollectSourceFilesFrom (NPath directory) - { - var sourceFiles = directory.Files ("*.cs").ToArray (); - if (sourceFiles.Length > 0) - return sourceFiles; - - sourceFiles = directory.Files ("*.il").ToArray (); - if (sourceFiles.Length > 0) - return sourceFiles; - - throw new FileNotFoundException ($"Didn't find any sources files in {directory}"); - } - - protected static NPath MakeSupportingAssemblyReferencePathAbsolute (NPath outputDirectory, string referenceFileName) - { - // Not a good idea to use a full path in a test, but maybe someone is trying to quickly test something locally - if (Path.IsPathRooted (referenceFileName)) - return referenceFileName.ToNPath (); + public class TestCaseCompiler + { + protected readonly TestCaseCompilationMetadataProvider _metadataProvider; + protected readonly TestCaseSandbox _sandbox; + protected readonly ILInputCompiler _ilCompiler; + + public TestCaseCompiler(TestCaseSandbox sandbox, TestCaseCompilationMetadataProvider metadataProvider) + : this(sandbox, metadataProvider, new ILInputCompiler()) + { + } + + public TestCaseCompiler(TestCaseSandbox sandbox, TestCaseCompilationMetadataProvider metadataProvider, ILInputCompiler ilCompiler) + { + _ilCompiler = ilCompiler; + _sandbox = sandbox; + _metadataProvider = metadataProvider; + } + + public NPath CompileTestIn(NPath outputDirectory, string outputName, IEnumerable sourceFiles, string[] commonReferences, string[] mainAssemblyReferences, IEnumerable? defines, NPath[] resources, string[] additionalArguments) + { + var originalCommonReferences = commonReferences.Select(r => r.ToNPath()).ToArray(); + var originalDefines = defines?.ToArray() ?? Array.Empty(); + + Prepare(outputDirectory); + + var removeFromLinkerInputAssemblies = new List(); + var compiledReferences = CompileBeforeTestCaseAssemblies(outputDirectory, originalCommonReferences, originalDefines, removeFromLinkerInputAssemblies).ToArray(); + var allTestCaseReferences = originalCommonReferences + .Concat(compiledReferences) + .Concat(mainAssemblyReferences.Select(r => r.ToNPath())) + .ToArray(); + + var options = CreateOptionsForTestCase( + outputDirectory.Combine(outputName), + sourceFiles.Select(s => s.ToNPath()).ToArray(), + allTestCaseReferences, + originalDefines, + resources, + additionalArguments); + var testAssembly = CompileAssembly(options); + + + // The compile after step is used by tests to mess around with the input to the illink tool. Generally speaking, it doesn't seem like we would ever want to mess with the + // expectations assemblies because this would undermine our ability to inspect them for expected results during ResultChecking. The UnityLinker UnresolvedHandling tests depend on this + // behavior of skipping the after test compile + if (outputDirectory != _sandbox.ExpectationsDirectory) + { + CompileAfterTestCaseAssemblies(outputDirectory, originalCommonReferences, originalDefines, removeFromLinkerInputAssemblies); + + foreach (var assemblyToRemove in removeFromLinkerInputAssemblies) + assemblyToRemove.DeleteIfExists(); + } + + return testAssembly; + } + + protected virtual void Prepare(NPath outputDirectory) + { + } + + protected virtual CompilerOptions CreateOptionsForTestCase(NPath outputPath, NPath[] sourceFiles, NPath[] references, string[] defines, NPath[] resources, string[] additionalArguments) + { + return new CompilerOptions + { + OutputPath = outputPath, + SourceFiles = sourceFiles, + References = references, + Defines = defines.Concat(_metadataProvider.GetDefines()).ToArray(), + Resources = resources, + AdditionalArguments = additionalArguments, + CompilerToUse = _metadataProvider.GetCSharpCompilerToUse() + }; + } + + protected virtual CompilerOptions CreateOptionsForSupportingAssembly(SetupCompileInfo setupCompileInfo, NPath outputDirectory, NPath[] sourceFiles, NPath[] references, string[] defines, NPath[] resources) + { + var allDefines = defines.Concat(setupCompileInfo.Defines ?? Array.Empty()).ToArray(); + var allReferences = references.Concat(setupCompileInfo.References?.Select(p => MakeSupportingAssemblyReferencePathAbsolute(outputDirectory, p)) ?? Array.Empty()).ToArray(); + string[]? additionalArguments = setupCompileInfo.AdditionalArguments; + return new CompilerOptions + { + OutputPath = outputDirectory.Combine(setupCompileInfo.OutputName), + SourceFiles = sourceFiles, + References = allReferences, + Defines = allDefines, + Resources = resources, + AdditionalArguments = additionalArguments, + CompilerToUse = setupCompileInfo.CompilerToUse?.ToLowerInvariant() + }; + } + + private IEnumerable CompileBeforeTestCaseAssemblies(NPath outputDirectory, NPath[] references, string[] defines, IList removeFromLinkerInputAssemblies) + { + foreach (var setupCompileInfo in _metadataProvider.GetSetupCompileAssembliesBefore()) + { + NPath outputFolder; + if (setupCompileInfo.OutputSubFolder == null) + { + outputFolder = outputDirectory; + } + else + { + outputFolder = outputDirectory.Combine(setupCompileInfo.OutputSubFolder); + Directory.CreateDirectory(outputFolder.ToString()); + } + + var options = CreateOptionsForSupportingAssembly( + setupCompileInfo, + outputFolder, + CollectSetupBeforeSourcesFiles(setupCompileInfo), + references, + defines, + CollectSetupBeforeResourcesFiles(setupCompileInfo)); + var output = CompileAssembly(options); + + if (setupCompileInfo.RemoveFromLinkerInput) + removeFromLinkerInputAssemblies.Add(output); + + if (setupCompileInfo.AddAsReference) + yield return output; + } + } + + private void CompileAfterTestCaseAssemblies(NPath outputDirectory, NPath[] references, string[] defines, IList removeFromLinkerInputAssemblies) + { + foreach (var setupCompileInfo in _metadataProvider.GetSetupCompileAssembliesAfter()) + { + var options = CreateOptionsForSupportingAssembly( + setupCompileInfo, + outputDirectory, + CollectSetupAfterSourcesFiles(setupCompileInfo), + references, + defines, + CollectSetupAfterResourcesFiles(setupCompileInfo)); + var output = CompileAssembly(options); + + if (setupCompileInfo.RemoveFromLinkerInput) + removeFromLinkerInputAssemblies.Add(output); + } + } + + private NPath[] CollectSetupBeforeSourcesFiles(SetupCompileInfo info) + { + return CollectSourceFilesFrom(_sandbox.BeforeReferenceSourceDirectoryFor(info.OutputName)); + } + + private NPath[] CollectSetupAfterSourcesFiles(SetupCompileInfo info) + { + return CollectSourceFilesFrom(_sandbox.AfterReferenceSourceDirectoryFor(info.OutputName)); + } + + private NPath[] CollectSetupBeforeResourcesFiles(SetupCompileInfo info) + { + return _sandbox.BeforeReferenceResourceDirectoryFor(info.OutputName).Files().ToArray(); + } + + private NPath[] CollectSetupAfterResourcesFiles(SetupCompileInfo info) + { + return _sandbox.AfterReferenceResourceDirectoryFor(info.OutputName).Files().ToArray(); + } + + private static NPath[] CollectSourceFilesFrom(NPath directory) + { + var sourceFiles = directory.Files("*.cs").ToArray(); + if (sourceFiles.Length > 0) + return sourceFiles; + + sourceFiles = directory.Files("*.il").ToArray(); + if (sourceFiles.Length > 0) + return sourceFiles; + + throw new FileNotFoundException($"Didn't find any sources files in {directory}"); + } + + protected static NPath MakeSupportingAssemblyReferencePathAbsolute(NPath outputDirectory, string referenceFileName) + { + // Not a good idea to use a full path in a test, but maybe someone is trying to quickly test something locally + if (Path.IsPathRooted(referenceFileName)) + return referenceFileName.ToNPath(); #if NET - if (referenceFileName.StartsWith ("System.", StringComparison.Ordinal) || - referenceFileName.StartsWith ("Mono.", StringComparison.Ordinal) || - referenceFileName.StartsWith ("Microsoft.", StringComparison.Ordinal) || - referenceFileName == "netstandard.dll") { - - var frameworkDir = Path.GetFullPath (Path.GetDirectoryName (typeof (object).Assembly.Location)!); - var filePath = Path.Combine (frameworkDir, referenceFileName); - - if (File.Exists (filePath)) - return filePath.ToNPath (); - } + if (referenceFileName.StartsWith("System.", StringComparison.Ordinal) || + referenceFileName.StartsWith("Mono.", StringComparison.Ordinal) || + referenceFileName.StartsWith("Microsoft.", StringComparison.Ordinal) || + referenceFileName == "netstandard.dll") + { + + var frameworkDir = Path.GetFullPath(Path.GetDirectoryName(typeof(object).Assembly.Location)!); + var filePath = Path.Combine(frameworkDir, referenceFileName); + + if (File.Exists(filePath)) + return filePath.ToNPath(); + } #endif - var possiblePath = outputDirectory.Combine (referenceFileName); - if (possiblePath.FileExists ()) - return possiblePath; + var possiblePath = outputDirectory.Combine(referenceFileName); + if (possiblePath.FileExists()) + return possiblePath; - return referenceFileName.ToNPath (); - } + return referenceFileName.ToNPath(); + } - protected NPath CompileAssembly (CompilerOptions options) - { - if (options.SourceFiles.Any (path => path.ExtensionWithDot == ".cs")) - return CompileCSharpAssembly (options); + protected NPath CompileAssembly(CompilerOptions options) + { + if (options.SourceFiles.Any(path => path.ExtensionWithDot == ".cs")) + return CompileCSharpAssembly(options); - if (options.SourceFiles.Any (path => path.ExtensionWithDot == ".il")) - return CompileIlAssembly (options); + if (options.SourceFiles.Any(path => path.ExtensionWithDot == ".il")) + return CompileIlAssembly(options); - throw new NotSupportedException ($"Unable to compile sources files with extension `{options.SourceFiles.First ().ExtensionWithDot}`"); - } + throw new NotSupportedException($"Unable to compile sources files with extension `{options.SourceFiles.First().ExtensionWithDot}`"); + } - protected virtual NPath CompileCSharpAssemblyWithDefaultCompiler (CompilerOptions options) - { + protected virtual NPath CompileCSharpAssemblyWithDefaultCompiler(CompilerOptions options) + { #if NET - return CompileCSharpAssemblyWithRoslyn (options); + return CompileCSharpAssemblyWithRoslyn(options); #else - return CompileCSharpAssemblyWithCsc (options); + return CompileCSharpAssemblyWithCsc (options); #endif - } + } #if NET - protected virtual NPath CompileCSharpAssemblyWithRoslyn (CompilerOptions options) - { - var languageVersion = LanguageVersion.Default; - var compilationOptions = new CSharpCompilationOptions ( - outputKind: options.OutputPath.FileName.EndsWith (".exe") ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary, - assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default - ); - // Default debug info format for the current platform. - DebugInformationFormat debugType = RuntimeInformation.IsOSPlatform (OSPlatform.Windows) ? DebugInformationFormat.Pdb : DebugInformationFormat.PortablePdb; - bool emitPdb = false; - if (options.AdditionalArguments != null) { - foreach (var option in options.AdditionalArguments) { - switch (option) { - case "/unsafe": - compilationOptions = compilationOptions.WithAllowUnsafe (true); - break; - case "/optimize+": - compilationOptions = compilationOptions.WithOptimizationLevel (OptimizationLevel.Release); - break; - case "/optimize-": - compilationOptions = compilationOptions.WithOptimizationLevel (OptimizationLevel.Debug); - break; - case "/debug:full": - case "/debug:pdbonly": - // Use platform's default debug info. This behavior is the same as csc. - emitPdb = true; - break; - case "/debug:portable": - emitPdb = true; - debugType = DebugInformationFormat.PortablePdb; - break; - case "/debug:embedded": - emitPdb = true; - debugType = DebugInformationFormat.Embedded; - break; - case "/langversion:7.3": - languageVersion = LanguageVersion.CSharp7_3; - break; - default: - var splitIndex = option.IndexOf (":"); - if (splitIndex != -1 && option[..splitIndex] == "/main") { - var mainTypeName = option[(splitIndex + 1)..]; - compilationOptions = compilationOptions.WithMainTypeName (mainTypeName); - break; - } - throw new NotImplementedException (option); - } - } - } - var parseOptions = new CSharpParseOptions (preprocessorSymbols: options.Defines, languageVersion: languageVersion); - var emitOptions = new EmitOptions (debugInformationFormat: debugType); - var pdbPath = (!emitPdb || debugType == DebugInformationFormat.Embedded) ? null : options.OutputPath.ChangeExtension (".pdb").ToString (); - - var syntaxTrees = options.SourceFiles.Select (p => - CSharpSyntaxTree.ParseText ( - text: p.ReadAllText (), - options: parseOptions - ) - ); - - var compilation = CSharpCompilation.Create ( - assemblyName: options.OutputPath.FileNameWithoutExtension, - syntaxTrees: syntaxTrees, - references: options.References.Select (r => MetadataReference.CreateFromFile (r)), - options: compilationOptions - ); - - var manifestResources = options.Resources.Select (r => { - var fullPath = r.ToString (); - return new ResourceDescription ( - resourceName: Path.GetFileName (fullPath), - dataProvider: () => new FileStream (fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), - isPublic: true - ); - }); - - EmitResult result; - using (var outputStream = File.Create (options.OutputPath.ToString ())) - using (var pdbStream = pdbPath == null ? null : File.Create (pdbPath)) { - result = compilation.Emit ( - peStream: outputStream, - pdbStream: pdbStream, - manifestResources: manifestResources, - options: emitOptions - ); - } - - var errors = new StringBuilder (); - if (result.Success) - return options.OutputPath; - - foreach (var diagnostic in result.Diagnostics) - errors.AppendLine (diagnostic.ToString ()); - throw new Exception ("Roslyn compilation errors: " + errors); - } + protected virtual NPath CompileCSharpAssemblyWithRoslyn(CompilerOptions options) + { + var languageVersion = LanguageVersion.Default; + var compilationOptions = new CSharpCompilationOptions( + outputKind: options.OutputPath.FileName.EndsWith(".exe") ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary, + assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default + ); + // Default debug info format for the current platform. + DebugInformationFormat debugType = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? DebugInformationFormat.Pdb : DebugInformationFormat.PortablePdb; + bool emitPdb = false; + if (options.AdditionalArguments != null) + { + foreach (var option in options.AdditionalArguments) + { + switch (option) + { + case "/unsafe": + compilationOptions = compilationOptions.WithAllowUnsafe(true); + break; + case "/optimize+": + compilationOptions = compilationOptions.WithOptimizationLevel(OptimizationLevel.Release); + break; + case "/optimize-": + compilationOptions = compilationOptions.WithOptimizationLevel(OptimizationLevel.Debug); + break; + case "/debug:full": + case "/debug:pdbonly": + // Use platform's default debug info. This behavior is the same as csc. + emitPdb = true; + break; + case "/debug:portable": + emitPdb = true; + debugType = DebugInformationFormat.PortablePdb; + break; + case "/debug:embedded": + emitPdb = true; + debugType = DebugInformationFormat.Embedded; + break; + case "/langversion:7.3": + languageVersion = LanguageVersion.CSharp7_3; + break; + default: + var splitIndex = option.IndexOf(":"); + if (splitIndex != -1 && option[..splitIndex] == "/main") + { + var mainTypeName = option[(splitIndex + 1)..]; + compilationOptions = compilationOptions.WithMainTypeName(mainTypeName); + break; + } + throw new NotImplementedException(option); + } + } + } + var parseOptions = new CSharpParseOptions(preprocessorSymbols: options.Defines, languageVersion: languageVersion); + var emitOptions = new EmitOptions(debugInformationFormat: debugType); + var pdbPath = (!emitPdb || debugType == DebugInformationFormat.Embedded) ? null : options.OutputPath.ChangeExtension(".pdb").ToString(); + + var syntaxTrees = options.SourceFiles.Select(p => + CSharpSyntaxTree.ParseText( + text: p.ReadAllText(), + options: parseOptions + ) + ); + + var compilation = CSharpCompilation.Create( + assemblyName: options.OutputPath.FileNameWithoutExtension, + syntaxTrees: syntaxTrees, + references: options.References.Select(r => MetadataReference.CreateFromFile(r)), + options: compilationOptions + ); + + var manifestResources = options.Resources.Select(r => + { + var fullPath = r.ToString(); + return new ResourceDescription( + resourceName: Path.GetFileName(fullPath), + dataProvider: () => new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), + isPublic: true + ); + }); + + EmitResult result; + using (var outputStream = File.Create(options.OutputPath.ToString())) + using (var pdbStream = pdbPath == null ? null : File.Create(pdbPath)) + { + result = compilation.Emit( + peStream: outputStream, + pdbStream: pdbStream, + manifestResources: manifestResources, + options: emitOptions + ); + } + + var errors = new StringBuilder(); + if (result.Success) + return options.OutputPath; + + foreach (var diagnostic in result.Diagnostics) + errors.AppendLine(diagnostic.ToString()); + throw new Exception("Roslyn compilation errors: " + errors); + } #endif - protected virtual NPath CompileCSharpAssemblyWithCsc (CompilerOptions options) - { + protected virtual NPath CompileCSharpAssemblyWithCsc(CompilerOptions options) + { #if NET - return CompileCSharpAssemblyWithRoslyn (options); + return CompileCSharpAssemblyWithRoslyn(options); #else - return CompileCSharpAssemblyWithExternalCompiler (LocateCscExecutable (), options, "/shared "); + return CompileCSharpAssemblyWithExternalCompiler (LocateCscExecutable (), options, "/shared "); #endif - } - - protected virtual NPath CompileCSharpAssemblyWithMcs (CompilerOptions options) - { - if (Environment.OSVersion.Platform == PlatformID.Win32NT) - CompileCSharpAssemblyWithExternalCompiler (LocateMcsExecutable (), options, string.Empty); - - return CompileCSharpAssemblyWithDefaultCompiler (options); - } - - protected NPath CompileCSharpAssemblyWithExternalCompiler (string executable, CompilerOptions options, string compilerSpecificArguments) - { - var capturedOutput = new List (); - var process = new Process (); - process.StartInfo.FileName = executable; - process.StartInfo.Arguments = OptionsToCompilerCommandLineArguments (options, compilerSpecificArguments); - process.StartInfo.UseShellExecute = false; - process.StartInfo.CreateNoWindow = true; - process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; - process.StartInfo.RedirectStandardOutput = true; - process.OutputDataReceived += (sender, args) => capturedOutput.Add (args.Data!); - process.Start (); - process.BeginOutputReadLine (); - process.WaitForExit (); - - if (process.ExitCode != 0) - Assert.Fail($"Failed to compile assembly with csc: {options.OutputPath}\n{capturedOutput.Aggregate ((buff, s) => buff + Environment.NewLine + s)}"); - - return options.OutputPath; - } - - private static string LocateMcsExecutable () - { - if (Environment.OSVersion.Platform == PlatformID.Win32NT) - throw new IgnoreTestException ("We don't have a universal way of locating mcs on Windows"); - - return "mcs"; - } - - protected string OptionsToCompilerCommandLineArguments (CompilerOptions options, string compilerSpecificArguments) - { - var builder = new StringBuilder (); - if (!string.IsNullOrEmpty (compilerSpecificArguments)) - builder.Append (compilerSpecificArguments); - builder.Append ($"/out:{options.OutputPath}"); - var target = options.OutputPath.ExtensionWithDot == ".exe" ? "exe" : "library"; - builder.Append ($" /target:{target}"); - if (options.Defines != null && options.Defines.Length > 0) - builder.Append (options.Defines.Aggregate (string.Empty, (buff, arg) => $"{buff} /define:{arg}")); - - builder.Append (options.References.Aggregate (string.Empty, (buff, arg) => $"{buff} /r:{arg}")); - - if (options.Resources != null && options.Resources.Length > 0) - builder.Append (options.Resources.Aggregate (string.Empty, (buff, arg) => $"{buff} /res:{arg}")); - - if (options.AdditionalArguments != null && options.AdditionalArguments.Length > 0) - builder.Append (options.AdditionalArguments.Aggregate (string.Empty, (buff, arg) => $"{buff} {arg}")); - - builder.Append (options.SourceFiles.Aggregate (string.Empty, (buff, arg) => $"{buff} {arg}")); - - return builder.ToString (); - } - - protected NPath CompileCSharpAssembly (CompilerOptions options) - { - if (string.IsNullOrEmpty (options.CompilerToUse)) - return CompileCSharpAssemblyWithDefaultCompiler (options); - - if (options.CompilerToUse == "csc") - return CompileCSharpAssemblyWithCsc (options); - - if (options.CompilerToUse == "mcs") - return CompileCSharpAssemblyWithMcs (options); - - throw new ArgumentException ($"Invalid compiler value `{options.CompilerToUse}`"); - } - - protected NPath CompileIlAssembly (CompilerOptions options) - { - return _ilCompiler.Compile (options); - } - } + } + + protected virtual NPath CompileCSharpAssemblyWithMcs(CompilerOptions options) + { + if (Environment.OSVersion.Platform == PlatformID.Win32NT) + CompileCSharpAssemblyWithExternalCompiler(LocateMcsExecutable(), options, string.Empty); + + return CompileCSharpAssemblyWithDefaultCompiler(options); + } + + protected NPath CompileCSharpAssemblyWithExternalCompiler(string executable, CompilerOptions options, string compilerSpecificArguments) + { + var capturedOutput = new List(); + var process = new Process(); + process.StartInfo.FileName = executable; + process.StartInfo.Arguments = OptionsToCompilerCommandLineArguments(options, compilerSpecificArguments); + process.StartInfo.UseShellExecute = false; + process.StartInfo.CreateNoWindow = true; + process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; + process.StartInfo.RedirectStandardOutput = true; + process.OutputDataReceived += (sender, args) => capturedOutput.Add(args.Data!); + process.Start(); + process.BeginOutputReadLine(); + process.WaitForExit(); + + if (process.ExitCode != 0) + Assert.Fail($"Failed to compile assembly with csc: {options.OutputPath}\n{capturedOutput.Aggregate((buff, s) => buff + Environment.NewLine + s)}"); + + return options.OutputPath; + } + + private static string LocateMcsExecutable() + { + if (Environment.OSVersion.Platform == PlatformID.Win32NT) + throw new IgnoreTestException("We don't have a universal way of locating mcs on Windows"); + + return "mcs"; + } + + protected string OptionsToCompilerCommandLineArguments(CompilerOptions options, string compilerSpecificArguments) + { + var builder = new StringBuilder(); + if (!string.IsNullOrEmpty(compilerSpecificArguments)) + builder.Append(compilerSpecificArguments); + builder.Append($"/out:{options.OutputPath}"); + var target = options.OutputPath.ExtensionWithDot == ".exe" ? "exe" : "library"; + builder.Append($" /target:{target}"); + if (options.Defines != null && options.Defines.Length > 0) + builder.Append(options.Defines.Aggregate(string.Empty, (buff, arg) => $"{buff} /define:{arg}")); + + builder.Append(options.References.Aggregate(string.Empty, (buff, arg) => $"{buff} /r:{arg}")); + + if (options.Resources != null && options.Resources.Length > 0) + builder.Append(options.Resources.Aggregate(string.Empty, (buff, arg) => $"{buff} /res:{arg}")); + + if (options.AdditionalArguments != null && options.AdditionalArguments.Length > 0) + builder.Append(options.AdditionalArguments.Aggregate(string.Empty, (buff, arg) => $"{buff} {arg}")); + + builder.Append(options.SourceFiles.Aggregate(string.Empty, (buff, arg) => $"{buff} {arg}")); + + return builder.ToString(); + } + + protected NPath CompileCSharpAssembly(CompilerOptions options) + { + if (string.IsNullOrEmpty(options.CompilerToUse)) + return CompileCSharpAssemblyWithDefaultCompiler(options); + + if (options.CompilerToUse == "csc") + return CompileCSharpAssemblyWithCsc(options); + + if (options.CompilerToUse == "mcs") + return CompileCSharpAssemblyWithMcs(options); + + throw new ArgumentException($"Invalid compiler value `{options.CompilerToUse}`"); + } + + protected NPath CompileIlAssembly(CompilerOptions options) + { + return _ilCompiler.Compile(options); + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseLinkerOptions.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseLinkerOptions.cs index 29d34834129e5c..bfb43fb162fcde 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseLinkerOptions.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseLinkerOptions.cs @@ -7,32 +7,32 @@ namespace Mono.Linker.Tests.TestCasesRunner { - public class TestCaseLinkerOptions - { - public string TrimMode; - public string DefaultAssembliesAction; - public List<(string Action, string Assembly)> AssembliesAction = new(); - - public string Il8n; - public bool IgnoreDescriptors; - public bool IgnoreSubstitutions; - public bool IgnoreLinkAttributes; - public string KeepTypeForwarderOnlyAssemblies; - public string LinkSymbols; - public bool SkipUnresolved; - public bool StripDescriptors; - public bool StripSubstitutions; - public bool StripLinkAttributes; - public bool DumpDependencies; - - public bool IlcFrameworkCompilation; - - public List> AdditionalArguments = new List> (); - - public List Descriptors = new List (); - - public List Substitutions = new List (); - - public List LinkAttributes = new List (); - } + public class TestCaseLinkerOptions + { + public string TrimMode; + public string DefaultAssembliesAction; + public List<(string Action, string Assembly)> AssembliesAction = new(); + + public string Il8n; + public bool IgnoreDescriptors; + public bool IgnoreSubstitutions; + public bool IgnoreLinkAttributes; + public string KeepTypeForwarderOnlyAssemblies; + public string LinkSymbols; + public bool SkipUnresolved; + public bool StripDescriptors; + public bool StripSubstitutions; + public bool StripLinkAttributes; + public bool DumpDependencies; + + public bool IlcFrameworkCompilation; + + public List> AdditionalArguments = new List>(); + + public List Descriptors = new List(); + + public List Substitutions = new List(); + + public List LinkAttributes = new List(); + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseMetadataProvider.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseMetadataProvider.cs index a6c6a9543d6e13..15bbb2ac3d1f5a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseMetadataProvider.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseMetadataProvider.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -8,141 +9,149 @@ using Mono.Linker.Tests.Cases.Expectations.Metadata; using Mono.Linker.Tests.Extensions; using Mono.Linker.Tests.TestCases; -using System; namespace Mono.Linker.Tests.TestCasesRunner { - public class TestCaseMetadataProvider : BaseMetadataProvider - { - public TestCaseMetadataProvider (TestCase testCase, AssemblyDefinition fullTestCaseAssemblyDefinition) - : base (testCase, fullTestCaseAssemblyDefinition) - { - } - - public virtual TestCaseLinkerOptions GetLinkerOptions (NPath inputPath) - { - var tclo = new TestCaseLinkerOptions { - Il8n = GetOptionAttributeValue (nameof (Il8nAttribute), "none"), - IgnoreDescriptors = GetOptionAttributeValue (nameof (IgnoreDescriptorsAttribute), true), - IgnoreSubstitutions = GetOptionAttributeValue (nameof (IgnoreSubstitutionsAttribute), true), - IgnoreLinkAttributes = GetOptionAttributeValue (nameof (IgnoreLinkAttributesAttribute), true), - KeepTypeForwarderOnlyAssemblies = GetOptionAttributeValue (nameof (KeepTypeForwarderOnlyAssembliesAttribute), string.Empty), - LinkSymbols = GetOptionAttributeValue (nameof (SetupLinkerLinkSymbolsAttribute), string.Empty), - TrimMode = GetOptionAttributeValue (nameof (SetupLinkerTrimModeAttribute), null), - DefaultAssembliesAction = GetOptionAttributeValue (nameof (SetupLinkerDefaultActionAttribute), null), - SkipUnresolved = GetOptionAttributeValue (nameof (SkipUnresolvedAttribute), false), - StripDescriptors = GetOptionAttributeValue (nameof (StripDescriptorsAttribute), true), - StripSubstitutions = GetOptionAttributeValue (nameof (StripSubstitutionsAttribute), true), - StripLinkAttributes = GetOptionAttributeValue (nameof (StripLinkAttributesAttribute), true), - DumpDependencies = GetOptionAttribute (nameof (DumpDependenciesAttribute)), - IlcFrameworkCompilation = _testCaseTypeDefinition.HasAttribute (nameof (SetupIlcWholeProgramAnalysisAttribute)), - }; - - foreach (var assemblyAction in _testCaseTypeDefinition.CustomAttributes.Where (attr => attr.AttributeType.Name == nameof (SetupLinkerActionAttribute))) { - var ca = assemblyAction.ConstructorArguments; - tclo.AssembliesAction.Add (((string) ca[0].Value, (string) ca[1].Value)); - } - - foreach (var descFile in _testCaseTypeDefinition.CustomAttributes.Where (attr => attr.AttributeType.Name == nameof (SetupLinkerDescriptorFile))) { - var ca = descFile.ConstructorArguments; - var file = (string) ca[0].Value; - tclo.Descriptors.Add (Path.Combine (inputPath, file)); - } - - foreach (var subsFile in _testCaseTypeDefinition.CustomAttributes.Where (attr => attr.AttributeType.Name == nameof (SetupLinkerSubstitutionFileAttribute))) { - var ca = subsFile.ConstructorArguments; - var file = (string) ca[0].Value; - tclo.Substitutions.Add (Path.Combine (inputPath, file)); - } - - foreach (var linkAttrFile in _testCaseTypeDefinition.CustomAttributes.Where (attr => attr.AttributeType.Name == nameof (SetupLinkAttributesFile))) { - var ca = linkAttrFile.ConstructorArguments; - var file = (string) ca[0].Value; - tclo.LinkAttributes.Add (Path.Combine (inputPath, file)); - } - - foreach (var additionalArgumentAttr in _testCaseTypeDefinition.CustomAttributes.Where (attr => attr.AttributeType.Name == nameof (SetupLinkerArgumentAttribute))) { - var ca = additionalArgumentAttr.ConstructorArguments; - var values = ((CustomAttributeArgument[]) ca[1].Value)!.Select (arg => arg.Value.ToString ()!).ToArray (); - // Since custom attribute arguments need to be constant expressions, we need to add - // the path to the temp directory (where the custom assembly is located) here. - switch ((string) ca[0].Value) { - case "--custom-step": - int pos = values[0].IndexOf (","); - if (pos != -1) { - string custom_assembly_path = values[0].Substring (pos + 1); - if (!Path.IsPathRooted (custom_assembly_path)) - values[0] = string.Concat (values[0].AsSpan (0, pos + 1), Path.Combine (inputPath, custom_assembly_path)); - } - break; - case "-a": - if (!Path.IsPathRooted (values[0])) - values[0] = Path.Combine (inputPath, values[0]); - - break; - } - - tclo.AdditionalArguments.Add (new KeyValuePair ((string) ca[0].Value, values)); - } - - return tclo; - } - - public virtual IEnumerable GetResponseFiles () - { - return _testCaseTypeDefinition.CustomAttributes - .Where (attr => attr.AttributeType.Name == nameof (SetupLinkerResponseFileAttribute)) - .Select (GetSourceAndRelativeDestinationValue); - } - - public virtual IEnumerable GetDescriptorFiles () - { - return _testCaseTypeDefinition.CustomAttributes - .Where (attr => attr.AttributeType.Name == nameof (SetupLinkerDescriptorFile)) - .Select (GetSourceAndRelativeDestinationValue); - } - - public virtual IEnumerable GetSubstitutionFiles () - { - return _testCaseTypeDefinition.CustomAttributes - .Where (attr => attr.AttributeType.Name == nameof (SetupLinkerSubstitutionFileAttribute)) - .Select (GetSourceAndRelativeDestinationValue); - } - - public virtual IEnumerable GetLinkAttributesFiles () - { - return _testCaseTypeDefinition.CustomAttributes - .Where (attr => attr.AttributeType.Name == nameof (SetupLinkAttributesFile)) - .Select (GetSourceAndRelativeDestinationValue); - } - - public IEnumerable GetDeleteBefore () - { - return _testCaseTypeDefinition.CustomAttributes - .Where (attr => attr.AttributeType.Name == nameof (DeleteBeforeAttribute)) - .Select (attr => (string)attr.ConstructorArguments[0].Value); - } - - public virtual IEnumerable GetExtraLinkerReferences () - { - var netcoreappDir = Path.GetDirectoryName (typeof (object).Assembly.Location)!; - foreach (var assembly in Directory.EnumerateFiles (netcoreappDir)) { - if (Path.GetExtension (assembly) != ".dll") - continue; - var assemblyName = Path.GetFileNameWithoutExtension (assembly); - if (assemblyName.Contains ("Native")) - continue; - if (assemblyName.StartsWith ("Microsoft") || - assemblyName.StartsWith ("System") || - assemblyName == "mscorlib" || assemblyName == "netstandard") - yield return assembly.ToNPath (); - } - } - - public virtual bool LinkPublicAndFamily () - { - return _testCaseTypeDefinition.CustomAttributes - .FirstOrDefault (attr => attr.AttributeType.Name == nameof (SetupLinkerLinkPublicAndFamilyAttribute)) != null; - } - } + public class TestCaseMetadataProvider : BaseMetadataProvider + { + public TestCaseMetadataProvider(TestCase testCase, AssemblyDefinition fullTestCaseAssemblyDefinition) + : base(testCase, fullTestCaseAssemblyDefinition) + { + } + + public virtual TestCaseLinkerOptions GetLinkerOptions(NPath inputPath) + { + var tclo = new TestCaseLinkerOptions + { + Il8n = GetOptionAttributeValue(nameof(Il8nAttribute), "none"), + IgnoreDescriptors = GetOptionAttributeValue(nameof(IgnoreDescriptorsAttribute), true), + IgnoreSubstitutions = GetOptionAttributeValue(nameof(IgnoreSubstitutionsAttribute), true), + IgnoreLinkAttributes = GetOptionAttributeValue(nameof(IgnoreLinkAttributesAttribute), true), + KeepTypeForwarderOnlyAssemblies = GetOptionAttributeValue(nameof(KeepTypeForwarderOnlyAssembliesAttribute), string.Empty), + LinkSymbols = GetOptionAttributeValue(nameof(SetupLinkerLinkSymbolsAttribute), string.Empty), + TrimMode = GetOptionAttributeValue(nameof(SetupLinkerTrimModeAttribute), null), + DefaultAssembliesAction = GetOptionAttributeValue(nameof(SetupLinkerDefaultActionAttribute), null), + SkipUnresolved = GetOptionAttributeValue(nameof(SkipUnresolvedAttribute), false), + StripDescriptors = GetOptionAttributeValue(nameof(StripDescriptorsAttribute), true), + StripSubstitutions = GetOptionAttributeValue(nameof(StripSubstitutionsAttribute), true), + StripLinkAttributes = GetOptionAttributeValue(nameof(StripLinkAttributesAttribute), true), + DumpDependencies = GetOptionAttribute(nameof(DumpDependenciesAttribute)), + IlcFrameworkCompilation = _testCaseTypeDefinition.HasAttribute(nameof(SetupIlcWholeProgramAnalysisAttribute)), + }; + + foreach (var assemblyAction in _testCaseTypeDefinition.CustomAttributes.Where(attr => attr.AttributeType.Name == nameof(SetupLinkerActionAttribute))) + { + var ca = assemblyAction.ConstructorArguments; + tclo.AssembliesAction.Add(((string)ca[0].Value, (string)ca[1].Value)); + } + + foreach (var descFile in _testCaseTypeDefinition.CustomAttributes.Where(attr => attr.AttributeType.Name == nameof(SetupLinkerDescriptorFile))) + { + var ca = descFile.ConstructorArguments; + var file = (string)ca[0].Value; + tclo.Descriptors.Add(Path.Combine(inputPath, file)); + } + + foreach (var subsFile in _testCaseTypeDefinition.CustomAttributes.Where(attr => attr.AttributeType.Name == nameof(SetupLinkerSubstitutionFileAttribute))) + { + var ca = subsFile.ConstructorArguments; + var file = (string)ca[0].Value; + tclo.Substitutions.Add(Path.Combine(inputPath, file)); + } + + foreach (var linkAttrFile in _testCaseTypeDefinition.CustomAttributes.Where(attr => attr.AttributeType.Name == nameof(SetupLinkAttributesFile))) + { + var ca = linkAttrFile.ConstructorArguments; + var file = (string)ca[0].Value; + tclo.LinkAttributes.Add(Path.Combine(inputPath, file)); + } + + foreach (var additionalArgumentAttr in _testCaseTypeDefinition.CustomAttributes.Where(attr => attr.AttributeType.Name == nameof(SetupLinkerArgumentAttribute))) + { + var ca = additionalArgumentAttr.ConstructorArguments; + var values = ((CustomAttributeArgument[])ca[1].Value)!.Select(arg => arg.Value.ToString()!).ToArray(); + // Since custom attribute arguments need to be constant expressions, we need to add + // the path to the temp directory (where the custom assembly is located) here. + switch ((string)ca[0].Value) + { + case "--custom-step": + int pos = values[0].IndexOf(","); + if (pos != -1) + { + string custom_assembly_path = values[0].Substring(pos + 1); + if (!Path.IsPathRooted(custom_assembly_path)) + values[0] = string.Concat(values[0].AsSpan(0, pos + 1), Path.Combine(inputPath, custom_assembly_path)); + } + break; + case "-a": + if (!Path.IsPathRooted(values[0])) + values[0] = Path.Combine(inputPath, values[0]); + + break; + } + + tclo.AdditionalArguments.Add(new KeyValuePair((string)ca[0].Value, values)); + } + + return tclo; + } + + public virtual IEnumerable GetResponseFiles() + { + return _testCaseTypeDefinition.CustomAttributes + .Where(attr => attr.AttributeType.Name == nameof(SetupLinkerResponseFileAttribute)) + .Select(GetSourceAndRelativeDestinationValue); + } + + public virtual IEnumerable GetDescriptorFiles() + { + return _testCaseTypeDefinition.CustomAttributes + .Where(attr => attr.AttributeType.Name == nameof(SetupLinkerDescriptorFile)) + .Select(GetSourceAndRelativeDestinationValue); + } + + public virtual IEnumerable GetSubstitutionFiles() + { + return _testCaseTypeDefinition.CustomAttributes + .Where(attr => attr.AttributeType.Name == nameof(SetupLinkerSubstitutionFileAttribute)) + .Select(GetSourceAndRelativeDestinationValue); + } + + public virtual IEnumerable GetLinkAttributesFiles() + { + return _testCaseTypeDefinition.CustomAttributes + .Where(attr => attr.AttributeType.Name == nameof(SetupLinkAttributesFile)) + .Select(GetSourceAndRelativeDestinationValue); + } + + public IEnumerable GetDeleteBefore() + { + return _testCaseTypeDefinition.CustomAttributes + .Where(attr => attr.AttributeType.Name == nameof(DeleteBeforeAttribute)) + .Select(attr => (string)attr.ConstructorArguments[0].Value); + } + + public virtual IEnumerable GetExtraLinkerReferences() + { + var netcoreappDir = Path.GetDirectoryName(typeof(object).Assembly.Location)!; + foreach (var assembly in Directory.EnumerateFiles(netcoreappDir)) + { + if (Path.GetExtension(assembly) != ".dll") + continue; + var assemblyName = Path.GetFileNameWithoutExtension(assembly); + if (assemblyName.Contains("Native")) + continue; + if (assemblyName.StartsWith("Microsoft") || + assemblyName.StartsWith("System") || + assemblyName == "mscorlib" || assemblyName == "netstandard") + yield return assembly.ToNPath(); + } + } + + public virtual bool LinkPublicAndFamily() + { + return _testCaseTypeDefinition.CustomAttributes + .FirstOrDefault(attr => attr.AttributeType.Name == nameof(SetupLinkerLinkPublicAndFamilyAttribute)) != null; + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseSandbox.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseSandbox.cs index c3cd3fbcd3b3ae..13e696a879c4e0 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseSandbox.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseSandbox.cs @@ -10,17 +10,17 @@ namespace Mono.Linker.Tests.TestCasesRunner { - partial class TestCaseSandbox - { - private const string _linkerAssemblyPath = "";//typeof (Trimmer).Assembly.Location; + partial class TestCaseSandbox + { + private const string _linkerAssemblyPath = "";//typeof (Trimmer).Assembly.Location; - private static partial NPath GetArtifactsTestPath () - { - // Converts paths like /root-folder/runtime/artifacts/bin/Mono.Linker.Tests/x64/Debug/Mono.Linker.Tests.dll - // to /root-folder/runtime/artifacts/bin/ILLink.testcases/ - string artifacts = (string) AppContext.GetData ("Mono.Linker.Tests.ArtifactsBinDir")!; - string tests = Path.Combine (artifacts, "ILLink.testcases"); - return new NPath (tests); - } - } + private static partial NPath GetArtifactsTestPath() + { + // Converts paths like /root-folder/runtime/artifacts/bin/Mono.Linker.Tests/x64/Debug/Mono.Linker.Tests.dll + // to /root-folder/runtime/artifacts/bin/ILLink.testcases/ + string artifacts = (string)AppContext.GetData("Mono.Linker.Tests.ArtifactsBinDir")!; + string tests = Path.Combine(artifacts, "ILLink.testcases"); + return new NPath(tests); + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestInfraMultiFileCompilationModuleGroup.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestInfraMultiFileCompilationModuleGroup.cs index b8c44ab2b35568..33d76b172f8772 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestInfraMultiFileCompilationModuleGroup.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestInfraMultiFileCompilationModuleGroup.cs @@ -10,50 +10,51 @@ namespace Mono.Linker.Tests.TestCasesRunner { - /// - /// Represents a non-leaf multifile compilation group where types contained in the group are always fully expanded. - /// - public class TestInfraMultiFileSharedCompilationModuleGroup : MultiFileCompilationModuleGroup - { - public TestInfraMultiFileSharedCompilationModuleGroup (CompilerTypeSystemContext context, IEnumerable compilationModuleSet) - : base (context, compilationModuleSet) - { - } - - public override bool ShouldProduceFullVTable (TypeDesc type) - { - return false; - } - - public override bool ShouldPromoteToFullType (TypeDesc type) - { - return ShouldProduceFullVTable (type); - } - - public override bool PresenceOfEETypeImpliesAllMethodsOnType (TypeDesc type) - { - return (type.HasInstantiation || type.IsArray) && ShouldProduceFullVTable (type) && - type.ConvertToCanonForm (CanonicalFormKind.Specific).IsCanonicalSubtype (CanonicalFormKind.Any); - } - - public override bool AllowInstanceMethodOptimization (MethodDesc method) - { - // Both the instance methods and the owning type are homed in a single compilation group - // so if we're able to generate the body, we would also generate the owning type here - // and nowhere else. - if (ContainsMethodBody (method, unboxingStub: false)) { - TypeDesc owningType = method.OwningType; - return owningType.IsDefType && !owningType.HasInstantiation && !method.HasInstantiation; - } - return false; - } - - public override bool AllowVirtualMethodOnAbstractTypeOptimization (MethodDesc method) - { - // Not really safe to do this since we need to assume IgnoreAccessChecks - // and we wouldn't know all derived types when compiling methods on the type - // that introduces this method. - return false; - } - } + /// + /// Represents a non-leaf multifile compilation group where types contained in the group are always fully expanded. + /// + public class TestInfraMultiFileSharedCompilationModuleGroup : MultiFileCompilationModuleGroup + { + public TestInfraMultiFileSharedCompilationModuleGroup(CompilerTypeSystemContext context, IEnumerable compilationModuleSet) + : base(context, compilationModuleSet) + { + } + + public override bool ShouldProduceFullVTable(TypeDesc type) + { + return false; + } + + public override bool ShouldPromoteToFullType(TypeDesc type) + { + return ShouldProduceFullVTable(type); + } + + public override bool PresenceOfEETypeImpliesAllMethodsOnType(TypeDesc type) + { + return (type.HasInstantiation || type.IsArray) && ShouldProduceFullVTable(type) && + type.ConvertToCanonForm(CanonicalFormKind.Specific).IsCanonicalSubtype(CanonicalFormKind.Any); + } + + public override bool AllowInstanceMethodOptimization(MethodDesc method) + { + // Both the instance methods and the owning type are homed in a single compilation group + // so if we're able to generate the body, we would also generate the owning type here + // and nowhere else. + if (ContainsMethodBody(method, unboxingStub: false)) + { + TypeDesc owningType = method.OwningType; + return owningType.IsDefType && !owningType.HasInstantiation && !method.HasInstantiation; + } + return false; + } + + public override bool AllowVirtualMethodOnAbstractTypeOptimization(MethodDesc method) + { + // Not really safe to do this since we need to assume IgnoreAccessChecks + // and we wouldn't know all derived types when compiling methods on the type + // that introduces this method. + return false; + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestRunner.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestRunner.cs index 6be7c7ed5c0b0f..97bcdf2d79f735 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestRunner.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestRunner.cs @@ -12,48 +12,52 @@ namespace Mono.Linker.Tests.TestCasesRunner { - public partial class TestRunner - { - partial void IgnoreTest (string reason) - { - throw new IgnoreTestException (reason); - } - - static IEnumerable additionalDefines = new string[] { "NATIVEAOT" }; - private partial IEnumerable? GetAdditionalDefines () => additionalDefines; - - private static T GetResultOfTaskThatMakesAssertions (Task task) - { - try { - return task.Result; - } catch (AggregateException e) { - if (e.InnerException != null) { - if (e.InnerException is XunitException) - throw e.InnerException; - } - - throw; - } - } - - protected partial TrimmingCustomizations? CustomizeTrimming (TrimmingDriver linker, TestCaseMetadataProvider metadataProvider) - => null; - - protected partial void AddDumpDependenciesOptions (TestCaseLinkerOptions caseDefinedOptions, ManagedCompilationResult compilationResult, TrimmingArgumentBuilder builder, TestCaseMetadataProvider metadataProvider) - { - } - - static partial void AddOutputDirectory (TestCaseSandbox sandbox, ManagedCompilationResult compilationResult, TrimmingArgumentBuilder builder) - { - builder.AddOutputDirectory (sandbox.OutputDirectory.Combine (compilationResult.InputAssemblyPath.FileNameWithoutExtension + ".obj")); - } - - static partial void AddInputReference (NPath inputReference, TrimmingArgumentBuilder builder) - { - // It's important to add all assemblies as "link" assemblies since the default configuration - // is to run the compiler in multi-file mode which will not process anything which is just in the reference set. - builder.AddLinkAssembly (inputReference); - builder.AddReference (inputReference); - } - } + public partial class TestRunner + { + partial void IgnoreTest(string reason) + { + throw new IgnoreTestException(reason); + } + + static IEnumerable additionalDefines = new string[] { "NATIVEAOT" }; + private partial IEnumerable? GetAdditionalDefines() => additionalDefines; + + private static T GetResultOfTaskThatMakesAssertions(Task task) + { + try + { + return task.Result; + } + catch (AggregateException e) + { + if (e.InnerException != null) + { + if (e.InnerException is XunitException) + throw e.InnerException; + } + + throw; + } + } + + protected partial TrimmingCustomizations? CustomizeTrimming(TrimmingDriver linker, TestCaseMetadataProvider metadataProvider) + => null; + + protected partial void AddDumpDependenciesOptions(TestCaseLinkerOptions caseDefinedOptions, ManagedCompilationResult compilationResult, TrimmingArgumentBuilder builder, TestCaseMetadataProvider metadataProvider) + { + } + + static partial void AddOutputDirectory(TestCaseSandbox sandbox, ManagedCompilationResult compilationResult, TrimmingArgumentBuilder builder) + { + builder.AddOutputDirectory(sandbox.OutputDirectory.Combine(compilationResult.InputAssemblyPath.FileNameWithoutExtension + ".obj")); + } + + static partial void AddInputReference(NPath inputReference, TrimmingArgumentBuilder builder) + { + // It's important to add all assemblies as "link" assemblies since the default configuration + // is to run the compiler in multi-file mode which will not process anything which is just in the reference set. + builder.AddLinkAssembly(inputReference); + builder.AddReference(inputReference); + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmedTestCaseResult.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmedTestCaseResult.cs index ed54092b7005b9..2a83391df3ec01 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmedTestCaseResult.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmedTestCaseResult.cs @@ -7,32 +7,32 @@ namespace Mono.Linker.Tests.TestCasesRunner { - partial class TrimmedTestCaseResult - { - public readonly ILScanResults TrimmingResults; + partial class TrimmedTestCaseResult + { + public readonly ILScanResults TrimmingResults; - public TrimmedTestCaseResult ( - TestCase testCase, - NPath inputAssemblyPath, - NPath outputAssemblyPath, - NPath expectationsAssemblyPath, - TestCaseSandbox sandbox, - TestCaseMetadataProvider metadataProvider, - ManagedCompilationResult compilationResult, - TrimmingTestLogger logger, - TrimmingCustomizations? customizations, - ILScanResults trimmingResults) - { - // Ignore outputAssemblyPath because ILCompiler trimming tests don't write output assemblies. - // Ignore TrimmingCustomizatoins which are not used by ILCompiler trimming tests. - TestCase = testCase; - InputAssemblyPath = inputAssemblyPath; - ExpectationsAssemblyPath = expectationsAssemblyPath; - Sandbox = sandbox; - MetadataProvider = metadataProvider; - CompilationResult = compilationResult; - Logger = logger; - TrimmingResults = trimmingResults; - } - } + public TrimmedTestCaseResult( + TestCase testCase, + NPath inputAssemblyPath, + NPath outputAssemblyPath, + NPath expectationsAssemblyPath, + TestCaseSandbox sandbox, + TestCaseMetadataProvider metadataProvider, + ManagedCompilationResult compilationResult, + TrimmingTestLogger logger, + TrimmingCustomizations? customizations, + ILScanResults trimmingResults) + { + // Ignore outputAssemblyPath because ILCompiler trimming tests don't write output assemblies. + // Ignore TrimmingCustomizatoins which are not used by ILCompiler trimming tests. + TestCase = testCase; + InputAssemblyPath = inputAssemblyPath; + ExpectationsAssemblyPath = expectationsAssemblyPath; + Sandbox = sandbox; + MetadataProvider = metadataProvider; + CompilationResult = compilationResult; + Logger = logger; + TrimmingResults = trimmingResults; + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingArgumentBuilder.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingArgumentBuilder.cs index e108cced4bde5a..8bd67f51877520 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingArgumentBuilder.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingArgumentBuilder.cs @@ -9,312 +9,323 @@ namespace Mono.Linker.Tests.TestCasesRunner { - public class TrimmingArgumentBuilder - { - private readonly TestCaseMetadataProvider _metadataProvider; - - private ILCompilerOptions? _options; - private ILCompilerOptions Options => _options ?? throw new InvalidOperationException ("Invalid state: Build() was already called"); - - public TrimmingArgumentBuilder (TestCaseMetadataProvider metadataProvider) - { - _options = new ILCompilerOptions (); - _metadataProvider = metadataProvider; - - string runtimeBinDir = (string) AppContext.GetData ("Mono.Linker.Tests.RuntimeBinDirectory")!; - AppendExpandedPaths (Options.ReferenceFilePaths, Path.Combine (runtimeBinDir, "aotsdk", "*.dll")); - - string runtimePackDir = (string) AppContext.GetData ("Mono.Linker.Tests.MicrosoftNetCoreAppRuntimePackDirectory")!; - if (!Directory.Exists (runtimePackDir) && runtimePackDir.Contains ("Debug")) { - // Frequently we'll have a Debug runtime and Release libraries, which actually produces a Release runtime pack - // but from within VS we're see Debug everything. So if the runtime pack directory doesn't exist - // try the Release path (simple string replace) - string candidate = runtimePackDir.Replace ("Debug", "Release"); - if (Directory.Exists (candidate)) - runtimePackDir = candidate; - } - AppendExpandedPaths (Options.ReferenceFilePaths, Path.Combine (runtimePackDir, "*.dll")); - - Options.InitAssemblies.Add ("System.Private.CoreLib"); - Options.InitAssemblies.Add ("System.Private.StackTraceMetadata"); - Options.InitAssemblies.Add ("System.Private.TypeLoader"); - Options.InitAssemblies.Add ("System.Private.Reflection.Execution"); - - Options.FeatureSwitches.Add ("System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization", false); - Options.FeatureSwitches.Add ("System.Resources.ResourceManager.AllowCustomResourceTypes", false); - Options.FeatureSwitches.Add ("System.Linq.Expressions.CanEmitObjectArrayDelegate", false); - Options.FeatureSwitches.Add ("System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported", false); - Options.FeatureSwitches.Add ("System.Diagnostics.Debugger.IsSupported", false); - Options.FeatureSwitches.Add ("System.Text.Encoding.EnableUnsafeUTF7Encoding", false); - Options.FeatureSwitches.Add ("System.Diagnostics.Tracing.EventSource.IsSupported", false); - Options.FeatureSwitches.Add ("System.Globalization.Invariant", true); - Options.FeatureSwitches.Add ("System.Resources.UseSystemResourceKeys", true); - - Options.FrameworkCompilation = false; - } - - public virtual void AddSearchDirectory (NPath directory) - { - } - - public virtual void AddReference (NPath path) - { - AppendExpandedPaths (Options.ReferenceFilePaths, path.ToString ()); - } - - public virtual void AddOutputDirectory (NPath directory) - { - } - - public virtual void AddLinkXmlFile (string file) - { - Options.Descriptors.Add (file); - } - - public virtual void AddResponseFile (NPath path) - { - } - - public virtual void AddTrimMode (string value) - { - } - - public virtual void AddDefaultAction (string value) - { - } - - public virtual void AddLinkAssembly (string fileName) - { - Options.TrimAssemblies.Add (Path.GetFileNameWithoutExtension(fileName)); - } - - public virtual void LinkFromAssembly (string fileName) - { - AppendExpandedPaths (Options.InputFilePaths, fileName); - } - - public virtual void LinkFromPublicAndFamily (string fileName) - { - } - - public virtual void IgnoreDescriptors (bool value) - { - } - - public virtual void IgnoreSubstitutions (bool value) - { - } - - public virtual void IgnoreLinkAttributes (bool value) - { - } - - public virtual void AddIl8n (string value) - { - } - - public virtual void AddKeepTypeForwarderOnlyAssemblies (string value) - { - } - - public virtual void AddLinkSymbols (string value) - { - } - - public virtual void AddAssemblyAction (string action, string assembly) - { - switch (action) { - case "copy": - Options.AdditionalRootAssemblies.Add (assembly); - break; - } - } - - public virtual void AddSkipUnresolved (bool skipUnresolved) - { - } - - public virtual void AddStripDescriptors (bool stripDescriptors) - { - } - - public virtual void AddStripSubstitutions (bool stripSubstitutions) - { - } - - public virtual void AddStripLinkAttributes (bool stripLinkAttributes) - { - } - - public virtual void AddSubstitutions (string file) - { - Options.SubstitutionFiles.Add (file); - } - - public virtual void AddLinkAttributes (string file) - { - } - - public virtual void AddAdditionalArgument (string flag, string[] values) - { - if (flag == "--feature") { - Options.FeatureSwitches.Add (values[0], bool.Parse (values[1])); - } - else if (flag == "--singlewarn") { - Options.SingleWarn = true; - } - else if (flag.StartsWith("--warnaserror")) - { - if (flag == "--warnaserror" || flag == "--warnaserror+") - { - if (values.Length == 0) - Options.TreatWarningsAsErrors = true; - else - { - foreach (int warning in ProcessWarningCodes(values)) - Options.WarningsAsErrors[warning] = true; - } - - } - else if (flag == "--warnaserror-") - { - if (values.Length == 0) - Options.TreatWarningsAsErrors = false; - else - { - foreach (int warning in ProcessWarningCodes(values)) - Options.WarningsAsErrors[warning] = false; - } - } - } - else if (flag == "--notrimwarn") { - Options.SuppressedWarningCategories.Add(MessageSubCategory.TrimAnalysis); - } - else if (flag == "--noaotwarn") { - Options.SuppressedWarningCategories.Add(MessageSubCategory.AotAnalysis); - } - } - - public virtual void ProcessTestInputAssembly (NPath inputAssemblyPath) - { - if (_metadataProvider.LinkPublicAndFamily ()) - LinkFromPublicAndFamily (inputAssemblyPath.ToString ()); - else - LinkFromAssembly (inputAssemblyPath.ToString ()); - } - - public virtual void ProcessOptions (TestCaseLinkerOptions options) - { - if (options.TrimMode != null) - AddTrimMode (options.TrimMode); - - if (options.DefaultAssembliesAction != null) - AddDefaultAction (options.DefaultAssembliesAction); - - if (options.AssembliesAction != null) { - foreach (var (action, assembly) in options.AssembliesAction) - AddAssemblyAction (action, assembly); - } - - // Honoring descriptors causes a ton of stuff to be preserved. That's good for normal use cases, but for - // our test cases that pollutes the results - IgnoreDescriptors (options.IgnoreDescriptors); - - IgnoreSubstitutions (options.IgnoreSubstitutions); - - IgnoreLinkAttributes (options.IgnoreLinkAttributes); + public class TrimmingArgumentBuilder + { + private readonly TestCaseMetadataProvider _metadataProvider; + + private ILCompilerOptions? _options; + private ILCompilerOptions Options => _options ?? throw new InvalidOperationException("Invalid state: Build() was already called"); + + public TrimmingArgumentBuilder(TestCaseMetadataProvider metadataProvider) + { + _options = new ILCompilerOptions(); + _metadataProvider = metadataProvider; + + string runtimeBinDir = (string)AppContext.GetData("Mono.Linker.Tests.RuntimeBinDirectory")!; + AppendExpandedPaths(Options.ReferenceFilePaths, Path.Combine(runtimeBinDir, "aotsdk", "*.dll")); + + string runtimePackDir = (string)AppContext.GetData("Mono.Linker.Tests.MicrosoftNetCoreAppRuntimePackDirectory")!; + if (!Directory.Exists(runtimePackDir) && runtimePackDir.Contains("Debug")) + { + // Frequently we'll have a Debug runtime and Release libraries, which actually produces a Release runtime pack + // but from within VS we're see Debug everything. So if the runtime pack directory doesn't exist + // try the Release path (simple string replace) + string candidate = runtimePackDir.Replace("Debug", "Release"); + if (Directory.Exists(candidate)) + runtimePackDir = candidate; + } + AppendExpandedPaths(Options.ReferenceFilePaths, Path.Combine(runtimePackDir, "*.dll")); + + Options.InitAssemblies.Add("System.Private.CoreLib"); + Options.InitAssemblies.Add("System.Private.StackTraceMetadata"); + Options.InitAssemblies.Add("System.Private.TypeLoader"); + Options.InitAssemblies.Add("System.Private.Reflection.Execution"); + + Options.FeatureSwitches.Add("System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization", false); + Options.FeatureSwitches.Add("System.Resources.ResourceManager.AllowCustomResourceTypes", false); + Options.FeatureSwitches.Add("System.Linq.Expressions.CanEmitObjectArrayDelegate", false); + Options.FeatureSwitches.Add("System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported", false); + Options.FeatureSwitches.Add("System.Diagnostics.Debugger.IsSupported", false); + Options.FeatureSwitches.Add("System.Text.Encoding.EnableUnsafeUTF7Encoding", false); + Options.FeatureSwitches.Add("System.Diagnostics.Tracing.EventSource.IsSupported", false); + Options.FeatureSwitches.Add("System.Globalization.Invariant", true); + Options.FeatureSwitches.Add("System.Resources.UseSystemResourceKeys", true); + + Options.FrameworkCompilation = false; + } + + public virtual void AddSearchDirectory(NPath directory) + { + } + + public virtual void AddReference(NPath path) + { + AppendExpandedPaths(Options.ReferenceFilePaths, path.ToString()); + } + + public virtual void AddOutputDirectory(NPath directory) + { + } + + public virtual void AddLinkXmlFile(string file) + { + Options.Descriptors.Add(file); + } + + public virtual void AddResponseFile(NPath path) + { + } + + public virtual void AddTrimMode(string value) + { + } + + public virtual void AddDefaultAction(string value) + { + } + + public virtual void AddLinkAssembly(string fileName) + { + Options.TrimAssemblies.Add(Path.GetFileNameWithoutExtension(fileName)); + } + + public virtual void LinkFromAssembly(string fileName) + { + AppendExpandedPaths(Options.InputFilePaths, fileName); + } + + public virtual void LinkFromPublicAndFamily(string fileName) + { + } + + public virtual void IgnoreDescriptors(bool value) + { + } + + public virtual void IgnoreSubstitutions(bool value) + { + } + + public virtual void IgnoreLinkAttributes(bool value) + { + } + + public virtual void AddIl8n(string value) + { + } + + public virtual void AddKeepTypeForwarderOnlyAssemblies(string value) + { + } + + public virtual void AddLinkSymbols(string value) + { + } + + public virtual void AddAssemblyAction(string action, string assembly) + { + switch (action) + { + case "copy": + Options.AdditionalRootAssemblies.Add(assembly); + break; + } + } + + public virtual void AddSkipUnresolved(bool skipUnresolved) + { + } + + public virtual void AddStripDescriptors(bool stripDescriptors) + { + } + + public virtual void AddStripSubstitutions(bool stripSubstitutions) + { + } + + public virtual void AddStripLinkAttributes(bool stripLinkAttributes) + { + } + + public virtual void AddSubstitutions(string file) + { + Options.SubstitutionFiles.Add(file); + } + + public virtual void AddLinkAttributes(string file) + { + } + + public virtual void AddAdditionalArgument(string flag, string[] values) + { + if (flag == "--feature") + { + Options.FeatureSwitches.Add(values[0], bool.Parse(values[1])); + } + else if (flag == "--singlewarn") + { + Options.SingleWarn = true; + } + else if (flag.StartsWith("--warnaserror")) + { + if (flag == "--warnaserror" || flag == "--warnaserror+") + { + if (values.Length == 0) + Options.TreatWarningsAsErrors = true; + else + { + foreach (int warning in ProcessWarningCodes(values)) + Options.WarningsAsErrors[warning] = true; + } + + } + else if (flag == "--warnaserror-") + { + if (values.Length == 0) + Options.TreatWarningsAsErrors = false; + else + { + foreach (int warning in ProcessWarningCodes(values)) + Options.WarningsAsErrors[warning] = false; + } + } + } + else if (flag == "--notrimwarn") + { + Options.SuppressedWarningCategories.Add(MessageSubCategory.TrimAnalysis); + } + else if (flag == "--noaotwarn") + { + Options.SuppressedWarningCategories.Add(MessageSubCategory.AotAnalysis); + } + } + + public virtual void ProcessTestInputAssembly(NPath inputAssemblyPath) + { + if (_metadataProvider.LinkPublicAndFamily()) + LinkFromPublicAndFamily(inputAssemblyPath.ToString()); + else + LinkFromAssembly(inputAssemblyPath.ToString()); + } + + public virtual void ProcessOptions(TestCaseLinkerOptions options) + { + if (options.TrimMode != null) + AddTrimMode(options.TrimMode); + + if (options.DefaultAssembliesAction != null) + AddDefaultAction(options.DefaultAssembliesAction); + + if (options.AssembliesAction != null) + { + foreach (var (action, assembly) in options.AssembliesAction) + AddAssemblyAction(action, assembly); + } + + // Honoring descriptors causes a ton of stuff to be preserved. That's good for normal use cases, but for + // our test cases that pollutes the results + IgnoreDescriptors(options.IgnoreDescriptors); + + IgnoreSubstitutions(options.IgnoreSubstitutions); + + IgnoreLinkAttributes(options.IgnoreLinkAttributes); #if !NET - if (!string.IsNullOrEmpty (options.Il8n)) - AddIl8n (options.Il8n); + if (!string.IsNullOrEmpty (options.Il8n)) + AddIl8n (options.Il8n); #endif - if (!string.IsNullOrEmpty (options.KeepTypeForwarderOnlyAssemblies)) - AddKeepTypeForwarderOnlyAssemblies (options.KeepTypeForwarderOnlyAssemblies); + if (!string.IsNullOrEmpty(options.KeepTypeForwarderOnlyAssemblies)) + AddKeepTypeForwarderOnlyAssemblies(options.KeepTypeForwarderOnlyAssemblies); - if (!string.IsNullOrEmpty (options.LinkSymbols)) - AddLinkSymbols (options.LinkSymbols); + if (!string.IsNullOrEmpty(options.LinkSymbols)) + AddLinkSymbols(options.LinkSymbols); - AddSkipUnresolved (options.SkipUnresolved); + AddSkipUnresolved(options.SkipUnresolved); - AddStripDescriptors (options.StripDescriptors); + AddStripDescriptors(options.StripDescriptors); - AddStripSubstitutions (options.StripSubstitutions); + AddStripSubstitutions(options.StripSubstitutions); - AddStripLinkAttributes (options.StripLinkAttributes); + AddStripLinkAttributes(options.StripLinkAttributes); - foreach (var descriptor in options.Descriptors) - AddLinkXmlFile (descriptor); + foreach (var descriptor in options.Descriptors) + AddLinkXmlFile(descriptor); - foreach (var substitutions in options.Substitutions) - AddSubstitutions (substitutions); + foreach (var substitutions in options.Substitutions) + AddSubstitutions(substitutions); - foreach (var attributeDefinition in options.LinkAttributes) - AddLinkAttributes (attributeDefinition); + foreach (var attributeDefinition in options.LinkAttributes) + AddLinkAttributes(attributeDefinition); - // A list of expensive optimizations which should not run by default - AddAdditionalArgument ("--disable-opt", new[] { "ipconstprop" }); + // A list of expensive optimizations which should not run by default + AddAdditionalArgument("--disable-opt", new[] { "ipconstprop" }); - // Unity uses different argument format and needs to be able to translate to their format. In order to make that easier - // we keep the information in flag + values format for as long as we can so that this information doesn't have to be parsed out of a single string - foreach (var additionalArgument in options.AdditionalArguments) - AddAdditionalArgument (additionalArgument.Key, additionalArgument.Value); + // Unity uses different argument format and needs to be able to translate to their format. In order to make that easier + // we keep the information in flag + values format for as long as we can so that this information doesn't have to be parsed out of a single string + foreach (var additionalArgument in options.AdditionalArguments) + AddAdditionalArgument(additionalArgument.Key, additionalArgument.Value); - if (options.IlcFrameworkCompilation) - Options.FrameworkCompilation = true; - } + if (options.IlcFrameworkCompilation) + Options.FrameworkCompilation = true; + } - private static void AppendExpandedPaths (Dictionary dictionary, string pattern) - { - bool empty = true; + private static void AppendExpandedPaths(Dictionary dictionary, string pattern) + { + bool empty = true; - string directoryName = Path.GetDirectoryName (pattern)!; - string searchPattern = Path.GetFileName (pattern); + string directoryName = Path.GetDirectoryName(pattern)!; + string searchPattern = Path.GetFileName(pattern); - if (directoryName == "") - directoryName = "."; + if (directoryName == "") + directoryName = "."; - if (Directory.Exists (directoryName)) { - foreach (string fileName in Directory.EnumerateFiles (directoryName, searchPattern)) { - string fullFileName = Path.GetFullPath (fileName); + if (Directory.Exists(directoryName)) + { + foreach (string fileName in Directory.EnumerateFiles(directoryName, searchPattern)) + { + string fullFileName = Path.GetFullPath(fileName); - string simpleName = Path.GetFileNameWithoutExtension (fileName); + string simpleName = Path.GetFileNameWithoutExtension(fileName); - if (!dictionary.ContainsKey (simpleName)) { - dictionary.Add (simpleName, fullFileName); - } + if (!dictionary.ContainsKey(simpleName)) + { + dictionary.Add(simpleName, fullFileName); + } - empty = false; - } - } + empty = false; + } + } - if (empty) { - throw new Exception ("No files matching " + pattern); - } - } + if (empty) + { + throw new Exception("No files matching " + pattern); + } + } - private static readonly char[] s_separator = new char[] { ',', ';', ' ' }; + private static readonly char[] s_separator = new char[] { ',', ';', ' ' }; - private static IEnumerable ProcessWarningCodes(IEnumerable warningCodes) - { - foreach (string value in warningCodes) - { - string[] values = value.Split(s_separator, StringSplitOptions.RemoveEmptyEntries); - foreach (string id in values) - { - if (!id.StartsWith("IL", StringComparison.Ordinal) || !ushort.TryParse(id.AsSpan(2), out ushort code)) - continue; + private static IEnumerable ProcessWarningCodes(IEnumerable warningCodes) + { + foreach (string value in warningCodes) + { + string[] values = value.Split(s_separator, StringSplitOptions.RemoveEmptyEntries); + foreach (string id in values) + { + if (!id.StartsWith("IL", StringComparison.Ordinal) || !ushort.TryParse(id.AsSpan(2), out ushort code)) + continue; - yield return code; - } - } - } + yield return code; + } + } + } - public ILCompilerOptions Build () - { - var options = Options; - _options = null; - return options; - } - } + public ILCompilerOptions Build() + { + var options = Options; + _options = null; + return options; + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingCustomizations.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingCustomizations.cs index f6ef0009a701f2..edb5b1030bbc7b 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingCustomizations.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingCustomizations.cs @@ -5,7 +5,7 @@ namespace Mono.Linker.Tests.TestCasesRunner { - public class TrimmingCustomizations - { - } + public class TrimmingCustomizations + { + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingDriver.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingDriver.cs index a97f9638c5f8f0..ecf6dad1155a67 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingDriver.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingDriver.cs @@ -18,194 +18,202 @@ namespace Mono.Linker.Tests.TestCasesRunner { - public class TrimmingDriver - { - internal const string DefaultSystemModule = "System.Private.CoreLib"; - - public ILScanResults Trim (ILCompilerOptions options, TrimmingCustomizations? customizations, ILogWriter logWriter) - { - ComputeDefaultOptions (out var targetOS, out var targetArchitecture); - var targetDetails = new TargetDetails (targetArchitecture, targetOS, TargetAbi.NativeAot); - CompilerTypeSystemContext typeSystemContext = - new CompilerTypeSystemContext (targetDetails, SharedGenericsMode.CanonicalReferenceTypes, DelegateFeature.All, genericCycleDepthCutoff: -1); - - typeSystemContext.InputFilePaths = options.InputFilePaths; - typeSystemContext.ReferenceFilePaths = options.ReferenceFilePaths; - typeSystemContext.SetSystemModule (typeSystemContext.GetModuleForSimpleName (DefaultSystemModule)); - - List inputModules = new List (); - foreach (var inputFile in typeSystemContext.InputFilePaths) { - EcmaModule module = typeSystemContext.GetModuleFromPath (inputFile.Value); - inputModules.Add (module); - } - - foreach (var trimAssembly in options.TrimAssemblies) { - EcmaModule module = typeSystemContext.GetModuleForSimpleName (trimAssembly); - inputModules.Add (module); - } - - CompilationModuleGroup compilationGroup; - if (options.FrameworkCompilation) - compilationGroup = new SingleFileCompilationModuleGroup (); - else - compilationGroup = new TestInfraMultiFileSharedCompilationModuleGroup (typeSystemContext, inputModules); - - List compilationRoots = new List (); - EcmaModule? entrypointModule = null; - foreach (var inputFile in typeSystemContext.InputFilePaths) { - EcmaModule module = typeSystemContext.GetModuleFromPath (inputFile.Value); - - if (module.PEReader.PEHeaders.IsExe) { - if (entrypointModule != null) - throw new Exception ("Multiple EXE modules"); - entrypointModule = module; - } - - compilationRoots.Add (new UnmanagedEntryPointsRootProvider (module)); - } - - compilationRoots.Add (new MainMethodRootProvider (entrypointModule, CreateInitializerList (typeSystemContext, options), generateLibraryAndModuleInitializers: true)); - - foreach (var rootedAssembly in options.AdditionalRootAssemblies) { - EcmaModule module = typeSystemContext.GetModuleForSimpleName (rootedAssembly); - - // We only root the module type. The rest will fall out because we treat rootedAssemblies - // same as conditionally rooted ones and here we're fulfilling the condition ("something is used"). - compilationRoots.Add ( - new GenericRootProvider (module, - (ModuleDesc module, IRootingServiceProvider rooter) => rooter.AddReflectionRoot (module.GetGlobalModuleType (), "Command line root"))); - } - - ILProvider ilProvider = new NativeAotILProvider (); - - Logger logger = new Logger ( - logWriter, - ilProvider, - isVerbose: true, - suppressedWarnings: Enumerable.Empty (), - options.SingleWarn, - singleWarnEnabledModules: Enumerable.Empty (), - singleWarnDisabledModules: Enumerable.Empty (), - suppressedCategories: options.SuppressedWarningCategories, - treatWarningsAsErrors: options.TreatWarningsAsErrors, - warningsAsErrors: options.WarningsAsErrors); - - foreach (var descriptor in options.Descriptors) { - if (!File.Exists (descriptor)) - throw new FileNotFoundException ($"'{descriptor}' doesn't exist"); - compilationRoots.Add (new ILCompiler.DependencyAnalysis.TrimmingDescriptorNode (descriptor)); - } - - var featureSwitches = options.FeatureSwitches; - BodyAndFieldSubstitutions substitutions = default; - IReadOnlyDictionary>? resourceBlocks = default; - foreach (string substitutionFilePath in options.SubstitutionFiles) - { - using FileStream fs = File.OpenRead(substitutionFilePath); - substitutions.AppendFrom(BodySubstitutionsParser.GetSubstitutions( - logger, typeSystemContext, XmlReader.Create(fs), substitutionFilePath, featureSwitches)); - - fs.Seek(0, SeekOrigin.Begin); - - resourceBlocks = ManifestResourceBlockingPolicy.UnionBlockings(resourceBlocks, - ManifestResourceBlockingPolicy.SubstitutionsReader.GetSubstitutions( - logger, typeSystemContext, XmlReader.Create(fs), substitutionFilePath, featureSwitches)); - } - - SubstitutionProvider substitutionProvider = new SubstitutionProvider(logger, featureSwitches, substitutions); - ilProvider = new SubstitutedILProvider(ilProvider, substitutionProvider, new DevirtualizationManager()); - - CompilerGeneratedState compilerGeneratedState = new CompilerGeneratedState (ilProvider, logger); - - UsageBasedMetadataManager metadataManager = new UsageBasedMetadataManager( - compilationGroup, - typeSystemContext, - new NoMetadataBlockingPolicy(), - new ManifestResourceBlockingPolicy(logger, options.FeatureSwitches, new Dictionary>()), - logFile: null, - stackTracePolicy: new NoStackTraceEmissionPolicy(), - invokeThunkGenerationPolicy: new DefaultDynamicInvokeThunkGenerationPolicy(), - flowAnnotations: new FlowAnnotations(logger, ilProvider, compilerGeneratedState), - generationOptions: UsageBasedMetadataGenerationOptions.ReflectionILScanning, - options: default, - logger: logger, - featureSwitchValues: options.FeatureSwitches, - rootEntireAssembliesModules: Array.Empty(), - additionalRootedAssemblies: options.AdditionalRootAssemblies.ToArray(), - trimmedAssemblies: options.TrimAssemblies.ToArray(), - satelliteAssemblyFilePaths: Array.Empty()); - - PInvokeILEmitterConfiguration pinvokePolicy = new ILCompilerTestPInvokePolicy (); - InteropStateManager interopStateManager = new InteropStateManager (typeSystemContext.GeneratedAssembly); - InteropStubManager interopStubManager = new UsageBasedInteropStubManager (interopStateManager, pinvokePolicy, logger); - - TypeMapManager typeMapManager = new UsageBasedTypeMapManager (TypeMapMetadata.Empty); - if (entrypointModule is { Assembly: EcmaAssembly entryAssembly }) - { - typeMapManager = new UsageBasedTypeMapManager (TypeMapMetadata.CreateFromAssembly(entryAssembly, typeSystemContext)); - } - - CompilationBuilder builder = new RyuJitCompilationBuilder (typeSystemContext, compilationGroup) - .UseILProvider (ilProvider) - .UseCompilationUnitPrefix(""); - - IILScanner scanner = builder.GetILScannerBuilder () - .UseCompilationRoots (compilationRoots) - .UseMetadataManager (metadataManager) - .UseParallelism (System.Diagnostics.Debugger.IsAttached ? 1 : -1) - .UseInteropStubManager (interopStubManager) - .UseTypeMapManager (typeMapManager) - .ToILScanner (); - - return scanner.Scan (); - } - - public static void ComputeDefaultOptions (out TargetOS os, out TargetArchitecture arch) - { - if (RuntimeInformation.IsOSPlatform (OSPlatform.Windows)) - os = TargetOS.Windows; - else if (RuntimeInformation.IsOSPlatform (OSPlatform.Linux)) - os = TargetOS.Linux; - else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) - os = TargetOS.OSX; - else if (RuntimeInformation.IsOSPlatform (OSPlatform.FreeBSD)) - os = TargetOS.FreeBSD; - else - throw new NotImplementedException (); - - switch (RuntimeInformation.ProcessArchitecture) { - case Architecture.X86: - arch = TargetArchitecture.X86; - break; - case Architecture.X64: - arch = TargetArchitecture.X64; - break; - case Architecture.Arm: - arch = TargetArchitecture.ARM; - break; - case Architecture.Arm64: - arch = TargetArchitecture.ARM64; - break; - default: - throw new NotImplementedException (); - } - } - - private static IReadOnlyCollection CreateInitializerList (CompilerTypeSystemContext context, ILCompilerOptions options) - { - List assembliesWithInitalizers = new List (); - - // Build a list of assemblies that have an initializer that needs to run before - // any user code runs. - foreach (string initAssemblyName in options.InitAssemblies) { - ModuleDesc assembly = context.ResolveAssembly (new AssemblyNameInfo (initAssemblyName), throwIfNotFound: true); - assembliesWithInitalizers.Add (assembly); - } - - var libraryInitializers = new LibraryInitializers (context, assembliesWithInitalizers); - - List initializerList = new List (libraryInitializers.LibraryInitializerMethods); - return initializerList; - } - } + public class TrimmingDriver + { + internal const string DefaultSystemModule = "System.Private.CoreLib"; + + public ILScanResults Trim(ILCompilerOptions options, TrimmingCustomizations? customizations, ILogWriter logWriter) + { + ComputeDefaultOptions(out var targetOS, out var targetArchitecture); + var targetDetails = new TargetDetails(targetArchitecture, targetOS, TargetAbi.NativeAot); + CompilerTypeSystemContext typeSystemContext = + new CompilerTypeSystemContext(targetDetails, SharedGenericsMode.CanonicalReferenceTypes, DelegateFeature.All, genericCycleDepthCutoff: -1); + + typeSystemContext.InputFilePaths = options.InputFilePaths; + typeSystemContext.ReferenceFilePaths = options.ReferenceFilePaths; + typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(DefaultSystemModule)); + + List inputModules = new List(); + foreach (var inputFile in typeSystemContext.InputFilePaths) + { + EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); + inputModules.Add(module); + } + + foreach (var trimAssembly in options.TrimAssemblies) + { + EcmaModule module = typeSystemContext.GetModuleForSimpleName(trimAssembly); + inputModules.Add(module); + } + + CompilationModuleGroup compilationGroup; + if (options.FrameworkCompilation) + compilationGroup = new SingleFileCompilationModuleGroup(); + else + compilationGroup = new TestInfraMultiFileSharedCompilationModuleGroup(typeSystemContext, inputModules); + + List compilationRoots = new List(); + EcmaModule? entrypointModule = null; + foreach (var inputFile in typeSystemContext.InputFilePaths) + { + EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); + + if (module.PEReader.PEHeaders.IsExe) + { + if (entrypointModule != null) + throw new Exception("Multiple EXE modules"); + entrypointModule = module; + } + + compilationRoots.Add(new UnmanagedEntryPointsRootProvider(module)); + } + + compilationRoots.Add(new MainMethodRootProvider(entrypointModule, CreateInitializerList(typeSystemContext, options), generateLibraryAndModuleInitializers: true)); + + foreach (var rootedAssembly in options.AdditionalRootAssemblies) + { + EcmaModule module = typeSystemContext.GetModuleForSimpleName(rootedAssembly); + + // We only root the module type. The rest will fall out because we treat rootedAssemblies + // same as conditionally rooted ones and here we're fulfilling the condition ("something is used"). + compilationRoots.Add( + new GenericRootProvider(module, + (ModuleDesc module, IRootingServiceProvider rooter) => rooter.AddReflectionRoot(module.GetGlobalModuleType(), "Command line root"))); + } + + ILProvider ilProvider = new NativeAotILProvider(); + + Logger logger = new Logger( + logWriter, + ilProvider, + isVerbose: true, + suppressedWarnings: Enumerable.Empty(), + options.SingleWarn, + singleWarnEnabledModules: Enumerable.Empty(), + singleWarnDisabledModules: Enumerable.Empty(), + suppressedCategories: options.SuppressedWarningCategories, + treatWarningsAsErrors: options.TreatWarningsAsErrors, + warningsAsErrors: options.WarningsAsErrors); + + foreach (var descriptor in options.Descriptors) + { + if (!File.Exists(descriptor)) + throw new FileNotFoundException($"'{descriptor}' doesn't exist"); + compilationRoots.Add(new ILCompiler.DependencyAnalysis.TrimmingDescriptorNode(descriptor)); + } + + var featureSwitches = options.FeatureSwitches; + BodyAndFieldSubstitutions substitutions = default; + IReadOnlyDictionary>? resourceBlocks = default; + foreach (string substitutionFilePath in options.SubstitutionFiles) + { + using FileStream fs = File.OpenRead(substitutionFilePath); + substitutions.AppendFrom(BodySubstitutionsParser.GetSubstitutions( + logger, typeSystemContext, XmlReader.Create(fs), substitutionFilePath, featureSwitches)); + + fs.Seek(0, SeekOrigin.Begin); + + resourceBlocks = ManifestResourceBlockingPolicy.UnionBlockings(resourceBlocks, + ManifestResourceBlockingPolicy.SubstitutionsReader.GetSubstitutions( + logger, typeSystemContext, XmlReader.Create(fs), substitutionFilePath, featureSwitches)); + } + + SubstitutionProvider substitutionProvider = new SubstitutionProvider(logger, featureSwitches, substitutions); + ilProvider = new SubstitutedILProvider(ilProvider, substitutionProvider, new DevirtualizationManager()); + + CompilerGeneratedState compilerGeneratedState = new CompilerGeneratedState(ilProvider, logger); + + UsageBasedMetadataManager metadataManager = new UsageBasedMetadataManager( + compilationGroup, + typeSystemContext, + new NoMetadataBlockingPolicy(), + new ManifestResourceBlockingPolicy(logger, options.FeatureSwitches, new Dictionary>()), + logFile: null, + stackTracePolicy: new NoStackTraceEmissionPolicy(), + invokeThunkGenerationPolicy: new DefaultDynamicInvokeThunkGenerationPolicy(), + flowAnnotations: new FlowAnnotations(logger, ilProvider, compilerGeneratedState), + generationOptions: UsageBasedMetadataGenerationOptions.ReflectionILScanning, + options: default, + logger: logger, + featureSwitchValues: options.FeatureSwitches, + rootEntireAssembliesModules: Array.Empty(), + additionalRootedAssemblies: options.AdditionalRootAssemblies.ToArray(), + trimmedAssemblies: options.TrimAssemblies.ToArray(), + satelliteAssemblyFilePaths: Array.Empty()); + + PInvokeILEmitterConfiguration pinvokePolicy = new ILCompilerTestPInvokePolicy(); + InteropStateManager interopStateManager = new InteropStateManager(typeSystemContext.GeneratedAssembly); + InteropStubManager interopStubManager = new UsageBasedInteropStubManager(interopStateManager, pinvokePolicy, logger); + + TypeMapManager typeMapManager = new UsageBasedTypeMapManager(TypeMapMetadata.Empty); + if (entrypointModule is { Assembly: EcmaAssembly entryAssembly }) + { + typeMapManager = new UsageBasedTypeMapManager(TypeMapMetadata.CreateFromAssembly(entryAssembly, typeSystemContext)); + } + + CompilationBuilder builder = new RyuJitCompilationBuilder(typeSystemContext, compilationGroup) + .UseILProvider(ilProvider) + .UseCompilationUnitPrefix(""); + + IILScanner scanner = builder.GetILScannerBuilder() + .UseCompilationRoots(compilationRoots) + .UseMetadataManager(metadataManager) + .UseParallelism(System.Diagnostics.Debugger.IsAttached ? 1 : -1) + .UseInteropStubManager(interopStubManager) + .UseTypeMapManager(typeMapManager) + .ToILScanner(); + + return scanner.Scan(); + } + + public static void ComputeDefaultOptions(out TargetOS os, out TargetArchitecture arch) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + os = TargetOS.Windows; + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + os = TargetOS.Linux; + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + os = TargetOS.OSX; + else if (RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD)) + os = TargetOS.FreeBSD; + else + throw new NotImplementedException(); + + switch (RuntimeInformation.ProcessArchitecture) + { + case Architecture.X86: + arch = TargetArchitecture.X86; + break; + case Architecture.X64: + arch = TargetArchitecture.X64; + break; + case Architecture.Arm: + arch = TargetArchitecture.ARM; + break; + case Architecture.Arm64: + arch = TargetArchitecture.ARM64; + break; + default: + throw new NotImplementedException(); + } + } + + private static IReadOnlyCollection CreateInitializerList(CompilerTypeSystemContext context, ILCompilerOptions options) + { + List assembliesWithInitalizers = new List(); + + // Build a list of assemblies that have an initializer that needs to run before + // any user code runs. + foreach (string initAssemblyName in options.InitAssemblies) + { + ModuleDesc assembly = context.ResolveAssembly(new AssemblyNameInfo(initAssemblyName), throwIfNotFound: true); + assembliesWithInitalizers.Add(assembly); + } + + var libraryInitializers = new LibraryInitializers(context, assembliesWithInitalizers); + + List initializerList = new List(libraryInitializers.LibraryInitializerMethods); + return initializerList; + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingTestLogger.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingTestLogger.cs index 9e1bec7a057093..3bc19c3eef01a2 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingTestLogger.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingTestLogger.cs @@ -8,46 +8,49 @@ namespace Mono.Linker.Tests.TestCasesRunner { - public class TrimmingTestLogger : ILogWriter - { - private readonly StringWriter _infoStringWriter; - private readonly TextWriter _infoWriter; - - private readonly List _messageContainers; - - public TrimmingTestLogger () - { - _infoStringWriter = new StringWriter (); - _infoWriter = TextWriter.Synchronized (_infoStringWriter); - _messageContainers = new List (); - } - - public TextWriter Writer => _infoWriter; - - public List GetLoggedMessages () - { - return _messageContainers; - } - - public void WriteError (MessageContainer error) - { - lock (_messageContainers) { - _messageContainers.Add (error); - } - } - - public void WriteMessage (MessageContainer message) - { - lock (_messageContainers) { - _messageContainers.Add (message); - } - } - - public void WriteWarning (MessageContainer warning) - { - lock (_messageContainers) { - _messageContainers.Add (warning); - } - } - } + public class TrimmingTestLogger : ILogWriter + { + private readonly StringWriter _infoStringWriter; + private readonly TextWriter _infoWriter; + + private readonly List _messageContainers; + + public TrimmingTestLogger() + { + _infoStringWriter = new StringWriter(); + _infoWriter = TextWriter.Synchronized(_infoStringWriter); + _messageContainers = new List(); + } + + public TextWriter Writer => _infoWriter; + + public List GetLoggedMessages() + { + return _messageContainers; + } + + public void WriteError(MessageContainer error) + { + lock (_messageContainers) + { + _messageContainers.Add(error); + } + } + + public void WriteMessage(MessageContainer message) + { + lock (_messageContainers) + { + _messageContainers.Add(message); + } + } + + public void WriteWarning(MessageContainer warning) + { + lock (_messageContainers) + { + _messageContainers.Add(warning); + } + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Tests/DocumentationSignatureParserTests.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Tests/DocumentationSignatureParserTests.cs index c8df47cc328556..a06b08ebc2ff8e 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Tests/DocumentationSignatureParserTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Tests/DocumentationSignatureParserTests.cs @@ -16,545 +16,553 @@ namespace Mono.Linker.Tests { - public class DocumentationSignatureParserTests - { - [Theory] - [ClassData (typeof (MemberAssertions))] - public void TestSignatureParsing (TypeSystemEntity member, MemberAssertionsCollector.CustomAttribute customAttribute) - { - var attributeString = (string) customAttribute.Value.FixedArguments[0].Value!; - switch (customAttribute.AttributeType.Name) { - case nameof (ExpectExactlyResolvedDocumentationSignatureAttribute): - CheckUniqueParsedString (member, attributeString); - break; - case nameof (ExpectGeneratedDocumentationSignatureAttribute): - // CheckGeneratedString (member, attributeString); - break; - case nameof (ExpectResolvedDocumentationSignatureAttribute): - CheckParsedString (member, attributeString); - break; - case nameof (ExpectUnresolvedDocumentationSignatureAttribute): - CheckUnresolvedDocumentationSignature (member, attributeString); - break; - default: - throw new NotImplementedException (); - } - } - - public class MemberAssertions : MemberAssertionsCollector - { - public MemberAssertions () : base (typeof (DocumentationSignatureParserTests)) - { } - } - - private static void CheckUniqueParsedString (TypeSystemEntity member, string input) - { - var module = GetModule (member); - Assert.NotNull (module); - var parseResults = DocumentationSignatureParser.GetMembersForDocumentationSignature (input, module); - Assert.Single (parseResults); - TypeSystemEntity result = parseResults.First (); - switch (member) { - case PropertyPseudoDesc p: - var actualProperty = Assert.IsType (result); - Assert.Equal (p.OwningType, actualProperty.OwningType); - Assert.Equal (p.Name, actualProperty.Name); - break; - case EventPseudoDesc e: - var actualEvent = Assert.IsType (result); - Assert.Equal (e.OwningType, actualEvent.OwningType); - Assert.Equal (e.Name, actualEvent.Name); - break; - default: - Assert.Equal (member, parseResults.First ()); - break; - } - } - - // Currently NativeAOT has only a partial implementation of the generator since it doesn't need it for anything - // other than signature parsing (which uses the generator for certain parts). + public class DocumentationSignatureParserTests + { + [Theory] + [ClassData(typeof(MemberAssertions))] + public void TestSignatureParsing(TypeSystemEntity member, MemberAssertionsCollector.CustomAttribute customAttribute) + { + var attributeString = (string)customAttribute.Value.FixedArguments[0].Value!; + switch (customAttribute.AttributeType.Name) + { + case nameof(ExpectExactlyResolvedDocumentationSignatureAttribute): + CheckUniqueParsedString(member, attributeString); + break; + case nameof(ExpectGeneratedDocumentationSignatureAttribute): + // CheckGeneratedString (member, attributeString); + break; + case nameof(ExpectResolvedDocumentationSignatureAttribute): + CheckParsedString(member, attributeString); + break; + case nameof(ExpectUnresolvedDocumentationSignatureAttribute): + CheckUnresolvedDocumentationSignature(member, attributeString); + break; + default: + throw new NotImplementedException(); + } + } + + public class MemberAssertions : MemberAssertionsCollector + { + public MemberAssertions() : base(typeof(DocumentationSignatureParserTests)) + { } + } + + private static void CheckUniqueParsedString(TypeSystemEntity member, string input) + { + var module = GetModule(member); + Assert.NotNull(module); + var parseResults = DocumentationSignatureParser.GetMembersForDocumentationSignature(input, module); + Assert.Single(parseResults); + TypeSystemEntity result = parseResults.First(); + switch (member) + { + case PropertyPseudoDesc p: + var actualProperty = Assert.IsType(result); + Assert.Equal(p.OwningType, actualProperty.OwningType); + Assert.Equal(p.Name, actualProperty.Name); + break; + case EventPseudoDesc e: + var actualEvent = Assert.IsType(result); + Assert.Equal(e.OwningType, actualEvent.OwningType); + Assert.Equal(e.Name, actualEvent.Name); + break; + default: + Assert.Equal(member, parseResults.First()); + break; + } + } + + // Currently NativeAOT has only a partial implementation of the generator since it doesn't need it for anything + // other than signature parsing (which uses the generator for certain parts). #if false - private static void CheckGeneratedString (TypeSystemEntity member, string expected) - { - var builder = new StringBuilder (); - DocumentationSignatureGenerator.PartVisitor.Instance.AppendName (builder, type); - Assert.Equal (expected, builder.ToString ()); - } + private static void CheckGeneratedString (TypeSystemEntity member, string expected) + { + var builder = new StringBuilder (); + DocumentationSignatureGenerator.PartVisitor.Instance.AppendName (builder, type); + Assert.Equal (expected, builder.ToString ()); + } #endif - private static void CheckParsedString (TypeSystemEntity member, string input) - { - var module = GetModule (member); - Assert.NotNull (module); - var parseResults = DocumentationSignatureParser.GetMembersForDocumentationSignature (input, module); - Assert.Contains (member, parseResults); - } - - private static void CheckUnresolvedDocumentationSignature (TypeSystemEntity member, string input) - { - var module = GetModule (member); - Assert.NotNull (module); - var parseResults = DocumentationSignatureParser.GetMembersForDocumentationSignature (input, module); - Assert.DoesNotContain (member, parseResults); - } - - private static ModuleDesc? GetModule (TypeSystemEntity entity) - { - return entity switch { - MethodDesc method => (method.OwningType as MetadataType)?.Module, - FieldDesc field => (field.OwningType as MetadataType)?.Module, - MetadataType type => type.Module, - PropertyPseudoDesc property => property.OwningType.Module, - EventPseudoDesc @event => @event.OwningType.Module, - _ => throw new InvalidOperationException (), - }; - } - - // testcases - - [ExpectGeneratedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.A")] - [ExpectExactlyResolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.A")] - public class A - { - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.#ctor")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.#ctor")] - public A () - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.#ctor(System.Int32)")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.#ctor(System.Int32)")] - public A (int a) - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.#cctor")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.#cctor")] - static A () - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[])")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[])")] - public static void M (int[] a) - { - } - - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32,System.Int32,System.Int32)~System.Int32")] - public static int M (int a, int b, int c) - { - return 0; - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MRef(System.Int32@)")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MRef(System.Int32@)")] - public static void MRef (ref int a) - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MOut(System.Int32@)")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MOut(System.Int32@)")] - public static void MOut (out int a) - { - a = 5; - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MIn(System.Int32@)")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MIn(System.Int32@)")] - public static void MIn (in int a) - { - } - - private static int i; - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MRefReturn")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MRefReturn")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MRefReturn~System.Int32@")] - public static ref int MRefReturn () - { - return ref i; - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M")] - [ExpectResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M")] // binds to both. - [ExpectResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M()")] // binds to both. - public static void M () - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M()")] - [ExpectResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M")] - [ExpectResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M()")] - public static void M (__arglist) - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[][])")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[][])")] - public static void M (int[][] a) - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[][0:,0:,0:])")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[][0:,0:,0:])")] - public static void M (int[,,][] a) - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[0:,0:])")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[0:,0:])")] - public static void M (int[,] a) - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Object)")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Object)")] - public static void M (dynamic d) - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32*)")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32*)")] - public static unsafe void M (int* a) - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M``1(Mono.Linker.Tests.DocumentationSignatureParserTests.S{Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A,``0}}**[0:,0:,0:][][][0:,0:]@)")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M``1(Mono.Linker.Tests.DocumentationSignatureParserTests.S{Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A,``0}}**[0:,0:,0:][][][0:,0:]@)")] - public static unsafe void M (ref S>**[,][][][,,] a) - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Collections.Generic.List{System.Int32[]})")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Collections.Generic.List{System.Int32[]})")] - public static void M (List a) - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32,)")] - //[ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32,)")] - // there's no way to reference this, since the parsing logic doesn't like it. - public static void M (int abo, __arglist) - { - } - - [ExpectGeneratedDocumentationSignature ("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Prop")] - [ExpectExactlyResolvedDocumentationSignature ("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Prop")] - public int Prop { get; set; } - - [ExpectGeneratedDocumentationSignature ("F:Mono.Linker.Tests.DocumentationSignatureParserTests.A.field")] - [ExpectExactlyResolvedDocumentationSignature ("F:Mono.Linker.Tests.DocumentationSignatureParserTests.A.field")] - public int field; - - - [ExpectGeneratedDocumentationSignature ("E:Mono.Linker.Tests.DocumentationSignatureParserTests.A.OnEvent")] - [ExpectExactlyResolvedDocumentationSignature ("E:Mono.Linker.Tests.DocumentationSignatureParserTests.A.OnEvent")] - public event EventHandler? OnEvent; - - [ExpectGeneratedDocumentationSignature ("E:Mono.Linker.Tests.DocumentationSignatureParserTests.A.OnEventInt")] - [ExpectExactlyResolvedDocumentationSignature ("E:Mono.Linker.Tests.DocumentationSignatureParserTests.A.OnEventInt")] - public event Action? OnEventInt; - - [ExpectGeneratedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Del")] - [ExpectExactlyResolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Del")] - public delegate int Del (int a, int b); - - [ExpectGeneratedDocumentationSignature ("E:Mono.Linker.Tests.DocumentationSignatureParserTests.A.OnEventDel")] - [ExpectExactlyResolvedDocumentationSignature ("E:Mono.Linker.Tests.DocumentationSignatureParserTests.A.OnEventDel")] - public event Del? OnEventDel; - - // prevent warning about unused events - public void UseEvents () - { - OnEventDel?.Invoke (1, 2); - OnEventInt?.Invoke (1); - OnEvent?.Invoke (null, new EventArgs ()); - } - - [ExpectGeneratedDocumentationSignature ("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Item(System.Int32)")] - [ExpectExactlyResolvedDocumentationSignature ("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Item(System.Int32)")] - public int this[int i] { - get => 0; - set { } - } - - [ExpectGeneratedDocumentationSignature ("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Item(System.String,System.Int32)")] - [ExpectExactlyResolvedDocumentationSignature ("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Item(System.String,System.Int32)")] - public int this[string s, int i] { - get => 0; - set { } - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] - public static implicit operator bool (A a) => false; - - // C# will not generate a return type for this method, but we will. - // [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] - // [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] - //public static int op_Implicit (A a) => 0; - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_UnaryPlus(Mono.Linker.Tests.DocumentationSignatureParserTests.A)")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_UnaryPlus(Mono.Linker.Tests.DocumentationSignatureParserTests.A)")] - public static A? operator + (A a) => null; - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Addition(Mono.Linker.Tests.DocumentationSignatureParserTests.A,Mono.Linker.Tests.DocumentationSignatureParserTests.A)")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Addition(Mono.Linker.Tests.DocumentationSignatureParserTests.A,Mono.Linker.Tests.DocumentationSignatureParserTests.A)")] - public static A? operator + (A left, A right) => null; - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MWithReturnType")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MWithReturnType~System.Boolean")] - public static bool MWithReturnType () => false; - } - - public struct S - { - } - - [ExpectGeneratedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.A`1")] - [ExpectExactlyResolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.A`1")] - public class A - { - [ExpectGeneratedDocumentationSignature ("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A`1.Item(`0)")] - [ExpectExactlyResolvedDocumentationSignature ("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A`1.Item(`0)")] - public int this[T t] { - get => 0; - set { } - } - } - - [ExpectExactlyResolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.B")] - [ExpectGeneratedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.B")] - public class B - { - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.B.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A{Mono.Linker.Tests.DocumentationSignatureParserTests.B},System.Collections.Generic.List{Mono.Linker.Tests.DocumentationSignatureParserTests.A}})")] - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.B.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A{Mono.Linker.Tests.DocumentationSignatureParserTests.B},System.Collections.Generic.List{Mono.Linker.Tests.DocumentationSignatureParserTests.A}})")] - public static void Method (G, List> l) - { - } - } - - [ExpectGeneratedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2")] - [ExpectExactlyResolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2")] - public class G - { - [ExpectGeneratedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1")] - [ExpectExactlyResolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1")] - public class NG - { - [ExpectGeneratedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1.NG2`1")] - [ExpectExactlyResolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1.NG2`1")] - public class NG2 - { - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1.NG2`1.Method``1(`0,`1,`2,`3,``0)")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1.NG2`1.Method``1(`0,`1,`2,`3,``0)")] - public void Method (T t, U u, V v, W w, X x) - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1.NG2`1.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{`0,`1}.NG{`2}.NG2{`3})")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1.NG2`1.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{`0,`1}.NG{`2}.NG2{`3})")] - public void Method (NG2 n) - { - } - } - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{`0,`1})")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{`0,`1})")] - public void Method (G g) - { - } - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method")] - public static void Method () - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method(System.Int32)")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method(System.Int32)")] - public static void Method (int i) - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.IntMethod")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.IntMethod")] - public static int IntMethod () => 0; - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A,Mono.Linker.Tests.DocumentationSignatureParserTests.A})")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A,Mono.Linker.Tests.DocumentationSignatureParserTests.A})")] - public static void Method (G g) - { - } - - [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A,Mono.Linker.Tests.DocumentationSignatureParserTests.A}.NG{Mono.Linker.Tests.DocumentationSignatureParserTests.A})")] - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A,Mono.Linker.Tests.DocumentationSignatureParserTests.A}.NG{Mono.Linker.Tests.DocumentationSignatureParserTests.A})")] - public static void Method (G.NG g) - { - } - - public class Invalid - { - [ExpectUnresolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoReturnType~")] - public static int NoReturnType () => 0; - - [ExpectUnresolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoParameters(,)")] - public static void NoParameters (int a, int b) - { - } - - [ExpectUnresolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoClosingParen(")] - public static void NoClosingParen () { } - - [ExpectUnresolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Whitespace ")] - [ExpectUnresolvedDocumentationSignature (" T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Whitespace")] - [ExpectUnresolvedDocumentationSignature ("T: Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Whitespace")] - [ExpectUnresolvedDocumentationSignature ("T :Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Whitespace")] - [ExpectUnresolvedDocumentationSignature ("")] - [ExpectUnresolvedDocumentationSignature (" ")] - public class Whitespace - { - [ExpectUnresolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Whitespace.Method(System.Int32, System.Int32)")] - public static void Method (int a, int b) - { - } - - [ExpectUnresolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Whitespace.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic{System.Int32, System.Int32})")] - public static void Method (Generic g) - { - } - } - - public class Generic - { - } - - [ExpectUnresolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic{`1}")] - [ExpectUnresolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic{T}")] - [ExpectUnresolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic")] - public class Generic - { - [ExpectUnresolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic``1.MethodSyntaxForTypeParameter(`0)")] - - public void MethodSyntaxForTypeParameter (T t) - { - } - - [ExpectUnresolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic`1.MethodSyntaxForTypeGenericArgument(Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic{``0})")] - public void MethodSyntaxForTypeGenericArgument (Generic g) - { - } - - [ExpectUnresolvedDocumentationSignature ("P:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic`1.Item(``0)")] - public bool this[T t] { - get => false; - set { } - } - } - - [ExpectUnresolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.MethodWithGenericInstantiation(Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic`1)")] - public static void MethodWithGenericInstantiation (Generic g) - { - } - - [ExpectUnresolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Method(System.Int32[:,:])")] - [ExpectUnresolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Method(System.Int32[0:,)")] - public static void Method (int[,] a) - { - } - - [ExpectUnresolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NonGenericMethod(``0)")] - public static void NonGenericMethod (int i) - { - } - - [ExpectUnresolvedDocumentationSignature ("P:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Item(`0)")] - [ExpectUnresolvedDocumentationSignature ("P:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Item(``0)")] - public int this[int i] { - get => 0; - set { } - } - - [ExpectUnresolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.MethodMissingArgumentTypeName(System.)")] - public static void MethodMissingArgumentTypeName (int i) - { - } - - [ExpectUnresolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.")] - public class NoType - { - [ExpectUnresolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid..Method")] - public static void Method () - { - } - } - - // prevent warning about unused events - public void UseEvents () - { - OnEvent?.Invoke (null, new EventArgs ()); - OnEventArgs?.Invoke (null, new EventArgs ()); - } - - [ExpectUnresolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoParameterType()")] - public static void NoParameterType (int i) - { - } - - [ExpectUnresolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoParameterType(Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic{})")] - public static void NoGenericParameterType (Generic g) - { - } - - [ExpectUnresolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.TypeWithMethodGenericParameters``1")] - public class TypeWithMethodGenericParameters - { - } - - public class GenericType - { - [ExpectUnresolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.GenericType`2.TypeWithMethodGenericParameters``1")] - public class TypeWithMethodGenericParameters - { - } - } - - // our parser won't match fields with `, unlike roslyn. - [ExpectUnresolvedDocumentationSignature ("F:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.field`gibberish")] - public int field; - - [ExpectUnresolvedDocumentationSignature ("E:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.OnEvent`gibberish")] - public event EventHandler? OnEvent; - - // the below work, but seem like they shouldn't. See https://github.com/dotnet/linker/issues/1214. - - [ExpectExactlyResolvedDocumentationSignature ("TMono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoColon")] - public class NoColon - { - } - - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoClosingParenWithParameters(System.Int32")] - public static void NoClosingParenWithParameters (int a) - { - } - - [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoClosingBrace(Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic{Mono.Linker.Tests.DocumentationSignatureParserTests.A)")] - public static void NoClosingBrace (Generic g) - { - } - - [ExpectExactlyResolvedDocumentationSignature ("F:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.fieldArgs(gibberish")] - public int fieldArgs; - - [ExpectExactlyResolvedDocumentationSignature ("E:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.OnEventArgs(gibberish")] - public event EventHandler? OnEventArgs; - - [ExpectExactlyResolvedDocumentationSignature ("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NestedType{")] - public class NestedType - { - } - } - } + private static void CheckParsedString(TypeSystemEntity member, string input) + { + var module = GetModule(member); + Assert.NotNull(module); + var parseResults = DocumentationSignatureParser.GetMembersForDocumentationSignature(input, module); + Assert.Contains(member, parseResults); + } + + private static void CheckUnresolvedDocumentationSignature(TypeSystemEntity member, string input) + { + var module = GetModule(member); + Assert.NotNull(module); + var parseResults = DocumentationSignatureParser.GetMembersForDocumentationSignature(input, module); + Assert.DoesNotContain(member, parseResults); + } + + private static ModuleDesc? GetModule(TypeSystemEntity entity) + { + return entity switch + { + MethodDesc method => (method.OwningType as MetadataType)?.Module, + FieldDesc field => (field.OwningType as MetadataType)?.Module, + MetadataType type => type.Module, + PropertyPseudoDesc property => property.OwningType.Module, + EventPseudoDesc @event => @event.OwningType.Module, + _ => throw new InvalidOperationException(), + }; + } + + // testcases + + [ExpectGeneratedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.A")] + [ExpectExactlyResolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.A")] + public class A + { + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.#ctor")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.#ctor")] + public A() + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.#ctor(System.Int32)")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.#ctor(System.Int32)")] + public A(int a) + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.#cctor")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.#cctor")] + static A() + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[])")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[])")] + public static void M(int[] a) + { + } + + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32,System.Int32,System.Int32)~System.Int32")] + public static int M(int a, int b, int c) + { + return 0; + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MRef(System.Int32@)")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MRef(System.Int32@)")] + public static void MRef(ref int a) + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MOut(System.Int32@)")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MOut(System.Int32@)")] + public static void MOut(out int a) + { + a = 5; + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MIn(System.Int32@)")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MIn(System.Int32@)")] + public static void MIn(in int a) + { + } + + private static int i; + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MRefReturn")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MRefReturn")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MRefReturn~System.Int32@")] + public static ref int MRefReturn() + { + return ref i; + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M")] + [ExpectResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M")] // binds to both. + [ExpectResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M()")] // binds to both. + public static void M() + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M()")] + [ExpectResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M")] + [ExpectResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M()")] + public static void M(__arglist) + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[][])")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[][])")] + public static void M(int[][] a) + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[][0:,0:,0:])")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[][0:,0:,0:])")] + public static void M(int[,,][] a) + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[0:,0:])")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32[0:,0:])")] + public static void M(int[,] a) + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Object)")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Object)")] + public static void M(dynamic d) + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32*)")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32*)")] + public static unsafe void M(int* a) + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M``1(Mono.Linker.Tests.DocumentationSignatureParserTests.S{Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A,``0}}**[0:,0:,0:][][][0:,0:]@)")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M``1(Mono.Linker.Tests.DocumentationSignatureParserTests.S{Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A,``0}}**[0:,0:,0:][][][0:,0:]@)")] + public static unsafe void M(ref S>**[,][][][,,] a) + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Collections.Generic.List{System.Int32[]})")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Collections.Generic.List{System.Int32[]})")] + public static void M(List a) + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32,)")] + //[ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32,)")] + // there's no way to reference this, since the parsing logic doesn't like it. + public static void M(int abo, __arglist) + { + } + + [ExpectGeneratedDocumentationSignature("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Prop")] + [ExpectExactlyResolvedDocumentationSignature("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Prop")] + public int Prop { get; set; } + + [ExpectGeneratedDocumentationSignature("F:Mono.Linker.Tests.DocumentationSignatureParserTests.A.field")] + [ExpectExactlyResolvedDocumentationSignature("F:Mono.Linker.Tests.DocumentationSignatureParserTests.A.field")] + public int field; + + + [ExpectGeneratedDocumentationSignature("E:Mono.Linker.Tests.DocumentationSignatureParserTests.A.OnEvent")] + [ExpectExactlyResolvedDocumentationSignature("E:Mono.Linker.Tests.DocumentationSignatureParserTests.A.OnEvent")] + public event EventHandler? OnEvent; + + [ExpectGeneratedDocumentationSignature("E:Mono.Linker.Tests.DocumentationSignatureParserTests.A.OnEventInt")] + [ExpectExactlyResolvedDocumentationSignature("E:Mono.Linker.Tests.DocumentationSignatureParserTests.A.OnEventInt")] + public event Action? OnEventInt; + + [ExpectGeneratedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Del")] + [ExpectExactlyResolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Del")] + public delegate int Del(int a, int b); + + [ExpectGeneratedDocumentationSignature("E:Mono.Linker.Tests.DocumentationSignatureParserTests.A.OnEventDel")] + [ExpectExactlyResolvedDocumentationSignature("E:Mono.Linker.Tests.DocumentationSignatureParserTests.A.OnEventDel")] + public event Del? OnEventDel; + + // prevent warning about unused events + public void UseEvents() + { + OnEventDel?.Invoke(1, 2); + OnEventInt?.Invoke(1); + OnEvent?.Invoke(null, new EventArgs()); + } + + [ExpectGeneratedDocumentationSignature("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Item(System.Int32)")] + [ExpectExactlyResolvedDocumentationSignature("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Item(System.Int32)")] + public int this[int i] + { + get => 0; + set { } + } + + [ExpectGeneratedDocumentationSignature("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Item(System.String,System.Int32)")] + [ExpectExactlyResolvedDocumentationSignature("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A.Item(System.String,System.Int32)")] + public int this[string s, int i] + { + get => 0; + set { } + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] + public static implicit operator bool(A a) => false; + + // C# will not generate a return type for this method, but we will. + // [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] + // [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] + //public static int op_Implicit (A a) => 0; + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_UnaryPlus(Mono.Linker.Tests.DocumentationSignatureParserTests.A)")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_UnaryPlus(Mono.Linker.Tests.DocumentationSignatureParserTests.A)")] + public static A? operator +(A a) => null; + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Addition(Mono.Linker.Tests.DocumentationSignatureParserTests.A,Mono.Linker.Tests.DocumentationSignatureParserTests.A)")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Addition(Mono.Linker.Tests.DocumentationSignatureParserTests.A,Mono.Linker.Tests.DocumentationSignatureParserTests.A)")] + public static A? operator +(A left, A right) => null; + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MWithReturnType")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.MWithReturnType~System.Boolean")] + public static bool MWithReturnType() => false; + } + + public struct S + { + } + + [ExpectGeneratedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.A`1")] + [ExpectExactlyResolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.A`1")] + public class A + { + [ExpectGeneratedDocumentationSignature("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A`1.Item(`0)")] + [ExpectExactlyResolvedDocumentationSignature("P:Mono.Linker.Tests.DocumentationSignatureParserTests.A`1.Item(`0)")] + public int this[T t] + { + get => 0; + set { } + } + } + + [ExpectExactlyResolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.B")] + [ExpectGeneratedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.B")] + public class B + { + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.B.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A{Mono.Linker.Tests.DocumentationSignatureParserTests.B},System.Collections.Generic.List{Mono.Linker.Tests.DocumentationSignatureParserTests.A}})")] + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.B.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A{Mono.Linker.Tests.DocumentationSignatureParserTests.B},System.Collections.Generic.List{Mono.Linker.Tests.DocumentationSignatureParserTests.A}})")] + public static void Method(G, List> l) + { + } + } + + [ExpectGeneratedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2")] + [ExpectExactlyResolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2")] + public class G + { + [ExpectGeneratedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1")] + [ExpectExactlyResolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1")] + public class NG + { + [ExpectGeneratedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1.NG2`1")] + [ExpectExactlyResolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1.NG2`1")] + public class NG2 + { + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1.NG2`1.Method``1(`0,`1,`2,`3,``0)")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1.NG2`1.Method``1(`0,`1,`2,`3,``0)")] + public void Method(T t, U u, V v, W w, X x) + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1.NG2`1.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{`0,`1}.NG{`2}.NG2{`3})")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.NG`1.NG2`1.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{`0,`1}.NG{`2}.NG2{`3})")] + public void Method(NG2 n) + { + } + } + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{`0,`1})")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.G`2.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{`0,`1})")] + public void Method(G g) + { + } + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method")] + public static void Method() + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method(System.Int32)")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method(System.Int32)")] + public static void Method(int i) + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.IntMethod")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.IntMethod")] + public static int IntMethod() => 0; + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A,Mono.Linker.Tests.DocumentationSignatureParserTests.A})")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A,Mono.Linker.Tests.DocumentationSignatureParserTests.A})")] + public static void Method(G g) + { + } + + [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A,Mono.Linker.Tests.DocumentationSignatureParserTests.A}.NG{Mono.Linker.Tests.DocumentationSignatureParserTests.A})")] + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.G{Mono.Linker.Tests.DocumentationSignatureParserTests.A,Mono.Linker.Tests.DocumentationSignatureParserTests.A}.NG{Mono.Linker.Tests.DocumentationSignatureParserTests.A})")] + public static void Method(G.NG g) + { + } + + public class Invalid + { + [ExpectUnresolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoReturnType~")] + public static int NoReturnType() => 0; + + [ExpectUnresolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoParameters(,)")] + public static void NoParameters(int a, int b) + { + } + + [ExpectUnresolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoClosingParen(")] + public static void NoClosingParen() { } + + [ExpectUnresolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Whitespace ")] + [ExpectUnresolvedDocumentationSignature(" T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Whitespace")] + [ExpectUnresolvedDocumentationSignature("T: Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Whitespace")] + [ExpectUnresolvedDocumentationSignature("T :Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Whitespace")] + [ExpectUnresolvedDocumentationSignature("")] + [ExpectUnresolvedDocumentationSignature(" ")] + public class Whitespace + { + [ExpectUnresolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Whitespace.Method(System.Int32, System.Int32)")] + public static void Method(int a, int b) + { + } + + [ExpectUnresolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Whitespace.Method(Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic{System.Int32, System.Int32})")] + public static void Method(Generic g) + { + } + } + + public class Generic + { + } + + [ExpectUnresolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic{`1}")] + [ExpectUnresolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic{T}")] + [ExpectUnresolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic")] + public class Generic + { + [ExpectUnresolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic``1.MethodSyntaxForTypeParameter(`0)")] + + public void MethodSyntaxForTypeParameter(T t) + { + } + + [ExpectUnresolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic`1.MethodSyntaxForTypeGenericArgument(Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic{``0})")] + public void MethodSyntaxForTypeGenericArgument(Generic g) + { + } + + [ExpectUnresolvedDocumentationSignature("P:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic`1.Item(``0)")] + public bool this[T t] + { + get => false; + set { } + } + } + + [ExpectUnresolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.MethodWithGenericInstantiation(Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic`1)")] + public static void MethodWithGenericInstantiation(Generic g) + { + } + + [ExpectUnresolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Method(System.Int32[:,:])")] + [ExpectUnresolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Method(System.Int32[0:,)")] + public static void Method(int[,] a) + { + } + + [ExpectUnresolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NonGenericMethod(``0)")] + public static void NonGenericMethod(int i) + { + } + + [ExpectUnresolvedDocumentationSignature("P:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Item(`0)")] + [ExpectUnresolvedDocumentationSignature("P:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Item(``0)")] + public int this[int i] + { + get => 0; + set { } + } + + [ExpectUnresolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.MethodMissingArgumentTypeName(System.)")] + public static void MethodMissingArgumentTypeName(int i) + { + } + + [ExpectUnresolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.")] + public class NoType + { + [ExpectUnresolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid..Method")] + public static void Method() + { + } + } + + // prevent warning about unused events + public void UseEvents() + { + OnEvent?.Invoke(null, new EventArgs()); + OnEventArgs?.Invoke(null, new EventArgs()); + } + + [ExpectUnresolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoParameterType()")] + public static void NoParameterType(int i) + { + } + + [ExpectUnresolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoParameterType(Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic{})")] + public static void NoGenericParameterType(Generic g) + { + } + + [ExpectUnresolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.TypeWithMethodGenericParameters``1")] + public class TypeWithMethodGenericParameters + { + } + + public class GenericType + { + [ExpectUnresolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.GenericType`2.TypeWithMethodGenericParameters``1")] + public class TypeWithMethodGenericParameters + { + } + } + + // our parser won't match fields with `, unlike roslyn. + [ExpectUnresolvedDocumentationSignature("F:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.field`gibberish")] + public int field; + + [ExpectUnresolvedDocumentationSignature("E:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.OnEvent`gibberish")] + public event EventHandler? OnEvent; + + // the below work, but seem like they shouldn't. See https://github.com/dotnet/linker/issues/1214. + + [ExpectExactlyResolvedDocumentationSignature("TMono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoColon")] + public class NoColon + { + } + + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoClosingParenWithParameters(System.Int32")] + public static void NoClosingParenWithParameters(int a) + { + } + + [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NoClosingBrace(Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.Generic{Mono.Linker.Tests.DocumentationSignatureParserTests.A)")] + public static void NoClosingBrace(Generic g) + { + } + + [ExpectExactlyResolvedDocumentationSignature("F:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.fieldArgs(gibberish")] + public int fieldArgs; + + [ExpectExactlyResolvedDocumentationSignature("E:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.OnEventArgs(gibberish")] + public event EventHandler? OnEventArgs; + + [ExpectExactlyResolvedDocumentationSignature("T:Mono.Linker.Tests.DocumentationSignatureParserTests.Invalid.NestedType{")] + public class NestedType + { + } + } + } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/LibraryImportAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/LibraryImportAttribute.cs index eaa95b7c260638..b5dd3804d58f34 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/LibraryImportAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/LibraryImportAttribute.cs @@ -18,9 +18,9 @@ namespace System.Runtime.InteropServices public #else #pragma warning disable CS0436 // Type conflicts with imported type - // Some assemblies that target downlevel have InternalsVisibleTo to their test assemblies. - // As this is only used in this repo and isn't a problem in shipping code, - // just disable the duplicate type warning. + // Some assemblies that target downlevel have InternalsVisibleTo to their test assemblies. + // As this is only used in this repo and isn't a problem in shipping code, + // just disable the duplicate type warning. internal #endif sealed class LibraryImportAttribute : Attribute diff --git a/src/tools/illink/.editorconfig b/src/tools/illink/.editorconfig index e7988b173c83c3..da62d145532377 100644 --- a/src/tools/illink/.editorconfig +++ b/src/tools/illink/.editorconfig @@ -6,9 +6,6 @@ file_header_template = Copyright (c) .NET Foundation and contributors. All right ### Code Style Analyzers -# Spacing around keywords -dotnet_diagnostic.SA1000.severity = none - # Access modifier must be declared dotnet_diagnostic.SA1400.severity = none diff --git a/src/tools/illink/external/Mono.Options/Options.cs b/src/tools/illink/external/Mono.Options/Options.cs index b89840c83b6c25..20b48797870563 100644 --- a/src/tools/illink/external/Mono.Options/Options.cs +++ b/src/tools/illink/external/Mono.Options/Options.cs @@ -192,562 +192,605 @@ namespace NDesk.Options namespace Mono.Options #endif { - static class StringCoda { - - public static IEnumerable WrappedLines (string self, params int[] widths) - { - IEnumerable w = widths; - return WrappedLines (self, w); - } - - public static IEnumerable WrappedLines (string self, IEnumerable widths) - { - if (widths == null) - throw new ArgumentNullException ("widths"); - return CreateWrappedLinesIterator (self, widths); - } - - private static IEnumerable CreateWrappedLinesIterator (string self, IEnumerable widths) - { - if (string.IsNullOrEmpty (self)) { - yield return string.Empty; - yield break; - } - using (IEnumerator ewidths = widths.GetEnumerator ()) { - bool? hw = null; - int width = GetNextWidth (ewidths, int.MaxValue, ref hw); - int start = 0, end; - do { - end = GetLineEnd (start, width, self); - char c = self [end-1]; - if (char.IsWhiteSpace (c)) - --end; - bool needContinuation = end != self.Length && !IsEolChar (c); - string continuation = ""; - if (needContinuation) { - --end; - continuation = "-"; - } - string line = self.Substring (start, end - start) + continuation; - yield return line; - start = end; - if (char.IsWhiteSpace (c)) - ++start; - width = GetNextWidth (ewidths, width, ref hw); - } while (start < self.Length); - } - } - - private static int GetNextWidth (IEnumerator ewidths, int curWidth, ref bool? eValid) - { - if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) { - curWidth = (eValid = ewidths.MoveNext ()).Value ? ewidths.Current : curWidth; - // '.' is any character, - is for a continuation - const string minWidth = ".-"; - if (curWidth < minWidth.Length) - throw new ArgumentOutOfRangeException ("widths", - string.Format ("Element must be >= {0}, was {1}.", minWidth.Length, curWidth)); - return curWidth; - } - // no more elements, use the last element. - return curWidth; - } - - private static bool IsEolChar (char c) - { - return !char.IsLetterOrDigit (c); - } - - private static int GetLineEnd (int start, int length, string description) - { - int end = System.Math.Min (start + length, description.Length); - int sep = -1; - for (int i = start; i < end; ++i) { - if (description [i] == '\n') - return i+1; - if (IsEolChar (description [i])) - sep = i+1; - } - if (sep == -1 || end == description.Length) - return end; - return sep; - } - } - - public class OptionValueCollection : IList, IList { - - List values = new List (); - OptionContext c; - - internal OptionValueCollection (OptionContext c) - { - this.c = c; - } - - #region ICollection - void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);} - bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}} - object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}} - #endregion - - #region ICollection - public void Add (string item) {values.Add (item);} - public void Clear () {values.Clear ();} - public bool Contains (string item) {return values.Contains (item);} - public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);} - public bool Remove (string item) {return values.Remove (item);} - public int Count {get {return values.Count;}} - public bool IsReadOnly {get {return false;}} - #endregion - - #region IEnumerable - IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();} - #endregion - - #region IEnumerable - public IEnumerator GetEnumerator () {return values.GetEnumerator ();} - #endregion - - #region IList - int IList.Add (object value) {return (values as IList).Add (value);} - bool IList.Contains (object value) {return (values as IList).Contains (value);} - int IList.IndexOf (object value) {return (values as IList).IndexOf (value);} - void IList.Insert (int index, object value) {(values as IList).Insert (index, value);} - void IList.Remove (object value) {(values as IList).Remove (value);} - void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);} - bool IList.IsFixedSize {get {return false;}} - object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}} - #endregion - - #region IList - public int IndexOf (string item) {return values.IndexOf (item);} - public void Insert (int index, string item) {values.Insert (index, item);} - public void RemoveAt (int index) {values.RemoveAt (index);} - - private void AssertValid (int index) - { - if (c.Option == null) - throw new InvalidOperationException ("OptionContext.Option is null."); - if (index >= c.Option.MaxValueCount) - throw new ArgumentOutOfRangeException ("index"); - if (c.Option.OptionValueType == OptionValueType.Required && - index >= values.Count) - throw new OptionException (string.Format ( - c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), - c.OptionName); - } - - public string this [int index] { - get { - AssertValid (index); - return index >= values.Count ? null : values [index]; - } - set { - values [index] = value; - } - } - #endregion - - public List ToList () - { - return new List (values); - } - - public string[] ToArray () - { - return values.ToArray (); - } - - public override string ToString () - { - return string.Join (", ", values.ToArray ()); - } - } - - public class OptionContext { - private Option option; - private string name; - private int index; - private OptionSet set; - private OptionValueCollection c; - - public OptionContext (OptionSet set) - { - this.set = set; - this.c = new OptionValueCollection (this); - } - - public Option Option { - get {return option;} - set {option = value;} - } - - public string OptionName { - get {return name;} - set {name = value;} - } - - public int OptionIndex { - get {return index;} - set {index = value;} - } - - public OptionSet OptionSet { - get {return set;} - } - - public OptionValueCollection OptionValues { - get {return c;} - } - } - - public enum OptionValueType { - None, - Optional, - Required, - } - - public abstract class Option { - string prototype, description; - string[] names; - OptionValueType type; - int count; - string[] separators; - bool hidden; - - protected Option (string prototype, string description) - : this (prototype, description, 1, false) - { - } - - protected Option (string prototype, string description, int maxValueCount) - : this (prototype, description, maxValueCount, false) - { - } - - protected Option (string prototype, string description, int maxValueCount, bool hidden) - { - if (prototype == null) - throw new ArgumentNullException ("prototype"); - if (prototype.Length == 0) - throw new ArgumentException ("Cannot be the empty string.", "prototype"); - if (maxValueCount < 0) - throw new ArgumentOutOfRangeException ("maxValueCount"); - - this.prototype = prototype; - this.description = description; - this.count = maxValueCount; - this.names = (this is OptionSet.Category) - // append GetHashCode() so that "duplicate" categories have distinct - // names, e.g. adding multiple "" categories should be valid. - ? [prototype + this.GetHashCode ()] - : prototype.Split ('|'); - - if (this is OptionSet.Category || this is CommandOption) - return; - - this.type = ParsePrototype (); - this.hidden = hidden; - - if (this.count == 0 && type != OptionValueType.None) - throw new ArgumentException ( - "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + - "OptionValueType.Optional.", - "maxValueCount"); - if (this.type == OptionValueType.None && maxValueCount > 1) - throw new ArgumentException ( - string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), - "maxValueCount"); - if (Array.IndexOf (names, "<>") >= 0 && - ((names.Length == 1 && this.type != OptionValueType.None) || - (names.Length > 1 && this.MaxValueCount > 1))) - throw new ArgumentException ( - "The default option handler '<>' cannot require values.", - "prototype"); - } - - public string Prototype {get {return prototype;}} - public string Description {get {return description;}} - public OptionValueType OptionValueType {get {return type;}} - public int MaxValueCount {get {return count;}} - public bool Hidden {get {return hidden;}} - - public string[] GetNames () - { - return (string[]) names.Clone (); - } - - public string[] GetValueSeparators () - { - if (separators == null) - return new string [0]; - return (string[]) separators.Clone (); - } - - protected static T Parse (string value, OptionContext c) - { - Type tt = typeof (T); + static class StringCoda + { + + public static IEnumerable WrappedLines(string self, params int[] widths) + { + IEnumerable w = widths; + return WrappedLines(self, w); + } + + public static IEnumerable WrappedLines(string self, IEnumerable widths) + { + if (widths == null) + throw new ArgumentNullException("widths"); + return CreateWrappedLinesIterator(self, widths); + } + + private static IEnumerable CreateWrappedLinesIterator(string self, IEnumerable widths) + { + if (string.IsNullOrEmpty(self)) + { + yield return string.Empty; + yield break; + } + using (IEnumerator ewidths = widths.GetEnumerator()) + { + bool? hw = null; + int width = GetNextWidth(ewidths, int.MaxValue, ref hw); + int start = 0, end; + do + { + end = GetLineEnd(start, width, self); + char c = self[end - 1]; + if (char.IsWhiteSpace(c)) + --end; + bool needContinuation = end != self.Length && !IsEolChar(c); + string continuation = ""; + if (needContinuation) + { + --end; + continuation = "-"; + } + string line = self.Substring(start, end - start) + continuation; + yield return line; + start = end; + if (char.IsWhiteSpace(c)) + ++start; + width = GetNextWidth(ewidths, width, ref hw); + } while (start < self.Length); + } + } + + private static int GetNextWidth(IEnumerator ewidths, int curWidth, ref bool? eValid) + { + if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) + { + curWidth = (eValid = ewidths.MoveNext()).Value ? ewidths.Current : curWidth; + // '.' is any character, - is for a continuation + const string minWidth = ".-"; + if (curWidth < minWidth.Length) + throw new ArgumentOutOfRangeException("widths", + string.Format("Element must be >= {0}, was {1}.", minWidth.Length, curWidth)); + return curWidth; + } + // no more elements, use the last element. + return curWidth; + } + + private static bool IsEolChar(char c) + { + return !char.IsLetterOrDigit(c); + } + + private static int GetLineEnd(int start, int length, string description) + { + int end = System.Math.Min(start + length, description.Length); + int sep = -1; + for (int i = start; i < end; ++i) + { + if (description[i] == '\n') + return i + 1; + if (IsEolChar(description[i])) + sep = i + 1; + } + if (sep == -1 || end == description.Length) + return end; + return sep; + } + } + + public class OptionValueCollection : IList, IList + { + + List values = new List(); + OptionContext c; + + internal OptionValueCollection(OptionContext c) + { + this.c = c; + } + + #region ICollection + void ICollection.CopyTo(Array array, int index) { (values as ICollection).CopyTo(array, index); } + bool ICollection.IsSynchronized { get { return (values as ICollection).IsSynchronized; } } + object ICollection.SyncRoot { get { return (values as ICollection).SyncRoot; } } + #endregion + + #region ICollection + public void Add(string item) { values.Add(item); } + public void Clear() { values.Clear(); } + public bool Contains(string item) { return values.Contains(item); } + public void CopyTo(string[] array, int arrayIndex) { values.CopyTo(array, arrayIndex); } + public bool Remove(string item) { return values.Remove(item); } + public int Count { get { return values.Count; } } + public bool IsReadOnly { get { return false; } } + #endregion + + #region IEnumerable + IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); } + #endregion + + #region IEnumerable + public IEnumerator GetEnumerator() { return values.GetEnumerator(); } + #endregion + + #region IList + int IList.Add(object value) { return (values as IList).Add(value); } + bool IList.Contains(object value) { return (values as IList).Contains(value); } + int IList.IndexOf(object value) { return (values as IList).IndexOf(value); } + void IList.Insert(int index, object value) { (values as IList).Insert(index, value); } + void IList.Remove(object value) { (values as IList).Remove(value); } + void IList.RemoveAt(int index) { (values as IList).RemoveAt(index); } + bool IList.IsFixedSize { get { return false; } } + object IList.this[int index] { get { return this[index]; } set { (values as IList)[index] = value; } } + #endregion + + #region IList + public int IndexOf(string item) { return values.IndexOf(item); } + public void Insert(int index, string item) { values.Insert(index, item); } + public void RemoveAt(int index) { values.RemoveAt(index); } + + private void AssertValid(int index) + { + if (c.Option == null) + throw new InvalidOperationException("OptionContext.Option is null."); + if (index >= c.Option.MaxValueCount) + throw new ArgumentOutOfRangeException("index"); + if (c.Option.OptionValueType == OptionValueType.Required && + index >= values.Count) + throw new OptionException(string.Format( + c.OptionSet.MessageLocalizer("Missing required value for option '{0}'."), c.OptionName), + c.OptionName); + } + + public string this[int index] + { + get + { + AssertValid(index); + return index >= values.Count ? null : values[index]; + } + set + { + values[index] = value; + } + } + #endregion + + public List ToList() + { + return new List(values); + } + + public string[] ToArray() + { + return values.ToArray(); + } + + public override string ToString() + { + return string.Join(", ", values.ToArray()); + } + } + + public class OptionContext + { + private Option option; + private string name; + private int index; + private OptionSet set; + private OptionValueCollection c; + + public OptionContext(OptionSet set) + { + this.set = set; + this.c = new OptionValueCollection(this); + } + + public Option Option + { + get { return option; } + set { option = value; } + } + + public string OptionName + { + get { return name; } + set { name = value; } + } + + public int OptionIndex + { + get { return index; } + set { index = value; } + } + + public OptionSet OptionSet + { + get { return set; } + } + + public OptionValueCollection OptionValues + { + get { return c; } + } + } + + public enum OptionValueType + { + None, + Optional, + Required, + } + + public abstract class Option + { + string prototype, description; + string[] names; + OptionValueType type; + int count; + string[] separators; + bool hidden; + + protected Option(string prototype, string description) + : this(prototype, description, 1, false) + { + } + + protected Option(string prototype, string description, int maxValueCount) + : this(prototype, description, maxValueCount, false) + { + } + + protected Option(string prototype, string description, int maxValueCount, bool hidden) + { + if (prototype == null) + throw new ArgumentNullException("prototype"); + if (prototype.Length == 0) + throw new ArgumentException("Cannot be the empty string.", "prototype"); + if (maxValueCount < 0) + throw new ArgumentOutOfRangeException("maxValueCount"); + + this.prototype = prototype; + this.description = description; + this.count = maxValueCount; + this.names = (this is OptionSet.Category) + // append GetHashCode() so that "duplicate" categories have distinct + // names, e.g. adding multiple "" categories should be valid. + ? [prototype + this.GetHashCode()] + : prototype.Split('|'); + + if (this is OptionSet.Category || this is CommandOption) + return; + + this.type = ParsePrototype(); + this.hidden = hidden; + + if (this.count == 0 && type != OptionValueType.None) + throw new ArgumentException( + "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + + "OptionValueType.Optional.", + "maxValueCount"); + if (this.type == OptionValueType.None && maxValueCount > 1) + throw new ArgumentException( + string.Format("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), + "maxValueCount"); + if (Array.IndexOf(names, "<>") >= 0 && + ((names.Length == 1 && this.type != OptionValueType.None) || + (names.Length > 1 && this.MaxValueCount > 1))) + throw new ArgumentException( + "The default option handler '<>' cannot require values.", + "prototype"); + } + + public string Prototype { get { return prototype; } } + public string Description { get { return description; } } + public OptionValueType OptionValueType { get { return type; } } + public int MaxValueCount { get { return count; } } + public bool Hidden { get { return hidden; } } + + public string[] GetNames() + { + return (string[])names.Clone(); + } + + public string[] GetValueSeparators() + { + if (separators == null) + return new string[0]; + return (string[])separators.Clone(); + } + + protected static T Parse(string value, OptionContext c) + { + Type tt = typeof(T); #if PCL TypeInfo ti = tt.GetTypeInfo (); #else - Type ti = tt; + Type ti = tt; #endif - bool nullable = - ti.IsValueType && - ti.IsGenericType && - !ti.IsGenericTypeDefinition && - ti.GetGenericTypeDefinition () == typeof (Nullable<>); + bool nullable = + ti.IsValueType && + ti.IsGenericType && + !ti.IsGenericTypeDefinition && + ti.GetGenericTypeDefinition() == typeof(Nullable<>); #if PCL Type targetType = nullable ? tt.GenericTypeArguments [0] : tt; #else - Type targetType = nullable ? tt.GetGenericArguments () [0] : tt; + Type targetType = nullable ? tt.GetGenericArguments()[0] : tt; #endif - T t = default (T); - try { - if (value != null) { + T t = default(T); + try + { + if (value != null) + { #if PCL if (targetType.GetTypeInfo ().IsEnum) t = (T) Enum.Parse (targetType, value, true); else t = (T) Convert.ChangeType (value, targetType); #else - TypeConverter conv = TypeDescriptor.GetConverter (targetType); - t = (T) conv.ConvertFromString (value); + TypeConverter conv = TypeDescriptor.GetConverter(targetType); + t = (T)conv.ConvertFromString(value); #endif - } - } - catch (Exception e) { - throw new OptionException ( - string.Format ( - c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."), - value, targetType.Name, c.OptionName), - c.OptionName, e); - } - return t; - } - - internal string[] Names {get {return names;}} - internal string[] ValueSeparators {get {return separators;}} - - static readonly char[] NameTerminator = new char[]{'=', ':'}; - - private OptionValueType ParsePrototype () - { - char type = '\0'; - List seps = new List (); - for (int i = 0; i < names.Length; ++i) { - string name = names [i]; - if (name.Length == 0) - throw new ArgumentException ("Empty option names are not supported.", "prototype"); - - int end = name.IndexOfAny (NameTerminator); - if (end == -1) - continue; - names [i] = name.Substring (0, end); - if (type == '\0' || type == name [end]) - type = name [end]; - else - throw new ArgumentException ( - string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]), - "prototype"); - AddSeparators (name, end, seps); - } - - if (type == '\0') - return OptionValueType.None; - - if (count <= 1 && seps.Count != 0) - throw new ArgumentException ( - string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count), - "prototype"); - if (count > 1) { - if (seps.Count == 0) - this.separators = new string[]{":", "="}; - else if (seps.Count == 1 && seps [0].Length == 0) - this.separators = null; - else - this.separators = seps.ToArray (); - } - - return type == '=' ? OptionValueType.Required : OptionValueType.Optional; - } - - private static void AddSeparators (string name, int end, ICollection seps) - { - int start = -1; - for (int i = end+1; i < name.Length; ++i) { - switch (name [i]) { - case '{': - if (start != -1) - throw new ArgumentException ( - string.Format ("Ill-formed name/value separator found in \"{0}\".", name), - "prototype"); - start = i+1; - break; - case '}': - if (start == -1) - throw new ArgumentException ( - string.Format ("Ill-formed name/value separator found in \"{0}\".", name), - "prototype"); - seps.Add (name.Substring (start, i-start)); - start = -1; - break; - default: - if (start == -1) - seps.Add (name [i].ToString ()); - break; - } - } - if (start != -1) - throw new ArgumentException ( - string.Format ("Ill-formed name/value separator found in \"{0}\".", name), - "prototype"); - } - - public void Invoke (OptionContext c) - { - OnParseComplete (c); - c.OptionName = null; - c.Option = null; - c.OptionValues.Clear (); - } - - protected abstract void OnParseComplete (OptionContext c); - - internal void InvokeOnParseComplete (OptionContext c) - { - OnParseComplete (c); - } - - public override string ToString () - { - return Prototype; - } - } - - public abstract class ArgumentSource { - - protected ArgumentSource () - { - } - - public abstract string[] GetNames (); - public abstract string Description { get; } - public abstract bool GetArguments (string value, out IEnumerable replacement); + } + } + catch (Exception e) + { + throw new OptionException( + string.Format( + c.OptionSet.MessageLocalizer("Could not convert string `{0}' to type {1} for option `{2}'."), + value, targetType.Name, c.OptionName), + c.OptionName, e); + } + return t; + } + + internal string[] Names { get { return names; } } + internal string[] ValueSeparators { get { return separators; } } + + static readonly char[] NameTerminator = new char[] { '=', ':' }; + + private OptionValueType ParsePrototype() + { + char type = '\0'; + List seps = new List(); + for (int i = 0; i < names.Length; ++i) + { + string name = names[i]; + if (name.Length == 0) + throw new ArgumentException("Empty option names are not supported.", "prototype"); + + int end = name.IndexOfAny(NameTerminator); + if (end == -1) + continue; + names[i] = name.Substring(0, end); + if (type == '\0' || type == name[end]) + type = name[end]; + else + throw new ArgumentException( + string.Format("Conflicting option types: '{0}' vs. '{1}'.", type, name[end]), + "prototype"); + AddSeparators(name, end, seps); + } + + if (type == '\0') + return OptionValueType.None; + + if (count <= 1 && seps.Count != 0) + throw new ArgumentException( + string.Format("Cannot provide key/value separators for Options taking {0} value(s).", count), + "prototype"); + if (count > 1) + { + if (seps.Count == 0) + this.separators = new string[] { ":", "=" }; + else if (seps.Count == 1 && seps[0].Length == 0) + this.separators = null; + else + this.separators = seps.ToArray(); + } + + return type == '=' ? OptionValueType.Required : OptionValueType.Optional; + } + + private static void AddSeparators(string name, int end, ICollection seps) + { + int start = -1; + for (int i = end + 1; i < name.Length; ++i) + { + switch (name[i]) + { + case '{': + if (start != -1) + throw new ArgumentException( + string.Format("Ill-formed name/value separator found in \"{0}\".", name), + "prototype"); + start = i + 1; + break; + case '}': + if (start == -1) + throw new ArgumentException( + string.Format("Ill-formed name/value separator found in \"{0}\".", name), + "prototype"); + seps.Add(name.Substring(start, i - start)); + start = -1; + break; + default: + if (start == -1) + seps.Add(name[i].ToString()); + break; + } + } + if (start != -1) + throw new ArgumentException( + string.Format("Ill-formed name/value separator found in \"{0}\".", name), + "prototype"); + } + + public void Invoke(OptionContext c) + { + OnParseComplete(c); + c.OptionName = null; + c.Option = null; + c.OptionValues.Clear(); + } + + protected abstract void OnParseComplete(OptionContext c); + + internal void InvokeOnParseComplete(OptionContext c) + { + OnParseComplete(c); + } + + public override string ToString() + { + return Prototype; + } + } + + public abstract class ArgumentSource + { + + protected ArgumentSource() + { + } + + public abstract string[] GetNames(); + public abstract string Description { get; } + public abstract bool GetArguments(string value, out IEnumerable replacement); #if !PCL || NETSTANDARD1_3 - public static IEnumerable GetArgumentsFromFile (string file) - { - return GetArguments (File.OpenText (file), true); - } + public static IEnumerable GetArgumentsFromFile(string file) + { + return GetArguments(File.OpenText(file), true); + } #endif - public static IEnumerable GetArguments (TextReader reader) - { - return GetArguments (reader, false); - } - - // Cribbed from mcs/driver.cs:LoadArgs(string) - static IEnumerable GetArguments (TextReader reader, bool close) - { - try { - StringBuilder arg = new StringBuilder (); - - string line; - while ((line = reader.ReadLine ()) != null) { - int t = line.Length; - - for (int i = 0; i < t; i++) { - char c = line [i]; - - if (c == '"' || c == '\'') { - char end = c; - - for (i++; i < t; i++){ - c = line [i]; - - if (c == end) - break; - arg.Append (c); - } - } else if (c == ' ') { - if (arg.Length > 0) { - yield return arg.ToString (); - arg.Length = 0; - } - } else - arg.Append (c); - } - if (arg.Length > 0) { - yield return arg.ToString (); - arg.Length = 0; - } - } - } - finally { - if (close) - reader.Dispose (); - } - } - } + public static IEnumerable GetArguments(TextReader reader) + { + return GetArguments(reader, false); + } + + // Cribbed from mcs/driver.cs:LoadArgs(string) + static IEnumerable GetArguments(TextReader reader, bool close) + { + try + { + StringBuilder arg = new StringBuilder(); + + string line; + while ((line = reader.ReadLine()) != null) + { + int t = line.Length; + + for (int i = 0; i < t; i++) + { + char c = line[i]; + + if (c == '"' || c == '\'') + { + char end = c; + + for (i++; i < t; i++) + { + c = line[i]; + + if (c == end) + break; + arg.Append(c); + } + } + else if (c == ' ') + { + if (arg.Length > 0) + { + yield return arg.ToString(); + arg.Length = 0; + } + } + else + arg.Append(c); + } + if (arg.Length > 0) + { + yield return arg.ToString(); + arg.Length = 0; + } + } + } + finally + { + if (close) + reader.Dispose(); + } + } + } #if !PCL || NETSTANDARD1_3 - public class ResponseFileSource : ArgumentSource { - - public override string[] GetNames () - { - return new string[]{"@file"}; - } - - public override string Description { - get {return "Read response file for more options.";} - } - - public override bool GetArguments (string value, out IEnumerable replacement) - { - if (string.IsNullOrEmpty (value) || !value.StartsWith ("@")) { - replacement = null; - return false; - } - replacement = ArgumentSource.GetArgumentsFromFile (value.Substring (1)); - return true; - } - } + public class ResponseFileSource : ArgumentSource + { + + public override string[] GetNames() + { + return new string[] { "@file" }; + } + + public override string Description + { + get { return "Read response file for more options."; } + } + + public override bool GetArguments(string value, out IEnumerable replacement) + { + if (string.IsNullOrEmpty(value) || !value.StartsWith("@")) + { + replacement = null; + return false; + } + replacement = ArgumentSource.GetArgumentsFromFile(value.Substring(1)); + return true; + } + } #endif #if !PCL - [Serializable] + [Serializable] #endif - public class OptionException : Exception { - private string option; - - public OptionException () - { - } - - public OptionException (string message, string optionName) - : base (message) - { - this.option = optionName; - } - - public OptionException (string message, string optionName, Exception innerException) - : base (message, innerException) - { - this.option = optionName; - } + public class OptionException : Exception + { + private string option; + + public OptionException() + { + } + + public OptionException(string message, string optionName) + : base(message) + { + this.option = optionName; + } + + public OptionException(string message, string optionName, Exception innerException) + : base(message, innerException) + { + this.option = optionName; + } #if !PCL - protected OptionException (SerializationInfo info, StreamingContext context) - : base (info, context) - { - this.option = info.GetString ("OptionName"); - } + protected OptionException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + this.option = info.GetString("OptionName"); + } #endif - public string OptionName { - get {return this.option;} - } + public string OptionName + { + get { return this.option; } + } #if !PCL && !NET #pragma warning disable 618 // SecurityPermissionAttribute is obsolete @@ -759,1056 +802,1135 @@ public override void GetObjectData (SerializationInfo info, StreamingContext con info.AddValue ("OptionName", option); } #endif - } - - public delegate void OptionAction (TKey key, TValue value); - - public class OptionSet : KeyedCollection - { - public OptionSet () - : this (null) - { - } - - public OptionSet (MessageLocalizerConverter localizer) - { - this.roSources = new ReadOnlyCollection (sources); - this.localizer = localizer; - if (this.localizer == null) { - this.localizer = delegate (string f) { - return f; - }; - } - } - - MessageLocalizerConverter localizer; - - public MessageLocalizerConverter MessageLocalizer { - get {return localizer;} - internal set {localizer = value;} - } - - List sources = new List (); - ReadOnlyCollection roSources; - - public ReadOnlyCollection ArgumentSources { - get {return roSources;} - } - - - protected override string GetKeyForItem (Option item) - { - if (item == null) - throw new ArgumentNullException ("option"); - if (item.Names != null && item.Names.Length > 0) - return item.Names [0]; - // This should never happen, as it's invalid for Option to be - // constructed w/o any names. - throw new InvalidOperationException ("Option has no names!"); - } - - [Obsolete ("Use KeyedCollection.this[string]")] - protected Option GetOptionForName (string option) - { - if (option == null) - throw new ArgumentNullException ("option"); - try { - return base [option]; - } - catch (KeyNotFoundException) { - return null; - } - } - - protected override void InsertItem (int index, Option item) - { - base.InsertItem (index, item); - AddImpl (item); - } - - protected override void RemoveItem (int index) - { - Option p = Items [index]; - base.RemoveItem (index); - // KeyedCollection.RemoveItem() handles the 0th item - for (int i = 1; i < p.Names.Length; ++i) { - Dictionary.Remove (p.Names [i]); - } - } - - protected override void SetItem (int index, Option item) - { - base.SetItem (index, item); - AddImpl (item); - } - - private void AddImpl (Option option) - { - if (option == null) - throw new ArgumentNullException ("option"); - List added = new List (option.Names.Length); - try { - // KeyedCollection.InsertItem/SetItem handle the 0th name. - for (int i = 1; i < option.Names.Length; ++i) { - Dictionary.Add (option.Names [i], option); - added.Add (option.Names [i]); - } - } - catch (Exception) { - foreach (string name in added) - Dictionary.Remove (name); - throw; - } - } - - public OptionSet Add (string header) - { - if (header == null) - throw new ArgumentNullException ("header"); - Add (new Category (header)); - return this; - } - - internal sealed class Category : Option { - - // Prototype starts with '=' because this is an invalid prototype - // (see Option.ParsePrototype(), and thus it'll prevent Category - // instances from being accidentally used as normal options. - public Category (string description) - : base ("=:Category:= " + description, description) - { - } - - protected override void OnParseComplete (OptionContext c) - { - throw new NotSupportedException ("Category.OnParseComplete should not be invoked."); - } - } - - - public new OptionSet Add (Option option) - { - base.Add (option); - return this; - } - - sealed class ActionOption : Option { - Action action; - - public ActionOption (string prototype, string description, int count, Action action) - : this (prototype, description, count, action, false) - { - } - - public ActionOption (string prototype, string description, int count, Action action, bool hidden) - : base (prototype, description, count, hidden) - { - if (action == null) - throw new ArgumentNullException ("action"); - this.action = action; - } - - protected override void OnParseComplete (OptionContext c) - { - action (c.OptionValues); - } - } - - public OptionSet Add (string prototype, Action action) - { - return Add (prototype, null, action); - } - - public OptionSet Add (string prototype, string description, Action action) - { - return Add (prototype, description, action, false); - } - - public OptionSet Add (string prototype, string description, Action action, bool hidden) - { - if (action == null) - throw new ArgumentNullException ("action"); - Option p = new ActionOption (prototype, description, 1, - delegate (OptionValueCollection v) { action (v [0]); }, hidden); - base.Add (p); - return this; - } - - public OptionSet Add (string prototype, OptionAction action) - { - return Add (prototype, null, action); - } - - public OptionSet Add (string prototype, string description, OptionAction action) - { - return Add (prototype, description, action, false); - } - - public OptionSet Add (string prototype, string description, OptionAction action, bool hidden) { - if (action == null) - throw new ArgumentNullException ("action"); - Option p = new ActionOption (prototype, description, 2, - delegate (OptionValueCollection v) {action (v [0], v [1]);}, hidden); - base.Add (p); - return this; - } - - sealed class ActionOption : Option { - Action action; - - public ActionOption (string prototype, string description, Action action) - : base (prototype, description, 1) - { - if (action == null) - throw new ArgumentNullException ("action"); - this.action = action; - } - - protected override void OnParseComplete (OptionContext c) - { - action (Parse (c.OptionValues [0], c)); - } - } - - sealed class ActionOption : Option { - OptionAction action; - - public ActionOption (string prototype, string description, OptionAction action) - : base (prototype, description, 2) - { - if (action == null) - throw new ArgumentNullException ("action"); - this.action = action; - } - - protected override void OnParseComplete (OptionContext c) - { - action ( - Parse (c.OptionValues [0], c), - Parse (c.OptionValues [1], c)); - } - } - - public OptionSet Add (string prototype, Action action) - { - return Add (prototype, null, action); - } - - public OptionSet Add (string prototype, string description, Action action) - { - return Add (new ActionOption (prototype, description, action)); - } - - public OptionSet Add (string prototype, OptionAction action) - { - return Add (prototype, null, action); - } - - public OptionSet Add (string prototype, string description, OptionAction action) - { - return Add (new ActionOption (prototype, description, action)); - } - - public OptionSet Add (ArgumentSource source) - { - if (source == null) - throw new ArgumentNullException ("source"); - sources.Add (source); - return this; - } - - protected virtual OptionContext CreateOptionContext () - { - return new OptionContext (this); - } - - public List Parse (IEnumerable arguments) - { - if (arguments == null) - throw new ArgumentNullException ("arguments"); - OptionContext c = CreateOptionContext (); - c.OptionIndex = -1; - bool process = true; - List unprocessed = new List (); - Option def = Contains ("<>") ? this ["<>"] : null; - ArgumentEnumerator ae = new ArgumentEnumerator (arguments); - foreach (string argument in ae) { - ++c.OptionIndex; - if (argument == "--") { - process = false; - continue; - } - if (!process) { - Unprocessed (unprocessed, def, c, argument); - continue; - } - if (AddSource (ae, argument)) - continue; - if (!Parse (argument, c)) - Unprocessed (unprocessed, def, c, argument); - } - if (c.Option != null) - c.Option.Invoke (c); - return unprocessed; - } - - class ArgumentEnumerator : IEnumerable { - List> sources = new List> (); - - public ArgumentEnumerator (IEnumerable arguments) - { - sources.Add (arguments.GetEnumerator ()); - } - - public void Add (IEnumerable arguments) - { - sources.Add (arguments.GetEnumerator ()); - } - - public IEnumerator GetEnumerator () - { - do { - IEnumerator c = sources [sources.Count-1]; - if (c.MoveNext ()) - yield return c.Current; - else { - c.Dispose (); - sources.RemoveAt (sources.Count-1); - } - } while (sources.Count > 0); - } - - IEnumerator IEnumerable.GetEnumerator () - { - return GetEnumerator (); - } - } - - bool AddSource (ArgumentEnumerator ae, string argument) - { - foreach (ArgumentSource source in sources) { - IEnumerable replacement; - if (!source.GetArguments (argument, out replacement)) - continue; - ae.Add (replacement); - return true; - } - return false; - } - - private static bool Unprocessed (ICollection extra, Option def, OptionContext c, string argument) - { - if (def == null) { - extra.Add (argument); - return false; - } - c.OptionValues.Add (argument); - c.Option = def; - c.Option.Invoke (c); - return false; - } - - private readonly Regex ValueOption = new Regex ( - @"^(?--|-|/)(?[^:=]+)((?[:=])(?.*))?$"); - - protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value) - { - if (argument == null) - throw new ArgumentNullException ("argument"); - - flag = name = sep = value = null; - Match m = ValueOption.Match (argument); - if (!m.Success) { - return false; - } - flag = m.Groups ["flag"].Value; - name = m.Groups ["name"].Value; - if (m.Groups ["sep"].Success && m.Groups ["value"].Success) { - sep = m.Groups ["sep"].Value; - value = m.Groups ["value"].Value; - } - return true; - } - - protected virtual bool Parse (string argument, OptionContext c) - { - if (c.Option != null) { - ParseValue (argument, c); - return true; - } - - string f, n, s, v; - if (!GetOptionParts (argument, out f, out n, out s, out v)) - return false; - - Option p; - if (Contains (n)) { - p = this [n]; - c.OptionName = f + n; - c.Option = p; - switch (p.OptionValueType) { - case OptionValueType.None: - c.OptionValues.Add (n); - c.Option.Invoke (c); - break; - case OptionValueType.Optional: - case OptionValueType.Required: - ParseValue (v, c); - break; - } - return true; - } - // no match; is it a bool option? - if (ParseBool (argument, n, c)) - return true; - // is it a bundled option? - if (ParseBundledValue (f, string.Concat (n + s + v), c)) - return true; - - return false; - } - - private void ParseValue (string option, OptionContext c) - { - if (option != null) - foreach (string o in c.Option.ValueSeparators != null - ? option.Split (c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None) - : new string[]{option}) { - c.OptionValues.Add (o); - } - if (c.OptionValues.Count == c.Option.MaxValueCount || - c.Option.OptionValueType == OptionValueType.Optional) - c.Option.Invoke (c); - else if (c.OptionValues.Count > c.Option.MaxValueCount) { - throw new OptionException (localizer (string.Format ( - "Error: Found {0} option values when expecting {1}.", - c.OptionValues.Count, c.Option.MaxValueCount)), - c.OptionName); - } - } - - private bool ParseBool (string option, string n, OptionContext c) - { - Option p; - string rn; - if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') && - Contains ((rn = n.Substring (0, n.Length-1)))) { - p = this [rn]; - string v = n [n.Length-1] == '+' ? option : null; - c.OptionName = option; - c.Option = p; - c.OptionValues.Add (v); - p.Invoke (c); - return true; - } - return false; - } - - private bool ParseBundledValue (string f, string n, OptionContext c) - { - if (f != "-") - return false; - for (int i = 0; i < n.Length; ++i) { - Option p; - string opt = f + n [i].ToString (); - string rn = n [i].ToString (); - if (!Contains (rn)) { - if (i == 0) - return false; - throw new OptionException (string.Format (localizer ( - "Cannot use unregistered option '{0}' in bundle '{1}'."), rn, f + n), null); - } - p = this [rn]; - switch (p.OptionValueType) { - case OptionValueType.None: - Invoke (c, opt, n, p); - break; - case OptionValueType.Optional: - case OptionValueType.Required: { - string v = n.Substring (i+1); - c.Option = p; - c.OptionName = opt; - ParseValue (v.Length != 0 ? v : null, c); - return true; - } - default: - throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType); - } - } - return true; - } - - private static void Invoke (OptionContext c, string name, string value, Option option) - { - c.OptionName = name; - c.Option = option; - c.OptionValues.Add (value); - option.Invoke (c); - } - - private const int OptionWidth = 29; - private const int Description_FirstWidth = 80 - OptionWidth; - private const int Description_RemWidth = 80 - OptionWidth - 2; - - static readonly string CommandHelpIndentStart = new string (' ', OptionWidth); - static readonly string CommandHelpIndentRemaining = new string (' ', OptionWidth + 2); - - public void WriteOptionDescriptions (TextWriter o) - { - foreach (Option p in this) { - int written = 0; - - if (p.Hidden) - continue; - - Category c = p as Category; - if (c != null) { - WriteDescription (o, p.Description, "", 80, 80); - continue; - } - CommandOption co = p as CommandOption; - if (co != null) { - WriteCommandDescription (o, co.Command); - continue; - } - - if (!WriteOptionPrototype (o, p, ref written)) - continue; - - if (written < OptionWidth) - o.Write (new string (' ', OptionWidth - written)); - else { - o.WriteLine (); - o.Write (new string (' ', OptionWidth)); - } - - WriteDescription (o, p.Description, new string (' ', OptionWidth+2), - Description_FirstWidth, Description_RemWidth); - } - - foreach (ArgumentSource s in sources) { - string[] names = s.GetNames (); - if (names == null || names.Length == 0) - continue; - - int written = 0; - - Write (o, ref written, " "); - Write (o, ref written, names [0]); - for (int i = 1; i < names.Length; ++i) { - Write (o, ref written, ", "); - Write (o, ref written, names [i]); - } - - if (written < OptionWidth) - o.Write (new string (' ', OptionWidth - written)); - else { - o.WriteLine (); - o.Write (new string (' ', OptionWidth)); - } - - WriteDescription (o, s.Description, new string (' ', OptionWidth+2), - Description_FirstWidth, Description_RemWidth); - } - } - - internal void WriteCommandDescription (TextWriter o, Command c) - { - var name = new string (' ', 8) + c.Name; - if (name.Length < OptionWidth - 1) { - WriteDescription (o, name + new string (' ', OptionWidth - name.Length) + c.Help, CommandHelpIndentRemaining, 80, Description_RemWidth); - } else { - WriteDescription (o, name, "", 80, 80); - WriteDescription (o, CommandHelpIndentStart + c.Help, CommandHelpIndentRemaining, 80, Description_RemWidth); - } - } - - void WriteDescription (TextWriter o, string value, string prefix, int firstWidth, int remWidth) - { - bool indent = false; - foreach (string line in GetLines (localizer (GetDescription (value)), firstWidth, remWidth)) { - if (indent) - o.Write (prefix); - o.WriteLine (line); - indent = true; - } - } - - bool WriteOptionPrototype (TextWriter o, Option p, ref int written) - { - string[] names = p.Names; - - int i = GetNextOptionIndex (names, 0); - if (i == names.Length) - return false; - - if (names [i].Length == 1) { - Write (o, ref written, " -"); - Write (o, ref written, names [0]); - } - else { - Write (o, ref written, " --"); - Write (o, ref written, names [0]); - } - - for ( i = GetNextOptionIndex (names, i+1); - i < names.Length; i = GetNextOptionIndex (names, i+1)) { - Write (o, ref written, ", "); - Write (o, ref written, names [i].Length == 1 ? "-" : "--"); - Write (o, ref written, names [i]); - } - - if (p.OptionValueType == OptionValueType.Optional || - p.OptionValueType == OptionValueType.Required) { - if (p.OptionValueType == OptionValueType.Optional) { - Write (o, ref written, localizer ("[")); - } - Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description))); - string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 - ? p.ValueSeparators [0] - : " "; - for (int c = 1; c < p.MaxValueCount; ++c) { - Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description))); - } - if (p.OptionValueType == OptionValueType.Optional) { - Write (o, ref written, localizer ("]")); - } - } - return true; - } - - static int GetNextOptionIndex (string[] names, int i) - { - while (i < names.Length && names [i] == "<>") { - ++i; - } - return i; - } - - static void Write (TextWriter o, ref int n, string s) - { - n += s.Length; - o.Write (s); - } - - private static string GetArgumentName (int index, int maxIndex, string description) - { - if (description == null) - return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); - string[] nameStart; - if (maxIndex == 1) - nameStart = new string[]{"{0:", "{"}; - else - nameStart = new string[]{"{" + index + ":"}; - for (int i = 0; i < nameStart.Length; ++i) { - int start, j = 0; - do { - start = description.IndexOf (nameStart [i], j); - } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false); - if (start == -1) - continue; - int end = description.IndexOf ("}", start); - if (end == -1) - continue; - return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length); - } - return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); - } - - private static string GetDescription (string description) - { - if (description == null) - return string.Empty; - StringBuilder sb = new StringBuilder (description.Length); - int start = -1; - for (int i = 0; i < description.Length; ++i) { - switch (description [i]) { - case '{': - if (i == start) { - sb.Append ('{'); - start = -1; - } - else if (start < 0) - start = i + 1; - break; - case '}': - if (start < 0) { - if ((i+1) == description.Length || description [i+1] != '}') - throw new InvalidOperationException ("Invalid option description: " + description); - ++i; - sb.Append ("}"); - } - else { - sb.Append (description.Substring (start, i - start)); - start = -1; - } - break; - case ':': - if (start < 0) - goto default; - start = i + 1; - break; - default: - if (start < 0) - sb.Append (description [i]); - break; - } - } - return sb.ToString (); - } - - private static IEnumerable GetLines (string description, int firstWidth, int remWidth) - { - return StringCoda.WrappedLines (description, firstWidth, remWidth); - } - } - - public class Command - { - public string Name {get;} - public string Help {get;} - - public OptionSet Options {get; set;} - public Action> Run {get; set;} - - public CommandSet CommandSet {get; internal set;} - - public Command (string name, string help = null) - { - if (string.IsNullOrEmpty (name)) - throw new ArgumentNullException (nameof (name)); - - Name = name; - Help = help; - } - - public virtual int Invoke (IEnumerable arguments) - { - var rest = Options?.Parse (arguments) ?? arguments; - Run?.Invoke (rest); - return 0; - } - } - - class CommandOption : Option - { - public Command Command {get;} - - // Prototype starts with '=' because this is an invalid prototype - // (see Option.ParsePrototype(), and thus it'll prevent Category - // instances from being accidentally used as normal options. - public CommandOption (Command command, bool hidden = false) - : base ("=:Command:= " + command?.Name, command?.Name, maxValueCount: 0, hidden: hidden) - { - if (command == null) - throw new ArgumentNullException (nameof (command)); - Command = command; - } - - protected override void OnParseComplete (OptionContext c) - { - throw new NotSupportedException ("CommandOption.OnParseComplete should not be invoked."); - } - } - - class HelpOption : Option - { - Option option; - CommandSet commands; - - public HelpOption (CommandSet commands, Option d) - : base (d.Prototype, d.Description, d.MaxValueCount, d.Hidden) - { - this.commands = commands; - this.option = d; - } - - protected override void OnParseComplete (OptionContext c) - { - commands.showHelp = true; - - option?.InvokeOnParseComplete (c); - } - } - - class CommandOptionSet : OptionSet - { - CommandSet commands; - - public CommandOptionSet (CommandSet commands, MessageLocalizerConverter localizer) - : base (localizer) - { - this.commands = commands; - } - - protected override void SetItem (int index, Option item) - { - if (ShouldWrapOption (item)) { - base.SetItem (index, new HelpOption (commands, item)); - return; - } - base.SetItem (index, item); - } - - bool ShouldWrapOption (Option item) - { - if (item == null) - return false; - var help = item as HelpOption; - if (help != null) - return false; - foreach (var n in item.Names) { - if (n == "help") - return true; - } - return false; - } - - protected override void InsertItem (int index, Option item) - { - if (ShouldWrapOption (item)) { - base.InsertItem (index, new HelpOption (commands, item)); - return; - } - base.InsertItem (index, item); - } - } - - public class CommandSet : KeyedCollection - { - readonly OptionSet options; - readonly TextWriter outWriter; - readonly TextWriter errorWriter; - readonly string suite; - - HelpCommand help; - - internal bool showHelp; - - internal OptionSet Options => options; + } + + public delegate void OptionAction(TKey key, TValue value); + + public class OptionSet : KeyedCollection + { + public OptionSet() + : this(null) + { + } + + public OptionSet(MessageLocalizerConverter localizer) + { + this.roSources = new ReadOnlyCollection(sources); + this.localizer = localizer; + if (this.localizer == null) + { + this.localizer = delegate (string f) + { + return f; + }; + } + } + + MessageLocalizerConverter localizer; + + public MessageLocalizerConverter MessageLocalizer + { + get { return localizer; } + internal set { localizer = value; } + } + + List sources = new List(); + ReadOnlyCollection roSources; + + public ReadOnlyCollection ArgumentSources + { + get { return roSources; } + } + + + protected override string GetKeyForItem(Option item) + { + if (item == null) + throw new ArgumentNullException("option"); + if (item.Names != null && item.Names.Length > 0) + return item.Names[0]; + // This should never happen, as it's invalid for Option to be + // constructed w/o any names. + throw new InvalidOperationException("Option has no names!"); + } + + [Obsolete("Use KeyedCollection.this[string]")] + protected Option GetOptionForName(string option) + { + if (option == null) + throw new ArgumentNullException("option"); + try + { + return base[option]; + } + catch (KeyNotFoundException) + { + return null; + } + } + + protected override void InsertItem(int index, Option item) + { + base.InsertItem(index, item); + AddImpl(item); + } + + protected override void RemoveItem(int index) + { + Option p = Items[index]; + base.RemoveItem(index); + // KeyedCollection.RemoveItem() handles the 0th item + for (int i = 1; i < p.Names.Length; ++i) + { + Dictionary.Remove(p.Names[i]); + } + } + + protected override void SetItem(int index, Option item) + { + base.SetItem(index, item); + AddImpl(item); + } + + private void AddImpl(Option option) + { + if (option == null) + throw new ArgumentNullException("option"); + List added = new List(option.Names.Length); + try + { + // KeyedCollection.InsertItem/SetItem handle the 0th name. + for (int i = 1; i < option.Names.Length; ++i) + { + Dictionary.Add(option.Names[i], option); + added.Add(option.Names[i]); + } + } + catch (Exception) + { + foreach (string name in added) + Dictionary.Remove(name); + throw; + } + } + + public OptionSet Add(string header) + { + if (header == null) + throw new ArgumentNullException("header"); + Add(new Category(header)); + return this; + } + + internal sealed class Category : Option + { + + // Prototype starts with '=' because this is an invalid prototype + // (see Option.ParsePrototype(), and thus it'll prevent Category + // instances from being accidentally used as normal options. + public Category(string description) + : base("=:Category:= " + description, description) + { + } + + protected override void OnParseComplete(OptionContext c) + { + throw new NotSupportedException("Category.OnParseComplete should not be invoked."); + } + } + + + public new OptionSet Add(Option option) + { + base.Add(option); + return this; + } + + sealed class ActionOption : Option + { + Action action; + + public ActionOption(string prototype, string description, int count, Action action) + : this(prototype, description, count, action, false) + { + } + + public ActionOption(string prototype, string description, int count, Action action, bool hidden) + : base(prototype, description, count, hidden) + { + if (action == null) + throw new ArgumentNullException("action"); + this.action = action; + } + + protected override void OnParseComplete(OptionContext c) + { + action(c.OptionValues); + } + } + + public OptionSet Add(string prototype, Action action) + { + return Add(prototype, null, action); + } + + public OptionSet Add(string prototype, string description, Action action) + { + return Add(prototype, description, action, false); + } + + public OptionSet Add(string prototype, string description, Action action, bool hidden) + { + if (action == null) + throw new ArgumentNullException("action"); + Option p = new ActionOption(prototype, description, 1, + delegate (OptionValueCollection v) { action(v[0]); }, hidden); + base.Add(p); + return this; + } + + public OptionSet Add(string prototype, OptionAction action) + { + return Add(prototype, null, action); + } + + public OptionSet Add(string prototype, string description, OptionAction action) + { + return Add(prototype, description, action, false); + } + + public OptionSet Add(string prototype, string description, OptionAction action, bool hidden) + { + if (action == null) + throw new ArgumentNullException("action"); + Option p = new ActionOption(prototype, description, 2, + delegate (OptionValueCollection v) { action(v[0], v[1]); }, hidden); + base.Add(p); + return this; + } + + sealed class ActionOption : Option + { + Action action; + + public ActionOption(string prototype, string description, Action action) + : base(prototype, description, 1) + { + if (action == null) + throw new ArgumentNullException("action"); + this.action = action; + } + + protected override void OnParseComplete(OptionContext c) + { + action(Parse(c.OptionValues[0], c)); + } + } + + sealed class ActionOption : Option + { + OptionAction action; + + public ActionOption(string prototype, string description, OptionAction action) + : base(prototype, description, 2) + { + if (action == null) + throw new ArgumentNullException("action"); + this.action = action; + } + + protected override void OnParseComplete(OptionContext c) + { + action( + Parse(c.OptionValues[0], c), + Parse(c.OptionValues[1], c)); + } + } + + public OptionSet Add(string prototype, Action action) + { + return Add(prototype, null, action); + } + + public OptionSet Add(string prototype, string description, Action action) + { + return Add(new ActionOption(prototype, description, action)); + } + + public OptionSet Add(string prototype, OptionAction action) + { + return Add(prototype, null, action); + } + + public OptionSet Add(string prototype, string description, OptionAction action) + { + return Add(new ActionOption(prototype, description, action)); + } + + public OptionSet Add(ArgumentSource source) + { + if (source == null) + throw new ArgumentNullException("source"); + sources.Add(source); + return this; + } + + protected virtual OptionContext CreateOptionContext() + { + return new OptionContext(this); + } + + public List Parse(IEnumerable arguments) + { + if (arguments == null) + throw new ArgumentNullException("arguments"); + OptionContext c = CreateOptionContext(); + c.OptionIndex = -1; + bool process = true; + List unprocessed = new List(); + Option def = Contains("<>") ? this["<>"] : null; + ArgumentEnumerator ae = new ArgumentEnumerator(arguments); + foreach (string argument in ae) + { + ++c.OptionIndex; + if (argument == "--") + { + process = false; + continue; + } + if (!process) + { + Unprocessed(unprocessed, def, c, argument); + continue; + } + if (AddSource(ae, argument)) + continue; + if (!Parse(argument, c)) + Unprocessed(unprocessed, def, c, argument); + } + if (c.Option != null) + c.Option.Invoke(c); + return unprocessed; + } + + class ArgumentEnumerator : IEnumerable + { + List> sources = new List>(); + + public ArgumentEnumerator(IEnumerable arguments) + { + sources.Add(arguments.GetEnumerator()); + } + + public void Add(IEnumerable arguments) + { + sources.Add(arguments.GetEnumerator()); + } + + public IEnumerator GetEnumerator() + { + do + { + IEnumerator c = sources[sources.Count - 1]; + if (c.MoveNext()) + yield return c.Current; + else + { + c.Dispose(); + sources.RemoveAt(sources.Count - 1); + } + } while (sources.Count > 0); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + bool AddSource(ArgumentEnumerator ae, string argument) + { + foreach (ArgumentSource source in sources) + { + IEnumerable replacement; + if (!source.GetArguments(argument, out replacement)) + continue; + ae.Add(replacement); + return true; + } + return false; + } + + private static bool Unprocessed(ICollection extra, Option def, OptionContext c, string argument) + { + if (def == null) + { + extra.Add(argument); + return false; + } + c.OptionValues.Add(argument); + c.Option = def; + c.Option.Invoke(c); + return false; + } + + private readonly Regex ValueOption = new Regex( + @"^(?--|-|/)(?[^:=]+)((?[:=])(?.*))?$"); + + protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value) + { + if (argument == null) + throw new ArgumentNullException("argument"); + + flag = name = sep = value = null; + Match m = ValueOption.Match(argument); + if (!m.Success) + { + return false; + } + flag = m.Groups["flag"].Value; + name = m.Groups["name"].Value; + if (m.Groups["sep"].Success && m.Groups["value"].Success) + { + sep = m.Groups["sep"].Value; + value = m.Groups["value"].Value; + } + return true; + } + + protected virtual bool Parse(string argument, OptionContext c) + { + if (c.Option != null) + { + ParseValue(argument, c); + return true; + } + + string f, n, s, v; + if (!GetOptionParts(argument, out f, out n, out s, out v)) + return false; + + Option p; + if (Contains(n)) + { + p = this[n]; + c.OptionName = f + n; + c.Option = p; + switch (p.OptionValueType) + { + case OptionValueType.None: + c.OptionValues.Add(n); + c.Option.Invoke(c); + break; + case OptionValueType.Optional: + case OptionValueType.Required: + ParseValue(v, c); + break; + } + return true; + } + // no match; is it a bool option? + if (ParseBool(argument, n, c)) + return true; + // is it a bundled option? + if (ParseBundledValue(f, string.Concat(n + s + v), c)) + return true; + + return false; + } + + private void ParseValue(string option, OptionContext c) + { + if (option != null) + foreach (string o in c.Option.ValueSeparators != null + ? option.Split(c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None) + : new string[] { option }) + { + c.OptionValues.Add(o); + } + if (c.OptionValues.Count == c.Option.MaxValueCount || + c.Option.OptionValueType == OptionValueType.Optional) + c.Option.Invoke(c); + else if (c.OptionValues.Count > c.Option.MaxValueCount) + { + throw new OptionException(localizer(string.Format( + "Error: Found {0} option values when expecting {1}.", + c.OptionValues.Count, c.Option.MaxValueCount)), + c.OptionName); + } + } + + private bool ParseBool(string option, string n, OptionContext c) + { + Option p; + string rn; + if (n.Length >= 1 && (n[n.Length - 1] == '+' || n[n.Length - 1] == '-') && + Contains((rn = n.Substring(0, n.Length - 1)))) + { + p = this[rn]; + string v = n[n.Length - 1] == '+' ? option : null; + c.OptionName = option; + c.Option = p; + c.OptionValues.Add(v); + p.Invoke(c); + return true; + } + return false; + } + + private bool ParseBundledValue(string f, string n, OptionContext c) + { + if (f != "-") + return false; + for (int i = 0; i < n.Length; ++i) + { + Option p; + string opt = f + n[i].ToString(); + string rn = n[i].ToString(); + if (!Contains(rn)) + { + if (i == 0) + return false; + throw new OptionException(string.Format(localizer( + "Cannot use unregistered option '{0}' in bundle '{1}'."), rn, f + n), null); + } + p = this[rn]; + switch (p.OptionValueType) + { + case OptionValueType.None: + Invoke(c, opt, n, p); + break; + case OptionValueType.Optional: + case OptionValueType.Required: + { + string v = n.Substring(i + 1); + c.Option = p; + c.OptionName = opt; + ParseValue(v.Length != 0 ? v : null, c); + return true; + } + default: + throw new InvalidOperationException("Unknown OptionValueType: " + p.OptionValueType); + } + } + return true; + } + + private static void Invoke(OptionContext c, string name, string value, Option option) + { + c.OptionName = name; + c.Option = option; + c.OptionValues.Add(value); + option.Invoke(c); + } + + private const int OptionWidth = 29; + private const int Description_FirstWidth = 80 - OptionWidth; + private const int Description_RemWidth = 80 - OptionWidth - 2; + + static readonly string CommandHelpIndentStart = new string(' ', OptionWidth); + static readonly string CommandHelpIndentRemaining = new string(' ', OptionWidth + 2); + + public void WriteOptionDescriptions(TextWriter o) + { + foreach (Option p in this) + { + int written = 0; + + if (p.Hidden) + continue; + + Category c = p as Category; + if (c != null) + { + WriteDescription(o, p.Description, "", 80, 80); + continue; + } + CommandOption co = p as CommandOption; + if (co != null) + { + WriteCommandDescription(o, co.Command); + continue; + } + + if (!WriteOptionPrototype(o, p, ref written)) + continue; + + if (written < OptionWidth) + o.Write(new string(' ', OptionWidth - written)); + else + { + o.WriteLine(); + o.Write(new string(' ', OptionWidth)); + } + + WriteDescription(o, p.Description, new string(' ', OptionWidth + 2), + Description_FirstWidth, Description_RemWidth); + } + + foreach (ArgumentSource s in sources) + { + string[] names = s.GetNames(); + if (names == null || names.Length == 0) + continue; + + int written = 0; + + Write(o, ref written, " "); + Write(o, ref written, names[0]); + for (int i = 1; i < names.Length; ++i) + { + Write(o, ref written, ", "); + Write(o, ref written, names[i]); + } + + if (written < OptionWidth) + o.Write(new string(' ', OptionWidth - written)); + else + { + o.WriteLine(); + o.Write(new string(' ', OptionWidth)); + } + + WriteDescription(o, s.Description, new string(' ', OptionWidth + 2), + Description_FirstWidth, Description_RemWidth); + } + } + + internal void WriteCommandDescription(TextWriter o, Command c) + { + var name = new string(' ', 8) + c.Name; + if (name.Length < OptionWidth - 1) + { + WriteDescription(o, name + new string(' ', OptionWidth - name.Length) + c.Help, CommandHelpIndentRemaining, 80, Description_RemWidth); + } + else + { + WriteDescription(o, name, "", 80, 80); + WriteDescription(o, CommandHelpIndentStart + c.Help, CommandHelpIndentRemaining, 80, Description_RemWidth); + } + } + + void WriteDescription(TextWriter o, string value, string prefix, int firstWidth, int remWidth) + { + bool indent = false; + foreach (string line in GetLines(localizer(GetDescription(value)), firstWidth, remWidth)) + { + if (indent) + o.Write(prefix); + o.WriteLine(line); + indent = true; + } + } + + bool WriteOptionPrototype(TextWriter o, Option p, ref int written) + { + string[] names = p.Names; + + int i = GetNextOptionIndex(names, 0); + if (i == names.Length) + return false; + + if (names[i].Length == 1) + { + Write(o, ref written, " -"); + Write(o, ref written, names[0]); + } + else + { + Write(o, ref written, " --"); + Write(o, ref written, names[0]); + } + + for (i = GetNextOptionIndex(names, i + 1); + i < names.Length; i = GetNextOptionIndex(names, i + 1)) + { + Write(o, ref written, ", "); + Write(o, ref written, names[i].Length == 1 ? "-" : "--"); + Write(o, ref written, names[i]); + } + + if (p.OptionValueType == OptionValueType.Optional || + p.OptionValueType == OptionValueType.Required) + { + if (p.OptionValueType == OptionValueType.Optional) + { + Write(o, ref written, localizer("[")); + } + Write(o, ref written, localizer("=" + GetArgumentName(0, p.MaxValueCount, p.Description))); + string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 + ? p.ValueSeparators[0] + : " "; + for (int c = 1; c < p.MaxValueCount; ++c) + { + Write(o, ref written, localizer(sep + GetArgumentName(c, p.MaxValueCount, p.Description))); + } + if (p.OptionValueType == OptionValueType.Optional) + { + Write(o, ref written, localizer("]")); + } + } + return true; + } + + static int GetNextOptionIndex(string[] names, int i) + { + while (i < names.Length && names[i] == "<>") + { + ++i; + } + return i; + } + + static void Write(TextWriter o, ref int n, string s) + { + n += s.Length; + o.Write(s); + } + + private static string GetArgumentName(int index, int maxIndex, string description) + { + if (description == null) + return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); + string[] nameStart; + if (maxIndex == 1) + nameStart = new string[] { "{0:", "{" }; + else + nameStart = new string[] { "{" + index + ":" }; + for (int i = 0; i < nameStart.Length; ++i) + { + int start, j = 0; + do + { + start = description.IndexOf(nameStart[i], j); + } while (start >= 0 && j != 0 ? description[j++ - 1] == '{' : false); + if (start == -1) + continue; + int end = description.IndexOf("}", start); + if (end == -1) + continue; + return description.Substring(start + nameStart[i].Length, end - start - nameStart[i].Length); + } + return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); + } + + private static string GetDescription(string description) + { + if (description == null) + return string.Empty; + StringBuilder sb = new StringBuilder(description.Length); + int start = -1; + for (int i = 0; i < description.Length; ++i) + { + switch (description[i]) + { + case '{': + if (i == start) + { + sb.Append('{'); + start = -1; + } + else if (start < 0) + start = i + 1; + break; + case '}': + if (start < 0) + { + if ((i + 1) == description.Length || description[i + 1] != '}') + throw new InvalidOperationException("Invalid option description: " + description); + ++i; + sb.Append("}"); + } + else + { + sb.Append(description.Substring(start, i - start)); + start = -1; + } + break; + case ':': + if (start < 0) + goto default; + start = i + 1; + break; + default: + if (start < 0) + sb.Append(description[i]); + break; + } + } + return sb.ToString(); + } + + private static IEnumerable GetLines(string description, int firstWidth, int remWidth) + { + return StringCoda.WrappedLines(description, firstWidth, remWidth); + } + } + + public class Command + { + public string Name { get; } + public string Help { get; } + + public OptionSet Options { get; set; } + public Action> Run { get; set; } + + public CommandSet CommandSet { get; internal set; } + + public Command(string name, string help = null) + { + if (string.IsNullOrEmpty(name)) + throw new ArgumentNullException(nameof(name)); + + Name = name; + Help = help; + } + + public virtual int Invoke(IEnumerable arguments) + { + var rest = Options?.Parse(arguments) ?? arguments; + Run?.Invoke(rest); + return 0; + } + } + + class CommandOption : Option + { + public Command Command { get; } + + // Prototype starts with '=' because this is an invalid prototype + // (see Option.ParsePrototype(), and thus it'll prevent Category + // instances from being accidentally used as normal options. + public CommandOption(Command command, bool hidden = false) + : base("=:Command:= " + command?.Name, command?.Name, maxValueCount: 0, hidden: hidden) + { + if (command == null) + throw new ArgumentNullException(nameof(command)); + Command = command; + } + + protected override void OnParseComplete(OptionContext c) + { + throw new NotSupportedException("CommandOption.OnParseComplete should not be invoked."); + } + } + + class HelpOption : Option + { + Option option; + CommandSet commands; + + public HelpOption(CommandSet commands, Option d) + : base(d.Prototype, d.Description, d.MaxValueCount, d.Hidden) + { + this.commands = commands; + this.option = d; + } + + protected override void OnParseComplete(OptionContext c) + { + commands.showHelp = true; + + option?.InvokeOnParseComplete(c); + } + } + + class CommandOptionSet : OptionSet + { + CommandSet commands; + + public CommandOptionSet(CommandSet commands, MessageLocalizerConverter localizer) + : base(localizer) + { + this.commands = commands; + } + + protected override void SetItem(int index, Option item) + { + if (ShouldWrapOption(item)) + { + base.SetItem(index, new HelpOption(commands, item)); + return; + } + base.SetItem(index, item); + } + + bool ShouldWrapOption(Option item) + { + if (item == null) + return false; + var help = item as HelpOption; + if (help != null) + return false; + foreach (var n in item.Names) + { + if (n == "help") + return true; + } + return false; + } + + protected override void InsertItem(int index, Option item) + { + if (ShouldWrapOption(item)) + { + base.InsertItem(index, new HelpOption(commands, item)); + return; + } + base.InsertItem(index, item); + } + } + + public class CommandSet : KeyedCollection + { + readonly OptionSet options; + readonly TextWriter outWriter; + readonly TextWriter errorWriter; + readonly string suite; + + HelpCommand help; + + internal bool showHelp; + + internal OptionSet Options => options; #if !PCL || NETSTANDARD1_3 - public CommandSet(string suite, MessageLocalizerConverter localizer = null) - : this(suite, Console.Out, Console.Error, localizer) - { - } + public CommandSet(string suite, MessageLocalizerConverter localizer = null) + : this(suite, Console.Out, Console.Error, localizer) + { + } #endif - - public CommandSet (string suite, TextWriter output, TextWriter error, MessageLocalizerConverter localizer = null) - { - if (suite == null) - throw new ArgumentNullException (nameof (suite)); - if (output == null) - throw new ArgumentNullException (nameof (output)); - if (error == null) - throw new ArgumentNullException (nameof (error)); - - this.suite = suite; - options = new CommandOptionSet (this, localizer); - outWriter = output; - errorWriter = error; - } - - public string Suite => suite; - public TextWriter Out => outWriter; - public TextWriter Error => errorWriter; - public MessageLocalizerConverter MessageLocalizer => options.MessageLocalizer; - - protected override string GetKeyForItem (Command item) - { - return item?.Name; - } - - public new CommandSet Add (Command value) - { - if (value == null) - throw new ArgumentNullException (nameof (value)); - AddCommand (value); - options.Add (new CommandOption (value)); - return this; - } - - void AddCommand (Command value) - { - if (value.CommandSet != null && value.CommandSet != this) { - throw new ArgumentException ("Command instances can only be added to a single CommandSet.", nameof (value)); - } - value.CommandSet = this; - if (value.Options != null) { - value.Options.MessageLocalizer = options.MessageLocalizer; - } - - base.Add (value); - - help = help ?? value as HelpCommand; - } - - public CommandSet Add (string header) - { - options.Add (header); - return this; - } - - public CommandSet Add (Option option) - { - options.Add (option); - return this; - } - - public CommandSet Add (string prototype, Action action) - { - options.Add (prototype, action); - return this; - } - - public CommandSet Add (string prototype, string description, Action action) - { - options.Add (prototype, description, action); - return this; - } - - public CommandSet Add (string prototype, string description, Action action, bool hidden) - { - options.Add (prototype, description, action, hidden); - return this; - } - - public CommandSet Add (string prototype, OptionAction action) - { - options.Add (prototype, action); - return this; - } - - public CommandSet Add (string prototype, string description, OptionAction action) - { - options.Add (prototype, description, action); - return this; - } - - public CommandSet Add (string prototype, string description, OptionAction action, bool hidden) - { - options.Add (prototype, description, action, hidden); - return this; - } - - public CommandSet Add (string prototype, Action action) - { - options.Add (prototype, null, action); - return this; - } - public CommandSet Add (string prototype, string description, Action action) - { - options.Add (prototype, description, action); - return this; - } - - public CommandSet Add (string prototype, OptionAction action) - { - options.Add (prototype, action); - return this; - } - - public CommandSet Add (string prototype, string description, OptionAction action) - { - options.Add (prototype, description, action); - return this; - } - - public CommandSet Add (ArgumentSource source) - { - options.Add (source); - return this; - } - - public int Run (IEnumerable arguments) - { - if (arguments == null) - throw new ArgumentNullException (nameof (arguments)); - - this.showHelp = false; - if (help == null) { - help = new HelpCommand (); - AddCommand (help); - } - Action setHelp = v => showHelp = v != null; - if (!options.Contains ("help")) { - options.Add ("help", "", setHelp, hidden: true); - } - if (!options.Contains ("?")) { - options.Add ("?", "", setHelp, hidden: true); - } - var extra = options.Parse (arguments); - if (extra.Count == 0) { - if (showHelp) { - return help.Invoke (extra); - } - Out.WriteLine (options.MessageLocalizer ($"Use `{Suite} help` for usage.")); - return 1; - } - var command = Contains (extra [0]) ? this [extra [0]] : null; - if (command == null) { - help.WriteUnknownCommand (extra [0]); - return 1; - } - extra.RemoveAt (0); - if (showHelp) { - if (command.Options?.Contains ("help") ?? true) { - extra.Add ("--help"); - return command.Invoke (extra); - } - command.Options.WriteOptionDescriptions (Out); - return 0; - } - return command.Invoke (extra); - } - } - - public class HelpCommand : Command - { - public HelpCommand () - : base ("help", help: "Show this message and exit") - { - } - - public override int Invoke (IEnumerable arguments) - { - var extra = new List (arguments ?? new string [0]); - var _ = CommandSet.Options.MessageLocalizer; - if (extra.Count == 0) { - CommandSet.Options.WriteOptionDescriptions (CommandSet.Out); - return 0; - } - var command = CommandSet.Contains (extra [0]) - ? CommandSet [extra [0]] - : null; - if (command == this || extra [0] == "--help") { - CommandSet.Out.WriteLine (_ ($"Usage: {CommandSet.Suite} COMMAND [OPTIONS]")); - CommandSet.Out.WriteLine (_ ($"Use `{CommandSet.Suite} help COMMAND` for help on a specific command.")); - CommandSet.Out.WriteLine (); - CommandSet.Out.WriteLine (_ ($"Available commands:")); - CommandSet.Out.WriteLine (); - foreach (var c in CommandSet) { - CommandSet.Options.WriteCommandDescription (CommandSet.Out, c); - } - return 0; - } - if (command == null) { - WriteUnknownCommand (extra [0]); - return 1; - } - if (command.Options != null) { - command.Options.WriteOptionDescriptions (CommandSet.Out); - return 0; - } - return command.Invoke (new [] { "--help" }); - } - - internal void WriteUnknownCommand (string unknownCommand) - { - CommandSet.Error.WriteLine (CommandSet.Options.MessageLocalizer ($"{CommandSet.Suite}: Unknown command: {unknownCommand}")); - CommandSet.Error.WriteLine (CommandSet.Options.MessageLocalizer ($"{CommandSet.Suite}: Use `{CommandSet.Suite} help` for usage.")); - } - } + public CommandSet(string suite, TextWriter output, TextWriter error, MessageLocalizerConverter localizer = null) + { + if (suite == null) + throw new ArgumentNullException(nameof(suite)); + if (output == null) + throw new ArgumentNullException(nameof(output)); + if (error == null) + throw new ArgumentNullException(nameof(error)); + + this.suite = suite; + options = new CommandOptionSet(this, localizer); + outWriter = output; + errorWriter = error; + } + + public string Suite => suite; + public TextWriter Out => outWriter; + public TextWriter Error => errorWriter; + public MessageLocalizerConverter MessageLocalizer => options.MessageLocalizer; + + protected override string GetKeyForItem(Command item) + { + return item?.Name; + } + + public new CommandSet Add(Command value) + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + AddCommand(value); + options.Add(new CommandOption(value)); + return this; + } + + void AddCommand(Command value) + { + if (value.CommandSet != null && value.CommandSet != this) + { + throw new ArgumentException("Command instances can only be added to a single CommandSet.", nameof(value)); + } + value.CommandSet = this; + if (value.Options != null) + { + value.Options.MessageLocalizer = options.MessageLocalizer; + } + + base.Add(value); + + help = help ?? value as HelpCommand; + } + + public CommandSet Add(string header) + { + options.Add(header); + return this; + } + + public CommandSet Add(Option option) + { + options.Add(option); + return this; + } + + public CommandSet Add(string prototype, Action action) + { + options.Add(prototype, action); + return this; + } + + public CommandSet Add(string prototype, string description, Action action) + { + options.Add(prototype, description, action); + return this; + } + + public CommandSet Add(string prototype, string description, Action action, bool hidden) + { + options.Add(prototype, description, action, hidden); + return this; + } + + public CommandSet Add(string prototype, OptionAction action) + { + options.Add(prototype, action); + return this; + } + + public CommandSet Add(string prototype, string description, OptionAction action) + { + options.Add(prototype, description, action); + return this; + } + + public CommandSet Add(string prototype, string description, OptionAction action, bool hidden) + { + options.Add(prototype, description, action, hidden); + return this; + } + + public CommandSet Add(string prototype, Action action) + { + options.Add(prototype, null, action); + return this; + } + + public CommandSet Add(string prototype, string description, Action action) + { + options.Add(prototype, description, action); + return this; + } + + public CommandSet Add(string prototype, OptionAction action) + { + options.Add(prototype, action); + return this; + } + + public CommandSet Add(string prototype, string description, OptionAction action) + { + options.Add(prototype, description, action); + return this; + } + + public CommandSet Add(ArgumentSource source) + { + options.Add(source); + return this; + } + + public int Run(IEnumerable arguments) + { + if (arguments == null) + throw new ArgumentNullException(nameof(arguments)); + + this.showHelp = false; + if (help == null) + { + help = new HelpCommand(); + AddCommand(help); + } + Action setHelp = v => showHelp = v != null; + if (!options.Contains("help")) + { + options.Add("help", "", setHelp, hidden: true); + } + if (!options.Contains("?")) + { + options.Add("?", "", setHelp, hidden: true); + } + var extra = options.Parse(arguments); + if (extra.Count == 0) + { + if (showHelp) + { + return help.Invoke(extra); + } + Out.WriteLine(options.MessageLocalizer($"Use `{Suite} help` for usage.")); + return 1; + } + var command = Contains(extra[0]) ? this[extra[0]] : null; + if (command == null) + { + help.WriteUnknownCommand(extra[0]); + return 1; + } + extra.RemoveAt(0); + if (showHelp) + { + if (command.Options?.Contains("help") ?? true) + { + extra.Add("--help"); + return command.Invoke(extra); + } + command.Options.WriteOptionDescriptions(Out); + return 0; + } + return command.Invoke(extra); + } + } + + public class HelpCommand : Command + { + public HelpCommand() + : base("help", help: "Show this message and exit") + { + } + + public override int Invoke(IEnumerable arguments) + { + var extra = new List(arguments ?? new string[0]); + var _ = CommandSet.Options.MessageLocalizer; + if (extra.Count == 0) + { + CommandSet.Options.WriteOptionDescriptions(CommandSet.Out); + return 0; + } + var command = CommandSet.Contains(extra[0]) + ? CommandSet[extra[0]] + : null; + if (command == this || extra[0] == "--help") + { + CommandSet.Out.WriteLine(_($"Usage: {CommandSet.Suite} COMMAND [OPTIONS]")); + CommandSet.Out.WriteLine(_($"Use `{CommandSet.Suite} help COMMAND` for help on a specific command.")); + CommandSet.Out.WriteLine(); + CommandSet.Out.WriteLine(_($"Available commands:")); + CommandSet.Out.WriteLine(); + foreach (var c in CommandSet) + { + CommandSet.Options.WriteCommandDescription(CommandSet.Out, c); + } + return 0; + } + if (command == null) + { + WriteUnknownCommand(extra[0]); + return 1; + } + if (command.Options != null) + { + command.Options.WriteOptionDescriptions(CommandSet.Out); + return 0; + } + return command.Invoke(new[] { "--help" }); + } + + internal void WriteUnknownCommand(string unknownCommand) + { + CommandSet.Error.WriteLine(CommandSet.Options.MessageLocalizer($"{CommandSet.Suite}: Unknown command: {unknownCommand}")); + CommandSet.Error.WriteLine(CommandSet.Options.MessageLocalizer($"{CommandSet.Suite}: Use `{CommandSet.Suite} help` for usage.")); + } + } } diff --git a/src/tools/illink/src/ILLink.CodeFix/DynamicallyAccessedMembersCodeFixProvider.cs b/src/tools/illink/src/ILLink.CodeFix/DynamicallyAccessedMembersCodeFixProvider.cs index 194ec530ff86e9..f644fec90ea3be 100644 --- a/src/tools/illink/src/ILLink.CodeFix/DynamicallyAccessedMembersCodeFixProvider.cs +++ b/src/tools/illink/src/ILLink.CodeFix/DynamicallyAccessedMembersCodeFixProvider.cs @@ -30,22 +30,22 @@ private static ImmutableArray GetSupportedDiagnostics() diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsMethodReturnType)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsField)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsThisParameter)); - // diagDescriptorsArrayBuilder.Add (DiagnosticDescriptors.GetDiagnosticDescriptor (DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsGenericParameter)); + // diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsGenericParameter)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsMethodReturnType)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsField)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter)); - // diagDescriptorsArrayBuilder.Add (DiagnosticDescriptors.GetDiagnosticDescriptor (DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsGenericParameter)); + // diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsGenericParameter)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsParameter)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsMethodReturnType)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsField)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsThisParameter)); - // diagDescriptorsArrayBuilder.Add (DiagnosticDescriptors.GetDiagnosticDescriptor (DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsGenericParameter)); + // diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsGenericParameter)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsMethodReturnType)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsField)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsThisParameter)); - // diagDescriptorsArrayBuilder.Add (DiagnosticDescriptors.GetDiagnosticDescriptor (DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsGenericParameter)); + // diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsGenericParameter)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsParameter)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsMethodReturnType)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsField)); @@ -53,8 +53,8 @@ private static ImmutableArray GetSupportedDiagnostics() diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsGenericParameter)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides)); diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides)); - // diagDescriptorsArrayBuilder.Add (DiagnosticDescriptors.GetDiagnosticDescriptor (DiagnosticId.DynamicallyAccessedMembersMismatchOnImplicitThisBetweenOverrides)); - // diagDescriptorsArrayBuilder.Add (DiagnosticDescriptors.GetDiagnosticDescriptor (DiagnosticId.DynamicallyAccessedMembersMismatchOnGenericParameterBetweenOverrides)); + // diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchOnImplicitThisBetweenOverrides)); + // diagDescriptorsArrayBuilder.Add(DiagnosticDescriptors.GetDiagnosticDescriptor(DiagnosticId.DynamicallyAccessedMembersMismatchOnGenericParameterBetweenOverrides)); return diagDescriptorsArrayBuilder.ToImmutable(); } @@ -68,16 +68,16 @@ private static ImmutableArray GetSupportedDiagnostics() private static string FullyQualifiedAttributeName => DynamicallyAccessedMembersAnalyzer.FullyQualifiedDynamicallyAccessedMembersAttribute; private static readonly string[] AttributeOnReturn = { - DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter.AsString (), + DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter.AsString(), DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsMethodReturnType.AsString(), - DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsField.AsString (), - DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter.AsString (), - DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides.AsString () + DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsField.AsString(), + DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter.AsString(), + DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides.AsString() }; private static readonly string[] AttributeOnGeneric = { DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsParameter.AsString(), - DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsMethodReturnType.AsString (), + DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsMethodReturnType.AsString(), DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsField.AsString(), DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsThisParameter.AsString(), DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsGenericParameter.AsString(), diff --git a/src/tools/illink/src/ILLink.CodeFix/UnconditionalSuppressMessageCodeFixProvider.cs b/src/tools/illink/src/ILLink.CodeFix/UnconditionalSuppressMessageCodeFixProvider.cs index 92c0d5e4b9620f..85186bde8a8644 100644 --- a/src/tools/illink/src/ILLink.CodeFix/UnconditionalSuppressMessageCodeFixProvider.cs +++ b/src/tools/illink/src/ILLink.CodeFix/UnconditionalSuppressMessageCodeFixProvider.cs @@ -55,7 +55,7 @@ protected override SyntaxNode[] GetAttributeArguments(ISymbol? attributableSymbo var suppressionJustification = syntaxGenerator.AttributeArgument(Justification, syntaxGenerator.LiteralExpression("")); - // [UnconditionalSuppressWarning (category, id, Justification = "")] + // [UnconditionalSuppressWarning(category, id, Justification = "")] return [ruleCategory, ruleId, suppressionJustification]; } } diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/FeatureChecksValue.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/FeatureChecksValue.cs index 59e9ad93140ac8..0c300365065df2 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/FeatureChecksValue.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/FeatureChecksValue.cs @@ -7,7 +7,7 @@ namespace ILLink.RoslynAnalyzer.DataFlow { // Represents the feature conditions checked in a conditional expression, // such as - // Debug.Assert (RuntimeFeatures.IsDynamicCodeSupported) + // Debug.Assert(RuntimeFeatures.IsDynamicCodeSupported) // or // if (!RuntimeFeatures.IsDynamicCodeSupported) // For now, this is only designed to track the built-in "features"/"capabilities" diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowVisitor.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowVisitor.cs index e1f8eacbf7957e..0be768dd17b12c 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowVisitor.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowVisitor.cs @@ -498,7 +498,7 @@ public override TValue VisitFlowCaptureReference(IFlowCaptureReferenceOperation // LValueFlowCaptureProvider doesn't take into account IsInitialization = true, // so it doesn't properly detect this as an l-value capture. // Context: https://github.com/dotnet/roslyn/issues/60757 - // Debug.Assert (IsLValueFlowCapture (operation.Id)); + // Debug.Assert(IsLValueFlowCapture(operation.Id)); Debug.Assert(operation.GetValueUsageInfo(OwningSymbol).HasFlag(ValueUsageInfo.Write), $"{operation.Syntax.GetLocation().GetLineSpan()}"); Debug.Assert(operation.GetValueUsageInfo(OwningSymbol).HasFlag(ValueUsageInfo.Reference), @@ -513,7 +513,7 @@ public override TValue VisitFlowCaptureReference(IFlowCaptureReferenceOperation // where the variable is declared before being passed as an out param, for example: // string s; - // Method (out s, b ? 0 : 1); + // Method(out s, b ? 0 : 1); // The second argument is necessary to create multiple branches so that the compiler // turns both arguments into flow capture references, instead of just passing a local @@ -522,8 +522,8 @@ public override TValue VisitFlowCaptureReference(IFlowCaptureReferenceOperation // This can also happen for a deconstruction assignments, where the write is not to a byref. // Once the analyzer implements support for deconstruction assignments (https://github.com/dotnet/linker/issues/3158), // we can try enabling this assert to ensure that this case is only hit for byrefs. - // Debug.Assert (operation.GetValueUsageInfo (OwningSymbol).HasFlag (ValueUsageInfo.Reference), - // $"{operation.Syntax.GetLocation ().GetLineSpan ()}"); + // Debug.Assert(operation.GetValueUsageInfo(OwningSymbol).HasFlag(ValueUsageInfo.Reference), + // $"{operation.Syntax.GetLocation().GetLineSpan()}"); return TopValue; } @@ -644,8 +644,8 @@ public override TValue VisitPropertyReference(IPropertyReferenceOperation operat // Property references may be passed as ref/out parameters. // Enable this assert once we have support for deconstruction assignments. // https://github.com/dotnet/linker/issues/3158 - // Debug.Assert (operation.GetValueUsageInfo (OwningSymbol).HasFlag (ValueUsageInfo.Reference), - // $"{operation.Syntax.GetLocation ().GetLineSpan ()}"); + // Debug.Assert(operation.GetValueUsageInfo(OwningSymbol).HasFlag(ValueUsageInfo.Reference), + // $"{operation.Syntax.GetLocation().GetLineSpan()}"); return TopValue; } diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/TrimAnalysis/ReflectionAccessAnalyzer.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/TrimAnalysis/ReflectionAccessAnalyzer.cs index 516f46c1a5daea..1653cb96d3875f 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/TrimAnalysis/ReflectionAccessAnalyzer.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/TrimAnalysis/ReflectionAccessAnalyzer.cs @@ -42,10 +42,10 @@ internal void GetReflectionAccessDiagnostics(Location location, ITypeSymbol type break; /* Skip Type and InterfaceImplementation marking since doesnt seem relevant for diagnostic generation case ITypeSymbol nestedType: - MarkType (location, nestedType); + MarkType(location, nestedType); break; case InterfaceImplementation interfaceImplementation: - MarkInterfaceImplementation (location, interfaceImplementation, dependencyKind); + MarkInterfaceImplementation(location, interfaceImplementation, dependencyKind); break; */ case IEventSymbol @event: diff --git a/src/tools/illink/src/ILLink.Shared/TrimAnalysis/HandleCallAction.cs b/src/tools/illink/src/ILLink.Shared/TrimAnalysis/HandleCallAction.cs index 7e40ba2aa88c95..010caec506f83c 100644 --- a/src/tools/illink/src/ILLink.Shared/TrimAnalysis/HandleCallAction.cs +++ b/src/tools/illink/src/ILLink.Shared/TrimAnalysis/HandleCallAction.cs @@ -184,8 +184,8 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers } break; - // System.Reflection.MethodBase.GetMethodFromHandle (RuntimeMethodHandle handle) - // System.Reflection.MethodBase.GetMethodFromHandle (RuntimeMethodHandle handle, RuntimeTypeHandle declaringType) + // System.Reflection.MethodBase.GetMethodFromHandle(RuntimeMethodHandle handle) + // System.Reflection.MethodBase.GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType) case IntrinsicId.MethodBase_GetMethodFromHandle: { if (argumentValues[0].IsEmpty()) @@ -233,8 +233,8 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers throw new NotImplementedException("These intrinsics should be handled by the specific implementation: " + intrinsicId); // - // GetInterface (String) - // GetInterface (String, bool) + // GetInterface(String) + // GetInterface(String, bool) // case IntrinsicId.Type_GetInterface: { @@ -351,7 +351,7 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers // // System.Runtime.CompilerServices.RuntimeHelpers // - // RunClassConstructor (RuntimeTypeHandle type) + // RunClassConstructor(RuntimeTypeHandle type) // case IntrinsicId.RuntimeHelpers_RunClassConstructor: if (argumentValues[0].IsEmpty()) @@ -383,13 +383,13 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers break; // - // GetConstructors (BindingFlags) - // GetMethods (BindingFlags) - // GetFields (BindingFlags) - // GetEvents (BindingFlags) - // GetProperties (BindingFlags) - // GetNestedTypes (BindingFlags) - // GetMembers (BindingFlags) + // GetConstructors(BindingFlags) + // GetMethods(BindingFlags) + // GetFields(BindingFlags) + // GetEvents(BindingFlags) + // GetProperties(BindingFlags) + // GetNestedTypes(BindingFlags) + // GetMembers(BindingFlags) // case IntrinsicId.Type_GetConstructors__BindingFlags: case IntrinsicId.Type_GetMethods__BindingFlags: @@ -442,17 +442,17 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers break; // - // GetField (string) - // GetField (string, BindingFlags) - // GetEvent (string) - // GetEvent (string, BindingFlags) - // GetProperty (string) - // GetProperty (string, BindingFlags) - // GetProperty (string, Type) - // GetProperty (string, Type[]) - // GetProperty (string, Type, Type[]) - // GetProperty (string, Type, Type[], ParameterModifier[]) - // GetProperty (string, BindingFlags, Binder, Type, Type[], ParameterModifier[]) + // GetField(string) + // GetField(string, BindingFlags) + // GetEvent(string) + // GetEvent(string, BindingFlags) + // GetProperty(string) + // GetProperty(string, BindingFlags) + // GetProperty(string, Type) + // GetProperty(string, Type[]) + // GetProperty(string, Type, Type[]) + // GetProperty(string, Type, Type[], ParameterModifier[]) + // GetProperty(string, BindingFlags, Binder, Type, Type[], ParameterModifier[]) // case IntrinsicId.Type_GetField: case IntrinsicId.Type_GetProperty: @@ -519,9 +519,9 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers break; // - // GetMember (String) - // GetMember (String, BindingFlags) - // GetMember (String, MemberTypes, BindingFlags) + // GetMember(String) + // GetMember(String, BindingFlags) + // GetMember(String, MemberTypes, BindingFlags) // case IntrinsicId.Type_GetMember: { @@ -573,17 +573,17 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers break; // - // GetMethod (string) - // GetMethod (string, BindingFlags) - // GetMethod (string, Type[]) - // GetMethod (string, Type[], ParameterModifier[]) - // GetMethod (string, BindingFlags, Type[]) - // GetMethod (string, BindingFlags, Binder, Type[], ParameterModifier[]) - // GetMethod (string, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) - // GetMethod (string, int, Type[]) - // GetMethod (string, int, Type[], ParameterModifier[]?) - // GetMethod (string, int, BindingFlags, Binder?, Type[], ParameterModifier[]?) - // GetMethod (string, int, BindingFlags, Binder?, CallingConventions, Type[], ParameterModifier[]?) + // GetMethod(string) + // GetMethod(string, BindingFlags) + // GetMethod(string, Type[]) + // GetMethod(string, Type[], ParameterModifier[]) + // GetMethod(string, BindingFlags, Type[]) + // GetMethod(string, BindingFlags, Binder, Type[], ParameterModifier[]) + // GetMethod(string, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) + // GetMethod(string, int, Type[]) + // GetMethod(string, int, Type[], ParameterModifier[]?) + // GetMethod(string, int, BindingFlags, Binder?, Type[], ParameterModifier[]?) + // GetMethod(string, int, BindingFlags, Binder?, CallingConventions, Type[], ParameterModifier[]?) // case IntrinsicId.Type_GetMethod: { @@ -663,8 +663,8 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers break; // - // GetNestedType (string) - // GetNestedType (string, BindingFlags) + // GetNestedType(string) + // GetNestedType(string, BindingFlags) // case IntrinsicId.Type_GetNestedType: { @@ -746,10 +746,10 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers // // System.Reflection.RuntimeReflectionExtensions // - // static GetRuntimeEvent (this Type type, string name) - // static GetRuntimeField (this Type type, string name) - // static GetRuntimeMethod (this Type type, string name, Type[] parameters) - // static GetRuntimeProperty (this Type type, string name) + // static GetRuntimeEvent(this Type type, string name) + // static GetRuntimeField(this Type type, string name) + // static GetRuntimeMethod(this Type type, string name, Type[] parameters) + // static GetRuntimeProperty(this Type type, string name) // case IntrinsicId.RuntimeReflectionExtensions_GetRuntimeEvent: case IntrinsicId.RuntimeReflectionExtensions_GetRuntimeField: @@ -832,7 +832,7 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers // // System.Linq.Expressions.Expression // - // static New (Type) + // static New(Type) // case IntrinsicId.Expression_New: { @@ -854,7 +854,7 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers // // System.Linq.Expressions.Expression // - // static Property (Expression, MethodInfo) + // static Property(Expression, MethodInfo) // case IntrinsicId.Expression_Property when calledMethod.HasParameterOfType((ParameterIndex)1, "System.Reflection.MethodInfo"): { @@ -890,8 +890,8 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers // // System.Linq.Expressions.Expression // - // static Field (Expression, Type, String) - // static Property (Expression, Type, String) + // static Field(Expression, Type, String) + // static Property(Expression, Type, String) // case IntrinsicId.Expression_Field: case IntrinsicId.Expression_Property: @@ -946,7 +946,7 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers // // System.Linq.Expressions.Expression // - // static Call (Type, String, Type[], Expression[]) + // static Call(Type, String, Type[], Expression[]) // case IntrinsicId.Expression_Call: { @@ -1032,12 +1032,12 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers // // System.Type // - // GetType (string) - // GetType (string, Boolean) - // GetType (string, Boolean, Boolean) - // GetType (string, Func, Func) - // GetType (string, Func, Func, Boolean) - // GetType (string, Func, Func, Boolean, Boolean) + // GetType(string) + // GetType(string, Boolean) + // GetType(string, Boolean, Boolean) + // GetType(string, Func, Func) + // GetType(string, Func, Func, Boolean) + // GetType(string, Func, Func, Boolean, Boolean) // case IntrinsicId.Type_GetType: { @@ -1093,7 +1093,7 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers // // System.Type // - // Type MakeGenericType (params Type[] typeArguments) + // Type MakeGenericType(params Type[] typeArguments) // case IntrinsicId.Type_MakeGenericType: if (instanceValue.IsEmpty() || argumentValues[0].IsEmpty()) @@ -1275,10 +1275,10 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers break; // - // GetConstructor (Type[]) - // GetConstructor (BindingFlags, Type[]) - // GetConstructor (BindingFlags, Binder, Type[], ParameterModifier []) - // GetConstructor (BindingFlags, Binder, CallingConventions, Type[], ParameterModifier []) + // GetConstructor(Type[]) + // GetConstructor(BindingFlags, Type[]) + // GetConstructor(BindingFlags, Binder, Type[], ParameterModifier []) + // GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier []) // case IntrinsicId.Type_GetConstructor: { @@ -1337,7 +1337,7 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers // // System.Reflection.MethodInfo // - // MakeGenericMethod (Type[] typeArguments) + // MakeGenericMethod(Type[] typeArguments) // case IntrinsicId.MethodInfo_MakeGenericMethod: { @@ -1373,12 +1373,12 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers // // System.Activator // - // static CreateInstance (System.Type type) - // static CreateInstance (System.Type type, bool nonPublic) - // static CreateInstance (System.Type type, params object?[]? args) - // static CreateInstance (System.Type type, object?[]? args, object?[]? activationAttributes) - // static CreateInstance (System.Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture) - // static CreateInstance (System.Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) { throw null; } + // static CreateInstance(System.Type type) + // static CreateInstance(System.Type type, bool nonPublic) + // static CreateInstance(System.Type type, params object?[]? args) + // static CreateInstance(System.Type type, object?[]? args, object?[]? activationAttributes) + // static CreateInstance(System.Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture) + // static CreateInstance(System.Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) { throw null; } // case IntrinsicId.Activator_CreateInstance__Type: { @@ -1462,9 +1462,9 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers // // System.Activator // - // static CreateInstance (string assemblyName, string typeName) - // static CreateInstance (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) - // static CreateInstance (string assemblyName, string typeName, object?[]? activationAttributes) + // static CreateInstance(string assemblyName, string typeName) + // static CreateInstance(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) + // static CreateInstance(string assemblyName, string typeName, object?[]? activationAttributes) // case IntrinsicId.Activator_CreateInstance__AssemblyName_TypeName: ProcessCreateInstanceByName(calledMethod, argumentValues); @@ -1473,9 +1473,9 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers // // System.Activator // - // static CreateInstanceFrom (string assemblyFile, string typeName) - // static CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) - // static CreateInstanceFrom (string assemblyFile, string typeName, object? []? activationAttributes) + // static CreateInstanceFrom(string assemblyFile, string typeName) + // static CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) + // static CreateInstanceFrom(string assemblyFile, string typeName, object? []? activationAttributes) // case IntrinsicId.Activator_CreateInstanceFrom: ProcessCreateInstanceByName(calledMethod, argumentValues); @@ -1484,21 +1484,21 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers // // System.AppDomain // - // CreateInstance (string assemblyName, string typeName) - // CreateInstance (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) - // CreateInstance (string assemblyName, string typeName, object? []? activationAttributes) + // CreateInstance(string assemblyName, string typeName) + // CreateInstance(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) + // CreateInstance(string assemblyName, string typeName, object? []? activationAttributes) // - // CreateInstanceAndUnwrap (string assemblyName, string typeName) - // CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) - // CreateInstanceAndUnwrap (string assemblyName, string typeName, object? []? activationAttributes) + // CreateInstanceAndUnwrap(string assemblyName, string typeName) + // CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) + // CreateInstanceAndUnwrap(string assemblyName, string typeName, object? []? activationAttributes) // - // CreateInstanceFrom (string assemblyFile, string typeName) - // CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) - // CreateInstanceFrom (string assemblyFile, string typeName, object? []? activationAttributes) + // CreateInstanceFrom(string assemblyFile, string typeName) + // CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) + // CreateInstanceFrom(string assemblyFile, string typeName, object? []? activationAttributes) // - // CreateInstanceFromAndUnwrap (string assemblyFile, string typeName) - // CreateInstanceFromAndUnwrap (string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) - // CreateInstanceFromAndUnwrap (string assemblyFile, string typeName, object? []? activationAttributes) + // CreateInstanceFromAndUnwrap(string assemblyFile, string typeName) + // CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) + // CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, object? []? activationAttributes) // case IntrinsicId.AppDomain_CreateInstance: case IntrinsicId.AppDomain_CreateInstanceAndUnwrap: @@ -1510,9 +1510,9 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers // // System.Reflection.Assembly // - // CreateInstance (string typeName) - // CreateInstance (string typeName, bool ignoreCase) - // CreateInstance (string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object []? args, CultureInfo? culture, object []? activationAttributes) + // CreateInstance(string typeName) + // CreateInstance(string typeName, bool ignoreCase) + // CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object []? args, CultureInfo? culture, object []? activationAttributes) // case IntrinsicId.Assembly_CreateInstance: // For now always fail since we don't track assemblies (dotnet/linker/issues/1947) diff --git a/src/tools/illink/src/ILLink.Shared/TrimAnalysis/Intrinsics.cs b/src/tools/illink/src/ILLink.Shared/TrimAnalysis/Intrinsics.cs index 7e8bc4bb4b1f50..45b0c00c997a70 100644 --- a/src/tools/illink/src/ILLink.Shared/TrimAnalysis/Intrinsics.cs +++ b/src/tools/illink/src/ILLink.Shared/TrimAnalysis/Intrinsics.cs @@ -14,20 +14,20 @@ public static IntrinsicId GetIntrinsicIdForMethod(MethodProxy calledMethod) { return calledMethod.Name switch { - // static System.Reflection.IntrospectionExtensions.GetTypeInfo (Type type) + // static System.Reflection.IntrospectionExtensions.GetTypeInfo(Type type) "GetTypeInfo" when calledMethod.IsDeclaredOnType("System.Reflection.IntrospectionExtensions") => IntrinsicId.IntrospectionExtensions_GetTypeInfo, - // System.Reflection.TypeInfo.AsType () + // System.Reflection.TypeInfo.AsType() "AsType" when calledMethod.IsDeclaredOnType("System.Reflection.TypeInfo") => IntrinsicId.TypeInfo_AsType, - // System.Type.GetTypeInfo (Type type) + // System.Type.GetTypeInfo(Type type) "GetTypeFromHandle" when calledMethod.IsDeclaredOnType("System.Type") => IntrinsicId.Type_GetTypeFromHandle, // System.Type.TypeHandle getter "get_TypeHandle" when calledMethod.IsDeclaredOnType("System.Type") => IntrinsicId.Type_get_TypeHandle, - // static System.Reflection.MethodBase.GetMethodFromHandle (RuntimeMethodHandle handle) - // static System.Reflection.MethodBase.GetMethodFromHandle (RuntimeMethodHandle handle, RuntimeTypeHandle declaringType) + // static System.Reflection.MethodBase.GetMethodFromHandle(RuntimeMethodHandle handle) + // static System.Reflection.MethodBase.GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType) "GetMethodFromHandle" when calledMethod.IsDeclaredOnType("System.Reflection.MethodBase") && calledMethod.HasParameterOfType((ParameterIndex)0, "System.RuntimeMethodHandle") && (calledMethod.HasMetadataParametersCount(1) || calledMethod.HasMetadataParametersCount(2)) @@ -36,192 +36,192 @@ public static IntrinsicId GetIntrinsicIdForMethod(MethodProxy calledMethod) // System.Reflection.MethodBase.MethodHandle getter "get_MethodHandle" when calledMethod.IsDeclaredOnType("System.Reflection.MethodBase") => IntrinsicId.MethodBase_get_MethodHandle, - // static System.Type.MakeGenericType (Type [] typeArguments) + // static System.Type.MakeGenericType(Type[] typeArguments) "MakeGenericType" when calledMethod.IsDeclaredOnType("System.Type") => IntrinsicId.Type_MakeGenericType, - // static System.Reflection.RuntimeReflectionExtensions.GetMethodInfo (this Delegate del) + // static System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(this Delegate del) "GetMethodInfo" when calledMethod.IsDeclaredOnType("System.Reflection.RuntimeReflectionExtensions") && calledMethod.HasParameterOfType((ParameterIndex)0, "System.Delegate") => IntrinsicId.RuntimeReflectionExtensions_GetMethodInfo, - // static System.Reflection.RuntimeReflectionExtensions.GetRuntimeEvent (this Type type, string name) + // static System.Reflection.RuntimeReflectionExtensions.GetRuntimeEvent(this Type type, string name) "GetRuntimeEvent" when calledMethod.IsDeclaredOnType("System.Reflection.RuntimeReflectionExtensions") && calledMethod.HasParameterOfType((ParameterIndex)0, "System.Type") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") => IntrinsicId.RuntimeReflectionExtensions_GetRuntimeEvent, - // static System.Reflection.RuntimeReflectionExtensions.GetRuntimeField (this Type type, string name) + // static System.Reflection.RuntimeReflectionExtensions.GetRuntimeField(this Type type, string name) "GetRuntimeField" when calledMethod.IsDeclaredOnType("System.Reflection.RuntimeReflectionExtensions") && calledMethod.HasParameterOfType((ParameterIndex)0, "System.Type") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.,String") => IntrinsicId.RuntimeReflectionExtensions_GetRuntimeField, - // static System.Reflection.RuntimeReflectionExtensions.GetRuntimeMethod (this Type type, string name, Type[] parameters) + // static System.Reflection.RuntimeReflectionExtensions.GetRuntimeMethod(this Type type, string name, Type[] parameters) "GetRuntimeMethod" when calledMethod.IsDeclaredOnType("System.Reflection.RuntimeReflectionExtensions") && calledMethod.HasParameterOfType((ParameterIndex)0, "System.Type") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") => IntrinsicId.RuntimeReflectionExtensions_GetRuntimeMethod, - // static System.Reflection.RuntimeReflectionExtensions.GetRuntimeProperty (this Type type, string name) + // static System.Reflection.RuntimeReflectionExtensions.GetRuntimeProperty(this Type type, string name) "GetRuntimeProperty" when calledMethod.IsDeclaredOnType("System.Reflection.RuntimeReflectionExtensions") && calledMethod.HasParameterOfType((ParameterIndex)0, "System.Type") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") => IntrinsicId.RuntimeReflectionExtensions_GetRuntimeProperty, - // static System.Linq.Expressions.Expression.Call (Type, String, Type[], Expression[]) + // static System.Linq.Expressions.Expression.Call(Type, String, Type[], Expression[]) "Call" when calledMethod.IsDeclaredOnType("System.Linq.Expressions.Expression") && calledMethod.HasParameterOfType((ParameterIndex)0, "System.Type") && calledMethod.HasMetadataParametersCount(4) => IntrinsicId.Expression_Call, - // static System.Linq.Expressions.Expression.Field (Expression, Type, String) + // static System.Linq.Expressions.Expression.Field(Expression, Type, String) "Field" when calledMethod.IsDeclaredOnType("System.Linq.Expressions.Expression") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.Type") && calledMethod.HasMetadataParametersCount(3) => IntrinsicId.Expression_Field, - // static System.Linq.Expressions.Expression.Property (Expression, Type, String) - // static System.Linq.Expressions.Expression.Property (Expression, MethodInfo) + // static System.Linq.Expressions.Expression.Property(Expression, Type, String) + // static System.Linq.Expressions.Expression.Property(Expression, MethodInfo) "Property" when calledMethod.IsDeclaredOnType("System.Linq.Expressions.Expression") && ((calledMethod.HasParameterOfType((ParameterIndex)1, "System.Type") && calledMethod.HasMetadataParametersCount(3)) || (calledMethod.HasParameterOfType((ParameterIndex)1, "System.Reflection.MethodInfo") && calledMethod.HasMetadataParametersCount(2))) => IntrinsicId.Expression_Property, - // static System.Linq.Expressions.Expression.New (Type) + // static System.Linq.Expressions.Expression.New(Type) "New" when calledMethod.IsDeclaredOnType("System.Linq.Expressions.Expression") && calledMethod.HasParameterOfType((ParameterIndex)0, "System.Type") && calledMethod.HasMetadataParametersCount(1) => IntrinsicId.Expression_New, - // static Array System.Enum.GetValues (Type) + // static Array System.Enum.GetValues(Type) "GetValues" when calledMethod.IsDeclaredOnType("System.Enum") && calledMethod.HasParameterOfType((ParameterIndex)0, "System.Type") && calledMethod.HasMetadataParametersCount(1) => IntrinsicId.Enum_GetValues, - // static int System.Runtime.InteropServices.Marshal.SizeOf (Type) + // static int System.Runtime.InteropServices.Marshal.SizeOf(Type) "SizeOf" when calledMethod.IsDeclaredOnType("System.Runtime.InteropServices.Marshal") && calledMethod.HasParameterOfType((ParameterIndex)0, "System.Type") && calledMethod.HasMetadataParametersCount(1) => IntrinsicId.Marshal_SizeOf, - // static int System.Runtime.InteropServices.Marshal.OffsetOf (Type, string) + // static int System.Runtime.InteropServices.Marshal.OffsetOf(Type, string) "OffsetOf" when calledMethod.IsDeclaredOnType("System.Runtime.InteropServices.Marshal") && calledMethod.HasParameterOfType((ParameterIndex)0, "System.Type") && calledMethod.HasMetadataParametersCount(2) => IntrinsicId.Marshal_OffsetOf, - // static object System.Runtime.InteropServices.Marshal.PtrToStructure (IntPtr, Type) + // static object System.Runtime.InteropServices.Marshal.PtrToStructure(IntPtr, Type) "PtrToStructure" when calledMethod.IsDeclaredOnType("System.Runtime.InteropServices.Marshal") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.Type") && calledMethod.HasMetadataParametersCount(2) => IntrinsicId.Marshal_PtrToStructure, - // static void System.Runtime.InteropServices.Marshal.DestroyStructure (IntPtr, Type) + // static void System.Runtime.InteropServices.Marshal.DestroyStructure(IntPtr, Type) "DestroyStructure" when calledMethod.IsDeclaredOnType("System.Runtime.InteropServices.Marshal") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.Type") && calledMethod.HasMetadataParametersCount(2) => IntrinsicId.Marshal_DestroyStructure, - // static Delegate System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer (IntPtr, Type) + // static Delegate System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer(IntPtr, Type) "GetDelegateForFunctionPointer" when calledMethod.IsDeclaredOnType("System.Runtime.InteropServices.Marshal") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.Type") && calledMethod.HasMetadataParametersCount(2) => IntrinsicId.Marshal_GetDelegateForFunctionPointer, - // static System.Type.GetType (string) - // static System.Type.GetType (string, Boolean) - // static System.Type.GetType (string, Boolean, Boolean) - // static System.Type.GetType (string, Func, Func) - // static System.Type.GetType (string, Func, Func, Boolean) - // static System.Type.GetType (string, Func, Func, Boolean, Boolean) + // static System.Type.GetType(string) + // static System.Type.GetType(string, Boolean) + // static System.Type.GetType(string, Boolean, Boolean) + // static System.Type.GetType(string, Func, Func) + // static System.Type.GetType(string, Func, Func, Boolean) + // static System.Type.GetType(string, Func, Func, Boolean, Boolean) "GetType" when calledMethod.IsDeclaredOnType("System.Type") && calledMethod.HasParameterOfType((ParameterIndex)0, "System.String") => IntrinsicId.Type_GetType, - // System.Type.GetConstructor (Type[]) - // System.Type.GetConstructor (BindingFlags, Type[]) - // System.Type.GetConstructor (BindingFlags, Binder, Type[], ParameterModifier []) - // System.Type.GetConstructor (BindingFlags, Binder, CallingConventions, Type[], ParameterModifier []) + // System.Type.GetConstructor Type[]) + // System.Type.GetConstructor BindingFlags, Type[]) + // System.Type.GetConstructor BindingFlags, Binder, Type[], ParameterModifier []) + // System.Type.GetConstructor BindingFlags, Binder, CallingConventions, Type[], ParameterModifier []) "GetConstructor" when calledMethod.IsDeclaredOnType("System.Type") && !calledMethod.IsStatic() => IntrinsicId.Type_GetConstructor, - // System.Type.GetConstructors (BindingFlags) + // System.Type.GetConstructors(BindingFlags) "GetConstructors" when calledMethod.IsDeclaredOnType("System.Type") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.Reflection.BindingFlags") && calledMethod.HasMetadataParametersCount(1) && !calledMethod.IsStatic() => IntrinsicId.Type_GetConstructors__BindingFlags, - // System.Type.GetMethod (string) - // System.Type.GetMethod (string, BindingFlags) - // System.Type.GetMethod (string, Type[]) - // System.Type.GetMethod (string, Type[], ParameterModifier[]) - // System.Type.GetMethod (string, BindingFlags, Type[]) - // System.Type.GetMethod (string, BindingFlags, Binder, Type[], ParameterModifier[]) - // System.Type.GetMethod (string, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) - // System.Type.GetMethod (string, int, Type[]) - // System.Type.GetMethod (string, int, Type[], ParameterModifier[]?) - // System.Type.GetMethod (string, int, BindingFlags, Binder?, Type[], ParameterModifier[]?) - // System.Type.GetMethod (string, int, BindingFlags, Binder?, CallingConventions, Type[], ParameterModifier[]?) + // System.Type.GetMethod(string) + // System.Type.GetMethod(string, BindingFlags) + // System.Type.GetMethod(string, Type[]) + // System.Type.GetMethod(string, Type[], ParameterModifier[]) + // System.Type.GetMethod(string, BindingFlags, Type[]) + // System.Type.GetMethod(string, BindingFlags, Binder, Type[], ParameterModifier[]) + // System.Type.GetMethod(string, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) + // System.Type.GetMethod(string, int, Type[]) + // System.Type.GetMethod(string, int, Type[], ParameterModifier[]?) + // System.Type.GetMethod(string, int, BindingFlags, Binder?, Type[], ParameterModifier[]?) + // System.Type.GetMethod(string, int, BindingFlags, Binder?, CallingConventions, Type[], ParameterModifier[]?) "GetMethod" when calledMethod.IsDeclaredOnType("System.Type") && calledMethod.HasImplicitThis() && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") => IntrinsicId.Type_GetMethod, - // System.Type.GetMethods (BindingFlags) + // System.Type.GetMethods(BindingFlags) "GetMethods" when calledMethod.IsDeclaredOnType("System.Type") && calledMethod.HasImplicitThis() && calledMethod.HasMetadataParametersCount(1) && calledMethod.HasParameterOfType((ParameterIndex)1, "System.Reflection.BindingFlags") => IntrinsicId.Type_GetMethods__BindingFlags, - // System.Type.GetField (string) - // System.Type.GetField (string, BindingFlags) + // System.Type.GetField(string) + // System.Type.GetField(string, BindingFlags) "GetField" when calledMethod.IsDeclaredOnType("System.Type") && calledMethod.HasImplicitThis() && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") => IntrinsicId.Type_GetField, - // System.Type.GetFields (BindingFlags) + // System.Type.GetFields(BindingFlags) "GetFields" when calledMethod.IsDeclaredOnType("System.Type") && calledMethod.HasImplicitThis() && calledMethod.HasMetadataParametersCount(1) && calledMethod.HasParameterOfType((ParameterIndex)1, "System.Reflection.BindingFlags") => IntrinsicId.Type_GetFields__BindingFlags, - // System.Type.GetEvent (string) - // System.Type.GetEvent (string, BindingFlags) + // System.Type.GetEvent(string) + // System.Type.GetEvent(string, BindingFlags) "GetEvent" when calledMethod.IsDeclaredOnType("System.Type") && calledMethod.HasImplicitThis() && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") => IntrinsicId.Type_GetEvent, - // System.Type.GetEvents (BindingFlags) + // System.Type.GetEvents(BindingFlags) "GetEvents" when calledMethod.IsDeclaredOnType("System.Type") && calledMethod.HasImplicitThis() && calledMethod.HasMetadataParametersCount(1) && calledMethod.HasParameterOfType((ParameterIndex)1, "System.Reflection.BindingFlags") => IntrinsicId.Type_GetEvents__BindingFlags, - // System.Type.GetNestedType (string) - // System.Type.GetNestedType (string, BindingFlags) + // System.Type.GetNestedType(string) + // System.Type.GetNestedType(string, BindingFlags) "GetNestedType" when calledMethod.IsDeclaredOnType("System.Type") && calledMethod.HasImplicitThis() && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") => IntrinsicId.Type_GetNestedType, - // System.Type.GetNestedTypes (BindingFlags) + // System.Type.GetNestedTypes(BindingFlags) "GetNestedTypes" when calledMethod.IsDeclaredOnType("System.Type") && calledMethod.HasImplicitThis() && calledMethod.HasMetadataParametersCount(1) && calledMethod.HasParameterOfType((ParameterIndex)1, "System.Reflection.BindingFlags") => IntrinsicId.Type_GetNestedTypes__BindingFlags, - // System.Type.GetMember (String) - // System.Type.GetMember (String, BindingFlags) - // System.Type.GetMember (String, MemberTypes, BindingFlags) + // System.Type.GetMember(string) + // System.Type.GetMember(string, BindingFlags) + // System.Type.GetMember(string, MemberTypes, BindingFlags) "GetMember" when calledMethod.IsDeclaredOnType("System.Type") && calledMethod.HasImplicitThis() && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") @@ -230,15 +230,15 @@ public static IntrinsicId GetIntrinsicIdForMethod(MethodProxy calledMethod) (calledMethod.HasMetadataParametersCount(3) && calledMethod.HasParameterOfType((ParameterIndex)3, "System.Reflection.BindingFlags"))) => IntrinsicId.Type_GetMember, - // System.Type.GetMembers (BindingFlags) + // System.Type.GetMembers(BindingFlags) "GetMembers" when calledMethod.IsDeclaredOnType("System.Type") && calledMethod.HasImplicitThis() && calledMethod.HasMetadataParametersCount(1) && calledMethod.HasParameterOfType((ParameterIndex)1, "System.Reflection.BindingFlags") => IntrinsicId.Type_GetMembers__BindingFlags, - // System.Type.GetInterface (string) - // System.Type.GetInterface (string, bool) + // System.Type.GetInterface(string) + // System.Type.GetInterface(string, bool) "GetInterface" when calledMethod.IsDeclaredOnType("System.Type") && calledMethod.HasImplicitThis() && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") @@ -269,26 +269,26 @@ public static IntrinsicId GetIntrinsicIdForMethod(MethodProxy calledMethod) && !calledMethod.HasMetadataParameters() => IntrinsicId.Type_get_BaseType, - // System.Type.GetProperty (string) - // System.Type.GetProperty (string, BindingFlags) - // System.Type.GetProperty (string, Type) - // System.Type.GetProperty (string, Type[]) - // System.Type.GetProperty (string, Type, Type[]) - // System.Type.GetProperty (string, Type, Type[], ParameterModifier[]) - // System.Type.GetProperty (string, BindingFlags, Binder, Type, Type[], ParameterModifier[]) + // System.Type.GetProperty(string) + // System.Type.GetProperty(string, BindingFlags) + // System.Type.GetProperty(string, Type) + // System.Type.GetProperty(string, Type[]) + // System.Type.GetProperty(string, Type, Type[]) + // System.Type.GetProperty(string, Type, Type[], ParameterModifier[]) + // System.Type.GetProperty(string, BindingFlags, Binder, Type, Type[], ParameterModifier[]) "GetProperty" when calledMethod.IsDeclaredOnType("System.Type") && calledMethod.HasImplicitThis() && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") => IntrinsicId.Type_GetProperty, - // System.Type.GetProperties (BindingFlags) + // System.Type.GetProperties(BindingFlags) "GetProperties" when calledMethod.IsDeclaredOnType("System.Type") && calledMethod.HasImplicitThis() && calledMethod.HasParameterOfType((ParameterIndex)1, "System.Reflection.BindingFlags") && calledMethod.HasMetadataParametersCount(1) => IntrinsicId.Type_GetProperties__BindingFlags, - // static System.Object.GetType () + // static System.Object.GetType() "GetType" when calledMethod.IsDeclaredOnType("System.Object") => IntrinsicId.Object_GetType, @@ -299,76 +299,76 @@ public static IntrinsicId GetIntrinsicIdForMethod(MethodProxy calledMethod) "Empty" when calledMethod.IsDeclaredOnType("System.Array") => IntrinsicId.Array_Empty, - // static System.Array.CreateInstance (System.Type type, int length) + // static System.Array.CreateInstance(System.Type type, int length) "CreateInstance" when calledMethod.IsDeclaredOnType("System.Array") && calledMethod.HasMetadataParametersCount(2) && calledMethod.HasParameterOfType((ParameterIndex)1, "System.Int32") => IntrinsicId.Array_CreateInstance, - // static System.Activator.CreateInstance (System.Type type) - // static System.Activator.CreateInstance (System.Type type, bool nonPublic) - // static System.Activator.CreateInstance (System.Type type, params object?[]? args) - // static System.Activator.CreateInstance (System.Type type, object?[]? args, object?[]? activationAttributes) - // static System.Activator.CreateInstance (System.Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture) - // static System.Activator.CreateInstance (System.Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) { throw null; } + // static System.Activator.CreateInstance(System.Type type) + // static System.Activator.CreateInstance(System.Type type, bool nonPublic) + // static System.Activator.CreateInstance(System.Type type, params object?[]? args) + // static System.Activator.CreateInstance(System.Type type, object?[]? args, object?[]? activationAttributes) + // static System.Activator.CreateInstance(System.Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture) + // static System.Activator.CreateInstance(System.Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) { throw null; } "CreateInstance" when calledMethod.IsDeclaredOnType("System.Activator") && !calledMethod.HasGenericParameters() && calledMethod.HasParameterOfType((ParameterIndex)0, "System.Type") => IntrinsicId.Activator_CreateInstance__Type, - // static System.Activator.CreateInstance (string assemblyName, string typeName) - // static System.Activator.CreateInstance (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) - // static System.Activator.CreateInstance (string assemblyName, string typeName, object?[]? activationAttributes) + // static System.Activator.CreateInstance(string assemblyName, string typeName) + // static System.Activator.CreateInstance(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) + // static System.Activator.CreateInstance(string assemblyName, string typeName, object?[]? activationAttributes) "CreateInstance" when calledMethod.IsDeclaredOnType("System.Activator") && !calledMethod.HasGenericParameters() && calledMethod.HasParameterOfType((ParameterIndex)0, "System.String") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") => IntrinsicId.Activator_CreateInstance__AssemblyName_TypeName, - // static System.Activator.CreateInstanceFrom (string assemblyFile, string typeName) - // static System.Activator.CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) - // static System.Activator.CreateInstanceFrom (string assemblyFile, string typeName, object? []? activationAttributes) + // static System.Activator.CreateInstanceFrom(string assemblyFile, string typeName) + // static System.Activator.CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) + // static System.Activator.CreateInstanceFrom(string assemblyFile, string typeName, object? []? activationAttributes) "CreateInstanceFrom" when calledMethod.IsDeclaredOnType("System.Activator") && !calledMethod.HasGenericParameters() && calledMethod.HasParameterOfType((ParameterIndex)0, "System.String") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") => IntrinsicId.Activator_CreateInstanceFrom, - // System.AppDomain.CreateInstance (string assemblyName, string typeName) - // System.AppDomain.CreateInstance (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) - // System.AppDomain.CreateInstance (string assemblyName, string typeName, object? []? activationAttributes) + // System.AppDomain.CreateInstance(string assemblyName, string typeName) + // System.AppDomain.CreateInstance(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) + // System.AppDomain.CreateInstance(string assemblyName, string typeName, object? []? activationAttributes) "CreateInstance" when calledMethod.IsDeclaredOnType("System.AppDomain") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") && calledMethod.HasParameterOfType((ParameterIndex)2, "System.String") => IntrinsicId.AppDomain_CreateInstance, - // System.AppDomain.CreateInstanceAndUnwrap (string assemblyName, string typeName) - // System.AppDomain.CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) - // System.AppDomain.CreateInstanceAndUnwrap (string assemblyName, string typeName, object? []? activationAttributes) + // System.AppDomain.CreateInstanceAndUnwrap(string assemblyName, string typeName) + // System.AppDomain.CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) + // System.AppDomain.CreateInstanceAndUnwrap(string assemblyName, string typeName, object? []? activationAttributes) "CreateInstanceAndUnwrap" when calledMethod.IsDeclaredOnType("System.AppDomain") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") && calledMethod.HasParameterOfType((ParameterIndex)2, "System.String") => IntrinsicId.AppDomain_CreateInstanceAndUnwrap, - // System.AppDomain.CreateInstanceFrom (string assemblyFile, string typeName) - // System.AppDomain.CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) - // System.AppDomain.CreateInstanceFrom (string assemblyFile, string typeName, object? []? activationAttributes) + // System.AppDomain.CreateInstanceFrom(string assemblyFile, string typeName) + // System.AppDomain.CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) + // System.AppDomain.CreateInstanceFrom(string assemblyFile, string typeName, object? []? activationAttributes) "CreateInstanceFrom" when calledMethod.IsDeclaredOnType("System.AppDomain") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") && calledMethod.HasParameterOfType((ParameterIndex)2, "System.String") => IntrinsicId.AppDomain_CreateInstanceFrom, - // System.AppDomain.CreateInstanceFromAndUnwrap (string assemblyFile, string typeName) - // System.AppDomain.CreateInstanceFromAndUnwrap (string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) - // System.AppDomain.CreateInstanceFromAndUnwrap (string assemblyFile, string typeName, object? []? activationAttributes) + // System.AppDomain.CreateInstanceFromAndUnwrap(string assemblyFile, string typeName) + // System.AppDomain.CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object? []? args, System.Globalization.CultureInfo? culture, object? []? activationAttributes) + // System.AppDomain.CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, object? []? activationAttributes) "CreateInstanceFromAndUnwrap" when calledMethod.IsDeclaredOnType("System.AppDomain") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") && calledMethod.HasParameterOfType((ParameterIndex)2, "System.String") => IntrinsicId.AppDomain_CreateInstanceFromAndUnwrap, - // System.Reflection.Assembly.CreateInstance (string typeName) - // System.Reflection.Assembly.CreateInstance (string typeName, bool ignoreCase) - // System.Reflection.Assembly.CreateInstance (string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object []? args, CultureInfo? culture, object []? activationAttributes) + // System.Reflection.Assembly.CreateInstance(string typeName) + // System.Reflection.Assembly.CreateInstance(string typeName, bool ignoreCase) + // System.Reflection.Assembly.CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object []? args, CultureInfo? culture, object []? activationAttributes) "CreateInstance" when calledMethod.IsDeclaredOnType("System.Reflection.Assembly") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") => IntrinsicId.Assembly_CreateInstance, @@ -377,13 +377,13 @@ public static IntrinsicId GetIntrinsicIdForMethod(MethodProxy calledMethod) "get_Location" when calledMethod.IsDeclaredOnType("System.Reflection.Assembly") => IntrinsicId.Assembly_get_Location, - // System.Reflection.Assembly.GetFile (string) + // System.Reflection.Assembly.GetFile(string) "GetFile" when calledMethod.IsDeclaredOnType("System.Reflection.Assembly") && calledMethod.HasParameterOfType((ParameterIndex)1, "System.String") => IntrinsicId.Assembly_GetFile, - // System.Reflection.Assembly.GetFiles () - // System.Reflection.Assembly.GetFiles (bool) + // System.Reflection.Assembly.GetFiles() + // System.Reflection.Assembly.GetFiles(bool) "GetFiles" when calledMethod.IsDeclaredOnType("System.Reflection.Assembly") && (calledMethod.HasMetadataParametersCount(0) || calledMethod.HasParameterOfType((ParameterIndex)1, "System.Boolean")) => IntrinsicId.Assembly_GetFiles, @@ -396,12 +396,12 @@ public static IntrinsicId GetIntrinsicIdForMethod(MethodProxy calledMethod) "get_EscapedCodeBase" when calledMethod.IsDeclaredOnType("System.Reflection.AssemblyName") => IntrinsicId.AssemblyName_get_EscapedCodeBase, - // System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor (RuntimeTypeHandle type) + // System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(RuntimeTypeHandle type) "RunClassConstructor" when calledMethod.IsDeclaredOnType("System.Runtime.CompilerServices.RuntimeHelpers") && calledMethod.HasParameterOfType((ParameterIndex)0, "System.RuntimeTypeHandle") => IntrinsicId.RuntimeHelpers_RunClassConstructor, - // System.Reflection.MethodInfo.MakeGenericMethod (Type[] typeArguments) + // System.Reflection.MethodInfo.MakeGenericMethod(Type[] typeArguments) "MakeGenericMethod" when calledMethod.IsDeclaredOnType("System.Reflection.MethodInfo") && calledMethod.HasImplicitThis() && calledMethod.HasMetadataParametersCount(1) @@ -419,13 +419,13 @@ public static IntrinsicId GetIntrinsicIdForMethod(MethodProxy calledMethod) && calledMethod.HasMetadataParametersCount(0) => IntrinsicId.Delegate_get_Method, - // static System.Runtime.InteropServices.TypeMapping.GetOrCreateExternalTypeMapping () + // static System.Runtime.InteropServices.TypeMapping.GetOrCreateExternalTypeMapping() "GetOrCreateExternalTypeMapping" when calledMethod.IsDeclaredOnType("System.Runtime.InteropServices.TypeMapping") && calledMethod.IsStatic() && calledMethod.HasGenericParametersCount(1) => IntrinsicId.TypeMapping_GetOrCreateExternalTypeMapping, - // static System.Runtime.InteropServices.TypeMapping.GetOrCreateProxyTypeMapping () + // static System.Runtime.InteropServices.TypeMapping.GetOrCreateProxyTypeMapping() "GetOrCreateProxyTypeMapping" when calledMethod.IsDeclaredOnType("System.Runtime.InteropServices.TypeMapping") && calledMethod.IsStatic() && calledMethod.HasGenericParametersCount(1) diff --git a/src/tools/illink/src/analyzer/LinkerAnalyzerCore/DependencyGraph.cs b/src/tools/illink/src/analyzer/LinkerAnalyzerCore/DependencyGraph.cs index 539e2cbf8c25dd..4bb024d5d909d1 100644 --- a/src/tools/illink/src/analyzer/LinkerAnalyzerCore/DependencyGraph.cs +++ b/src/tools/illink/src/analyzer/LinkerAnalyzerCore/DependencyGraph.cs @@ -69,12 +69,12 @@ void Load(FileStream fileStream) switch (reader.NodeType) { case XmlNodeType.Element: - // Console.WriteLine (reader.Name); + // Console.WriteLine(reader.Name); if (reader.Name == "edge" && reader.IsStartElement()) { string b = reader.GetAttribute("b"); string e = reader.GetAttribute("e"); - //Console.WriteLine ("edge value " + b + " --> " + e); + //Console.WriteLine("edge value " + b + " --> " + e); if (e != b) { @@ -85,13 +85,13 @@ void Load(FileStream fileStream) if (!end.parentIndexes.Contains(begin.index)) { end.parentIndexes.Add(begin.index); - //Console.WriteLine (" end parent index: {0}", end.parentIndexes); + //Console.WriteLine(" end parent index: {0}", end.parentIndexes); } } } break; default: - //Console.WriteLine ("node: " + reader.NodeType); + //Console.WriteLine("node: " + reader.NodeType); break; } } @@ -115,7 +115,7 @@ public VertexData Vertex(string vertexName, bool create = false) counts[prefix] = count + 1; else counts[prefix] = 1; - //Console.WriteLine ("prefix " + prefix + " count " + counts[prefix]); + //Console.WriteLine("prefix " + prefix + " count " + counts[prefix]); if (prefix == "TypeDef") { Types.Add(vertex); diff --git a/src/tools/illink/src/linker/Linker.Dataflow/CompilerGeneratedState.cs b/src/tools/illink/src/linker/Linker.Dataflow/CompilerGeneratedState.cs index 56133bce64f42d..32eb57fd031cd3 100644 --- a/src/tools/illink/src/linker/Linker.Dataflow/CompilerGeneratedState.cs +++ b/src/tools/illink/src/linker/Linker.Dataflow/CompilerGeneratedState.cs @@ -354,15 +354,15 @@ referencedMethod.DeclaringType is var generatedType && /// Attempts to reverse the process of the compiler's alpha renaming. So if the original code was /// something like this: /// - /// void M<T> () { - /// Action a = () => { Console.WriteLine (typeof (T)); }; + /// void M<T>() { + /// Action a = () => { Console.WriteLine(typeof(T)); }; /// } /// /// The compiler will generate a nested class like this: /// /// class <>c__DisplayClass0<T> { - /// public void <M>b__0 () { - /// Console.WriteLine (typeof (T)); + /// public void <M>b__0() { + /// Console.WriteLine(typeof(T)); /// } /// } /// diff --git a/src/tools/illink/src/linker/Linker.Dataflow/MethodBodyScanner.cs b/src/tools/illink/src/linker/Linker.Dataflow/MethodBodyScanner.cs index 0ac227d3ea4c5c..967cdf795a55fc 100644 --- a/src/tools/illink/src/linker/Linker.Dataflow/MethodBodyScanner.cs +++ b/src/tools/illink/src/linker/Linker.Dataflow/MethodBodyScanner.cs @@ -276,9 +276,9 @@ public virtual void InterproceduralScan(MethodIL startingMethodIL) var calleeMethods = compilerGeneratedCallees.OfType(); // https://github.com/dotnet/linker/issues/2845 // Disabled asserts due to a bug - // Debug.Assert (interproceduralState.Count == 1 + calleeMethods.Count ()); + // Debug.Assert(interproceduralState.Count == 1 + calleeMethods.Count()); // foreach (var method in calleeMethods) - // Debug.Assert (interproceduralState.Any (kvp => kvp.Key.Method == method)); + // Debug.Assert(interproceduralState.Any(kvp => kvp.Key.Method == method)); } else { diff --git a/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs b/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs index 53019523f9573c..6b03933b8abcf7 100644 --- a/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs +++ b/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs @@ -137,9 +137,9 @@ static string FormatCustomAttribute(CustomAttribute ca) // // public sealed class RemoveAttributeInstancesAttribute : Attribute // { - // public RemoveAttributeInstancesAttribute () {} - // public RemoveAttributeInstancesAttribute (object values) {} // For legacy uses - // public RemoveAttributeInstancesAttribute (params object[] values) {} + // public RemoveAttributeInstancesAttribute() {} + // public RemoveAttributeInstancesAttribute(object values) {} // For legacy uses + // public RemoveAttributeInstancesAttribute(params object[] values) {} // } // const MethodAttributes ctorAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.Final; diff --git a/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs b/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs index 8a3d6e98d0f314..af9d3856007f42 100644 --- a/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs +++ b/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs @@ -4016,7 +4016,7 @@ protected internal virtual bool ProcessReflectionDependency(MethodBody body, Ins } // - // Tries to mark additional dependencies used in reflection like calls (e.g. typeof (MyClass).GetField ("fname")) + // Tries to mark additional dependencies used in reflection like calls (e.g. typeof(MyClass).GetField("fname")) // protected virtual void MarkReflectionLikeDependencies(MethodIL methodIL, bool requiresReflectionMethodBodyScanner, MessageOrigin origin) { diff --git a/src/tools/illink/src/linker/Linker/DynamicDependency.cs b/src/tools/illink/src/linker/Linker/DynamicDependency.cs index eebaa096d2fc9b..8bf34c9f446877 100644 --- a/src/tools/illink/src/linker/Linker/DynamicDependency.cs +++ b/src/tools/illink/src/linker/Linker/DynamicDependency.cs @@ -70,7 +70,7 @@ public DynamicDependency(DynamicallyAccessedMemberTypes memberTypes, string type // Don't honor the Condition until we have figured out the behavior for DynamicDependencyAttribute: // https://github.com/dotnet/linker/issues/1231 - // if (!ShouldProcess (context, customAttribute)) + // if (!ShouldProcess(context, customAttribute)) // return null; var dynamicDependency = GetDynamicDependency(customAttribute); diff --git a/src/tools/illink/src/linker/Linker/TypeNameResolver.cs b/src/tools/illink/src/linker/Linker/TypeNameResolver.cs index 747bb486afd78f..006ad300905a20 100644 --- a/src/tools/illink/src/linker/Linker/TypeNameResolver.cs +++ b/src/tools/illink/src/linker/Linker/TypeNameResolver.cs @@ -5,10 +5,9 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Mono.Cecil; - +using AssemblyNameInfo = System.Reflection.Metadata.AssemblyNameInfo; using TypeName = System.Reflection.Metadata.TypeName; using TypeNameParseOptions = System.Reflection.Metadata.TypeNameParseOptions; -using AssemblyNameInfo = System.Reflection.Metadata.AssemblyNameInfo; #nullable enable diff --git a/src/tools/illink/src/tlens/README.md b/src/tools/illink/src/tlens/README.md index 0a1066c9c03e9e..9c967034a18b5d 100644 --- a/src/tools/illink/src/tlens/README.md +++ b/src/tools/illink/src/tlens/README.md @@ -44,12 +44,12 @@ Consider following example where `tlens` can show suggestion for the code to be ```c# interface IOperation { - void Run (); + void Run(); } class CommonOperation : IOperation { - void IOperation.Run () + void IOperation.Run() { // Pulls complex dependencies } @@ -57,12 +57,12 @@ class CommonOperation : IOperation class RareOperation : IOperation { - void IOperation.Run () + void IOperation.Run() { // Pulls complex dependencies } - public void Run (IOperation operation) + public void Run(IOperation operation) { operation.Run(); } @@ -70,10 +70,10 @@ class RareOperation : IOperation class App { - public static void Main () + public static void Main() { - var rare = new RareOperation (); - rare.Run (rare); + var rare = new RareOperation(); + rare.Run(rare); } } ``` diff --git a/src/tools/illink/src/tlens/TLens/Driver.cs b/src/tools/illink/src/tlens/TLens/Driver.cs index 65b1c2cdb8a6c8..691be2d55c5284 100644 --- a/src/tools/illink/src/tlens/TLens/Driver.cs +++ b/src/tools/illink/src/tlens/TLens/Driver.cs @@ -25,32 +25,32 @@ static int Main(string[] args) var options = new OptionSet { { "l|lens=", "{NAME} of the lens to use. Default subset is used if not specified.", l => { - var lens = LensesCollection.GetLensByName (l); + var lens = LensesCollection.GetLensByName(l); if (lens != null) - analyzers.Add (lens); + analyzers.Add(lens); else { - Console.WriteLine ($"Error: Lens name '{l}' does not exist."); + Console.WriteLine($"Error: Lens name '{l}' does not exist."); error = true; } }}, { "d|dir=", "Additional location {PATH} to look for assembly references.", l => { - if (!Directory.Exists (l)) { - Console.WriteLine ($"Error: Directory '{l}' does not exist."); + if (!Directory.Exists(l)) { + Console.WriteLine($"Error: Directory '{l}' does not exist."); error = true; } else { - dirs.Add (Path.GetFullPath (l)); + dirs.Add(Path.GetFullPath(l)); } }}, { "all-lenses", "Uses all lenses available.", - l => analyzers.AddRange (LensesCollection.AllAnalyzers) }, + l => analyzers.AddRange(LensesCollection.AllAnalyzers) }, { "h|help", "Show this message and exit.", v => showUsage = v != null }, { "limit=", "Maximum number of findings reported by lens (defaults to 30).", - l => runner.MaxAnalyzerResults = int.Parse (l) }, + l => runner.MaxAnalyzerResults = int.Parse(l) }, }; List files; diff --git a/src/tools/illink/src/tlens/TLens/LensesCollection.cs b/src/tools/illink/src/tlens/TLens/LensesCollection.cs index fadc8200894927..b3ba2c7ee6adc1 100644 --- a/src/tools/illink/src/tlens/TLens/LensesCollection.cs +++ b/src/tools/illink/src/tlens/TLens/LensesCollection.cs @@ -39,32 +39,32 @@ public Analyzer CreateAnalyzer() // static readonly LensAnalyzerDetails[] all = [ - new LensAnalyzerDetails ("duplicated-code", - "Methods which are possible duplicates", typeof (DuplicatedCodeAnalyzer)), - new LensAnalyzerDetails ("fields-init", - "Constructors re-initializing fields to default values", typeof (RedundantFieldInitializationAnalyzer)), - new LensAnalyzerDetails ("fields-unread", - "Fields that are set but never read", typeof (UnnecessaryFieldsAssignmentAnalyzer)), - new LensAnalyzerDetails ("ifaces-dispatch", - "Interfaces which are called sparsely", typeof (InterfaceDispatchAnalyzer)), - new LensAnalyzerDetails ("ifaces-types", - "Interfaces with implementation but no type reference", typeof (InterfaceTypeCheckAnalyzers)), - new LensAnalyzerDetails ("inverted-ctors", - "Constructors calling same type constructor with default values", typeof (InverterCtorsChainAnalyzer)), - new LensAnalyzerDetails ("large-arrays", - "Methods creating large arrays", typeof (LargeStaticArraysAnalyzer)) { DefaultSet = true }, - new LensAnalyzerDetails ("large-cctors", - "Types with large static contructor", typeof (LargeStaticCtorAnalyzer)), - new LensAnalyzerDetails ("large-strings", - "Methods using large strings literals", typeof (LargeStringsAnalyzer)) { DefaultSet = true }, - new LensAnalyzerDetails ("operator-null", - "User operators used for null check", typeof (UserOperatorCalledForNullCheckAnalyzer)), - new LensAnalyzerDetails ("single-calls", - "Methods called sparsely", typeof (LimitedMethodCalls)), - new LensAnalyzerDetails ("single-construction", - "Types with limited number of constructions", typeof (TypeInstatiationAnalyzer)) { DefaultSet = true }, - new LensAnalyzerDetails ("unused-param", - "Methods with unused parameters", typeof (UnusedParametersAnalyzer)), + new LensAnalyzerDetails("duplicated-code", + "Methods which are possible duplicates", typeof(DuplicatedCodeAnalyzer)), + new LensAnalyzerDetails("fields-init", + "Constructors re-initializing fields to default values", typeof(RedundantFieldInitializationAnalyzer)), + new LensAnalyzerDetails("fields-unread", + "Fields that are set but never read", typeof(UnnecessaryFieldsAssignmentAnalyzer)), + new LensAnalyzerDetails("ifaces-dispatch", + "Interfaces which are called sparsely", typeof(InterfaceDispatchAnalyzer)), + new LensAnalyzerDetails("ifaces-types", + "Interfaces with implementation but no type reference", typeof(InterfaceTypeCheckAnalyzers)), + new LensAnalyzerDetails("inverted-ctors", + "Constructors calling same type constructor with default values", typeof(InverterCtorsChainAnalyzer)), + new LensAnalyzerDetails("large-arrays", + "Methods creating large arrays", typeof(LargeStaticArraysAnalyzer)) { DefaultSet = true }, + new LensAnalyzerDetails("large-cctors", + "Types with large static contructor", typeof(LargeStaticCtorAnalyzer)), + new LensAnalyzerDetails("large-strings", + "Methods using large strings literals", typeof(LargeStringsAnalyzer)) { DefaultSet = true }, + new LensAnalyzerDetails("operator-null", + "User operators used for null check", typeof(UserOperatorCalledForNullCheckAnalyzer)), + new LensAnalyzerDetails("single-calls", + "Methods called sparsely", typeof(LimitedMethodCalls)), + new LensAnalyzerDetails("single-construction", + "Types with limited number of constructions", typeof(TypeInstatiationAnalyzer)) { DefaultSet = true }, + new LensAnalyzerDetails("unused-param", + "Methods with unused parameters", typeof(UnusedParametersAnalyzer)), ]; public static IEnumerable All => all; diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests.Generator/TestCaseGenerator.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests.Generator/TestCaseGenerator.cs index 8b6549a4900108..8246733d896bcd 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests.Generator/TestCaseGenerator.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests.Generator/TestCaseGenerator.cs @@ -71,12 +71,12 @@ public static string GenerateClassHeader(string suiteName, bool newTestSuite) namespace {TestNamespace}{suiteNamespacePart} {{ - public sealed partial class {suiteClassName}Tests : LinkerTestBase - {{ + public sealed partial class {suiteClassName}Tests : LinkerTestBase + {{ "; if (newTestSuite) header += $@" - protected override string TestSuiteName => ""{suiteName}""; + protected override string TestSuiteName => ""{suiteName}""; "; return header; } @@ -84,18 +84,18 @@ public sealed partial class {suiteClassName}Tests : LinkerTestBase public static string GenerateFact(string testCase) { return $@" - [Fact] - public Task {testCase} () - {{ - return RunTest (allowMissingWarnings: true); - }} + [Fact] + public Task {testCase}() + {{ + return RunTest(allowMissingWarnings: true); + }} "; } public static string GenerateClassFooter() { return $@" - }} + }} }} "; } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersAnalyzerTests.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersAnalyzerTests.cs index d402cbf41ee071..1cbd480d087265 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersAnalyzerTests.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersAnalyzerTests.cs @@ -29,31 +29,31 @@ static Task VerifyDynamicallyAccessedMembersAnalyzer( public Task NoWarningsIfAnalyzerIsNotEnabled() { var TargetParameterWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Foo - { - } - - class C - { - public static void Main() - { - M(typeof(Foo)); - } - - private static void NeedsPublicMethodsOnParameter( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type parameter) - { - } - - private static void M(Type type) - { - NeedsPublicMethodsOnParameter(type); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Foo + { + } + + class C + { + public static void Main() + { + M(typeof(Foo)); + } + + private static void NeedsPublicMethodsOnParameter( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type parameter) + { + } + + private static void M(Type type) + { + NeedsPublicMethodsOnParameter(type); + } + } + """; return VerifyCS.VerifyAnalyzerAsync(TargetParameterWithAnnotations, consoleApplication: false); } @@ -62,30 +62,30 @@ private static void M(Type type) public Task SourceParameterDoesNotMatchTargetParameterAnnotations() { var TargetParameterWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Foo - { - } - - class C - { - public static void Main() - { - M(typeof(Foo)); - } - private static void NeedsPublicMethodsOnParameter( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type parameter) - { - } - - private static void M(Type type) - { - NeedsPublicMethodsOnParameter(type); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Foo + { + } + + class C + { + public static void Main() + { + M(typeof(Foo)); + } + private static void NeedsPublicMethodsOnParameter( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type parameter) + { + } + + private static void M(Type type) + { + NeedsPublicMethodsOnParameter(type); + } + } + """; // (21,3): warning IL2067: 'parameter' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethodsOnParameter(Type)'. // The parameter 'type' of method 'C.M(Type)' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. @@ -104,27 +104,27 @@ private static void M(Type type) public Task SourceParameterDoesNotMatchTargetMethodReturnTypeAnnotations() { var TargetMethodReturnTypeWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Foo - { - } - - class C - { - public static void Main() - { - M(typeof(Foo)); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type M(Type type) - { - return type; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Foo + { + } + + class C + { + public static void Main() + { + M(typeof(Foo)); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type M(Type type) + { + return type; + } + } + """; // (18,10): warning IL2068: 'C.M(Type)' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. // The parameter 'type' of method 'C.M(Type)' does not have matching annotations. @@ -143,29 +143,29 @@ private static Type M(Type type) public Task SourceParameterDoesNotMatchTargetFieldAnnotations() { var TargetFieldWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Foo - { - } - - class C - { - public static void Main() - { - M(typeof(Foo)); - } - - private static void M(Type type) - { - f = type; - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f = typeof(Foo); - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Foo + { + } + + class C + { + public static void Main() + { + M(typeof(Foo)); + } + + private static void M(Type type) + { + f = type; + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f = typeof(Foo); + } + """; // (17,3): warning IL2069: value stored in field 'C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. // The parameter 'type' of method 'C.M(Type)' does not have matching annotations. @@ -184,25 +184,25 @@ private static void M(Type type) public Task SourceParameterDoesNotMatchTargetMethodAnnotations() { var TargetMethodWithAnnotations = $$""" - using System; - - public class Foo - { - } - - class C - { - public static void Main() - { - M(typeof(Foo)); - } - - private static void M(Type type) - { - type.GetMethod("Bar"); - } - } - """; + using System; + + public class Foo + { + } + + class C + { + public static void Main() + { + M(typeof(Foo)); + } + + private static void M(Type type) + { + type.GetMethod("Bar"); + } + } + """; // The warning will be generated once dataflow is able to handle GetMethod intrinsic // (16,3): warning IL2070: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. @@ -224,31 +224,31 @@ private static void M(Type type) public Task SourceMethodReturnTypeDoesNotMatchTargetParameterAnnotations() { var TargetParameterWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class T - { - } - - class C - { - public static void Main() - { - NeedsPublicMethodsOnParameter(GetT()); - } - - private static void NeedsPublicMethodsOnParameter( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - - private static Type GetT() - { - return typeof(T); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class T + { + } + + class C + { + public static void Main() + { + NeedsPublicMethodsOnParameter(GetT()); + } + + private static void NeedsPublicMethodsOnParameter( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + + private static Type GetT() + { + return typeof(T); + } + } + """; // (12,3): warning IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethodsOnParameter(Type)'. // The return value of method 'C.GetT()' does not have matching annotations. @@ -264,32 +264,32 @@ private static Type GetT() public Task SourceMethodReturnTypeDoesNotMatchTargetMethodReturnTypeAnnotations() { var TargetMethodReturnTypeWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Foo - { - } - - class C - { - public static void Main() - { - M(); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type M() - { - return GetFoo(); - } - - private static Type GetFoo() - { - return typeof(Foo); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Foo + { + } + + class C + { + public static void Main() + { + M(); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type M() + { + return GetFoo(); + } + + private static Type GetFoo() + { + return typeof(Foo); + } + } + """; // (18,10): warning IL2073: 'C.M()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. // The return value of method 'C.GetT()' does not have matching annotations. @@ -305,29 +305,29 @@ private static Type GetFoo() public Task SourceMethodReturnTypeDoesNotMatchTargetFieldAnnotations() { var TargetFieldWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Foo - { - } - - class C - { - public static void Main() - { - f = M(); - } - - private static Type M() - { - return typeof(Foo); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f; - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Foo + { + } + + class C + { + public static void Main() + { + f = M(); + } + + private static Type M() + { + return typeof(Foo); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f; + } + """; // (12,3): warning IL2074: value stored in field 'C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. // The return value of method 'C.M()' does not have matching annotations. @@ -345,26 +345,26 @@ private static Type M() public Task SourceMethodReturnTypeDoesNotMatchTargetMethod() { var TargetMethodWithAnnotations = $$""" - using System; - - public class Foo - { - } - - class C - { - public static void Main() - { - GetFoo().GetMethod("Bar"); - - } - - private static Type GetFoo () - { - return typeof (Foo); - } - } - """; + using System; + + public class Foo + { + } + + class C + { + public static void Main() + { + GetFoo().GetMethod("Bar"); + + } + + private static Type GetFoo() + { + return typeof(Foo); + } + } + """; // The warning will be generated once dataflow is able to handle GetMethod intrinsic // (11,3): warning IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. @@ -383,28 +383,28 @@ private static Type GetFoo () public Task SourceFieldDoesNotMatchTargetParameterAnnotations() { var TargetParameterWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class Foo - { - } + public class Foo + { + } - class C - { - private static Type f = typeof(Foo); + class C + { + private static Type f = typeof(Foo); - public static void Main() - { - NeedsPublicMethods(f); - } + public static void Main() + { + NeedsPublicMethods(f); + } - private static void NeedsPublicMethods( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - } - """; + private static void NeedsPublicMethods( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + } + """; // (14,3): warning IL2077: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethods(Type)'. // The field 'C.f' does not have matching annotations. @@ -423,29 +423,29 @@ private static void NeedsPublicMethods( public Task SourceFieldDoesNotMatchTargetMethodReturnTypeAnnotations() { var TargetMethodReturnTypeWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Foo - { - } - - class C - { - private static Type f = typeof(Foo); - - public static void Main() - { - M(); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type M() - { - return f; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Foo + { + } + + class C + { + private static Type f = typeof(Foo); + + public static void Main() + { + M(); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type M() + { + return f; + } + } + """; // (20,10): warning IL2078: 'C.M()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. // The field 'C.f' does not have matching annotations. @@ -462,26 +462,26 @@ private static Type M() public Task SourceFieldDoesNotMatchTargetFieldAnnotations() { var TargetFieldWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Foo - { - } - - class C - { - private static Type f1 = typeof(Foo); - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f2 = typeof(Foo); - - public static void Main() - { - f2 = f1; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Foo + { + } + + class C + { + private static Type f1 = typeof(Foo); + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f2 = typeof(Foo); + + public static void Main() + { + f2 = f1; + } + } + """; // (17,3): warning IL2079: value stored in field 'C.f2' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. // The field 'C.f1' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. @@ -498,22 +498,22 @@ public static void Main() public Task SourceFieldDoesNotMatchTargetMethodAnnotations() { var TargetMethodWithAnnotations = $$""" - using System; - - public class Foo - { - } - - class C - { - private static Type f = typeof(Foo); - - public static void Main() - { - f.GetMethod("Bar"); - } - } - """; + using System; + + public class Foo + { + } + + class C + { + private static Type f = typeof(Foo); + + public static void Main() + { + f.GetMethod("Bar"); + } + } + """; // The warning will be generated once dataflow is able to handle GetMethod intrinsic // (13,3): warning IL2080: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. @@ -544,182 +544,182 @@ public static string GetSystemTypeBase() namespace System { - public class TestSystemTypeBase : Type - { - public override Assembly Assembly => throw new NotImplementedException (); - - public override string AssemblyQualifiedName => throw new NotImplementedException (); - - public override Type BaseType => throw new NotImplementedException (); - - public override string FullName => throw new NotImplementedException (); - - public override Guid GUID => throw new NotImplementedException (); - - public override Module Module => throw new NotImplementedException (); - - public override string Namespace => throw new NotImplementedException (); - - public override Type UnderlyingSystemType => throw new NotImplementedException (); - - public override string Name => throw new NotImplementedException (); - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors - | DynamicallyAccessedMemberTypes.NonPublicConstructors)] - public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr) - { - throw new NotImplementedException (); - } - - public override object[] GetCustomAttributes (bool inherit) - { - throw new NotImplementedException (); - } - - public override object[] GetCustomAttributes (Type attributeType, bool inherit) - { - throw new NotImplementedException (); - } - - public override Type GetElementType () - { - throw new NotImplementedException (); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents - | DynamicallyAccessedMemberTypes.NonPublicEvents)] - public override EventInfo GetEvent (string name, BindingFlags bindingAttr) - { - throw new NotImplementedException (); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] - public override EventInfo[] GetEvents (BindingFlags bindingAttr) - { - throw new NotImplementedException (); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] - public override FieldInfo GetField (string name, BindingFlags bindingAttr) - { - throw new NotImplementedException (); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields - | DynamicallyAccessedMemberTypes.NonPublicFields)] - public override FieldInfo[] GetFields (BindingFlags bindingAttr) - { - throw new NotImplementedException (); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] - public override Type GetInterface (string name, bool ignoreCase) - { - throw new NotImplementedException (); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] - public override Type[] GetInterfaces () - { - throw new NotImplementedException (); - } - - [DynamicallyAccessedMembers((DynamicallyAccessedMemberTypes)0x1FFF)] - public override MemberInfo[] GetMembers (BindingFlags bindingAttr) - { - throw new NotImplementedException (); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] - public override MethodInfo[] GetMethods (BindingFlags bindingAttr) - { - throw new NotImplementedException (); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] - public override Type GetNestedType (string name, BindingFlags bindingAttr) - { - throw new NotImplementedException (); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] - public override Type[] GetNestedTypes (BindingFlags bindingAttr) - { - throw new NotImplementedException (); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] - public override PropertyInfo[] GetProperties (BindingFlags bindingAttr) - { - throw new NotImplementedException (); - } - - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] - public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) - { - throw new NotImplementedException (); - } - - public override bool IsDefined (Type attributeType, bool inherit) - { - throw new NotImplementedException (); - } - - protected override TypeAttributes GetAttributeFlagsImpl () - { - throw new NotImplementedException (); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors - | DynamicallyAccessedMemberTypes.NonPublicConstructors)] - protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) - { - throw new NotImplementedException (); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] - protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) - { - throw new NotImplementedException (); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] - protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) - { - throw new NotImplementedException (); - } - - protected override bool HasElementTypeImpl () - { - throw new NotImplementedException (); - } - - protected override bool IsArrayImpl () - { - throw new NotImplementedException (); - } - - protected override bool IsByRefImpl () - { - throw new NotImplementedException (); - } - - protected override bool IsCOMObjectImpl () - { - throw new NotImplementedException (); - } - - protected override bool IsPointerImpl () - { - throw new NotImplementedException (); - } - - protected override bool IsPrimitiveImpl () - { - throw new NotImplementedException (); - } - } + public class TestSystemTypeBase : Type + { + public override Assembly Assembly => throw new NotImplementedException(); + + public override string AssemblyQualifiedName => throw new NotImplementedException(); + + public override Type BaseType => throw new NotImplementedException(); + + public override string FullName => throw new NotImplementedException(); + + public override Guid GUID => throw new NotImplementedException(); + + public override Module Module => throw new NotImplementedException(); + + public override string Namespace => throw new NotImplementedException(); + + public override Type UnderlyingSystemType => throw new NotImplementedException(); + + public override string Name => throw new NotImplementedException(); + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors + | DynamicallyAccessedMemberTypes.NonPublicConstructors)] + public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) + { + throw new NotImplementedException(); + } + + public override object[] GetCustomAttributes(bool inherit) + { + throw new NotImplementedException(); + } + + public override object[] GetCustomAttributes(Type attributeType, bool inherit) + { + throw new NotImplementedException(); + } + + public override Type GetElementType() + { + throw new NotImplementedException(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents + | DynamicallyAccessedMemberTypes.NonPublicEvents)] + public override EventInfo GetEvent(string name, BindingFlags bindingAttr) + { + throw new NotImplementedException(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] + public override EventInfo[] GetEvents(BindingFlags bindingAttr) + { + throw new NotImplementedException(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] + public override FieldInfo GetField(string name, BindingFlags bindingAttr) + { + throw new NotImplementedException(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields + | DynamicallyAccessedMemberTypes.NonPublicFields)] + public override FieldInfo[] GetFields(BindingFlags bindingAttr) + { + throw new NotImplementedException(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] + public override Type GetInterface(string name, bool ignoreCase) + { + throw new NotImplementedException(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] + public override Type[] GetInterfaces() + { + throw new NotImplementedException(); + } + + [DynamicallyAccessedMembers((DynamicallyAccessedMemberTypes)0x1FFF)] + public override MemberInfo[] GetMembers(BindingFlags bindingAttr) + { + throw new NotImplementedException(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] + public override MethodInfo[] GetMethods(BindingFlags bindingAttr) + { + throw new NotImplementedException(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] + public override Type GetNestedType(string name, BindingFlags bindingAttr) + { + throw new NotImplementedException(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] + public override Type[] GetNestedTypes(BindingFlags bindingAttr) + { + throw new NotImplementedException(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] + public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) + { + throw new NotImplementedException(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] + public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) + { + throw new NotImplementedException(); + } + + public override bool IsDefined(Type attributeType, bool inherit) + { + throw new NotImplementedException(); + } + + protected override TypeAttributes GetAttributeFlagsImpl() + { + throw new NotImplementedException(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors + | DynamicallyAccessedMemberTypes.NonPublicConstructors)] + protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + { + throw new NotImplementedException(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] + protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + { + throw new NotImplementedException(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] + protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) + { + throw new NotImplementedException(); + } + + protected override bool HasElementTypeImpl() + { + throw new NotImplementedException(); + } + + protected override bool IsArrayImpl() + { + throw new NotImplementedException(); + } + + protected override bool IsByRefImpl() + { + throw new NotImplementedException(); + } + + protected override bool IsCOMObjectImpl() + { + throw new NotImplementedException(); + } + + protected override bool IsPointerImpl() + { + throw new NotImplementedException(); + } + + protected override bool IsPrimitiveImpl() + { + throw new NotImplementedException(); + } + } } """; } @@ -728,28 +728,28 @@ protected override bool IsPrimitiveImpl () public Task SourceMethodDoesNotMatchTargetParameterAnnotations() { var TargetParameterWithAnnotations = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1(); - } - - private void M1() - { - M2(this); - } - - private static void M2( - [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( - System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1(); + } + + private void M1() + { + M2(this); + } + + private static void M2( + [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( + System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + } + } + """; // (198,4): warning IL2082: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. @@ -765,33 +765,33 @@ private static void M2( public Task ConversionOperation() { var ConversionOperation = $$""" - namespace System - { - class ConvertsToType - { - public static implicit operator Type(ConvertsToType value) => typeof (ConvertsToType); - } - - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1(); - } - - private void M1() - { - M2(new ConvertsToType()); - } - - private static void M2( - [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( - System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - } - } - """; + namespace System + { + class ConvertsToType + { + public static implicit operator Type(ConvertsToType value) => typeof(ConvertsToType); + } + + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1(); + } + + private void M1() + { + M2(new ConvertsToType()); + } + + private static void M2( + [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( + System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + } + } + """; return VerifyDynamicallyAccessedMembersAnalyzer(string.Concat(GetSystemTypeBase(), ConversionOperation), consoleApplication: false, // (203,4): warning IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. The return value of method 'System.ConvertsToType.implicit operator Type(ConvertsToType)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. @@ -806,35 +806,35 @@ private static void M2( public Task ConversionOperationAnnotationDoesNotMatch() { var AnnotatedConversionOperation = $$""" - namespace System - { - class ConvertsToType - { - [return: System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( - System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields)] - public static implicit operator Type(ConvertsToType value) => null; - } - - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1(); - } - - private void M1() - { - M2(new ConvertsToType()); - } - - private static void M2( - [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( - System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - } - } - """; + namespace System + { + class ConvertsToType + { + [return: System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( + System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields)] + public static implicit operator Type(ConvertsToType value) => null; + } + + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1(); + } + + private void M1() + { + M2(new ConvertsToType()); + } + + private static void M2( + [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( + System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + } + } + """; return VerifyDynamicallyAccessedMembersAnalyzer(string.Concat(GetSystemTypeBase(), AnnotatedConversionOperation), consoleApplication: false, // (205,4): warning IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. The return value of method 'System.ConvertsToType.implicit operator Type(ConvertsToType)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. @@ -847,35 +847,35 @@ private static void M2( public Task ConversionOperationAnnotationMatches() { var AnnotatedConversionOperation = $$""" - namespace System - { - class ConvertsToType - { - [return: System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( - System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] - public static implicit operator Type(ConvertsToType value) => null; - } - - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1(); - } - - private void M1() - { - M2(new ConvertsToType()); - } - - private static void M2( - [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( - System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - } - } - """; + namespace System + { + class ConvertsToType + { + [return: System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( + System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] + public static implicit operator Type(ConvertsToType value) => null; + } + + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1(); + } + + private void M1() + { + M2(new ConvertsToType()); + } + + private static void M2( + [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( + System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + } + } + """; return VerifyDynamicallyAccessedMembersAnalyzer(string.Concat(GetSystemTypeBase(), AnnotatedConversionOperation), consoleApplication: false); } @@ -885,24 +885,24 @@ private static void M2( public Task SourceMethodDoesNotMatchTargetMethodReturnTypeAnnotations() { var TargetMethodReturnTypeWithAnnotations = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M(); - } - - [return: System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( - System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] - private Type M() - { - return this; - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M(); + } + + [return: System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( + System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] + private Type M() + { + return this; + } + } + } + """; // (200,11): warning IL2083: 'System.C.M()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. // The implicit 'this' argument of method 'System.C.M()' does not have matching annotations. @@ -918,26 +918,26 @@ private Type M() public Task SourceMethodDoesNotMatchTargetFieldAnnotations() { var TargetFieldWithAnnotations = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M(); - } - - private void M() - { - f = this; - } - - [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( - System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f; - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M(); + } + + private void M() + { + f = this; + } + + [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( + System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f; + } + } + """; // (198,4): warning IL2084: value stored in field 'System.C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. // The implicit 'this' argument of method 'System.C.M()' does not have matching annotations. @@ -955,22 +955,22 @@ private void M() public Task SourceMethodDoesNotMatchTargetMethodAnnotations() { var TargetMethodWithAnnotations = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M(); - } - - private void M() - { - this.GetMethods(); - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M(); + } + + private void M() + { + this.GetMethods(); + } + } + } + """; // (198,4): warning IL2085: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethods()'. // The implicit 'this' argument of method 'System.C.M()' does not have matching annotations. @@ -987,27 +987,27 @@ private void M() public Task SourceGenericParameterDoesNotMatchTargetParameterAnnotations() { var TargetParameterWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M2(); - } - - private static void M1( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - - private static void M2() - { - M1(typeof(T)); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M2(); + } + + private static void M1( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + + private static void M2() + { + M1(typeof(T)); + } + } + """; // (18,3): warning IL2087: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.M1(Type)'. // The generic parameter 'T' of 'C.M2()' does not have matching annotations. @@ -1023,23 +1023,23 @@ private static void M2() public Task SourceGenericParameterDoesNotMatchTargetMethodReturnTypeAnnotations() { var TargetMethodReturnTypeWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M(); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] - private static Type M() - { - return typeof(T); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M(); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] + private static Type M() + { + return typeof(T); + } + } + """; // (14,10): warning IL2088: 'C.M()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors' requirements. // The generic parameter 'T' of 'C.M()' does not have matching annotations. @@ -1055,25 +1055,25 @@ private static Type M() public Task SourceGenericParameterDoesNotMatchTargetFieldAnnotations() { var TargetFieldWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M(); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f; - - private static void M() - { - f = typeof(T); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f; + + private static void M() + { + f = typeof(T); + } + } + """; // (16,3): warning IL2089: value stored in field 'C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. // The generic parameter 'T' of 'C.M()' does not have matching annotations. @@ -1092,25 +1092,25 @@ private static void M() public Task SourceGenericParameterDoesNotMatchTargetGenericParameterAnnotations() { var TargetGenericParameterWithAnnotations = $$""" - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M2(); - } - - private static void M1<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>() - { - } - - private static void M2() - { - M1(); - } - } - """; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M2(); + } + + private static void M1<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>() + { + } + + private static void M2() + { + M1(); + } + } + """; // (16,3): warning IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' // in 'C.M1()'. The generic parameter 'S' of 'C.M2()' does not have matching annotations. @@ -1126,25 +1126,25 @@ private static void M2() public Task SourceTypeofFlowsIntoTargetParameterAnnotations() { var TargetParameterWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Foo - { - } - - class C - { - public static void Main() - { - M(typeof(Foo)); - } - - private static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Foo + { + } + + class C + { + public static void Main() + { + M(typeof(Foo)); + } + + private static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + } + """; return VerifyDynamicallyAccessedMembersAnalyzer(TargetParameterWithAnnotations, consoleApplication: false); } @@ -1152,27 +1152,27 @@ private static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes public Task SourceTypeofFlowsIntoTargetMethodReturnTypeAnnotation() { var TargetMethodReturnTypeWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Foo - { - } - - class C - { - public static void Main() - { - M(); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type M() - { - return typeof(Foo); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Foo + { + } + + class C + { + public static void Main() + { + M(); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type M() + { + return typeof(Foo); + } + } + """; return VerifyDynamicallyAccessedMembersAnalyzer(TargetMethodReturnTypeWithAnnotations, consoleApplication: false); } @@ -1181,27 +1181,27 @@ private static Type M() public Task SourceParameterFlowsInfoTargetMethodReturnTypeAnnotations() { var TargetMethodReturnTypeWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Foo - { - } - - class C - { - public static void Main() - { - M(typeof(Foo)); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - return type; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Foo + { + } + + class C + { + public static void Main() + { + M(typeof(Foo)); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + return type; + } + } + """; return VerifyDynamicallyAccessedMembersAnalyzer(TargetMethodReturnTypeWithAnnotations, consoleApplication: false); } @@ -1210,29 +1210,29 @@ private static Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes public Task SourceParameterFlowsIntoTargetFieldAnnotations() { var TargetFieldWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Foo - { - } - - class C - { - public static void Main() - { - M(typeof(Foo)); - } - - private static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - f = type; - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f = typeof(Foo); - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Foo + { + } + + class C + { + public static void Main() + { + M(typeof(Foo)); + } + + private static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + f = type; + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f = typeof(Foo); + } + """; return VerifyDynamicallyAccessedMembersAnalyzer(TargetFieldWithAnnotations, consoleApplication: false); } @@ -1241,26 +1241,26 @@ private static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes public Task SourceParameterFlowsIntoTargetMethodAnnotations() { var TargetMethodWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Foo - { - } - - class C - { - public static void Main() - { - M(typeof(Foo)); - } - - private static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - type.GetMethod("Bar"); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Foo + { + } + + class C + { + public static void Main() + { + M(typeof(Foo)); + } + + private static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + type.GetMethod("Bar"); + } + } + """; return VerifyDynamicallyAccessedMembersAnalyzer(TargetMethodWithAnnotations, consoleApplication: false); } @@ -1269,19 +1269,19 @@ private static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes public Task MethodArgumentIsInvalidOperation() { var Source = """ - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - class C - { - public static void Main() - { - RequireAll(type); - } + class C + { + public static void Main() + { + RequireAll(type); + } - static void RequireAll([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type t) {} - } - """; + static void RequireAll([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type t) {} + } + """; return VerifyDynamicallyAccessedMembersAnalyzer(Source, consoleApplication: false, // (8,14): error CS0103: The name 'type' does not exist in the current context @@ -1292,20 +1292,20 @@ static void RequireAll([DynamicallyAccessedMembers(DynamicallyAccessedMemberType public Task MethodReturnIsInvalidOperation() { var Source = """ - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - class C - { - public static void Main() - { - GetTypeWithAll (); - } + class C + { + public static void Main() + { + GetTypeWithAll(); + } - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] - static Type GetTypeWithAll() => type; - } - """; + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] + static Type GetTypeWithAll() => type; + } + """; return VerifyDynamicallyAccessedMembersAnalyzer(Source, consoleApplication: false, // (12,34): error CS0103: The name 'type' does not exist in the current context @@ -1318,20 +1318,20 @@ public static void Main() public Task AssignmentSourceIsInvalidOperation() { var Source = """ - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - class C - { - public static void Main() - { - fieldRequiresAll = type; - } + class C + { + public static void Main() + { + fieldRequiresAll = type; + } - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] - static Type fieldRequiresAll; - } - """; + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] + static Type fieldRequiresAll; + } + """; return VerifyDynamicallyAccessedMembersAnalyzer(Source, consoleApplication: false, // (8,22): error CS0103: The name 'type' does not exist in the current context @@ -1344,20 +1344,20 @@ public static void Main() public Task AssignmentTargetIsInvalidOperation() { var Source = """ - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - class C - { - public static void Main() - { - type = GetTypeWithAll(); - } + class C + { + public static void Main() + { + type = GetTypeWithAll(); + } - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] - static Type GetTypeWithAll() => null; - } - """; + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] + static Type GetTypeWithAll() => null; + } + """; return VerifyDynamicallyAccessedMembersAnalyzer(Source, consoleApplication: false, // (8,9): error CS0103: The name 'type' does not exist in the current context @@ -1368,20 +1368,20 @@ public static void Main() public Task AssignmentTargetIsCapturedInvalidOperation() { var Source = """ - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - class C - { - public static void Main() - { - type ??= GetTypeWithAll(); - } + class C + { + public static void Main() + { + type ??= GetTypeWithAll(); + } - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] - static Type GetTypeWithAll() => null; - } - """; + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] + static Type GetTypeWithAll() => null; + } + """; return VerifyDynamicallyAccessedMembersAnalyzer(Source, consoleApplication: false, // (8,3): error CS0103: The name 'type' does not exist in the current context @@ -1393,9 +1393,9 @@ public Task AssignmentTargetHasNestedInvalidOperation() { // The assignment target is an IBinaryOperation whose right-hand side is an IInvalidOperation. var Source = $$""" - int a, b = 0; - a + = 3; - """; + int a, b = 0; + a + = 3; + """; return VerifyDynamicallyAccessedMembersAnalyzer(Source, consoleApplication: true, // (2,6): error CS1525: Invalid expression term '=' @@ -1411,20 +1411,20 @@ public Task AssignmentTargetHasNestedInvalidOperation() public Task CRefGenericParameterAnalysis() { var Source = """ - using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; - class C - { - /// - /// - /// - /// - /// - static CRequires Value => new CRequires (); - } + class C + { + /// + /// + /// + /// + /// + static CRequires Value => new CRequires); + } - class CRequires<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TInner> { public static bool IsIt => false; } - """; + class CRequires<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TInner> { public static bool IsIt => false; } + """; // The actual usage (ctor call) should warn, about missing annotation, but the cref should not. return VerifyDynamicallyAccessedMembersAnalyzer(Source, consoleApplication: false, @@ -1437,10 +1437,10 @@ public Task MethodParameterWithoutLocationAnalysis() { // The implicit main method has parameters var Source = """ - using System; - foreach (var arg in args) - Console.WriteLine (arg); - """; + using System; + foreach (var arg in args) + Console.WriteLine(arg); + """; return VerifyDynamicallyAccessedMembersAnalyzer(Source, consoleApplication: true); } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersCodeFixTests.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersCodeFixTests.cs index 78dbe6db801053..7f3fcb16951a89 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersCodeFixTests.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersCodeFixTests.cs @@ -45,41 +45,41 @@ static Task VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2067_MismatchParamTargetsParam() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - class C - { - static void M(Type t) { - M2(t); - } + class C + { + static void M(Type t) { + M2(t); + } - static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type t) {} - } - """; + static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type t) {} + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - class C - { - static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type t) { - M2(t); - } + class C + { + static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type t) { + M2(t); + } - static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type t) {} - } - """; + static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type t) {} + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(7,3): warning IL2067: 't' argument does not satisfy 'DynamicallyAccessedMemberTypes.All' in call to 'C.M2(Type)'. - // The parameter 't' of method 'C.M(Type)' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter) + // /0/Test0.cs(7,3): warning IL2067: 't' argument does not satisfy 'DynamicallyAccessedMemberTypes.All' in call to 'C.M2(Type)'. + // The parameter 't' of method 'C.M(Type)' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter) .WithSpan(7, 3, 7, 8) .WithSpan(6, 16, 6, 22) .WithArguments("t", @@ -95,45 +95,45 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2067_MismatchParamTargetsParam_WithReturn() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - class C - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] - static string M(Type t) { - M2(t); - return "Foo"; - } + class C + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] + static string M(Type t) { + M2(t); + return "Foo"; + } - static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) {} - } - """; + static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) {} + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - class C - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] - static string M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) { - M2(t); - return "Foo"; - } + class C + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] + static string M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) { + M2(t); + return "Foo"; + } - static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) {} - } - """; + static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) {} + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(7,3): warning IL2067: 't' argument does not satisfy 'DynamicallyAccessedMemberTypes.All' in call to 'C.M2(Type)'. - // The parameter 't' of method 'C.M(Type)' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter) + // /0/Test0.cs(7,3): warning IL2067: 't' argument does not satisfy 'DynamicallyAccessedMemberTypes.All' in call to 'C.M2(Type)'. + // The parameter 't' of method 'C.M(Type)' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter) .WithSpan(8, 3, 8, 8) .WithSpan(7, 18, 7, 24) .WithArguments("t", @@ -149,23 +149,23 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2067_TwoAttributesTurnsOffDiagnostic() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - static void M(Type t) { - M2(t); - } - - static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicFields)] Type t) {} - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + static void M(Type t) { + M2(t); + } + + static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicFields)] Type t) {} + } + """; var diag = new[] { - // /0/Test0.cs(7,3): warning IL2067: 't' argument does not satisfy 'DynamicallyAccessedMemberTypes.All' in call to 'C.M2(Type)'. - // The parameter 't' of method 'C.M(Type)' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter) + // /0/Test0.cs(7,3): warning IL2067: 't' argument does not satisfy 'DynamicallyAccessedMemberTypes.All' in call to 'C.M2(Type)'. + // The parameter 't' of method 'C.M(Type)' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter) .WithSpan(7, 3, 7, 8) .WithSpan(6, 16, 6, 22) .WithArguments("t", @@ -181,26 +181,26 @@ static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Public public async Task CodeFix_IL2067_AttributeTurnsOffCodeFix() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - class C - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] - static string M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { - M2(t); - return "Foo"; - } + class C + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] + static string M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { + M2(t); + return "Foo"; + } - static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) {} - } - """; + static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) {} + } + """; var diag = new[] { - // /0/Test0.cs(7,3): warning IL2067: 't' argument does not satisfy 'DynamicallyAccessedMemberTypes.All' in call to 'C.M2(Type)'. - // The parameter 't' of method 'C.M(Type)' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter) + // /0/Test0.cs(7,3): warning IL2067: 't' argument does not satisfy 'DynamicallyAccessedMemberTypes.All' in call to 'C.M2(Type)'. + // The parameter 't' of method 'C.M(Type)' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter) .WithSpan(8, 3, 8, 8) .WithArguments("t", "C.M2(Type)", @@ -215,40 +215,40 @@ static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Public public async Task CodeFix_IL2068_MismatchParamTargetsMethodReturn() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] - Type M(Type t) { - return t; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] + Type M(Type t) { + return t; + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] - Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type t) { - return t; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] + Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type t) { + return t; + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(8,10): warning IL2068: 'C.M(Type)' method return value does not satisfy 'DynamicallyAccessedMemberTypes.All' requirements. The parameter 't' of method 'C.M(Type)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic (DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsMethodReturnType) - .WithSpan (8, 10, 8, 11) - .WithSpan (7, 9, 7, 15) - .WithArguments ("C.M(Type)", + // /0/Test0.cs(8,10): warning IL2068: 'C.M(Type)' method return value does not satisfy 'DynamicallyAccessedMemberTypes.All' requirements. The parameter 't' of method 'C.M(Type)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsMethodReturnType) + .WithSpan(8, 10, 8, 11) + .WithSpan(7, 9, 7, 15) + .WithArguments("C.M(Type)", "t", "C.M(Type)", "'DynamicallyAccessedMemberTypes.All'") @@ -260,22 +260,22 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2068_ArgumentTurnsOffCodeFix_None() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] - Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.None)] Type t) { - return t; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] + Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.None)] Type t) { + return t; + } + } + """; var diag = new[] { - // /0/Test0.cs(8,10): warning IL2068: 'C.M(Type)' method return value does not satisfy 'DynamicallyAccessedMemberTypes.All' requirements. The parameter 't' of method 'C.M(Type)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic (DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsMethodReturnType) - .WithSpan (8, 10, 8, 11) - .WithArguments ("C.M(Type)", + // /0/Test0.cs(8,10): warning IL2068: 'C.M(Type)' method return value does not satisfy 'DynamicallyAccessedMemberTypes.All' requirements. The parameter 't' of method 'C.M(Type)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsMethodReturnType) + .WithSpan(8, 10, 8, 11) + .WithArguments("C.M(Type)", "t", "C.M(Type)", "'DynamicallyAccessedMemberTypes.All'") @@ -287,57 +287,57 @@ Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.None)] Type t) public async Task CodeFix_IL2069_MismatchParamTargetsField_PublicMethods() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M(typeof(C)); - } - - private static void M(Type type) - { - f = type; - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f = typeof(C); - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M(typeof(C)); + } + + private static void M(Type type) + { + f = type; + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f = typeof(C); + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M(typeof(C)); - } - - private static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - f = type; - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f = typeof(C); - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M(typeof(C)); + } + + private static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + f = type; + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f = typeof(C); + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(13,3): warning IL2069: value stored in field 'C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. - //The parameter 'type' of method 'C.M(Type)' does not have matching annotations. - //The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic (DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsField) + // /0/Test0.cs(13,3): warning IL2069: value stored in field 'C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. + //The parameter 'type' of method 'C.M(Type)' does not have matching annotations. + //The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsField) .WithSpan(13, 3, 13, 11) .WithSpan(11, 24, 11, 33) - .WithArguments ("C.f", + .WithArguments("C.f", "type", "C.M(Type)", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -349,43 +349,43 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2070_MismatchParamTargetsThisParam_PublicMethods() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M(typeof(C)); - } - static void M(Type t) - { - t.GetMethods(); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M(typeof(C)); + } + static void M(Type t) + { + t.GetMethods(); + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M(typeof(C)); - } - static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) - { - t.GetMethods(); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M(typeof(C)); + } + static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) + { + t.GetMethods(); + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(12,3): warning IL2070: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethods()'. The parameter 't' of method 'C.M(Type)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsThisParameter) + // /0/Test0.cs(12,3): warning IL2070: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethods()'. The parameter 't' of method 'C.M(Type)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsThisParameter) .WithSpan(12, 3, 12, 17) .WithSpan(10, 16, 10, 22) .WithArguments("System.Type.GetMethods()", @@ -400,48 +400,48 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2070_NonPublicMethods() { var test = $$""" - using System; - using System.Reflection; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M(typeof(C)); - } - static void M(Type t) - { - t.GetMethods(BindingFlags.NonPublic); - } - } - """; + using System; + using System.Reflection; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M(typeof(C)); + } + static void M(Type t) + { + t.GetMethods(BindingFlags.NonPublic); + } + } + """; var fixtest = $$""" - using System; - using System.Reflection; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M(typeof(C)); - } - static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) - { - t.GetMethods(BindingFlags.NonPublic); - } - } - """; + using System; + using System.Reflection; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M(typeof(C)); + } + static void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) + { + t.GetMethods(BindingFlags.NonPublic); + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(13,3): warning IL2070: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.NonPublicMethods' in call to 'System.Type.GetMethods(BindingFlags)'. - // The parameter 't' of method 'C.M(Type)' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsThisParameter) + // /0/Test0.cs(13,3): warning IL2070: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.NonPublicMethods' in call to 'System.Type.GetMethods(BindingFlags)'. + // The parameter 't' of method 'C.M(Type)' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsThisParameter) .WithSpan(13, 3, 13, 39) .WithSpan(11, 16, 11, 22) .WithArguments("System.Type.GetMethods(BindingFlags)", @@ -450,11 +450,11 @@ await VerifyDynamicallyAccessedMembersCodeFix( "'DynamicallyAccessedMemberTypes.NonPublicMethods'") }, fixedExpected: new[] { - // /0/Test0.cs(9,3): warning IL2111: Method 'C.M(Type)' with parameters or return value with `DynamicallyAccessedMembersAttribute` is accessed via reflection. - // Trimmer can't guarantee availability of the requirements of the method. - VerifyCS.Diagnostic (DiagnosticId.DynamicallyAccessedMembersMethodAccessedViaReflection) - .WithSpan (9, 3, 9, 15) - .WithArguments ("C.M(Type)") + // /0/Test0.cs(9,3): warning IL2111: Method 'C.M(Type)' with parameters or return value with `DynamicallyAccessedMembersAttribute` is accessed via reflection. + // Trimmer can't guarantee availability of the requirements of the method. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMethodAccessedViaReflection) + .WithSpan(9, 3, 9, 15) + .WithArguments("C.M(Type)") }); } @@ -462,53 +462,53 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2070_GetMethodsInArg() { var test = $$""" - using System.Reflection; - using System.Diagnostics.CodeAnalysis; - - namespace System - { - static class C - { - static void Main(Type t) - { - DoSomethingWithMethods(t.GetMethods()); - } - - static void DoSomethingWithMethods(MethodInfo[] m) - { - } - } - } - """; + using System.Reflection; + using System.Diagnostics.CodeAnalysis; + + namespace System + { + static class C + { + static void Main(Type t) + { + DoSomethingWithMethods(t.GetMethods()); + } + + static void DoSomethingWithMethods(MethodInfo[] m) + { + } + } + } + """; var fixtest = """ - using System.Reflection; - using System.Diagnostics.CodeAnalysis; - - namespace System - { - static class C - { - static void Main([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) - { - DoSomethingWithMethods(t.GetMethods()); - } - - static void DoSomethingWithMethods(MethodInfo[] m) - { - } - } - } - """; + using System.Reflection; + using System.Diagnostics.CodeAnalysis; + + namespace System + { + static class C + { + static void Main([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) + { + DoSomethingWithMethods(t.GetMethods()); + } + + static void DoSomethingWithMethods(MethodInfo[] m) + { + } + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(10,27): warning IL2070: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethods()'. - // The parameter 't' of method 'System.C.Main(Type)' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsThisParameter) + // /0/Test0.cs(10,27): warning IL2070: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethods()'. + // The parameter 't' of method 'System.C.Main(Type)' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsThisParameter) .WithSpan(10, 27, 10, 41) .WithSpan(8, 20, 8, 26) .WithArguments("System.Type.GetMethods()", @@ -523,60 +523,60 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2072_MismatchMethodReturnTargetsParam() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - NeedsPublicMethodsOnParameter(GetC()); - } - - private static void NeedsPublicMethodsOnParameter( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - - private static Type GetC() - { - return typeof(C); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + NeedsPublicMethodsOnParameter(GetC()); + } + + private static void NeedsPublicMethodsOnParameter( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + + private static Type GetC() + { + return typeof(C); + } + } + """; var fixtest = """ - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - NeedsPublicMethodsOnParameter(GetC()); - } - - private static void NeedsPublicMethodsOnParameter( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type GetC() - { - return typeof(C); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + NeedsPublicMethodsOnParameter(GetC()); + } + + private static void NeedsPublicMethodsOnParameter( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type GetC() + { + return typeof(C); + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(8,3): warning IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethodsOnParameter(Type)'. - // The return value of method 'C.GetT()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter) + // /0/Test0.cs(8,3): warning IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethodsOnParameter(Type)'. + // The return value of method 'C.GetT()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter) .WithSpan(8, 3, 8, 40) .WithSpan(16, 2, 19, 3) .WithArguments("type", @@ -591,60 +591,60 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2072_MismatchMethodReturnTargetsParam_WithAttributes() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - NeedsPublicMethodsOnParameter(GetC(typeof(C))); - } - - private static void NeedsPublicMethodsOnParameter( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) - { - } - - private static Type GetC([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) - { - return t; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + NeedsPublicMethodsOnParameter(GetC(typeof(C))); + } + + private static void NeedsPublicMethodsOnParameter( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) + { + } + + private static Type GetC([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) + { + return t; + } + } + """; var fixtest = """ - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - NeedsPublicMethodsOnParameter(GetC(typeof(C))); - } - - private static void NeedsPublicMethodsOnParameter( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) - { - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type GetC([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) - { - return t; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + NeedsPublicMethodsOnParameter(GetC(typeof(C))); + } + + private static void NeedsPublicMethodsOnParameter( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) + { + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type GetC([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) + { + return t; + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(8,3): warning IL2072: 't' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethodsOnParameter(Type)'. - // The return value of method 'C.GetC(Type)' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter) + // /0/Test0.cs(8,3): warning IL2072: 't' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethodsOnParameter(Type)'. + // The return value of method 'C.GetC(Type)' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter) .WithSpan(8, 3, 8, 49) .WithSpan(16, 2, 19, 3) .WithArguments("t", @@ -659,33 +659,33 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2072_AttributeTurnsOffCodeFix_None() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - NeedsPublicMethodsOnParameter(GetC()); - } - - private static void NeedsPublicMethodsOnParameter( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.None)] - private static Type GetC() - { - return typeof(C); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + NeedsPublicMethodsOnParameter(GetC()); + } + + private static void NeedsPublicMethodsOnParameter( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.None)] + private static Type GetC() + { + return typeof(C); + } + } + """; var diag = new[] { - // /0/Test0.cs(8,3): warning IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethodsOnParameter(Type)'. - // The return value of method 'C.GetT()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter) + // /0/Test0.cs(8,3): warning IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethodsOnParameter(Type)'. + // The return value of method 'C.GetT()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter) .WithSpan(8, 3, 8, 40) .WithArguments("type", "C.NeedsPublicMethodsOnParameter(Type)", @@ -699,33 +699,33 @@ private static Type GetC() public async Task CodeFix_IL2072_AttributeTurnsOffCodeFix() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - NeedsPublicMethodsOnParameter(GetT()); - } - - private static void NeedsPublicMethodsOnParameter( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] - private static Type GetT() - { - return typeof(C); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + NeedsPublicMethodsOnParameter(GetT()); + } + + private static void NeedsPublicMethodsOnParameter( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] + private static Type GetT() + { + return typeof(C); + } + } + """; var diag = new[] { - // /0/Test0.cs(8,3): warning IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethodsOnParameter(Type)'. - // The return value of method 'C.GetT()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter) + // /0/Test0.cs(8,3): warning IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethodsOnParameter(Type)'. + // The return value of method 'C.GetT()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter) .WithSpan(8, 3, 8, 40) .WithArguments("type", "C.NeedsPublicMethodsOnParameter(Type)", @@ -739,44 +739,44 @@ private static Type GetT() public async Task CodeFix_IL2073_MismatchMethodReturnTargetsMethodReturn() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C { - Type Main(Type t) { - return t; - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - Type M() { - return Main(typeof(C)); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C { + Type Main(Type t) { + return t; + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + Type M() { + return Main(typeof(C)); + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - Type Main([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) { - return t; - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - Type M() { - return Main(typeof(C)); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + Type Main([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) { + return t; + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + Type M() { + return Main(typeof(C)); + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(11,10): warning IL2073: 'C.M()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. - // The return value of method 'C.Main(Type)' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsMethodReturnType) + // /0/Test0.cs(11,10): warning IL2073: 'C.M()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. + // The return value of method 'C.Main(Type)' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsMethodReturnType) .WithSpan(11, 10, 11, 25) .WithSpan(5, 2, 7, 3) .WithArguments("C.M()", @@ -790,44 +790,44 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2073_MismatchMethodReturnTargetsMethodReturn_WithAttribute() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C { - Type Main([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) { - return t; - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) { - return Main(t); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C { + Type Main([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) { + return t; + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) { + return Main(t); + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - Type Main([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) { - return t; - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) { - return Main(t); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + Type Main([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) { + return t; + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) { + return Main(t); + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(11,10): warning IL2073: 'C.M(Type)' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. - // The return value of method 'C.Main(Type)' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsMethodReturnType) + // /0/Test0.cs(11,10): warning IL2073: 'C.M(Type)' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. + // The return value of method 'C.Main(Type)' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsMethodReturnType) .WithSpan(11, 10, 11, 17) .WithSpan(5, 2, 7, 3) .WithArguments("C.M(Type)", @@ -841,54 +841,54 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2074_MismatchMethodReturnTargetsField() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - f = M(); - } - - private static Type M() - { - return typeof(C); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f; - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + f = M(); + } + + private static Type M() + { + return typeof(C); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f; + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - f = M(); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type M() - { - return typeof(C); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f; - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + f = M(); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type M() + { + return typeof(C); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f; + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(8,3): warning IL2074: value stored in field 'C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. - // The return value of method 'C.M()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsField) + // /0/Test0.cs(8,3): warning IL2074: value stored in field 'C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. + // The return value of method 'C.M()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsField) .WithSpan(8, 3, 8, 10) .WithSpan(11, 2, 14, 3) .WithArguments("C.f", @@ -903,51 +903,51 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2075_MethodReturnTargetsParam_PublicMethods() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - GetC().GetMethod("Foo"); - } - - private static Type GetC () - { - return typeof (C); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + GetC().GetMethod("Foo"); + } + + private static Type GetC() + { + return typeof(C); + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - GetC().GetMethod("Foo"); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type GetC () - { - return typeof (C); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + GetC().GetMethod("Foo"); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type GetC) + { + return typeof(C); + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(8,3): warning IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. - //The return value of method 'C.GetFoo()' does not have matching annotations. - //The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic (DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter) + // /0/Test0.cs(8,3): warning IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. + //The return value of method 'C.GetFoo()' does not have matching annotations. + //The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter) .WithSpan(8, 3, 8, 26) .WithSpan(11, 2, 14, 3) - .WithArguments ("System.Type.GetMethod(String)", + .WithArguments("System.Type.GetMethod(String)", "C.GetC()", "'DynamicallyAccessedMemberTypes.PublicMethods'") }, @@ -958,50 +958,50 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2075_MethodAttributeLeavesOnCodeFix() { var test = $$""" - namespace System - { - class C : TestSystemTypeBase - { - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] - public static void Main() - { - GetC().GetMethod("Foo"); - } - - private static Type GetC () - { - return typeof(int); - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] + public static void Main() + { + GetC().GetMethod("Foo"); + } + + private static Type GetC) + { + return typeof(int); + } + } + } + """; var fixtest = $$""" - namespace System - { - class C : TestSystemTypeBase - { - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] - public static void Main() - { - GetC().GetMethod("Foo"); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type GetC () - { - return typeof(int); - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] + public static void Main() + { + GetC().GetMethod("Foo"); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type GetC() + { + return typeof(int); + } + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), test), fixedSource: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), fixtest), baselineExpected: new[] { - // /0/Test0.cs(8,3): warning IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. - //The return value of method 'C.GetFoo()' does not have matching annotations. - //The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic (DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter) + // /0/Test0.cs(8,3): warning IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. + //The return value of method 'C.GetFoo()' does not have matching annotations. + //The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter) .WithSpan(194, 4, 194, 27) .WithSpan(197, 3, 200, 4) .WithArguments("System.Type.GetMethod(String)", @@ -1015,50 +1015,50 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2075_MethodAttributeLeavesOnCodeFix_Reverse() { var test = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - GetC().GetMethod("Foo"); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] - private static Type GetC () - { - return typeof(int); - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + GetC().GetMethod("Foo"); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] + private static Type GetC() + { + return typeof(int); + } + } + } + """; var fixtest = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - GetC().GetMethod("Foo"); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type GetC () - { - return typeof(int); - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + GetC().GetMethod("Foo"); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type GetC() + { + return typeof(int); + } + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), test), fixedSource: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), fixtest), baselineExpected: new[] { - // /0/Test0.cs(8,3): warning IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. - //The return value of method 'C.GetFoo()' does not have matching annotations. - //The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic (DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter) + // /0/Test0.cs(8,3): warning IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. + //The return value of method 'C.GetFoo()' does not have matching annotations. + //The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter) .WithSpan(193, 4, 193, 27) .WithSpan(196, 3, 200, 4) .WithArguments("System.Type.GetMethod(String)", @@ -1072,52 +1072,52 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2075_ReutrnAttributeLeavesOnCodeFix() { var test = $$$""" - namespace System - { - class C : TestSystemTypeBase - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] - public static string Main() - { - GetC().GetMethod("Foo"); - return "Foo"; - } - - private static Type GetC () - { - return typeof(int); - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] + public static string Main() + { + GetC().GetMethod("Foo"); + return "Foo"; + } + + private static Type GetC() + { + return typeof(int); + } + } + } + """; var fixtest = $$""" - namespace System - { - class C : TestSystemTypeBase - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] - public static string Main() - { - GetC().GetMethod("Foo"); - return "Foo"; - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type GetC () - { - return typeof(int); - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] + public static string Main() + { + GetC().GetMethod("Foo"); + return "Foo"; + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type GetC() + { + return typeof(int); + } + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), test), fixedSource: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), fixtest), baselineExpected: new[] { - // /0/Test0.cs(8,3): warning IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. - //The return value of method 'C.GetFoo()' does not have matching annotations. - //The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic (DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter) + // /0/Test0.cs(8,3): warning IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. + //The return value of method 'C.GetFoo()' does not have matching annotations. + //The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter) .WithSpan(194, 4, 194, 27) .WithSpan(198, 3, 201, 4) .WithArguments("System.Type.GetMethod(String)", @@ -1131,52 +1131,52 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2077_MismatchFieldTargetsParam() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - private static Type f = typeof(C); - - public static void Main() - { - NeedsPublicMethods(f); - } - - private static void NeedsPublicMethods( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + private static Type f = typeof(C); + + public static void Main() + { + NeedsPublicMethods(f); + } + + private static void NeedsPublicMethods( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f = typeof(C); - - public static void Main() - { - NeedsPublicMethods(f); - } - - private static void NeedsPublicMethods( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f = typeof(C); + + public static void Main() + { + NeedsPublicMethods(f); + } + + private static void NeedsPublicMethods( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(10,3): warning IL2077: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethods(Type)'. - // The field 'C.f' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsParameter) + // /0/Test0.cs(10,3): warning IL2077: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethods(Type)'. + // The field 'C.f' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsParameter) .WithSpan(10, 3, 10, 24) .WithSpan(6, 22, 6, 35) .WithArguments("type", @@ -1192,30 +1192,30 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2077_AttributeTurnsOffCodeFix() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] - private static Type f = typeof(C); - - public static void Main() - { - NeedsPublicMethods(f); - } - - private static void NeedsPublicMethods( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] + private static Type f = typeof(C); + + public static void Main() + { + NeedsPublicMethods(f); + } + + private static void NeedsPublicMethods( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + } + """; var diag = new[] { - // /0/Test0.cs(11,3): warning IL2077: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethods(Type)'. - // The field 'C.f' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsParameter) + // /0/Test0.cs(11,3): warning IL2077: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethods(Type)'. + // The field 'C.f' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsParameter) .WithSpan(11, 3, 11, 24) .WithArguments("type", "C.NeedsPublicMethods(Type)", @@ -1227,44 +1227,44 @@ private static void NeedsPublicMethods( public async Task CodeFix_IL2078_MismatchFieldTargetsMethodReturn() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - public static Type Main() - { - return f; - } - - private static Type f; - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + public static Type Main() + { + return f; + } + + private static Type f; + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - public static Type Main() - { - return f; - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f; - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + public static Type Main() + { + return f; + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f; + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(9,10): warning IL2078: 'C.Main()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. - // The field 'C.f' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsMethodReturnType) + // /0/Test0.cs(9,10): warning IL2078: 'C.Main()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. + // The field 'C.f' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsMethodReturnType) .WithSpan(9, 10, 9, 11) .WithSpan(12, 22, 12, 23) .WithArguments("C.Main()", @@ -1278,26 +1278,26 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2078_AttributeTurnsOffCodeFix() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - public static Type Main() - { - return f; - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] - private static Type f; - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + public static Type Main() + { + return f; + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] + private static Type f; + } + """; var diag = new[] { - // /0/Test0.cs(9,10): warning IL2078: 'C.Main()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. - // The field 'C.f' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsMethodReturnType) + // /0/Test0.cs(9,10): warning IL2078: 'C.Main()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. + // The field 'C.f' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsMethodReturnType) .WithSpan(9, 10, 9, 11) .WithArguments("C.Main()", "C.f", @@ -1309,47 +1309,47 @@ public static Type Main() public async Task CodeFix_IL2079_MismatchFieldTargetsField() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - private static Type f1 = typeof(C); - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f2 = typeof(C); - - public static void Main() - { - f2 = f1; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + private static Type f1 = typeof(C); + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f2 = typeof(C); + + public static void Main() + { + f2 = f1; + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f1 = typeof(C); - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f2 = typeof(C); - - public static void Main() - { - f2 = f1; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f1 = typeof(C); + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f2 = typeof(C); + + public static void Main() + { + f2 = f1; + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(13,3): warning IL2079: value stored in field 'C.f2' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. - // The field 'C.f1' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsField) + // /0/Test0.cs(13,3): warning IL2079: value stored in field 'C.f2' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. + // The field 'C.f1' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsField) .WithSpan(13, 3, 13, 10) .WithSpan(6, 22, 6, 36) .WithArguments("C.f2", @@ -1363,28 +1363,28 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2079_AttributeTurnsOffCodeFix() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] - private static Type f1 = typeof(C); - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f2 = typeof(C); - - public static void Main() - { - f2 = f1; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] + private static Type f1 = typeof(C); + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f2 = typeof(C); + + public static void Main() + { + f2 = f1; + } + } + """; var diag = new[] { - // /0/Test0.cs(14,3): warning IL2079: value stored in field 'C.f2' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. - // The field 'C.f1' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsField) + // /0/Test0.cs(14,3): warning IL2079: value stored in field 'C.f2' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. + // The field 'C.f1' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsField) .WithSpan(14, 3, 14, 10) .WithArguments("C.f2", "C.f1", @@ -1397,42 +1397,42 @@ public static void Main() public async Task CodeFix_IL2080_MismatchFieldTargetsPrivateParam_PublicMethods() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - private static Type f = typeof(C); - - public static void Main() - { - f.GetMethod("Foo"); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + private static Type f = typeof(C); + + public static void Main() + { + f.GetMethod("Foo"); + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f = typeof(C); - - public static void Main() - { - f.GetMethod("Foo"); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f = typeof(C); + + public static void Main() + { + f.GetMethod("Foo"); + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(10,3): warning IL2080: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. - // The field 'C.f' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsThisParameter) + // /0/Test0.cs(10,3): warning IL2080: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. + // The field 'C.f' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsThisParameter) .WithSpan(10, 3, 10, 21) .WithSpan(6, 22, 6, 35) .WithArguments("System.Type.GetMethod(String)", @@ -1446,42 +1446,42 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2080_MismatchFieldTargetsPublicParam_PublicMethods() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static Type f = typeof(C); - - public static void Main() - { - f.GetMethod("Foo"); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static Type f = typeof(C); + + public static void Main() + { + f.GetMethod("Foo"); + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - public static Type f = typeof(C); - - public static void Main() - { - f.GetMethod("Foo"); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + public static Type f = typeof(C); + + public static void Main() + { + f.GetMethod("Foo"); + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(10,3): warning IL2080: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. - // The field 'C.f' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsThisParameter) + // /0/Test0.cs(10,3): warning IL2080: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. + // The field 'C.f' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsThisParameter) .WithSpan(10, 3, 10, 21) .WithSpan(6, 21, 6, 34) .WithArguments("System.Type.GetMethod(String)", @@ -1495,25 +1495,25 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2080_AttributeTurnsOffCodeFix() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] - public static Type f = typeof(C); - - public static void Main() - { - f.GetMethod("Foo"); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] + public static Type f = typeof(C); + + public static void Main() + { + f.GetMethod("Foo"); + } + } + """; var diag = new[] { - // /0/Test0.cs(11,3): warning IL2080: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. - // The field 'C.f' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsThisParameter) + // /0/Test0.cs(11,3): warning IL2080: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. + // The field 'C.f' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsThisParameter) .WithSpan(11, 3, 11, 21) .WithArguments("System.Type.GetMethod(String)", "C.f", @@ -1526,57 +1526,57 @@ public static void Main() public async Task CodeFix_IL2082_MismatchThisParamTargetsParam() { var test = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1(); - } - - private void M1() - { - M2(this); - } - - private static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) - { - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1(); + } + + private void M1() + { + M2(this); + } + + private static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) + { + } + } + } + """; var fixtest = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1(); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private void M1() - { - M2(this); - } - - private static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) - { - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private void M1() + { + M2(this); + } + + private static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) + { + } + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), test), fixedSource: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), fixtest), baselineExpected: new[] { - // /0/Test0.cs(198,4): warning IL2082: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. - // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter) + // /0/Test0.cs(198,4): warning IL2082: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. + // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter) .WithSpan(198, 4, 198, 12) .WithSpan(196, 3, 199, 4) .WithArguments("t", @@ -1585,9 +1585,9 @@ await VerifyDynamicallyAccessedMembersCodeFix( "'DynamicallyAccessedMemberTypes.PublicMethods'") }, fixedExpected: new[] { - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined - // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. - VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) + // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined + // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. + VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) .WithSpan(193, 4, 193, 16) .WithArguments("System.C.M1()") }); @@ -1597,61 +1597,61 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2082_ReturnKeepsOnCodeFix() { var test = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1(); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private string M1() - { - M2(this); - return "Foo"; - } - - private static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) - { - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1(); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private string M1() + { + M2(this); + return "Foo"; + } + + private static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) + { + } + } + } + """; var fixtest = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1(); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private string M1() - { - M2(this); - return "Foo"; - } - - private static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) - { - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1(); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private string M1() + { + M2(this); + return "Foo"; + } + + private static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) + { + } + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), test), fixedSource: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), fixtest), baselineExpected: new[] { - // /0/Test0.cs(198,4): warning IL2082: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. - // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter) + // /0/Test0.cs(198,4): warning IL2082: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. + // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter) .WithSpan(199, 4, 199, 12) .WithSpan(196, 3, 201, 4) .WithArguments("t", @@ -1660,9 +1660,9 @@ await VerifyDynamicallyAccessedMembersCodeFix( "'DynamicallyAccessedMemberTypes.PublicMethods'") }, fixedExpected: new[] { - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined - // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. - VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) + // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined + // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. + VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) .WithSpan(193, 4, 193, 16) .WithArguments("System.C.M1()") }); @@ -1672,61 +1672,61 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2082_ParamAttributeKeepsOnCodeFix() { var test = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1("Foo"); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] - private string M1([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] string s) - { - M2(this); - return s; - } - - private static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) - { - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1("Foo"); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] + private string M1([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] string s) + { + M2(this); + return s; + } + + private static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) + { + } + } + } + """; var fixtest = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1("Foo"); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private string M1([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] string s) - { - M2(this); - return s; - } - - private static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) - { - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1("Foo"); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private string M1([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] string s) + { + M2(this); + return s; + } + + private static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) + { + } + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), test), fixedSource: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), fixtest), baselineExpected: new[] { - // /0/Test0.cs(198,4): warning IL2082: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. - // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter) + // /0/Test0.cs(198,4): warning IL2082: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. + // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter) .WithSpan(199, 4, 199, 12) .WithSpan(196, 3, 201, 4) .WithArguments("t", @@ -1735,9 +1735,9 @@ await VerifyDynamicallyAccessedMembersCodeFix( "'DynamicallyAccessedMemberTypes.PublicMethods'") }, fixedExpected: new[] { - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined - // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. - VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) + // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined + // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. + VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) .WithSpan(193, 4, 193, 21) .WithArguments("System.C.M1(String)") }); @@ -1747,40 +1747,40 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2082_AttributeTurnsOffCodeFix() { var test = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1(); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] - private void M1() - { - M2(this); - } - - private static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) - { - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] + private void M1() + { + M2(this); + } + + private static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) + { + } + } + } + """; var diag = new[] { - // /0/Test0.cs(199,4): warning IL2082: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. - // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter) + // /0/Test0.cs(199,4): warning IL2082: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. + // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter) .WithSpan(199, 4, 199, 12) .WithArguments("t", "System.C.M2(Type)", "System.C.M1()", "'DynamicallyAccessedMemberTypes.PublicMethods'"), - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined - // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. - VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) + // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined + // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. + VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) .WithSpan(193, 4, 193, 16) .WithArguments("System.C.M1()") }; @@ -1792,49 +1792,49 @@ await VerifyDynamicallyAccessedMembersCodeFix(string.Concat(DynamicallyAccessedM public async Task CodeFix_IL2083_MismatchThisParamTargetsMethodReturn() { var test = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1(); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private Type M1() - { - return this; - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1(); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private Type M1() + { + return this; + } + } + } + """; var fixtest = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1(); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private Type M1() - { - return this; - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1(); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private Type M1() + { + return this; + } + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), test), fixedSource: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), fixtest), baselineExpected: new[] { - // /0/Test0.cs(199,11): warning IL2083: 'System.C.M1()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsMethodReturnType) + // /0/Test0.cs(199,11): warning IL2083: 'System.C.M1()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsMethodReturnType) .WithSpan(199, 11, 199, 15) .WithSpan(196, 3, 200, 4) .WithArguments("System.C.M1()", @@ -1842,9 +1842,9 @@ await VerifyDynamicallyAccessedMembersCodeFix( "'DynamicallyAccessedMemberTypes.PublicMethods'") }, fixedExpected: new[] { - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined - // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. - VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) + // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined + // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. + VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) .WithSpan(193, 4, 193, 16) .WithArguments("System.C.M1()") }); @@ -1854,51 +1854,51 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2083_ParamAttributeKeepsCodeFix() { var test = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1("Foo"); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private Type M1([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] string s) - { - s.AsSpan(); - return this; - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1("Foo"); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private Type M1([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] string s) + { + s.AsSpan(); + return this; + } + } + } + """; var fixtest = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1("Foo"); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private Type M1([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] string s) - { - s.AsSpan(); - return this; - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1("Foo"); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private Type M1([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] string s) + { + s.AsSpan(); + return this; + } + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), test), fixedSource: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), fixtest), baselineExpected: new[] { - // /0/Test0.cs(199,11): warning IL2083: 'System.C.M1()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsMethodReturnType) + // /0/Test0.cs(199,11): warning IL2083: 'System.C.M1()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsMethodReturnType) .WithSpan(200, 11, 200, 15) .WithSpan(196, 3, 201, 4) .WithArguments("System.C.M1(String)", @@ -1906,9 +1906,9 @@ await VerifyDynamicallyAccessedMembersCodeFix( "'DynamicallyAccessedMemberTypes.PublicMethods'") }, fixedExpected: new[] { - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined - // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. - VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) + // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined + // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. + VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) .WithSpan(193, 4, 193, 21) .WithArguments("System.C.M1(String)") }); @@ -1918,34 +1918,34 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2083_AttributeTurnsOffCodeFix() { var test = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1(); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] - private Type M1() - { - return this; - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1(); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] + private Type M1() + { + return this; + } + } + } + """; var diag = new[] { - // /0/Test0.cs(200,11): warning IL2083: 'System.C.M1()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsMethodReturnType) + // /0/Test0.cs(200,11): warning IL2083: 'System.C.M1()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsMethodReturnType) .WithSpan(200, 11, 200, 15) .WithArguments("System.C.M1()", "System.C.M1()", "'DynamicallyAccessedMemberTypes.PublicMethods'"), - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined - // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. - VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) + // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined + // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. + VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) .WithSpan(193, 4, 193, 16) .WithArguments("System.C.M1()") }; @@ -1958,55 +1958,55 @@ await VerifyDynamicallyAccessedMembersCodeFix(string.Concat(DynamicallyAccessedM public async Task CodeFix_IL2084_MismatchThisParamTargetsField() { var test = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M(); - } - - private void M() - { - f = this; - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f; - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M(); + } + + private void M() + { + f = this; + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f; + } + } + """; var fixtest = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M(); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private void M() - { - f = this; - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f; - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private void M() + { + f = this; + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f; + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), test), fixedSource: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), fixtest), baselineExpected: new[] { - // /0/Test0.cs(198,4): warning IL2084: value stored in field 'System.C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. - // The implicit 'this' argument of method 'System.C.M()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsField) + // /0/Test0.cs(198,4): warning IL2084: value stored in field 'System.C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. + // The implicit 'this' argument of method 'System.C.M()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsField) .WithSpan(198, 4, 198, 12) .WithSpan(196, 3, 199, 4) .WithArguments("System.C.f", @@ -2014,9 +2014,9 @@ await VerifyDynamicallyAccessedMembersCodeFix( "'DynamicallyAccessedMemberTypes.PublicMethods'") }, fixedExpected: new[] { - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M()' can not be statically determined - // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. - VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) + // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M()' can not be statically determined + // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. + VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) .WithSpan(193, 4, 193, 15) .WithArguments("System.C.M()") }); @@ -2026,59 +2026,59 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2085_MismatchThisParamTargetsThisParam() { var test = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1(); - } - - private void M1() - { - this.M2(); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private void M2() - { - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1(); + } + + private void M1() + { + this.M2(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private void M2() + { + } + } + } + """; var fixtest = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1(); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private void M1() - { - this.M2(); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private void M2() - { - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private void M1() + { + this.M2(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private void M2() + { + } + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), test), fixedSource: string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), fixtest), baselineExpected: new[] { - // /0/Test0.cs(198,4): warning IL2085: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2()'. - // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsThisParameter) + // /0/Test0.cs(198,4): warning IL2085: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2()'. + // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsThisParameter) .WithSpan(198, 4, 198, 13) .WithSpan(196, 3, 199, 4) .WithArguments("System.C.M2()", @@ -2086,9 +2086,9 @@ await VerifyDynamicallyAccessedMembersCodeFix( "'DynamicallyAccessedMemberTypes.PublicMethods'") }, fixedExpected: new[] { - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined - // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. - VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) + // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined + // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. + VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) .WithSpan(193, 4, 193, 16) .WithArguments("System.C.M1()") }); @@ -2098,40 +2098,40 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2085_AttributeTurnsOffCodeFix() { var test = $$""" - namespace System - { - class C : TestSystemTypeBase - { - public static void Main() - { - new C().M1(); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] - private void M1() - { - this.M2(); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private void M2() - { - } - } - } - """; + namespace System + { + class C : TestSystemTypeBase + { + public static void Main() + { + new C().M1(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] + private void M1() + { + this.M2(); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private void M2() + { + } + } + } + """; var diag = new[] { - // /0/Test0.cs(199,4): warning IL2085: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2()'. - // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsThisParameter) + // /0/Test0.cs(199,4): warning IL2085: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2()'. + // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsThisParameter) .WithSpan(199, 4, 199, 13) .WithArguments("System.C.M2()", "System.C.M1()", "'DynamicallyAccessedMemberTypes.PublicMethods'"), - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined - // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. - VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) + // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined + // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. + VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) .WithSpan(193, 4, 193, 16) .WithArguments("System.C.M1()") }; @@ -2143,57 +2143,57 @@ await VerifyDynamicallyAccessedMembersCodeFix(string.Concat(DynamicallyAccessedM public async Task CodeFix_IL2087_MismatchTypeArgumentTargetsParameter() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M2(); - } - - private static void M1( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - - private static void M2() - { - M1(typeof(T)); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M2(); + } + + private static void M1( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + + private static void M2() + { + M1(typeof(T)); + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M2(); - } - - private static void M1( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) - { - } - - private static void M2<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>() - { - M1(typeof(T)); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M2(); + } + + private static void M1( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) + { + } + + private static void M2<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>() + { + M1(typeof(T)); + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(18,3): warning IL2087: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.M1(Type)'. - // The generic parameter 'T' of 'C.M2()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsParameter) + // /0/Test0.cs(18,3): warning IL2087: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.M1(Type)'. + // The generic parameter 'T' of 'C.M2()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsParameter) .WithSpan(18, 3, 18, 16) .WithSpan(16, 25, 16, 26) .WithArguments("type", @@ -2209,49 +2209,49 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2088_MismatchTypeArgumentTargetsMethodReturnType() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M(); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] - private static Type M() - { - return typeof(T); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M(); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] + private static Type M() + { + return typeof(T); + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M(); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] - private static Type M<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>() - { - return typeof(T); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M(); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] + private static Type M<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>() + { + return typeof(T); + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(14,10): warning IL2088: 'C.M()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors' requirements. - // The generic parameter 'T' of 'C.M()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsMethodReturnType) + // /0/Test0.cs(14,10): warning IL2088: 'C.M()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors' requirements. + // The generic parameter 'T' of 'C.M()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsMethodReturnType) .WithSpan(14, 10, 14, 19) .WithSpan(12, 24, 12, 25) .WithArguments("C.M()", @@ -2266,28 +2266,28 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2088_AttributeTurnsOffCodeFix() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M(); - } - - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] - private static Type M<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>() - { - return typeof(T); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M(); + } + + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] + private static Type M<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>() + { + return typeof(T); + } + } + """; var diag = new[] { - // /0/Test0.cs(14,10): warning IL2088: 'C.M()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors' requirements. - // The generic parameter 'T' of 'C.M()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsMethodReturnType) + // /0/Test0.cs(14,10): warning IL2088: 'C.M()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors' requirements. + // The generic parameter 'T' of 'C.M()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsMethodReturnType) .WithSpan(14, 10, 14, 19) .WithArguments("C.M()", "T", @@ -2301,41 +2301,41 @@ public static void Main() public async Task CodeFix_IL2089_MismatchTypeArgumentTargetsField() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - f = typeof(T); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f; - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + f = typeof(T); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f; + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>() - { - f = typeof(T); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f; - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>() + { + f = typeof(T); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f; + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(8,3): warning IL2089: value stored in field 'C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The generic parameter 'T' of 'C.Main()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsField) + // /0/Test0.cs(8,3): warning IL2089: value stored in field 'C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The generic parameter 'T' of 'C.Main()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsField) .WithSpan(8, 3, 8, 16) .WithSpan(6, 26, 6, 27) .WithArguments("C.f", @@ -2350,23 +2350,23 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2089_AttributeTurnsOffCodeFix() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] T>() - { - f = typeof(T); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type f; - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] T>() + { + f = typeof(T); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type f; + } + """; var diag = new[] { - // /0/Test0.cs(8,3): warning IL2089: value stored in field 'C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The generic parameter 'T' of 'C.Main()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsField) + // /0/Test0.cs(8,3): warning IL2089: value stored in field 'C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The generic parameter 'T' of 'C.Main()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsField) .WithSpan(8, 3, 8, 16) .WithArguments("C.f", "T", @@ -2381,37 +2381,37 @@ class C public async Task CodeFix_IL2090_MismatchTypeArgumentTargetsThisParameter() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C { - - void M() - { - typeof(T).GetMethods(); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C { + + void M() + { + typeof(T).GetMethods(); + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T> { - - void M() - { - typeof(T).GetMethods(); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T> { + + void M() + { + typeof(T).GetMethods(); + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(8,3): warning IL2090: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethods()'. - // The generic parameter 'T' of 'C' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsThisParameter) + // /0/Test0.cs(8,3): warning IL2090: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethods()'. + // The generic parameter 'T' of 'C' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsThisParameter) .WithSpan(8, 3, 8, 25) .WithSpan(4, 9, 4, 10) .WithArguments("System.Type.GetMethods()", @@ -2425,22 +2425,22 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2090_AttributeTurnsOffCodeFix() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - class C<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] T> { + class C<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] T> { - void M() - { - typeof(T).GetMethods(); - } - } - """; + void M() + { + typeof(T).GetMethods(); + } + } + """; var diag = new[] { - // /0/Test0.cs(8,3): warning IL2090: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethods()'. - // The generic parameter 'T' of 'C' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsThisParameter) + // /0/Test0.cs(8,3): warning IL2090: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethods()'. + // The generic parameter 'T' of 'C' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsThisParameter) .WithSpan(8, 3, 8, 25) .WithArguments("System.Type.GetMethods()", "T", @@ -2454,22 +2454,22 @@ void M() public async Task CodeFix_IL2090_AttributeTurnsOffCodeFix_None() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - class C<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.None)] T> { + class C<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.None)] T> { - void M() - { - typeof(T).GetMethods(); - } - } - """; + void M() + { + typeof(T).GetMethods(); + } + } + """; var diag = new[] { - // /0/Test0.cs(8,3): warning IL2090: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethods()'. - // The generic parameter 'T' of 'C' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsThisParameter) + // /0/Test0.cs(8,3): warning IL2090: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethods()'. + // The generic parameter 'T' of 'C' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsThisParameter) .WithSpan(8, 3, 8, 25) .WithArguments("System.Type.GetMethods()", "T", @@ -2483,53 +2483,53 @@ void M() public async Task CodeFix_IL2091_MismatchTypeTargetsGenericParameter() { var test = $$""" - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M2(); - } - - private static void M1<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>() - { - } - - private static void M2() - { - M1(); - } - } - """; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M2(); + } + + private static void M1<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>() + { + } + + private static void M2() + { + M1(); + } + } + """; var fixtest = $$""" - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M2(); - } - - private static void M1<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>() - { - } - - private static void M2<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] S>() - { - M1(); - } - } - """; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M2(); + } + + private static void M1<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>() + { + } + + private static void M2<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] S>() + { + M1(); + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(16,3): warning IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in 'C.M1()'. - // The generic parameter 'S' of 'C.M2()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsGenericParameter) + // /0/Test0.cs(16,3): warning IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in 'C.M1()'. + // The generic parameter 'S' of 'C.M2()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsGenericParameter) .WithSpan(16, 3, 16, 10) .WithSpan(14, 25, 14, 26) .WithArguments("T", @@ -2545,30 +2545,30 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2091_AttributeTurnsOffCodeFix() { var test = $$""" - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - M2(); - } - - private static void M1<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>() - { - } - - private static void M2<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.None)] S>() - { - M1(); - } - } - """; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + M2(); + } + + private static void M1<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>() + { + } + + private static void M2<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.None)] S>() + { + M1(); + } + } + """; var diag = new[] { - // /0/Test0.cs(16,3): warning IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in 'C.M1()'. - // The generic parameter 'S' of 'C.M2()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsGenericParameter) + // /0/Test0.cs(16,3): warning IL2091: 'T' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in 'C.M1()'. + // The generic parameter 'S' of 'C.M2()' does not have matching annotations. + // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsGenericParameter) .WithSpan(16, 3, 16, 10) .WithArguments("T", "C.M1()", @@ -2583,44 +2583,44 @@ public static void Main() public async Task CodeFix_IL2092_MismatchMethodParamBtOverride_NonPublicMethods() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Base - { - public virtual void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} - } - - public class C : Base - { - public override void M(Type t) {} - - public static void Main() { - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Base + { + public virtual void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} + } + + public class C : Base + { + public override void M(Type t) {} + + public static void Main() { + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Base - { - public virtual void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} - } - - public class C : Base - { - public override void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} - - public static void Main() { - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Base + { + public virtual void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} + } + + public class C : Base + { + public override void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} + + public static void Main() { + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix(test, fixtest, new[] { - // /0/Test0.cs(11,30): warning IL2092: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the parameter 't' of method 'C.M(Type)' - // don't match overridden parameter 't' of method 'Base.M(Type)'. - // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides) + // /0/Test0.cs(11,30): warning IL2092: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the parameter 't' of method 'C.M(Type)' + // don't match overridden parameter 't' of method 'Base.M(Type)'. + // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides) .WithSpan(11, 30, 11, 31) .WithSpan(11, 30, 11, 31) .WithArguments("t", @@ -2634,49 +2634,49 @@ await VerifyDynamicallyAccessedMembersCodeFix(test, fixtest, new[] { public async Task CodeFix_IL2092_MismatchMethodParamBtOverride_NonPublicMethods_Reverse() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class Base - { - public virtual void M(Type t) {} - } + public class Base + { + public virtual void M(Type t) {} + } - public class C : Base - { - public override void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} + public class C : Base + { + public override void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} - public static void Main() { + public static void Main() { - } - } - """; + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class Base - { - public virtual void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} - } + public class Base + { + public virtual void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} + } - public class C : Base - { - public override void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} + public class C : Base + { + public override void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} - public static void Main() { + public static void Main() { - } - } - """; + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(11,108): warning IL2092: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the parameter 't' of method 'C.M(Type)' - // don't match overridden parameter 't' of method 'Base.M(Type)'. - // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides) + // /0/Test0.cs(11,108): warning IL2092: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the parameter 't' of method 'C.M(Type)' + // don't match overridden parameter 't' of method 'Base.M(Type)'. + // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides) .WithSpan(11, 108, 11, 109) .WithSpan(6, 29, 6, 30) .WithArguments("t", @@ -2691,28 +2691,28 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2092_BothAttributesTurnOffCodeFix() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class Base - { - public virtual void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) {} - } + public class Base + { + public virtual void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) {} + } - public class C : Base - { - public override void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} + public class C : Base + { + public override void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} - public static void Main() { + public static void Main() { - } - } - """; + } + } + """; var diag = new[] { - // /0/Test0.cs(11,108): warning IL2092: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the parameter 't' of method 'C.M(Type)' - // don't match overridden parameter 't' of method 'Base.M(Type)'. - // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides) + // /0/Test0.cs(11,108): warning IL2092: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the parameter 't' of method 'C.M(Type)' + // don't match overridden parameter 't' of method 'Base.M(Type)'. + // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides) .WithSpan(11, 108, 11, 109) .WithArguments("t", "C.M(Type)", @@ -2726,28 +2726,28 @@ public static void Main() { public async Task CodeFix_IL2092_TwoAttributesTurnOffCodeFix() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class Base - { - public virtual void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicFields)] Type t) {} - } + public class Base + { + public virtual void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicFields)] Type t) {} + } - public class C : Base - { - public override void M(Type t) {} + public class C : Base + { + public override void M(Type t) {} - public static void Main() { + public static void Main() { - } - } - """; + } + } + """; var diag = new[] { - // /0/Test0.cs(11,108): warning IL2092: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the parameter 't' of method 'C.M(Type)' - // don't match overridden parameter 't' of method 'Base.M(Type)'. - // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides) + // /0/Test0.cs(11,108): warning IL2092: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the parameter 't' of method 'C.M(Type)' + // don't match overridden parameter 't' of method 'Base.M(Type)'. + // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides) .WithSpan(11, 30, 11, 31) .WithSpan(11, 30, 11, 31) .WithArguments("t", @@ -2762,28 +2762,28 @@ public static void Main() { public async Task CodeFix_IL2092_BothAttributesTurnOffCodeFix_None() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class Base - { - public virtual void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.None)] Type t) {} - } + public class Base + { + public virtual void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.None)] Type t) {} + } - public class C : Base - { - public override void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} + public class C : Base + { + public override void M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) {} - public static void Main() { + public static void Main() { - } - } - """; + } + } + """; var diag = new[] { - // /0/Test0.cs(11,108): warning IL2092: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the parameter 't' of method 'C.M(Type)' - // don't match overridden parameter 't' of method 'Base.M(Type)'. - // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides) + // /0/Test0.cs(11,108): warning IL2092: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the parameter 't' of method 'C.M(Type)' + // don't match overridden parameter 't' of method 'Base.M(Type)'. + // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides) .WithSpan(11, 108, 11, 109) .WithArguments("t", "C.M(Type)", @@ -2797,58 +2797,58 @@ public static void Main() { public async Task CodeFix_IL2093_MismatchOnMethodReturnValueBetweenOverrides() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Base - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] - public virtual Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { - return t; - } - } - - public class C : Base - { - public override Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { - return t; - } - - public static void Main() { - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Base + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] + public virtual Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { + return t; + } + } + + public class C : Base + { + public override Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { + return t; + } + + public static void Main() { + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Base - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] - public virtual Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { - return t; - } - } - - public class C : Base - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] - public override Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { - return t; - } - - public static void Main() { - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Base + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] + public virtual Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { + return t; + } + } + + public class C : Base + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] + public override Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { + return t; + } + + public static void Main() { + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(14,23): warning IL2093: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the return value of method 'C.M(Type)' - // don't match overridden return value of method 'Base.M(Type)'. - // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides) + // /0/Test0.cs(14,23): warning IL2093: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the return value of method 'C.M(Type)' + // don't match overridden return value of method 'Base.M(Type)'. + // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides) .WithSpan(14, 23, 14, 24) .WithSpan(14, 23, 14, 24) .WithArguments("C.M(Type)", @@ -2861,58 +2861,58 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2093_MismatchOnMethodReturnValueBetweenOverrides_Reversed() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Base - { - public virtual Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { - return t; - } - } - - public class C : Base - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] - public override Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { - return t; - } - - public static void Main() { - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Base + { + public virtual Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { + return t; + } + } + + public class C : Base + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] + public override Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { + return t; + } + + public static void Main() { + } + } + """; var fixtest = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Base - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] - public virtual Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { - return t; - } - } - - public class C : Base - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] - public override Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { - return t; - } - - public static void Main() { - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Base + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] + public virtual Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { + return t; + } + } + + public class C : Base + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] + public override Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { + return t; + } + + public static void Main() { + } + } + """; await VerifyDynamicallyAccessedMembersCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(14,23): warning IL2093: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the return value of method 'C.M(Type)' - // don't match overridden return value of method 'Base.M(Type)'. - // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides) + // /0/Test0.cs(14,23): warning IL2093: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the return value of method 'C.M(Type)' + // don't match overridden return value of method 'Base.M(Type)'. + // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides) .WithSpan(14, 23, 14, 24) .WithSpan(6, 22, 6, 23) .WithArguments("C.M(Type)", @@ -2925,33 +2925,33 @@ await VerifyDynamicallyAccessedMembersCodeFix( public async Task CodeFix_IL2093_BothAttributesTurnOffCodeFix() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Base - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - public virtual Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { - return t; - } - } - - public class C : Base - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] - public override Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { - return t; - } - - public static void Main() { - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Base + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + public virtual Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { + return t; + } + } + + public class C : Base + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] + public override Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { + return t; + } + + public static void Main() { + } + } + """; var diag = new[] { - // /0/Test0.cs(15,23): warning IL2093: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the return value of method 'C.M(Type)' - // don't match overridden return value of method 'Base.M(Type)'. - // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides) + // /0/Test0.cs(15,23): warning IL2093: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the return value of method 'C.M(Type)' + // don't match overridden return value of method 'Base.M(Type)'. + // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides) .WithSpan(15, 23, 15, 24) .WithArguments("C.M(Type)", "Base.M(Type)") @@ -2963,33 +2963,33 @@ public static void Main() { public async Task CodeFix_IL2093_AttributesTurnOffCodeFix_None() { var test = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class Base - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.None)] - public virtual Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { - return t; - } - } - - public class C : Base - { - [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] - public override Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { - return t; - } - - public static void Main() { - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class Base + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.None)] + public virtual Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { + return t; + } + } + + public class C : Base + { + [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] + public override Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type t) { + return t; + } + + public static void Main() { + } + } + """; var diag = new[] { - // /0/Test0.cs(15,23): warning IL2093: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the return value of method 'C.M(Type)' - // don't match overridden return value of method 'Base.M(Type)'. - // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides) + // /0/Test0.cs(15,23): warning IL2093: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the return value of method 'C.M(Type)' + // don't match overridden return value of method 'Base.M(Type)'. + // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides) .WithSpan(15, 23, 15, 24) .WithArguments("C.M(Type)", "Base.M(Type)") diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresAssemblyFilesAnalyzerTests.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresAssemblyFilesAnalyzerTests.cs index b97719b9d6e5b7..326ddf9588251b 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresAssemblyFilesAnalyzerTests.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresAssemblyFilesAnalyzerTests.cs @@ -66,63 +66,63 @@ static Task VerifyRequiresAssemblyFilesCodeFix( public Task NoDynamicallyAccessedMembersWarningsIfOnlySingleFileAnalyzerIsEnabled() { var TargetParameterWithAnnotations = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - public static void Main() - { - MethodCallPattern(typeof(int)); - AssignmentPattern(typeof(int)); - ReflectionAccessPattern(); - FieldAccessPattern(); - GenericRequirement(); - } - - private static void NeedsPublicMethodsOnParameter( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type parameter) - { - } - - private static void MethodCallPattern(Type type) - { - NeedsPublicMethodsOnParameter(type); - } - - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type NeedsPublicMethosOnField; - - private static void AssignmentPattern(Type type) - { - NeedsPublicMethosOnField = type; - } - - private static void ReflectionAccessPattern() - { - Action action = NeedsPublicMethodsOnParameter; - } - - private static void FieldAccessPattern() - { - var i = BeforeFieldInit.StaticField; - } - - [RequiresUnreferencedCode("BeforeFieldInit")] - class BeforeFieldInit { - public static int StaticField = 0; - } - - private static void GenericRequirement() - { - new NeedsPublicMethodsOnTypeParameter(); - } - - class NeedsPublicMethodsOnTypeParameter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T> - { - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + public static void Main() + { + MethodCallPattern(typeof(int)); + AssignmentPattern(typeof(int)); + ReflectionAccessPattern(); + FieldAccessPattern(); + GenericRequirement(); + } + + private static void NeedsPublicMethodsOnParameter( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type parameter) + { + } + + private static void MethodCallPattern(Type type) + { + NeedsPublicMethodsOnParameter(type); + } + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + private static Type NeedsPublicMethosOnField; + + private static void AssignmentPattern(Type type) + { + NeedsPublicMethosOnField = type; + } + + private static void ReflectionAccessPattern() + { + Action action = NeedsPublicMethodsOnParameter; + } + + private static void FieldAccessPattern() + { + var i = BeforeFieldInit.StaticField; + } + + [RequiresUnreferencedCode("BeforeFieldInit")] + class BeforeFieldInit { + public static int StaticField = 0; + } + + private static void GenericRequirement() + { + new NeedsPublicMethodsOnTypeParameter(); + } + + class NeedsPublicMethodsOnTypeParameter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T> + { + } + } + """; return VerifyRequiresAssemblyFilesAnalyzer(TargetParameterWithAnnotations); } @@ -130,21 +130,21 @@ class NeedsPublicMethodsOnTypeParameter<[DynamicallyAccessedMembers(DynamicallyA public Task SimpleDiagnosticOnEvent() { var TestRequiresAssemblyFieldsOnEvent = $$""" - #nullable enable - using System.Diagnostics.CodeAnalysis; - - class C - { - [RequiresAssemblyFiles] - event System.EventHandler? E; - - void M() - { - E += (sender, e) => { }; - var evt = E; - } - } - """; + #nullable enable + using System.Diagnostics.CodeAnalysis; + + class C + { + [RequiresAssemblyFiles] + event System.EventHandler? E; + + void M() + { + E += (sender, e) => { }; + var evt = E; + } + } + """; return VerifyRequiresAssemblyFilesAnalyzer(TestRequiresAssemblyFieldsOnEvent, // (11,17): warning IL3002: Using member 'C.E' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(11, 3, 11, 26).WithArguments("C.E.add", "", "")); @@ -154,21 +154,21 @@ void M() public Task SimpleDiagnosticOnProperty() { var TestRequiresAssemblyFilesOnProperty = $$""" - using System.Collections.Generic; - using System.Diagnostics.CodeAnalysis; - - class C - { - [RequiresAssemblyFiles] - bool P { get; set; } - - void M() - { - P = false; - List b = new List { P }; - } - } - """; + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + + class C + { + [RequiresAssemblyFiles] + bool P { get; set; } + + void M() + { + P = false; + List b = new List { P }; + } + } + """; return VerifyRequiresAssemblyFilesAnalyzer(TestRequiresAssemblyFilesOnProperty, // (11,3): warning IL3002: Using member 'C.P' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(11, 3, 11, 12).WithArguments("C.P.set", "", ""), @@ -180,32 +180,32 @@ void M() public Task CallDangerousMethodInsideProperty() { var TestRequiresAssemblyFilesOnMethodInsideProperty = $$""" - using System.Diagnostics.CodeAnalysis; - - class C - { - bool @field; - - [RequiresAssemblyFiles] - bool P { - get { - return @field; - } - set { - CallDangerousMethod (); - @field = value; - } - } - - [RequiresAssemblyFiles] - void CallDangerousMethod () {} - - void M () - { - P = false; - } - } - """; + using System.Diagnostics.CodeAnalysis; + + class C + { + bool @field; + + [RequiresAssemblyFiles] + bool P { + get { + return @field; + } + set { + CallDangerousMethod(); + @field = value; + } + } + + [RequiresAssemblyFiles] + void CallDangerousMethod() {} + + void M() + { + P = false; + } + } + """; return VerifyRequiresAssemblyFilesAnalyzer(TestRequiresAssemblyFilesOnMethodInsideProperty, // (23,3): warning IL3002: Using member 'C.P' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(23, 3, 23, 12).WithArguments("C.P.set", "", "")); @@ -215,21 +215,21 @@ void M () public Task RequiresAssemblyFilesWithUrlOnly() { var TestRequiresAssemblyFilesWithMessageAndUrl = $$""" - using System.Diagnostics.CodeAnalysis; - - class C - { - [RequiresAssemblyFiles (Url = "https://helpurl")] - void M1() - { - } - - void M2() - { - M1(); - } - } - """; + using System.Diagnostics.CodeAnalysis; + + class C + { + [RequiresAssemblyFiles(Url = "https://helpurl")] + void M1() + { + } + + void M2() + { + M1(); + } + } + """; return VerifyRequiresAssemblyFilesAnalyzer(TestRequiresAssemblyFilesWithMessageAndUrl, // (12,3): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. https://helpurl VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(12, 3, 12, 5).WithArguments("C.M1()", "", " https://helpurl")); @@ -239,14 +239,14 @@ void M2() public Task NoDiagnosticIfMethodNotCalled() { var TestNoDiagnosticIfMethodNotCalled = $$""" - using System.Diagnostics.CodeAnalysis; - - class C - { - [RequiresAssemblyFiles] - void M() { } - } - """; + using System.Diagnostics.CodeAnalysis; + + class C + { + [RequiresAssemblyFiles] + void M() { } + } + """; return VerifyRequiresAssemblyFilesAnalyzer(TestNoDiagnosticIfMethodNotCalled); } @@ -254,27 +254,27 @@ void M() { } public Task NoDiagnosticIsProducedIfCallerIsAnnotated() { var TestNoDiagnosticIsProducedIfCallerIsAnnotated = $$""" - using System.Diagnostics.CodeAnalysis; - - class C - { - void M1() - { - M2(); - } - - [RequiresAssemblyFiles ("Warn from M2")] - void M2() - { - M3(); - } - - [RequiresAssemblyFiles ("Warn from M3")] - void M3() - { - } - } - """; + using System.Diagnostics.CodeAnalysis; + + class C + { + void M1() + { + M2(); + } + + [RequiresAssemblyFile("Warn from M2")] + void M2() + { + M3(); + } + + [RequiresAssemblyFiles("Warn from M3")] + void M3() + { + } + } + """; return VerifyRequiresAssemblyFilesAnalyzer(TestNoDiagnosticIsProducedIfCallerIsAnnotated, // (7,3): warning IL3002: Using member 'C.M2()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. Warn from M2. VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(7, 3, 7, 5).WithArguments("C.M2()", " Warn from M2.", "")); @@ -284,12 +284,12 @@ void M3() public Task GetExecutingAssemblyLocation() { const string src = $$""" - using System.Reflection; - class C - { - public string M() => Assembly.GetExecutingAssembly().Location; - } - """; + using System.Reflection; + class C + { + public string M() => Assembly.GetExecutingAssembly().Location; + } + """; return VerifyRequiresAssemblyFilesAnalyzer(src, // (5,26): warning IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. @@ -300,19 +300,19 @@ class C public Task GetAssemblyLocationViaAssemblyProperties() { var src = $$""" - using System.Reflection; - class C - { - public void M() - { - var a = Assembly.GetExecutingAssembly(); - _ = a.Location; - // below methods are marked as obsolete in 5.0 - // _ = a.CodeBase; - // _ = a.EscapedCodeBase; - } - } - """; + using System.Reflection; + class C + { + public void M() + { + var a = Assembly.GetExecutingAssembly(); + _ = a.Location; + // below methods are marked as obsolete in 5.0 + // _ = a.CodeBase; + // _ = a.EscapedCodeBase; + } + } + """; return VerifyRequiresAssemblyFilesAnalyzer(src, // (7,7): warning IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(7, 7, 7, 17).WithArguments("System.Reflection.Assembly.Location.get") @@ -323,17 +323,17 @@ public void M() public Task CallKnownDangerousAssemblyMethods() { var src = $$""" - using System.Reflection; - class C - { - public void M() - { - var a = Assembly.GetExecutingAssembly(); - _ = a.GetFile("/some/file/path"); - _ = a.GetFiles(); - } - } - """; + using System.Reflection; + class C + { + public void M() + { + var a = Assembly.GetExecutingAssembly(); + _ = a.GetFile("/some/file/path"); + _ = a.GetFiles(); + } + } + """; return VerifyRequiresAssemblyFilesAnalyzer(src, // (7,7): warning IL3001: Assemblies embedded in a single-file app cannot have additional files in the manifest. VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyGetFilesInSingleFile).WithSpan(7, 7, 7, 16).WithArguments("System.Reflection.Assembly.GetFile(String)"), @@ -346,17 +346,17 @@ public void M() public Task CallKnownDangerousAssemblyNameAttributes() { var src = $$""" - using System.Reflection; - class C - { - public void M() - { - var a = Assembly.GetExecutingAssembly().GetName(); - _ = a.CodeBase; - _ = a.EscapedCodeBase; - } - } - """; + using System.Reflection; + class C + { + public void M() + { + var a = Assembly.GetExecutingAssembly().GetName(); + _ = a.CodeBase; + _ = a.EscapedCodeBase; + } + } + """; return VerifyRequiresAssemblyFilesAnalyzer(src, // (7,7): warning SYSLIB0044: 'AssemblyName.CodeBase' is obsolete: 'AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported.' DiagnosticResult.CompilerWarning("SYSLIB0044").WithSpan(7, 7, 7, 17).WithArguments("System.Reflection.AssemblyName.CodeBase", "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported."), @@ -375,17 +375,17 @@ public Task GetAssemblyLocationFalsePositive() // This is an OK use of Location and GetFile since these assemblies were loaded from // a file, but the analyzer is conservative var src = $$""" - using System.Reflection; - class C - { - public void M() - { - var a = Assembly.LoadFrom("/some/path/not/in/bundle"); - _ = a.Location; - _ = a.GetFiles(); - } - } - """; + using System.Reflection; + class C + { + public void M() + { + var a = Assembly.LoadFrom("/some/path/not/in/bundle"); + _ = a.Location; + _ = a.GetFiles(); + } + } + """; return VerifyRequiresAssemblyFilesAnalyzer(src, // (7,7): warning IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(7, 7, 7, 17).WithArguments("System.Reflection.Assembly.Location.get"), @@ -398,15 +398,15 @@ public void M() public Task PublishSingleFileIsNotSet() { var src = $$""" - using System.Reflection; - class C - { - public void M() - { - var a = Assembly.GetExecutingAssembly().Location; - } - } - """; + using System.Reflection; + class C + { + public void M() + { + var a = Assembly.GetExecutingAssembly().Location; + } + } + """; // If 'PublishSingleFile' is not set to true, no diagnostics should be produced by the analyzer. This will // effectively verify that the number of produced diagnostics matches the number of expected ones (zero). return VerifyCS.VerifyAnalyzerAsync(src, consoleApplication: false); @@ -416,21 +416,21 @@ public void M() public Task SupressWarningsWithRequiresAssemblyFiles() { const string src = $$""" - using System.Reflection; - using System.Diagnostics.CodeAnalysis; - class C - { - [RequiresAssemblyFiles] - public void M() - { - var a = Assembly.GetExecutingAssembly(); - _ = a.Location; - var b = Assembly.GetExecutingAssembly(); - _ = b.GetFile("/some/file/path"); - _ = b.GetFiles(); - } - } - """; + using System.Reflection; + using System.Diagnostics.CodeAnalysis; + class C + { + [RequiresAssemblyFiles] + public void M() + { + var a = Assembly.GetExecutingAssembly(); + _ = a.Location; + var b = Assembly.GetExecutingAssembly(); + _ = b.GetFile("/some/file/path"); + _ = b.GetFiles(); + } + } + """; return VerifyRequiresAssemblyFilesAnalyzer(src); } @@ -439,69 +439,69 @@ public void M() public Task RequiresAssemblyFilesDiagnosticFix() { var test = $$""" - using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresAssemblyFiles("message")] - public int M1() => 0; - int M2() => M1(); - } - class D - { - public int M3(C c) => c.M1(); - public class E - { - public int M4(C c) => c.M1(); - } - } - public class E - { - public class F - { - public int M5(C c) => c.M1(); - } - } - """; + using System.Diagnostics.CodeAnalysis; + public class C + { + [RequiresAssemblyFiles("message")] + public int M1() => 0; + int M2() => M1(); + } + class D + { + public int M3(C c) => c.M1(); + public class E + { + public int M4(C c) => c.M1(); + } + } + public class E + { + public class F + { + public int M5(C c) => c.M1(); + } + } + """; var fixtest = $$""" - using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresAssemblyFiles("message")] - public int M1() => 0; - [RequiresAssemblyFiles("Calls C.M1()")] - int M2() => M1(); - } - class D - { - [RequiresAssemblyFiles("Calls C.M1()")] - public int M3(C c) => c.M1(); - public class E - { - [RequiresAssemblyFiles("Calls C.M1()")] - public int M4(C c) => c.M1(); - } - } - public class E - { - public class F - { - [RequiresAssemblyFiles()] - public int M5(C c) => c.M1(); - } - } - """; + using System.Diagnostics.CodeAnalysis; + public class C + { + [RequiresAssemblyFiles("message")] + public int M1() => 0; + [RequiresAssemblyFiles("Calls C.M1()")] + int M2() => M1(); + } + class D + { + [RequiresAssemblyFiles("Calls C.M1()")] + public int M3(C c) => c.M1(); + public class E + { + [RequiresAssemblyFiles("Calls C.M1()")] + public int M4(C c) => c.M1(); + } + } + public class E + { + public class F + { + [RequiresAssemblyFiles()] + public int M5(C c) => c.M1(); + } + } + """; return VerifyRequiresAssemblyFilesCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(6,14): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(6, 14, 6, 16).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(10,24): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(10, 24, 10, 28).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(13,25): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(13, 25, 13, 29).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(20,25): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(20, 25, 20, 29).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(6,14): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(6, 14, 6, 16).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(10,24): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(10, 24, 10, 28).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(13,25): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(13, 25, 13, 29).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(20,25): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(20, 25, 20, 29).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } @@ -510,41 +510,41 @@ public class F public Task FixInSingleFileSpecialCases() { var test = $$""" - using System.Reflection; - using System.Diagnostics.CodeAnalysis; - public class C - { - public static Assembly assembly = Assembly.LoadFrom("/some/path/not/in/bundle"); - public string M1() => assembly.Location; - public void M2() { - _ = assembly.GetFiles(); - } - } - """; + using System.Reflection; + using System.Diagnostics.CodeAnalysis; + public class C + { + public static Assembly assembly = Assembly.LoadFrom("/some/path/not/in/bundle"); + public string M1() => assembly.Location; + public void M2() { + _ = assembly.GetFiles(); + } + } + """; var fixtest = $$""" - using System.Reflection; - using System.Diagnostics.CodeAnalysis; - public class C - { - public static Assembly assembly = Assembly.LoadFrom("/some/path/not/in/bundle"); - - [RequiresAssemblyFiles()] - public string M1() => assembly.Location; - - [RequiresAssemblyFiles()] - public void M2() { - _ = assembly.GetFiles(); - } - } - """; + using System.Reflection; + using System.Diagnostics.CodeAnalysis; + public class C + { + public static Assembly assembly = Assembly.LoadFrom("/some/path/not/in/bundle"); + + [RequiresAssemblyFiles()] + public string M1() => assembly.Location; + + [RequiresAssemblyFiles()] + public void M2() { + _ = assembly.GetFiles(); + } + } + """; return VerifyRequiresAssemblyFilesCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(6,24): warning IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. - VerifyCS.Diagnostic (DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan (6, 24, 6, 41).WithArguments ("System.Reflection.Assembly.Location.get", "", ""), - // /0/Test0.cs(8,7): warning IL3001: 'System.Reflection.Assembly.GetFiles()' will throw for assemblies embedded in a single-file app - VerifyCS.Diagnostic (DiagnosticId.AvoidAssemblyGetFilesInSingleFile).WithSpan (8, 7, 8, 24).WithArguments("System.Reflection.Assembly.GetFiles()", "", ""), + // /0/Test0.cs(6,24): warning IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. + VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(6, 24, 6, 41).WithArguments("System.Reflection.Assembly.Location.get", "", ""), + // /0/Test0.cs(8,7): warning IL3001: 'System.Reflection.Assembly.GetFiles()' will throw for assemblies embedded in a single-file app + VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyGetFilesInSingleFile).WithSpan(8, 7, 8, 24).WithArguments("System.Reflection.Assembly.GetFiles()", "", ""), }, fixedExpected: Array.Empty()); } @@ -553,36 +553,36 @@ public void M2() { public Task FixInPropertyDecl() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresAssemblyFiles("message")] - public int M1() => 0; + public class C + { + [RequiresAssemblyFiles("message")] + public int M1() => 0; - int M2 => M1(); - } - """; + int M2 => M1(); + } + """; var fix = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresAssemblyFiles("message")] - public int M1() => 0; - - [RequiresAssemblyFiles("Calls C.M1()")] - int M2 => M1(); - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresAssemblyFiles("message")] + public int M1() => 0; + + [RequiresAssemblyFiles("Calls C.M1()")] + int M2 => M1(); + } + """; return VerifyRequiresAssemblyFilesCodeFix( source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(9,12): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(9, 12, 9, 14).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(9,12): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(9, 12, 9, 14).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } @@ -591,47 +591,47 @@ public class C public Task FixInPropertyAccessor() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresAssemblyFilesAttribute("message")] - public int M1() => 0; - - public int field; - - private int M2 { - get { return M1(); } - set { field = M1(); } - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresAssemblyFilesAttribute("message")] + public int M1() => 0; + + public int field; + + private int M2 { + get { return M1(); } + set { field = M1(); } + } + } + """; var fix = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresAssemblyFilesAttribute("message")] - public int M1() => 0; + public class C + { + [RequiresAssemblyFilesAttribute("message")] + public int M1() => 0; - public int field; + public int field; - private int M2 { - [RequiresAssemblyFiles("Calls C.M1()")] - get { return M1(); } + private int M2 { + [RequiresAssemblyFiles("Calls C.M1()")] + get { return M1(); } - [RequiresAssemblyFiles("Calls C.M1()")] - set { field = M1(); } - } - } - """; + [RequiresAssemblyFiles("Calls C.M1()")] + set { field = M1(); } + } + } + """; var diag = new[] { - // /0/Test0.cs(12,16): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(12, 16, 12, 18).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(13,17): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(13, 17, 13, 19).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(12,16): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(12, 16, 12, 18).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(13,17): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(13, 17, 13, 19).WithArguments("C.M1()", " message.", "") }; return VerifyRequiresAssemblyFilesCodeFix(src, fix, diag, Array.Empty()); } @@ -640,24 +640,24 @@ private int M2 { public Task FixInField() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - class C - { - public static Lazy _default = new Lazy(InitC); - public static C Default => _default.Value; - - [RequiresAssemblyFiles] - public static C InitC() { - C cObject = new C(); - return cObject; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + class C + { + public static Lazy _default = new Lazy(InitC); + public static C Default => _default.Value; + + [RequiresAssemblyFiles] + public static C InitC() { + C cObject = new C(); + return cObject; + } + } + """; var diag = new[] { - // /0/Test0.cs(5,47): warning IL3002: Using member 'C.InitC()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. - VerifyCS.Diagnostic (DiagnosticId.RequiresAssemblyFiles).WithSpan (5, 47, 5, 52).WithArguments ("C.InitC()", "", ""), + // /0/Test0.cs(5,47): warning IL3002: Using member 'C.InitC()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(5, 47, 5, 52).WithArguments("C.InitC()", "", ""), }; return VerifyRequiresAssemblyFilesCodeFix(src, src, diag, diag); } @@ -666,45 +666,45 @@ public static C InitC() { public Task FixInLocalFunc() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresAssemblyFiles("message")] - public int M1() => 0; - - Action M2() - { - void Wrapper () => M1(); - return Wrapper; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresAssemblyFiles("message")] + public int M1() => 0; + + Action M2() + { + void Wrapper() => M1(); + return Wrapper; + } + } + """; var fix = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresAssemblyFiles("message")] - public int M1() => 0; - - [RequiresAssemblyFiles("Calls Wrapper()")] - Action M2() - { - [RequiresAssemblyFiles("Calls C.M1()")] void Wrapper () => M1(); - return Wrapper; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresAssemblyFiles("message")] + public int M1() => 0; + + [RequiresAssemblyFiles("Calls Wrapper()")] + Action M2() + { + [RequiresAssemblyFiles("Calls C.M1()")] void Wrapper() => M1(); + return Wrapper; + } + } + """; // Roslyn currently doesn't simplify the attribute name properly, see https://github.com/dotnet/roslyn/issues/52039 return VerifyRequiresAssemblyFilesCodeFix( source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(11,22): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(11, 22, 11, 24).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(11,22): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(11, 22, 11, 24).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty(), numberOfIterations: 2); @@ -714,36 +714,36 @@ Action M2() public Task FixInCtor() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresAssemblyFiles("message")] - public int M1() => 0; + public class C + { + [RequiresAssemblyFiles("message")] + public int M1() => 0; - public C () => M1(); - } - """; + public C() => M1(); + } + """; var fix = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresAssemblyFiles("message")] - public int M1() => 0; - - [RequiresAssemblyFiles()] - public C () => M1(); - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresAssemblyFiles("message")] + public int M1() => 0; + + [RequiresAssemblyFiles()] + public C() => M1(); + } + """; return VerifyRequiresAssemblyFilesCodeFix( source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(9,17): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(9, 17, 9, 19).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(9,17): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(9, 17, 9, 19).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } @@ -752,50 +752,50 @@ public class C public Task FixInEvent() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresAssemblyFiles("message")] - public int M1() => 0; - - public event EventHandler E1 - { - add - { - var a = M1(); - } - remove { } - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresAssemblyFiles("message")] + public int M1() => 0; + + public event EventHandler E1 + { + add + { + var a = M1(); + } + remove { } + } + } + """; var fix = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresAssemblyFiles("message")] - public int M1() => 0; - - public event EventHandler E1 - { - [RequiresAssemblyFiles()] - add - { - var a = M1(); - } - remove { } - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresAssemblyFiles("message")] + public int M1() => 0; + + public event EventHandler E1 + { + [RequiresAssemblyFiles()] + add + { + var a = M1(); + } + remove { } + } + } + """; return VerifyRequiresAssemblyFilesCodeFix( source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(13,12): warning IL3002: Using method 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(13, 12, 13, 14).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(13,12): warning IL3002: Using method 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(13, 12, 13, 14).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresDynamicCodeAnalyzerTests.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresDynamicCodeAnalyzerTests.cs index 97ac1f3ec2060c..ca27be84603296 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresDynamicCodeAnalyzerTests.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresDynamicCodeAnalyzerTests.cs @@ -22,18 +22,18 @@ public class RequiresDynamicCodeAnalyzerTests namespace System.Diagnostics.CodeAnalysis { - [AttributeUsage (AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] - public sealed class RequiresDynamicCodeAttribute : Attribute - { - public RequiresDynamicCodeAttribute (string message) - { - Message = message; - } - - public string Message { get; } - - public string? Url { get; set; } - } + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] + public sealed class RequiresDynamicCodeAttribute : Attribute + { + public RequiresDynamicCodeAttribute(string message) + { + Message = message; + } + + public string Message { get; } + + public string? Url { get; set; } + } }"; static async Task VerifyRequiresDynamicCodeAnalyzer( @@ -79,81 +79,81 @@ static Task VerifyRequiresDynamicCodeCodeFix( public async Task SimpleDiagnosticFix() { var test = $$""" - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresDynamicCodeAttribute("message")] - public int M1() => 0; - - int M2() => M1(); - } - class D - { - public int M3(C c) => c.M1(); - - public class E - { - public int M4(C c) => c.M1(); - } - } - public class E - { - public class F - { - public int M5(C c) => c.M1(); - } - } - """; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresDynamicCodeAttribute("message")] + public int M1() => 0; + + int M2() => M1(); + } + class D + { + public int M3(C c) => c.M1(); + + public class E + { + public int M4(C c) => c.M1(); + } + } + public class E + { + public class F + { + public int M5(C c) => c.M1(); + } + } + """; var fixtest = $$""" - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresDynamicCodeAttribute("message")] - public int M1() => 0; - - [RequiresDynamicCode("Calls C.M1()")] - int M2() => M1(); - } - class D - { - [RequiresDynamicCode("Calls C.M1()")] - public int M3(C c) => c.M1(); - - public class E - { - [RequiresDynamicCode("Calls C.M1()")] - public int M4(C c) => c.M1(); - } - } - public class E - { - public class F - { - [RequiresDynamicCode()] - public int M5(C c) => c.M1(); - } - } - """; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresDynamicCodeAttribute("message")] + public int M1() => 0; + + [RequiresDynamicCode("Calls C.M1()")] + int M2() => M1(); + } + class D + { + [RequiresDynamicCode("Calls C.M1()")] + public int M3(C c) => c.M1(); + + public class E + { + [RequiresDynamicCode("Calls C.M1()")] + public int M4(C c) => c.M1(); + } + } + public class E + { + public class F + { + [RequiresDynamicCode()] + public int M5(C c) => c.M1(); + } + } + """; await VerifyRequiresDynamicCodeCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(8,14): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(8, 14, 8, 16).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(12,24): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(12, 24, 12, 28).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(16,25): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(16, 25, 16, 29).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(23,25): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(23, 25, 23, 29).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(8,14): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(8, 14, 8, 16).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(12,24): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(12, 24, 12, 28).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(16,25): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(16, 25, 16, 29).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(23,25): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(23, 25, 23, 29).WithArguments("C.M1()", " message.", "") }, fixedExpected: new[] { - // /0/Test0.cs(26,10): error CS7036: There is no argument given that corresponds to the required formal parameter 'message' of 'RequiresDynamicCodeAttribute.RequiresDynamicCodeAttribute(string)' - DiagnosticResult.CompilerError("CS7036").WithSpan(26, 10, 26, 31).WithArguments("message", "System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute.RequiresDynamicCodeAttribute(string)"), + // /0/Test0.cs(26,10): error CS7036: There is no argument given that corresponds to the required formal parameter 'message' of 'RequiresDynamicCodeAttribute.RequiresDynamicCodeAttribute(string)' + DiagnosticResult.CompilerError("CS7036").WithSpan(26, 10, 26, 31).WithArguments("message", "System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute.RequiresDynamicCodeAttribute(string)"), }); } @@ -162,23 +162,23 @@ await VerifyRequiresDynamicCodeCodeFix( public Task FixInLambda() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresDynamicCodeAttribute("message")] - public int M1() => 0; - - Action M2() - { - return () => M1(); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresDynamicCodeAttribute("message")] + public int M1() => 0; + + Action M2() + { + return () => M1(); + } + } + """; var diag = new[] { - // /0/Test0.cs(11,16): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(11, 16, 11, 18).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(11,16): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(11, 16, 11, 18).WithArguments("C.M1()", " message.", "") }; // No fix available inside a lambda, requires manual code change since attribute cannot // be applied @@ -189,45 +189,45 @@ Action M2() public Task FixInLocalFunc() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresDynamicCodeAttribute("message")] - public int M1() => 0; - - Action M2() - { - void Wrapper () => M1(); - return Wrapper; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresDynamicCodeAttribute("message")] + public int M1() => 0; + + Action M2() + { + void Wrapper() => M1(); + return Wrapper; + } + } + """; var fix = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresDynamicCodeAttribute("message")] - public int M1() => 0; - - [RequiresDynamicCode("Calls Wrapper()")] - Action M2() - { - [RequiresDynamicCode("Calls C.M1()")] void Wrapper () => M1(); - return Wrapper; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresDynamicCodeAttribute("message")] + public int M1() => 0; + + [RequiresDynamicCode("Calls Wrapper()")] + Action M2() + { + [RequiresDynamicCode("Calls C.M1()")] void Wrapper() => M1(); + return Wrapper; + } + } + """; // Roslyn currently doesn't simplify the attribute name properly, see https://github.com/dotnet/roslyn/issues/52039 return VerifyRequiresDynamicCodeCodeFix( source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(11,22): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(11, 22, 11, 24).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(11,22): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(11, 22, 11, 24).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty(), // The default iterations for the codefix is the number of diagnostics (1 in this case) @@ -240,41 +240,41 @@ Action M2() public Task FixInCtor() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresDynamicCodeAttribute("message")] - public static int M1() => 0; + public class C + { + [RequiresDynamicCodeAttribute("message")] + public static int M1() => 0; - public C() => M1(); - } - """; + public C() => M1(); + } + """; var fix = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresDynamicCodeAttribute("message")] - public static int M1() => 0; - - [RequiresDynamicCode()] - public C() => M1(); - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresDynamicCodeAttribute("message")] + public static int M1() => 0; + + [RequiresDynamicCode()] + public C() => M1(); + } + """; // Roslyn currently doesn't simplify the attribute name properly, see https://github.com/dotnet/roslyn/issues/52039 return VerifyRequiresDynamicCodeCodeFix( source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(9,16): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(9, 16, 9, 18).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(9,16): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(9, 16, 9, 18).WithArguments("C.M1()", " message.", "") }, fixedExpected: new[] { - // /0/Test0.cs(9,6): error CS7036: There is no argument given that corresponds to the required formal parameter 'message' of 'RequiresDynamicCodeAttribute.RequiresDynamicCodeAttribute(string)' - DiagnosticResult.CompilerError("CS7036").WithSpan(9, 6, 9, 27).WithArguments("message", "System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute.RequiresDynamicCodeAttribute(string)") + // /0/Test0.cs(9,6): error CS7036: There is no argument given that corresponds to the required formal parameter 'message' of 'RequiresDynamicCodeAttribute.RequiresDynamicCodeAttribute(string)' + DiagnosticResult.CompilerError("CS7036").WithSpan(9, 6, 9, 27).WithArguments("message", "System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute.RequiresDynamicCodeAttribute(string)") }); } @@ -282,20 +282,20 @@ public class C public Task FixInPropertyDecl() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresDynamicCodeAttribute("message")] - public int M1() => 0; + public class C + { + [RequiresDynamicCodeAttribute("message")] + public int M1() => 0; - int M2 => M1(); - } - """; + int M2 => M1(); + } + """; var diag = new[] { - // /0/Test0.cs(9,12): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(9, 12, 9, 14).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(9,12): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(9, 12, 9, 14).WithArguments("C.M1()", " message.", "") }; // Can't apply RDC on properties at the moment return VerifyRequiresDynamicCodeCodeFix(src, src, diag, diag); @@ -305,47 +305,47 @@ public class C public Task FixInPropertyAccessor() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresDynamicCodeAttribute("message")] - public int M1() => 0; - - public int field; - - private int M2 { - get { return M1(); } - set { field = M1(); } - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresDynamicCodeAttribute("message")] + public int M1() => 0; + + public int field; + + private int M2 { + get { return M1(); } + set { field = M1(); } + } + } + """; var fix = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresDynamicCodeAttribute("message")] - public int M1() => 0; + public class C + { + [RequiresDynamicCodeAttribute("message")] + public int M1() => 0; - public int field; + public int field; - private int M2 { - [RequiresDynamicCode("Calls C.M1()")] - get { return M1(); } + private int M2 { + [RequiresDynamicCode("Calls C.M1()")] + get { return M1(); } - [RequiresDynamicCode("Calls C.M1()")] - set { field = M1(); } - } - } - """; + [RequiresDynamicCode("Calls C.M1()")] + set { field = M1(); } + } + } + """; var diag = new[] { - // /0/Test0.cs(12,16): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(12, 16, 12, 18).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(13,17): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(13, 17, 13, 19).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(12,16): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(12, 16, 12, 18).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(13,17): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(13, 17, 13, 19).WithArguments("C.M1()", " message.", "") }; return VerifyRequiresDynamicCodeCodeFix(src, fix, diag, Array.Empty()); } @@ -354,39 +354,39 @@ private int M2 { public Task FixInClass() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresDynamicCodeAttribute("message")] - static int M1() => 0; + public class C + { + [RequiresDynamicCodeAttribute("message")] + static int M1() => 0; - static int Field = M1(); - } - """; + static int Field = M1(); + } + """; var fix = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - [RequiresDynamicCode()] - public class C - { - [RequiresDynamicCodeAttribute("message")] - static int M1() => 0; - - static int Field = M1(); - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + [RequiresDynamicCode()] + public class C + { + [RequiresDynamicCodeAttribute("message")] + static int M1() => 0; + + static int Field = M1(); + } + """; return VerifyRequiresDynamicCodeCodeFix(src, fix, baselineExpected: new[] { - // /0/Test0.cs(9,21,9,25): warning IL2026: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(9, 21, 9, 23).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(9,21,9,25): warning IL2026: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(9, 21, 9, 23).WithArguments("C.M1()", " message.", ""), }, fixedExpected: new[] { - // /0/Test0.cs(4,2): error CS7036: There is no argument given that corresponds to the required parameter 'message' of 'RequiresDynamicCodeAttribute.RequiresDynamicCodeAttribute(string)' - DiagnosticResult.CompilerError("CS7036").WithSpan(4, 2, 4, 23).WithArguments("message", "System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute.RequiresDynamicCodeAttribute(string)"), + // /0/Test0.cs(4,2): error CS7036: There is no argument given that corresponds to the required parameter 'message' of 'RequiresDynamicCodeAttribute.RequiresDynamicCodeAttribute(string)' + DiagnosticResult.CompilerError("CS7036").WithSpan(4, 2, 4, 23).WithArguments("message", "System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute.RequiresDynamicCodeAttribute(string)"), }); } @@ -394,12 +394,12 @@ public class C public Task MakeGenericTypeWithAllKnownTypes() { const string src = $$""" - class C - { - public void M() => typeof(Gen<>).MakeGenericType(typeof(object)); - } - class Gen { } - """; + class C + { + public void M() => typeof(Gen<>).MakeGenericType(typeof(object)); + } + class Gen { } + """; return VerifyRequiresDynamicCodeAnalyzer(src); } @@ -408,12 +408,12 @@ class Gen { } public Task MakeGenericTypeWithAllKnownTypesInGenericContext() { const string src = $$""" - class C - { - public void M() => typeof(Gen<>).MakeGenericType(typeof(T)); - } - class Gen { } - """; + class C + { + public void M() => typeof(Gen<>).MakeGenericType(typeof(T)); + } + class Gen { } + """; return VerifyRequiresDynamicCodeAnalyzer(src); } @@ -422,14 +422,14 @@ class Gen { } public Task MakeGenericTypeWithConstraint() { const string src = $$""" - using System; - class C - { - public void M() => typeof(Gen<>).MakeGenericType(GetObject()); - static Type GetObject() => typeof(object); - } - class Gen where T : class { } - """; + using System; + class C + { + public void M() => typeof(Gen<>).MakeGenericType(GetObject()); + static Type GetObject() => typeof(object); + } + class Gen where T : class { } + """; return VerifyRequiresDynamicCodeAnalyzer(src); } @@ -438,14 +438,14 @@ class Gen where T : class { } public Task MakeGenericTypeWithUnknownDefinition() { const string src = $$""" - using System; - class C - { - public void M() => GetDefinition().MakeGenericType(typeof(object)); - static Type GetDefinition() => typeof(Gen<>); - } - class Gen { } - """; + using System; + class C + { + public void M() => GetDefinition().MakeGenericType(typeof(object)); + static Type GetDefinition() => typeof(Gen<>); + } + class Gen { } + """; return VerifyRequiresDynamicCodeAnalyzer(src, // (4,21): warning IL3050: Using member 'System.Type.MakeGenericType(params Type[])' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The native code for this instantiation might not be available at runtime. @@ -456,14 +456,14 @@ class Gen { } public Task MakeGenericTypeWithUnknownArgument() { const string src = $$""" - using System; - class C - { - public void M() => typeof(Gen<>).MakeGenericType(GetObject()); - static Type GetObject() => typeof(object); - } - class Gen { } - """; + using System; + class C + { + public void M() => typeof(Gen<>).MakeGenericType(GetObject()); + static Type GetObject() => typeof(object); + } + class Gen { } + """; return VerifyRequiresDynamicCodeAnalyzer(src, // (4,21): warning IL3050: Using member 'System.Type.MakeGenericType(params Type[])' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The native code for this instantiation might not be available at runtime. @@ -474,12 +474,12 @@ class Gen { } public Task MakeGenericMethodWithAllKnownTypes() { const string src = $$""" - class C - { - public void M() => typeof(C).GetMethod(nameof(N)).MakeGenericMethod(typeof(object)); - public void N() { } - } - """; + class C + { + public void M() => typeof(C).GetMethod(nameof(N)).MakeGenericMethod(typeof(object)); + public void N() { } + } + """; return VerifyRequiresDynamicCodeAnalyzer(src); } @@ -488,12 +488,12 @@ public void N() { } public Task MakeGenericMethodWithAllKnownTypesInGenericContext() { const string src = $$""" - class C - { - public void M() => typeof(C).GetMethod(nameof(N)).MakeGenericMethod(typeof(T)); - public void N() { } - } - """; + class C + { + public void M() => typeof(C).GetMethod(nameof(N)).MakeGenericMethod(typeof(T)); + public void N() { } + } + """; return VerifyRequiresDynamicCodeAnalyzer(src); } @@ -502,14 +502,14 @@ public void N() { } public Task MakeGenericMethodWithConstraint() { const string src = $$""" - using System; - class C - { - public void M() => typeof(C).GetMethod(nameof(N)).MakeGenericMethod(GetObject()); - public void N() where T : class { } - static Type GetObject() => typeof(object); - } - """; + using System; + class C + { + public void M() => typeof(C).GetMethod(nameof(N)).MakeGenericMethod(GetObject()); + public void N() where T : class { } + static Type GetObject() => typeof(object); + } + """; return VerifyRequiresDynamicCodeAnalyzer(src); } @@ -518,14 +518,14 @@ public void N() where T : class { } public Task MakeGenericMethodWithUnknownDefinition() { const string src = $$""" - using System.Reflection; - class C - { - public void M() => GetMethodInfo().MakeGenericMethod(typeof(object)); - public void N() { } - public MethodInfo GetMethodInfo() => typeof(C).GetMethod(nameof(N)); - } - """; + using System.Reflection; + class C + { + public void M() => GetMethodInfo().MakeGenericMethod(typeof(object)); + public void N() { } + public MethodInfo GetMethodInfo() => typeof(C).GetMethod(nameof(N)); + } + """; return VerifyRequiresDynamicCodeAnalyzer(src, // (4,21): warning IL3050: Using member 'System.Reflection.MethodInfo.MakeGenericMethod(params Type[])' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The native code for this instantiation might not be available at runtime. @@ -536,14 +536,14 @@ public void N() { } public Task MakeGenericMethodWithUnknownArgument() { const string src = $$""" - using System; - class C - { - public void M() => typeof(C).GetMethod(nameof(N)).MakeGenericMethod(GetObject()); - public void N() { } - static Type GetObject() => typeof(object); - } - """; + using System; + class C + { + public void M() => typeof(C).GetMethod(nameof(N)).MakeGenericMethod(GetObject()); + public void N() { } + static Type GetObject() => typeof(object); + } + """; return VerifyRequiresDynamicCodeAnalyzer(src, // (4,21): warning IL3050: Using member 'System.Reflection.MethodInfo.MakeGenericMethod(params Type[])' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The native code for this instantiation might not be available at runtime. diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresUnreferencedCodeAnalyzerTests.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresUnreferencedCodeAnalyzerTests.cs index 4f034204392aa9..015403bf16497a 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresUnreferencedCodeAnalyzerTests.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresUnreferencedCodeAnalyzerTests.cs @@ -61,41 +61,41 @@ static Task VerifyRequiresUnreferencedCodeCodeFix( public async Task WarningInArgument() { var test = $$""" - using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresUnreferencedCode("message")] - public int M1() => 0; - public void M2(int x) - { - } - public void M3() => M2(M1()); - } - """; + using System.Diagnostics.CodeAnalysis; + public class C + { + [RequiresUnreferencedCode("message")] + public int M1() => 0; + public void M2(int x) + { + } + public void M3() => M2(M1()); + } + """; var fixtest = $$""" - using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresUnreferencedCode("message")] - public int M1() => 0; - public void M2(int x) - { - } - - [RequiresUnreferencedCode()] - public void M3() => M2(M1()); - } - """; + using System.Diagnostics.CodeAnalysis; + public class C + { + [RequiresUnreferencedCode("message")] + public int M1() => 0; + public void M2(int x) + { + } + + [RequiresUnreferencedCode()] + public void M3() => M2(M1()); + } + """; await VerifyRequiresUnreferencedCodeCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(9,25): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 25, 9, 27).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(9,25): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 25, 9, 27).WithArguments("C.M1()", " message.", ""), }, fixedExpected: new[] { - // /0/Test0.cs(10,3): error CS7036: There is no argument given that corresponds to the required formal parameter 'message' of 'RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)' - DiagnosticResult.CompilerError("CS7036").WithSpan(10, 6, 10, 32).WithArguments("message", "System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)"), + // /0/Test0.cs(10,3): error CS7036: There is no argument given that corresponds to the required formal parameter 'message' of 'RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)' + DiagnosticResult.CompilerError("CS7036").WithSpan(10, 6, 10, 32).WithArguments("message", "System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)"), }); } @@ -103,81 +103,81 @@ await VerifyRequiresUnreferencedCodeCodeFix( public async Task SimpleDiagnosticFix() { var test = $$""" - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresUnreferencedCodeAttribute("message")] - public int M1() => 0; - - int M2() => M1(); - } - class D - { - public int M3(C c) => c.M1(); - - public class E - { - public int M4(C c) => c.M1(); - } - } - public class E - { - public class F - { - public int M5(C c) => c.M1(); - } - } - """; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresUnreferencedCodeAttribute("message")] + public int M1() => 0; + + int M2() => M1(); + } + class D + { + public int M3(C c) => c.M1(); + + public class E + { + public int M4(C c) => c.M1(); + } + } + public class E + { + public class F + { + public int M5(C c) => c.M1(); + } + } + """; var fixtest = $$""" - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresUnreferencedCodeAttribute("message")] - public int M1() => 0; - - [RequiresUnreferencedCode("Calls C.M1()")] - int M2() => M1(); - } - class D - { - [RequiresUnreferencedCode("Calls C.M1()")] - public int M3(C c) => c.M1(); - - public class E - { - [RequiresUnreferencedCode("Calls C.M1()")] - public int M4(C c) => c.M1(); - } - } - public class E - { - public class F - { - [RequiresUnreferencedCode()] - public int M5(C c) => c.M1(); - } - } - """; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresUnreferencedCodeAttribute("message")] + public int M1() => 0; + + [RequiresUnreferencedCode("Calls C.M1()")] + int M2() => M1(); + } + class D + { + [RequiresUnreferencedCode("Calls C.M1()")] + public int M3(C c) => c.M1(); + + public class E + { + [RequiresUnreferencedCode("Calls C.M1()")] + public int M4(C c) => c.M1(); + } + } + public class E + { + public class F + { + [RequiresUnreferencedCode()] + public int M5(C c) => c.M1(); + } + } + """; await VerifyRequiresUnreferencedCodeCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(8,14): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic (DiagnosticId.RequiresUnreferencedCode).WithSpan (8, 14, 8, 16).WithArguments ("C.M1()", " message.", ""), - // /0/Test0.cs(12,24): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan (12, 24, 12, 28).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(16,25): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic (DiagnosticId.RequiresUnreferencedCode).WithSpan (16, 25, 16, 29).WithArguments ("C.M1()", " message.", ""), - // /0/Test0.cs(23,25): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic (DiagnosticId.RequiresUnreferencedCode).WithSpan (23, 25, 23, 29).WithArguments ("C.M1()", " message.", "") + // /0/Test0.cs(8,14): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(8, 14, 8, 16).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(12,24): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(12, 24, 12, 28).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(16,25): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(16, 25, 16, 29).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(23,25): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(23, 25, 23, 29).WithArguments("C.M1()", " message.", "") }, fixedExpected: new[] { - // /0/Test0.cs(26,10): error CS7036: There is no argument given that corresponds to the required formal parameter 'message' of 'RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)' - DiagnosticResult.CompilerError("CS7036").WithSpan(26, 10, 26, 36).WithArguments("message", "System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)"), + // /0/Test0.cs(26,10): error CS7036: There is no argument given that corresponds to the required formal parameter 'message' of 'RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)' + DiagnosticResult.CompilerError("CS7036").WithSpan(26, 10, 26, 36).WithArguments("message", "System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)"), }); } @@ -185,23 +185,23 @@ await VerifyRequiresUnreferencedCodeCodeFix( public Task FixInLambda() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresUnreferencedCodeAttribute("message")] - public int M1() => 0; - - Action M2() - { - return () => M1(); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresUnreferencedCodeAttribute("message")] + public int M1() => 0; + + Action M2() + { + return () => M1(); + } + } + """; var diag = new[] { - // /0/Test0.cs(11,16): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(11, 16, 11, 18).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(11,16): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(11, 16, 11, 18).WithArguments("C.M1()", " message.", "") }; // No fix available inside a lambda, requires manual code change since attribute cannot // be applied @@ -212,45 +212,45 @@ Action M2() public Task FixInLocalFunc() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresUnreferencedCodeAttribute("message")] - public int M1() => 0; - - Action M2() - { - void Wrapper () => M1(); - return Wrapper; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresUnreferencedCodeAttribute("message")] + public int M1() => 0; + + Action M2() + { + void Wrapper() => M1(); + return Wrapper; + } + } + """; var fix = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresUnreferencedCodeAttribute("message")] - public int M1() => 0; - - [RequiresUnreferencedCode("Calls Wrapper()")] - Action M2() - { - [RequiresUnreferencedCode("Calls C.M1()")] void Wrapper () => M1(); - return Wrapper; - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresUnreferencedCodeAttribute("message")] + public int M1() => 0; + + [RequiresUnreferencedCode("Calls Wrapper()")] + Action M2() + { + [RequiresUnreferencedCode("Calls C.M1()")] void Wrapper() => M1(); + return Wrapper; + } + } + """; // Roslyn currently doesn't simplify the attribute name properly, see https://github.com/dotnet/roslyn/issues/52039 return VerifyRequiresUnreferencedCodeCodeFix( source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(11,22): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(11, 22, 11, 24).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(11,22): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(11, 22, 11, 24).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty(), // The default iterations for the codefix is the number of diagnostics (1 in this case) @@ -263,41 +263,41 @@ Action M2() public Task FixInCtor() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresUnreferencedCodeAttribute("message")] - public static int M1() => 0; + public class C + { + [RequiresUnreferencedCodeAttribute("message")] + public static int M1() => 0; - public C() => M1(); - } - """; + public C() => M1(); + } + """; var fix = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresUnreferencedCodeAttribute("message")] - public static int M1() => 0; - - [RequiresUnreferencedCode()] - public C() => M1(); - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresUnreferencedCodeAttribute("message")] + public static int M1() => 0; + + [RequiresUnreferencedCode()] + public C() => M1(); + } + """; // Roslyn currently doesn't simplify the attribute name properly, see https://github.com/dotnet/roslyn/issues/52039 return VerifyRequiresUnreferencedCodeCodeFix( source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(9,16): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 16, 9, 18).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(9,16): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 16, 9, 18).WithArguments("C.M1()", " message.", "") }, fixedExpected: new[] { - // /0/Test0.cs(9,3): error CS7036: There is no argument given that corresponds to the required formal parameter 'message' of 'RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)' - DiagnosticResult.CompilerError ("CS7036").WithSpan (9, 6, 9, 32).WithArguments ("message", "System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)") + // /0/Test0.cs(9,3): error CS7036: There is no argument given that corresponds to the required formal parameter 'message' of 'RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)' + DiagnosticResult.CompilerError("CS7036").WithSpan(9, 6, 9, 32).WithArguments("message", "System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)") }); } @@ -305,20 +305,20 @@ public class C public Task FixInPropertyDecl() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresUnreferencedCodeAttribute("message")] - public int M1() => 0; + public class C + { + [RequiresUnreferencedCodeAttribute("message")] + public int M1() => 0; - int M2 => M1(); - } - """; + int M2 => M1(); + } + """; var diag = new[] { - // /0/Test0.cs(10,15): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 12, 9, 14).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(10,15): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 12, 9, 14).WithArguments("C.M1()", " message.", "") }; // Can't apply RUC on properties at the moment return VerifyRequiresUnreferencedCodeCodeFix(src, src, diag, diag); @@ -328,47 +328,47 @@ public class C public Task FixInPropertyAccessor() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresUnreferencedCodeAttribute("message")] - public int M1() => 0; - - public int field; - - private int M2 { - get { return M1(); } - set { field = M1(); } - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresUnreferencedCodeAttribute("message")] + public int M1() => 0; + + public int field; + + private int M2 { + get { return M1(); } + set { field = M1(); } + } + } + """; var fix = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresUnreferencedCodeAttribute("message")] - public int M1() => 0; + public class C + { + [RequiresUnreferencedCodeAttribute("message")] + public int M1() => 0; - public int field; + public int field; - private int M2 { - [RequiresUnreferencedCode("Calls C.M1()")] - get { return M1(); } + private int M2 { + [RequiresUnreferencedCode("Calls C.M1()")] + get { return M1(); } - [RequiresUnreferencedCode("Calls C.M1()")] - set { field = M1(); } - } - } - """; + [RequiresUnreferencedCode("Calls C.M1()")] + set { field = M1(); } + } + } + """; var diag = new[] { - // /0/Test0.cs(12,16): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(12, 16, 12, 18).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(13,17): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(13, 17, 13, 19).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(12,16): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(12, 16, 12, 18).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(13,17): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(13, 17, 13, 19).WithArguments("C.M1()", " message.", "") }; return VerifyRequiresUnreferencedCodeCodeFix(src, fix, diag, Array.Empty()); } @@ -377,39 +377,39 @@ private int M2 { public Task FixInClass() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresUnreferencedCodeAttribute("message")] - static int M1() => 0; + public class C + { + [RequiresUnreferencedCodeAttribute("message")] + static int M1() => 0; - static int Field = M1(); - } - """; + static int Field = M1(); + } + """; var fix = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - [RequiresUnreferencedCode()] - public class C - { - [RequiresUnreferencedCodeAttribute("message")] - static int M1() => 0; - - static int Field = M1(); - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + [RequiresUnreferencedCode()] + public class C + { + [RequiresUnreferencedCodeAttribute("message")] + static int M1() => 0; + + static int Field = M1(); + } + """; return VerifyRequiresUnreferencedCodeCodeFix(src, fix, baselineExpected: new[] { - // /0/Test0.cs(9,21): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 21, 9, 23).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(9,21): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 21, 9, 23).WithArguments("C.M1()", " message.", "") }, fixedExpected: new[] { - // /0/Test0.cs(4,2): error CS7036: There is no argument given that corresponds to the required parameter 'message' of 'RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)' - DiagnosticResult.CompilerError("CS7036").WithSpan(4, 2, 4, 28).WithArguments("message", "System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)"), + // /0/Test0.cs(4,2): error CS7036: There is no argument given that corresponds to the required parameter 'message' of 'RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)' + DiagnosticResult.CompilerError("CS7036").WithSpan(4, 2, 4, 28).WithArguments("message", "System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)"), }); } @@ -417,23 +417,23 @@ public class C public Task TestMakeGenericMethodUsage() { var source = $$""" - using System.Diagnostics.CodeAnalysis; - using System.Reflection; - - class C - { - static void M1 (MethodInfo methodInfo) - { - methodInfo.MakeGenericMethod (typeof (C)); - } - - [RequiresUnreferencedCode ("Message from RUC")] - static void M2 (MethodInfo methodInfo) - { - methodInfo.MakeGenericMethod (typeof (C)); - } - } - """; + using System.Diagnostics.CodeAnalysis; + using System.Reflection; + + class C + { + static void M1(MethodInfo methodInfo) + { + methodInfo.MakeGenericMethod(typeof(C)); + } + + [RequiresUnreferencedCode("Message from RUC")] + static void M2(MethodInfo methodInfo) + { + methodInfo.MakeGenericMethod(typeof(C)); + } + } + """; return VerifyRequiresUnreferencedCodeAnalyzer(source, // (8,3): warning IL2060: Call to 'System.Reflection.MethodInfo.MakeGenericMethod(params Type[])' can not be statically analyzed. It's not possible to guarantee the availability of requirements of the generic method. @@ -444,23 +444,23 @@ static void M2 (MethodInfo methodInfo) public Task TestMakeGenericTypeUsage() { var source = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - class C - { - static void M1 (Type t) - { - typeof (Nullable<>).MakeGenericType (typeof (C)); - } - - [RequiresUnreferencedCode ("Message from RUC")] - static void M2 (Type t) - { - typeof (Nullable<>).MakeGenericType (typeof (C)); - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + class C + { + static void M1(Type t) + { + typeof(Nullable<>).MakeGenericType(typeof(C)); + } + + [RequiresUnreferencedCode("Message from RUC")] + static void M2(Type t) + { + typeof(Nullable<>).MakeGenericType(typeof(C)); + } + } + """; return VerifyRequiresUnreferencedCodeAnalyzer(source); } @@ -469,14 +469,14 @@ static void M2 (Type t) public Task VerifyThatAnalysisOfFieldsDoesNotNullRef() { var source = $$""" - using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; - [DynamicallyAccessedMembers (field)] - class C - { - public const DynamicallyAccessedMemberTypes field = DynamicallyAccessedMemberTypes.PublicMethods; - } - """; + [DynamicallyAccessedMembers(field)] + class C + { + public const DynamicallyAccessedMemberTypes field = DynamicallyAccessedMemberTypes.PublicMethods; + } + """; return VerifyRequiresUnreferencedCodeAnalyzer(source); } @@ -485,14 +485,14 @@ class C public Task TestPropertyAssignmentInAssemblyAttribute() { var source = $$""" - using System; - [assembly: MyAttribute (Value = 5)] - - class MyAttribute : Attribute - { - public int Value { get; set; } - } - """; + using System; + [assembly: MyAttribute(Value = 5)] + + class MyAttribute : Attribute + { + public int Value { get; set; } + } + """; return VerifyRequiresUnreferencedCodeAnalyzer(source); } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/TestChecker.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/TestChecker.cs index 899a3b4a6bbe36..655fcf13b9aeb2 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/TestChecker.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/TestChecker.cs @@ -386,7 +386,7 @@ private bool LogContains(AttributeSyntax attribute, IReadOnlyList di findText = LinkerTestBase.GetStringFromExpression(args["#0"], _semanticModel); // If the text starts with `warning IL...` then it probably follows the pattern - // 'warning : :' + // 'warning : :' // We don't want to repeat the location in the error message for the analyzer, so // it's better to just trim here. We've already filtered by diagnostic location so // the text location shouldn't matter diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/UnconditionalSuppressMessageCodeFixTests.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/UnconditionalSuppressMessageCodeFixTests.cs index f4399633ca4151..071e10a5bb5161 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/UnconditionalSuppressMessageCodeFixTests.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/UnconditionalSuppressMessageCodeFixTests.cs @@ -20,18 +20,18 @@ public class UnconditionalSuppressMessageCodeFixTests namespace System.Diagnostics.CodeAnalysis { - [AttributeUsage (AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] - public sealed class RequiresDynamicCodeAttribute : Attribute - { - public RequiresDynamicCodeAttribute (string message) - { - Message = message; - } - - public string Message { get; } - - public string? Url { get; set; } - } + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] + public sealed class RequiresDynamicCodeAttribute : Attribute + { + public RequiresDynamicCodeAttribute(string message) + { + Message = message; + } + + public string Message { get; } + + public string? Url { get; set; } + } }"; static Task VerifyUnconditionalSuppressMessageCodeFixWithRUC( @@ -118,8 +118,8 @@ public class C test, fixtest, baselineExpected: new[] { - // /0/Test0.cs(7,17): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCSUSM.Diagnostic (DiagnosticId.RequiresUnreferencedCode).WithSpan (7, 17, 7, 19).WithArguments ("C.M1()", " message.", ""), + // /0/Test0.cs(7,17): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(7, 17, 7, 19).WithArguments("C.M1()", " message.", ""), }, fixedExpected: Array.Empty()); } @@ -148,8 +148,8 @@ public class C test, fixtest, baselineExpected: new[] { - // /0/Test0.cs(7,17): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCSUSM.Diagnostic (DiagnosticId.RequiresAssemblyFiles).WithSpan (7, 17, 7, 19).WithArguments ("C.M1()", " message.", "") + // /0/Test0.cs(7,17): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCSUSM.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(7, 17, 7, 19).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } @@ -178,8 +178,8 @@ public class C test, fixtest, baselineExpected: new[] { - // /0/Test0.cs(7,17): warning IL3050: Members annotated with 'RequiresDynamicCodeAttribute' require dynamic access otherwise can break functionality when trimming application code. message. - VerifyCSUSM.Diagnostic (DiagnosticId.RequiresDynamicCode).WithSpan (7, 17, 7, 19).WithArguments ("C.M1()", " message.", "") + // /0/Test0.cs(7,17): warning IL3050: Members annotated with 'RequiresDynamicCodeAttribute' require dynamic access otherwise can break functionality when trimming application code. message. + VerifyCSUSM.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(7, 17, 7, 19).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } @@ -219,10 +219,10 @@ public void M2() { test, fixtest, baselineExpected: new[] { - // /0/Test0.cs(7,27): warning IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. - VerifyCSUSM.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan (7, 27, 7, 44).WithArguments ("System.Reflection.Assembly.Location.get", "", ""), - // /0/Test0.cs(9,13): warning IL3001: 'System.Reflection.Assembly.GetFiles()' will throw for assemblies embedded in a single-file app - VerifyCSUSM.Diagnostic(DiagnosticId.AvoidAssemblyGetFilesInSingleFile).WithSpan (9, 13, 9, 30).WithArguments("System.Reflection.Assembly.GetFiles()", "", ""), + // /0/Test0.cs(7,27): warning IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. + VerifyCSUSM.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(7, 27, 7, 44).WithArguments("System.Reflection.Assembly.Location.get", "", ""), + // /0/Test0.cs(9,13): warning IL3001: 'System.Reflection.Assembly.GetFiles()' will throw for assemblies embedded in a single-file app + VerifyCSUSM.Diagnostic(DiagnosticId.AvoidAssemblyGetFilesInSingleFile).WithSpan(9, 13, 9, 30).WithArguments("System.Reflection.Assembly.GetFiles()", "", ""), }, fixedExpected: Array.Empty()); } @@ -257,8 +257,8 @@ public class C src, fix, baselineExpected: new[] { - // /0/Test0.cs(10,15): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCSUSM.Diagnostic (DiagnosticId.RequiresUnreferencedCode).WithSpan(10, 15, 10, 17).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(10,15): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(10, 15, 10, 17).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } @@ -267,47 +267,47 @@ public class C public Task FixInPropertyAccessor() { var src = $$""" - using System; - using System.Diagnostics.CodeAnalysis; - - public class C - { - [RequiresUnreferencedCodeAttribute("message")] - public int M1() => 0; - - public int field; - - private int M2 { - get { return M1(); } - set { field = M1(); } - } - } - """; + using System; + using System.Diagnostics.CodeAnalysis; + + public class C + { + [RequiresUnreferencedCodeAttribute("message")] + public int M1() => 0; + + public int field; + + private int M2 { + get { return M1(); } + set { field = M1(); } + } + } + """; var fix = $$""" - using System; - using System.Diagnostics.CodeAnalysis; + using System; + using System.Diagnostics.CodeAnalysis; - public class C - { - [RequiresUnreferencedCodeAttribute("message")] - public int M1() => 0; + public class C + { + [RequiresUnreferencedCodeAttribute("message")] + public int M1() => 0; - public int field; + public int field; - private int M2 { - [UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "")] - get { return M1(); } + private int M2 { + [UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "")] + get { return M1(); } - [UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "")] - set { field = M1(); } - } - } - """; + [UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "")] + set { field = M1(); } + } + } + """; var diag = new[] { - // /0/Test0.cs(12,16): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(12, 16, 12, 18).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(13,17): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(13, 17, 13, 19).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(12,16): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(12, 16, 12, 18).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(13,17): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(13, 17, 13, 19).WithArguments("C.M1()", " message.", "") }; return VerifyUnconditionalSuppressMessageCodeFixWithRUC(src, fix, diag, Array.Empty()); } @@ -348,8 +348,8 @@ public static C InitC() { src, fixtest, baselineExpected: new[] { - // /0/Test0.cs(6,50): warning IL3002: Using member 'C.InitC()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. - VerifyCSUSM.Diagnostic (DiagnosticId.RequiresAssemblyFiles).WithSpan (6, 50, 6, 55).WithArguments ("C.InitC()", "", ""), + // /0/Test0.cs(6,50): warning IL3002: Using member 'C.InitC()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. + VerifyCSUSM.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(6, 50, 6, 55).WithArguments("C.InitC()", "", ""), }, fixedExpected: Array.Empty()); } @@ -368,7 +368,7 @@ public class C Action M2() { - void Wrapper () => M1(); + void Wrapper() => M1(); return Wrapper; } }"; @@ -383,7 +383,7 @@ public class C Action M2() { - [UnconditionalSuppressMessage(""Trimming"", ""IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code"", Justification = """")] void Wrapper () => M1(); + [UnconditionalSuppressMessage(""Trimming"", ""IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code"", Justification = """")] void Wrapper() => M1(); return Wrapper; } }"; @@ -392,8 +392,8 @@ Action M2() src, fix, baselineExpected: new[] { - // /0/Test0.cs(12,28): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCSUSM.Diagnostic (DiagnosticId.RequiresUnreferencedCode).WithSpan(12, 28, 12, 30).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(12,28): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(12, 28, 12, 30).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } @@ -410,7 +410,7 @@ public class C [RequiresUnreferencedCodeAttribute(""message"")] public int M1() => 0; - public C () => M1(); + public C() => M1(); }"; var fix = @" using System; @@ -422,14 +422,14 @@ public class C public int M1() => 0; [UnconditionalSuppressMessage(""Trimming"", ""IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code"", Justification = """")] - public C () => M1(); + public C() => M1(); }"; return VerifyUnconditionalSuppressMessageCodeFixWithRUC( src, fix, baselineExpected: new[] { - // /0/Test0.cs(10,15): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCSUSM.Diagnostic (DiagnosticId.RequiresUnreferencedCode).WithSpan(10, 20, 10, 22).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(10,15): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(10, 20, 10, 22).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } @@ -478,8 +478,8 @@ public event EventHandler E1 src, fix, baselineExpected: new[] { - // /0/Test0.cs(14,21): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCSUSM.Diagnostic (DiagnosticId.RequiresUnreferencedCode).WithSpan(14, 21, 14, 23).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(14,21): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(14, 21, 14, 23).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/AdvancedTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/AdvancedTests.g.cs index 217047462a7ffc..8cd232bd2ca4d0 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/AdvancedTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/AdvancedTests.g.cs @@ -4,26 +4,26 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class AdvancedTests : LinkerTestBase - { + public sealed partial class AdvancedTests : LinkerTestBase + { - [Fact] - public Task DeadCodeElimination1 () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task DeadCodeElimination1() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task FieldThatOnlyGetsSetIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task FieldThatOnlyGetsSetIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task TypeCheckRemovalDisabled () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task TypeCheckRemovalDisabled() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.CscTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.CscTests.g.cs index 028ec904acd518..156c00f6416a87 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.CscTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.CscTests.g.cs @@ -4,118 +4,118 @@ namespace ILLink.RoslynAnalyzer.Tests.Attributes { - public sealed partial class CscTests : LinkerTestBase - { - - protected override string TestSuiteName => "Attributes.Csc"; - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeArrayOnAttributeCtorOnType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeCtorOnAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeCtorOnAssemblyOtherTypesInAttributeAssemblyUsed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeCtorOnEvent () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeCtorOnMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeCtorOnProperty () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeCtorOnType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeFieldOnAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeFieldOnEvent () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeFieldOnMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeFieldOnProperty () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeFieldOnType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributePropertyOnAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributePropertyOnEvent () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributePropertyOnMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributePropertyOnProperty () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyIsTypeOnAttributePropertyOnType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OnlyTypeUsedInAssemblyWithReferenceIsTypeOnAttributeCtorOnType () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class CscTests : LinkerTestBase + { + + protected override string TestSuiteName => "Attributes.Csc"; + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeArrayOnAttributeCtorOnType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeCtorOnAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeCtorOnAssemblyOtherTypesInAttributeAssemblyUsed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeCtorOnEvent() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeCtorOnMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeCtorOnProperty() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeCtorOnType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeFieldOnAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeFieldOnEvent() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeFieldOnMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeFieldOnProperty() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributeFieldOnType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributePropertyOnAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributePropertyOnEvent() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributePropertyOnMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributePropertyOnProperty() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyIsTypeOnAttributePropertyOnType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OnlyTypeUsedInAssemblyWithReferenceIsTypeOnAttributeCtorOnType() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.Debugger.KeepDebugMembersTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.Debugger.KeepDebugMembersTests.g.cs index 0975be65225014..87612434301815 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.Debugger.KeepDebugMembersTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.Debugger.KeepDebugMembersTests.g.cs @@ -4,94 +4,94 @@ namespace ILLink.RoslynAnalyzer.Tests.Attributes.Debugger { - public sealed partial class KeepDebugMembersTests : LinkerTestBase - { - - protected override string TestSuiteName => "Attributes.Debugger.KeepDebugMembers"; - - [Fact] - public Task DebuggerDisplayAttributeOnAssemblyUsingTarget () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayAttributeOnAssemblyUsingTargetOnUnusedType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayAttributeOnAssemblyUsingTargetTypeNameInOtherAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayAttributeOnAssemblyUsingTargetTypeNameInSameAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayAttributeOnAssemblyUsingTargetTypeNameOfGenericTypeInOtherAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayAttributeOnAssemblyUsingTargetTypeNameOfNestedTypeInOtherAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayAttributeOnGenerics () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayAttributeOnType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayAttributeOnTypeThatIsNotUsed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayAttributeOnTypeWithNonExistentMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayOnTypeWithCallToExtensionMethodOnFieldType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayOnTypeWithCallToMethodOnFieldType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerTypeProxyAttributeOnAssemblyUsingTarget () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerTypeProxyAttributeOnType () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class KeepDebugMembersTests : LinkerTestBase + { + + protected override string TestSuiteName => "Attributes.Debugger.KeepDebugMembers"; + + [Fact] + public Task DebuggerDisplayAttributeOnAssemblyUsingTarget() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayAttributeOnAssemblyUsingTargetOnUnusedType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayAttributeOnAssemblyUsingTargetTypeNameInOtherAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayAttributeOnAssemblyUsingTargetTypeNameInSameAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayAttributeOnAssemblyUsingTargetTypeNameOfGenericTypeInOtherAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayAttributeOnAssemblyUsingTargetTypeNameOfNestedTypeInOtherAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayAttributeOnGenerics() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayAttributeOnType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayAttributeOnTypeThatIsNotUsed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayAttributeOnTypeWithNonExistentMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayOnTypeWithCallToExtensionMethodOnFieldType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayOnTypeWithCallToMethodOnFieldType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerTypeProxyAttributeOnAssemblyUsingTarget() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerTypeProxyAttributeOnType() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.DebuggerTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.DebuggerTests.g.cs index 70f89bf10ac802..6f9f3d0ee5775c 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.DebuggerTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.DebuggerTests.g.cs @@ -4,58 +4,58 @@ namespace ILLink.RoslynAnalyzer.Tests.Attributes { - public sealed partial class DebuggerTests : LinkerTestBase - { - - protected override string TestSuiteName => "Attributes.Debugger"; - - [Fact] - public Task DebuggerDisplayAttributeOnAssemblyUsingTarget () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayAttributeOnAssemblyUsingTargetOnUnusedType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayAttributeOnAssemblyUsingTargetTypeNameInOtherAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayAttributeOnType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayAttributeOnTypeCopy () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerDisplayAttributeOnTypeThatIsNotUsed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerTypeProxyAttributeOnAssemblyUsingTarget () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DebuggerTypeProxyAttributeOnType () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class DebuggerTests : LinkerTestBase + { + + protected override string TestSuiteName => "Attributes.Debugger"; + + [Fact] + public Task DebuggerDisplayAttributeOnAssemblyUsingTarget() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayAttributeOnAssemblyUsingTargetOnUnusedType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayAttributeOnAssemblyUsingTargetTypeNameInOtherAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayAttributeOnType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayAttributeOnTypeCopy() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerDisplayAttributeOnTypeThatIsNotUsed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerTypeProxyAttributeOnAssemblyUsingTarget() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DebuggerTypeProxyAttributeOnType() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.NoSecurityTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.NoSecurityTests.g.cs index 7eb7eff2af9a71..16b49bd46f52f8 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.NoSecurityTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.NoSecurityTests.g.cs @@ -4,28 +4,28 @@ namespace ILLink.RoslynAnalyzer.Tests.Attributes { - public sealed partial class NoSecurityTests : LinkerTestBase - { + public sealed partial class NoSecurityTests : LinkerTestBase + { - protected override string TestSuiteName => "Attributes.NoSecurity"; + protected override string TestSuiteName => "Attributes.NoSecurity"; - [Fact] - public Task CoreLibrarySecurityAttributeTypesAreRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CoreLibrarySecurityAttributeTypesAreRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task SecurityAttributesOnUsedMethodAreRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task SecurityAttributesOnUsedMethodAreRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task SecurityAttributesOnUsedTypeAreRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task SecurityAttributesOnUsedTypeAreRemoved() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.OnlyKeepUsedTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.OnlyKeepUsedTests.g.cs index 893331bcc141b9..6b2cca5d61b32a 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.OnlyKeepUsedTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.OnlyKeepUsedTests.g.cs @@ -4,196 +4,196 @@ namespace ILLink.RoslynAnalyzer.Tests.Attributes { - public sealed partial class OnlyKeepUsedTests : LinkerTestBase - { - - protected override string TestSuiteName => "Attributes.OnlyKeepUsed"; - - [Fact] - public Task AttributeDefinedAndUsedInOtherAssemblyIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeUsedByAttributeIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanLinkCoreLibrariesWithOnlyKeepUsedAttributes () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ComAttributesArePreserved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ContextStaticIsPreservedOnField () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CoreLibraryUnusedAssemblyAttributesAreRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CoreLibraryUsedAssemblyAttributesAreKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task FixedLengthArrayAttributesArePreserved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MethodWithUnmanagedConstraint () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NullableOnConstraintsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NullableOnConstraintsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ThreadStaticIsPreservedOnField () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedAttributeOnGenericParameterIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedAttributeOnReturnTypeIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedAttributePreservedViaLinkXmlIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedAttributeTypeOnAssemblyIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedAttributeTypeOnEventIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedAttributeTypeOnMethodIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedAttributeTypeOnModuleIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedAttributeTypeOnParameterIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedAttributeTypeOnPropertyIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedAttributeTypeOnTypeIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedAttributeWithTypeForwarderIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedDerivedAttributeType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedAttributeTypeOnAssemblyIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedAttributeTypeOnEventIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedAttributeTypeOnMethodIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedAttributeTypeOnModuleIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedAttributeTypeOnParameterIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedAttributeTypeOnPropertyIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedAttributeTypeOnTypeIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class OnlyKeepUsedTests : LinkerTestBase + { + + protected override string TestSuiteName => "Attributes.OnlyKeepUsed"; + + [Fact] + public Task AttributeDefinedAndUsedInOtherAssemblyIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeUsedByAttributeIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanLinkCoreLibrariesWithOnlyKeepUsedAttributes() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ComAttributesArePreserved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ContextStaticIsPreservedOnField() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CoreLibraryUnusedAssemblyAttributesAreRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CoreLibraryUsedAssemblyAttributesAreKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task FixedLengthArrayAttributesArePreserved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MethodWithUnmanagedConstraint() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NullableOnConstraintsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NullableOnConstraintsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ThreadStaticIsPreservedOnField() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedAttributeOnGenericParameterIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedAttributeOnReturnTypeIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedAttributePreservedViaLinkXmlIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedAttributeTypeOnAssemblyIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedAttributeTypeOnEventIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedAttributeTypeOnMethodIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedAttributeTypeOnModuleIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedAttributeTypeOnParameterIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedAttributeTypeOnPropertyIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedAttributeTypeOnTypeIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedAttributeWithTypeForwarderIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedDerivedAttributeType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedAttributeTypeOnAssemblyIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedAttributeTypeOnEventIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedAttributeTypeOnMethodIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedAttributeTypeOnModuleIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedAttributeTypeOnParameterIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedAttributeTypeOnPropertyIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedAttributeTypeOnTypeIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.StructLayoutTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.StructLayoutTests.g.cs index 603e80d6743da2..2fcd7216700034 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.StructLayoutTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Attributes.StructLayoutTests.g.cs @@ -4,34 +4,34 @@ namespace ILLink.RoslynAnalyzer.Tests.Attributes { - public sealed partial class StructLayoutTests : LinkerTestBase - { + public sealed partial class StructLayoutTests : LinkerTestBase + { - protected override string TestSuiteName => "Attributes.StructLayout"; + protected override string TestSuiteName => "Attributes.StructLayout"; - [Fact] - public Task AutoClass () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task AutoClass() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task ExplicitClass () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task ExplicitClass() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task SequentialClass () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task SequentialClass() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UnusedTypeWithSequentialLayoutIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UnusedTypeWithSequentialLayoutIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/AttributesTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/AttributesTests.g.cs index dc69ebb930a723..53a48052a45301 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/AttributesTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/AttributesTests.g.cs @@ -4,178 +4,178 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class AttributesTests : LinkerTestBase - { - - protected override string TestSuiteName => "Attributes"; - - [Fact] - public Task AssemblyAttributeAccessesMembers () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AssemblyAttributeIsRemovedIfOnlyTypesUsedInAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AssemblyAttributeKeptInComplexCase () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeOnAssemblyIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeOnAssemblyIsKeptIfDeclarationIsSkipped () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeOnParameterInUsedMethodIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeOnPreservedTypeIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeOnPreservedTypeWithTypeUsedInConstructorIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeOnPreservedTypeWithTypeUsedInDifferentNamespaceIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeOnPreservedTypeWithTypeUsedInFieldIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeOnPreservedTypeWithTypeUsedInPropertySetterIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeOnPreservedTypeWithUsedSetter () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeOnUsedFieldIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeOnUsedMethodIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeOnUsedPropertyIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task BoxedValues () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CoreLibraryAssemblyAttributesAreKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task FixedLengthArrayAttributesArePreserved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericAttributes () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task IVTUnused () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task IVTUnusedKeptWhenKeepingUsedAttributesOnly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task IVTUsed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MarshalAsCustomMarshaler () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MarshalAsCustomMarshalerInterface () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SecurityAttributesOnUsedMethodAreKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SecurityAttributesOnUsedTypeAreKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task TypeUsedInObjectArrayConstructorArgumentOnAttributeIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task TypeWithDynamicInterfaceCastableImplementationAttributeIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class AttributesTests : LinkerTestBase + { + + protected override string TestSuiteName => "Attributes"; + + [Fact] + public Task AssemblyAttributeAccessesMembers() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AssemblyAttributeIsRemovedIfOnlyTypesUsedInAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AssemblyAttributeKeptInComplexCase() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeOnAssemblyIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeOnAssemblyIsKeptIfDeclarationIsSkipped() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeOnParameterInUsedMethodIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeOnPreservedTypeIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeOnPreservedTypeWithTypeUsedInConstructorIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeOnPreservedTypeWithTypeUsedInDifferentNamespaceIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeOnPreservedTypeWithTypeUsedInFieldIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeOnPreservedTypeWithTypeUsedInPropertySetterIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeOnPreservedTypeWithUsedSetter() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeOnUsedFieldIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeOnUsedMethodIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeOnUsedPropertyIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task BoxedValues() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CoreLibraryAssemblyAttributesAreKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task FixedLengthArrayAttributesArePreserved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericAttributes() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task IVTUnused() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task IVTUnusedKeptWhenKeepingUsedAttributesOnly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task IVTUsed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MarshalAsCustomMarshaler() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MarshalAsCustomMarshalerInterface() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SecurityAttributesOnUsedMethodAreKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SecurityAttributesOnUsedTypeAreKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task TypeUsedInObjectArrayConstructorArgumentOnAttributeIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task TypeWithDynamicInterfaceCastableImplementationAttributeIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/BCLFeatures.ETWTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/BCLFeatures.ETWTests.g.cs index a820bbcfb0754f..595fd02114321c 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/BCLFeatures.ETWTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/BCLFeatures.ETWTests.g.cs @@ -4,22 +4,22 @@ namespace ILLink.RoslynAnalyzer.Tests.BCLFeatures { - public sealed partial class ETWTests : LinkerTestBase - { + public sealed partial class ETWTests : LinkerTestBase + { - protected override string TestSuiteName => "BCLFeatures.ETW"; + protected override string TestSuiteName => "BCLFeatures.ETW"; - [Fact] - public Task CustomEventSource () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CustomEventSource() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task CustomLibraryEventSource () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CustomLibraryEventSource() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/BCLFeaturesTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/BCLFeaturesTests.g.cs index 490fe5b7eaf96c..52e57e2a31b817 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/BCLFeaturesTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/BCLFeaturesTests.g.cs @@ -4,16 +4,16 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class BCLFeaturesTests : LinkerTestBase - { + public sealed partial class BCLFeaturesTests : LinkerTestBase + { - protected override string TestSuiteName => "BCLFeatures"; + protected override string TestSuiteName => "BCLFeatures"; - [Fact] - public Task SerializationCtors () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task SerializationCtors() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/BasicTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/BasicTests.g.cs index 76a31b14d9561c..506ecf61be904f 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/BasicTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/BasicTests.g.cs @@ -4,178 +4,178 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class BasicTests : LinkerTestBase - { - - protected override string TestSuiteName => "Basic"; - - [Fact] - public Task ComplexNestedClassesHasUnusedRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DelegateBeginInvokeEndInvokePair () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InitializerForArrayIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InstantiatedTypeWithOverridesFromObject () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceMethodImplementedOnBaseClassDoesNotGetStripped () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task LinkerHandlesRefFields () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MultiLevelNestedClassesAllRemovedWhenNonUsed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NestedDelegateInvokeMethodsPreserved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NeverInstantiatedTypeWithOverridesFromObject () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UninvokedInterfaceMemberGetsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedClassGetsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedDelegateGetsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedEnumGetsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedEventGetsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedFieldGetsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedFieldsOfStructsAreKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedMethodGetsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedNestedClassGetsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedPropertyGetsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedPropertySetterRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedEnumIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedEventIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedEventOnInterfaceIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedEventOnInterfaceIsRemovedWhenUsedFromClass () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedGenericInterfaceIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedInterfaceIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedPropertyIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedStructIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class BasicTests : LinkerTestBase + { + + protected override string TestSuiteName => "Basic"; + + [Fact] + public Task ComplexNestedClassesHasUnusedRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DelegateBeginInvokeEndInvokePair() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InitializerForArrayIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InstantiatedTypeWithOverridesFromObject() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceMethodImplementedOnBaseClassDoesNotGetStripped() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task LinkerHandlesRefFields() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MultiLevelNestedClassesAllRemovedWhenNonUsed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NestedDelegateInvokeMethodsPreserved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NeverInstantiatedTypeWithOverridesFromObject() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UninvokedInterfaceMemberGetsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedClassGetsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedDelegateGetsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedEnumGetsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedEventGetsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedFieldGetsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedFieldsOfStructsAreKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedMethodGetsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedNestedClassGetsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedPropertyGetsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedPropertySetterRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedEnumIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedEventIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedEventOnInterfaceIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedEventOnInterfaceIsRemovedWhenUsedFromClass() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedGenericInterfaceIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedInterfaceIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedPropertyIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedStructIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CodegenAnnotationTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CodegenAnnotationTests.g.cs index 46bf2126ad7fd4..c253b855f99cb6 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CodegenAnnotationTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CodegenAnnotationTests.g.cs @@ -4,16 +4,16 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class CodegenAnnotationTests : LinkerTestBase - { + public sealed partial class CodegenAnnotationTests : LinkerTestBase + { - protected override string TestSuiteName => "CodegenAnnotation"; + protected override string TestSuiteName => "CodegenAnnotation"; - [Fact] - public Task ReflectionBlockedTest () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task ReflectionBlockedTest() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CommandLine.MvidTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CommandLine.MvidTests.g.cs index 8236d814f1b6b6..2b5dfbefe86d09 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CommandLine.MvidTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CommandLine.MvidTests.g.cs @@ -4,34 +4,34 @@ namespace ILLink.RoslynAnalyzer.Tests.CommandLine { - public sealed partial class MvidTests : LinkerTestBase - { + public sealed partial class MvidTests : LinkerTestBase + { - protected override string TestSuiteName => "CommandLine.Mvid"; + protected override string TestSuiteName => "CommandLine.Mvid"; - [Fact] - public Task DefaultMvidBehavior () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task DefaultMvidBehavior() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task DeterministicMvidWorks () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task DeterministicMvidWorks() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task NewMvidWorks () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task NewMvidWorks() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task RetainMvid () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task RetainMvid() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CommandLineTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CommandLineTests.g.cs index 8e11b1a6ccaf24..3b312a92cd329a 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CommandLineTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CommandLineTests.g.cs @@ -4,46 +4,46 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class CommandLineTests : LinkerTestBase - { - - protected override string TestSuiteName => "CommandLine"; - - [Fact] - public Task AddCustomStep () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CustomStepApplyPreserve () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CustomStepData () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DuplicateRootAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InvalidArguments () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ResponseFilesWork () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class CommandLineTests : LinkerTestBase + { + + protected override string TestSuiteName => "CommandLine"; + + [Fact] + public Task AddCustomStep() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CustomStepApplyPreserve() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CustomStepData() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DuplicateRootAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InvalidArguments() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ResponseFilesWork() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ComponentModelTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ComponentModelTests.g.cs index 41dce7a9349ac1..23d36e5ce40ebd 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ComponentModelTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ComponentModelTests.g.cs @@ -4,28 +4,28 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class ComponentModelTests : LinkerTestBase - { + public sealed partial class ComponentModelTests : LinkerTestBase + { - protected override string TestSuiteName => "ComponentModel"; + protected override string TestSuiteName => "ComponentModel"; - [Fact] - public Task CustomTypeConvertor () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CustomTypeConvertor() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task TypeConverterOnMembers () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task TypeConverterOnMembers() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task TypeDescriptionProviderAttributeOnType () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task TypeDescriptionProviderAttributeOnType() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CoreLinkTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CoreLinkTests.g.cs index 06270991798430..310074052e0217 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CoreLinkTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CoreLinkTests.g.cs @@ -4,76 +4,76 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class CoreLinkTests : LinkerTestBase - { + public sealed partial class CoreLinkTests : LinkerTestBase + { - protected override string TestSuiteName => "CoreLink"; + protected override string TestSuiteName => "CoreLink"; - [Fact] - public Task CanOverrideIsTrimmableAttribute () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CanOverrideIsTrimmableAttribute() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task CanUseIsTrimmableAttribute () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CanUseIsTrimmableAttribute() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task CopyOfCoreLibrariesKeepsUnusedTypes () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CopyOfCoreLibrariesKeepsUnusedTypes() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task DelegateAndMulticastDelegateKeepInstantiatedReqs () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task DelegateAndMulticastDelegateKeepInstantiatedReqs() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task InstantiatedStructWithOverridesFromObject () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task InstantiatedStructWithOverridesFromObject() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task InstantiatedTypeWithOverridesFromObject () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task InstantiatedTypeWithOverridesFromObject() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task InvalidIsTrimmableAttribute () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task InvalidIsTrimmableAttribute() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task LinkingOfCoreLibrariesRemovesUnusedMethods () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task LinkingOfCoreLibrariesRemovesUnusedMethods() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task LinkingOfCoreLibrariesRemovesUnusedTypes () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task LinkingOfCoreLibrariesRemovesUnusedTypes() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task NeverInstantiatedTypeWithOverridesFromObject () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task NeverInstantiatedTypeWithOverridesFromObject() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task NoSecurityPlusOnlyKeepUsedRemovesAllSecurityAttributesFromCoreLibraries () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task NoSecurityPlusOnlyKeepUsedRemovesAllSecurityAttributesFromCoreLibraries() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CppCLITests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CppCLITests.g.cs index fd89497c6f13d1..4cd63bdf285736 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CppCLITests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/CppCLITests.g.cs @@ -4,22 +4,22 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class CppCLITests : LinkerTestBase - { + public sealed partial class CppCLITests : LinkerTestBase + { - protected override string TestSuiteName => "CppCLI"; + protected override string TestSuiteName => "CppCLI"; - [Fact] - public Task CppCLIAssemblyIsAnalyzed () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CppCLIAssemblyIsAnalyzed() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task NonCopyActionWarnOnCppCLI () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task NonCopyActionWarnOnCppCLI() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/DataFlowTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/DataFlowTests.g.cs index a50e4dfd16075e..dc1ff8cb67c8ea 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/DataFlowTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/DataFlowTests.g.cs @@ -4,56 +4,56 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class DataFlowTests : LinkerTestBase - { - - [Fact] - public Task ExponentialDataFlow () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericParameterDataFlowMarking () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceImplementedThroughBaseValidation () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MethodByRefParameterDataFlow () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ModifierDataFlow () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task StaticInterfaceMethodDataflow () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task TypeInfoIntrinsics () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnsafeDataFlow () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class DataFlowTests : LinkerTestBase + { + + [Fact] + public Task ExponentialDataFlow() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericParameterDataFlowMarking() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceImplementedThroughBaseValidation() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MethodByRefParameterDataFlow() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ModifierDataFlow() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task StaticInterfaceMethodDataflow() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task TypeInfoIntrinsics() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnsafeDataFlow() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/DynamicDependenciesTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/DynamicDependenciesTests.g.cs index 0f707a45ec06a5..89fdfaa11820ca 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/DynamicDependenciesTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/DynamicDependenciesTests.g.cs @@ -4,118 +4,118 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class DynamicDependenciesTests : LinkerTestBase - { - - protected override string TestSuiteName => "DynamicDependencies"; - - [Fact] - public Task DynamicDependencyField () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyFromAttributeXml () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyFromAttributeXmlOnNonReferencedAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyFromCopiedAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyKeptOption () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyMemberSignatureWildcard () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyMemberTypes () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyMethodInAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyMethodInNonReferencedAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyMethodInNonReferencedAssemblyChained () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyMethodInNonReferencedAssemblyChainedReference () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyMethodInNonReferencedAssemblyWithEmbeddedXml () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyMethodInNonReferencedAssemblyWithSweptReferences () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyOnForwardedType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyOnUnusedMethodInNonReferencedAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyOnUnusedMethodInNonReferencedAssemblyWithCopyUsedAction () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyOnUnusedMethodInNonReferencedAssemblyWithEmbeddedXml () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class DynamicDependenciesTests : LinkerTestBase + { + + protected override string TestSuiteName => "DynamicDependencies"; + + [Fact] + public Task DynamicDependencyField() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyFromAttributeXml() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyFromAttributeXmlOnNonReferencedAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyFromCopiedAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyKeptOption() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyMemberSignatureWildcard() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyMemberTypes() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyMethodInAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyMethodInNonReferencedAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyMethodInNonReferencedAssemblyChained() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyMethodInNonReferencedAssemblyChainedReference() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyMethodInNonReferencedAssemblyWithEmbeddedXml() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyMethodInNonReferencedAssemblyWithSweptReferences() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyOnForwardedType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyOnUnusedMethodInNonReferencedAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyOnUnusedMethodInNonReferencedAssemblyWithCopyUsedAction() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyOnUnusedMethodInNonReferencedAssemblyWithEmbeddedXml() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ExtensibilityTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ExtensibilityTests.g.cs index cd8ff52be10b30..259478c47f4011 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ExtensibilityTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ExtensibilityTests.g.cs @@ -4,70 +4,70 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class ExtensibilityTests : LinkerTestBase - { + public sealed partial class ExtensibilityTests : LinkerTestBase + { - protected override string TestSuiteName => "Extensibility"; + protected override string TestSuiteName => "Extensibility"; - [Fact] - public Task CustomStepCanFixAbstractMethods () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CustomStepCanFixAbstractMethods() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task CustomStepCanPreserveMethodsAfterMark () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CustomStepCanPreserveMethodsAfterMark() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task CustomStepCanPreserveMethodsBeforeMark () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CustomStepCanPreserveMethodsBeforeMark() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task CustomStepCanResolveTypesAfterSweep () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CustomStepCanResolveTypesAfterSweep() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task CustomStepsCanShareState () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CustomStepsCanShareState() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task CustomWarningUsage () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CustomWarningUsage() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task MarkHandlerUsage () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task MarkHandlerUsage() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task MarkSubStepsDispatcherUsage () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task MarkSubStepsDispatcherUsage() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task SubStepDispatcherFields () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task SubStepDispatcherFields() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task SubStepDispatcherUsage () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task SubStepDispatcherUsage() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/FeatureSettingsTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/FeatureSettingsTests.g.cs index c381e22ffb3365..1ba066973bf6d9 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/FeatureSettingsTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/FeatureSettingsTests.g.cs @@ -4,34 +4,34 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class FeatureSettingsTests : LinkerTestBase - { + public sealed partial class FeatureSettingsTests : LinkerTestBase + { - protected override string TestSuiteName => "FeatureSettings"; + protected override string TestSuiteName => "FeatureSettings"; - [Fact] - public Task FeatureDescriptors () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task FeatureDescriptors() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task FeatureSubstitutions () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task FeatureSubstitutions() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task FeatureSubstitutionsInvalid () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task FeatureSubstitutionsInvalid() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task FeatureSubstitutionsNested () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task FeatureSubstitutionsNested() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/FunctionPointersTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/FunctionPointersTests.g.cs index 37dc04ddb8c4fd..c8ae211cee4d21 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/FunctionPointersTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/FunctionPointersTests.g.cs @@ -4,22 +4,22 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class FunctionPointersTests : LinkerTestBase - { + public sealed partial class FunctionPointersTests : LinkerTestBase + { - protected override string TestSuiteName => "FunctionPointers"; + protected override string TestSuiteName => "FunctionPointers"; - [Fact] - public Task CanCompileInterfaceWithFunctionPointerParameter () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CanCompileInterfaceWithFunctionPointerParameter() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task CanCompileMethodWithFunctionPointerParameter () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CanCompileMethodWithFunctionPointerParameter() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/GenericsTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/GenericsTests.g.cs index 373e72a087b5f7..065c4b9bb96b60 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/GenericsTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/GenericsTests.g.cs @@ -4,104 +4,104 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class GenericsTests : LinkerTestBase - { - - [Fact] - public Task ArrayVariantCasting () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ByRefLike () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CorrectOverloadedMethodGetsStrippedInGenericClass () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DerivedClassWithMethodOfSameNameAsBaseButDifferentNumberOfGenericParametersUnusedBaseWillGetStripped () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInstanceInterfaceMethodImplementedWithDifferentGenericArgumentNameDoesNotGetStripped () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MdArrayVariantCasting () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MethodWithParameterWhichHasGenericParametersAndOverrideUsesADifferentNameForGenericParameter () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MethodWithParameterWhichHasGenericParametersAndOverrideUsesADifferentNameForGenericParameterNestedCase () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MethodWithParameterWhichHasGenericParametersAndOverrideUsesADifferentNameForGenericParameterNestedCase2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NewConstraintOnClass () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OverrideWithAnotherVirtualMethodOfSameNameWithDifferentParameterType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnresolvedGenerics () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedOverloadedGenericMethodInGenericClassIsNotStripped () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedOverloadedGenericMethodInstanceInGenericClassIsNotStripped () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedOverloadedGenericMethodWithNoParametersIsNotStripped () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task VariantCasting () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class GenericsTests : LinkerTestBase + { + + [Fact] + public Task ArrayVariantCasting() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ByRefLike() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CorrectOverloadedMethodGetsStrippedInGenericClass() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DerivedClassWithMethodOfSameNameAsBaseButDifferentNumberOfGenericParametersUnusedBaseWillGetStripped() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInstanceInterfaceMethodImplementedWithDifferentGenericArgumentNameDoesNotGetStripped() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MdArrayVariantCasting() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MethodWithParameterWhichHasGenericParametersAndOverrideUsesADifferentNameForGenericParameter() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MethodWithParameterWhichHasGenericParametersAndOverrideUsesADifferentNameForGenericParameterNestedCase() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MethodWithParameterWhichHasGenericParametersAndOverrideUsesADifferentNameForGenericParameterNestedCase2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NewConstraintOnClass() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OverrideWithAnotherVirtualMethodOfSameNameWithDifferentParameterType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnresolvedGenerics() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedOverloadedGenericMethodInGenericClassIsNotStripped() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedOverloadedGenericMethodInstanceInGenericClassIsNotStripped() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedOverloadedGenericMethodWithNoParametersIsNotStripped() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task VariantCasting() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.AbstractClasses.NoKeptCtor.OverrideRemovalTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.AbstractClasses.NoKeptCtor.OverrideRemovalTests.g.cs index 5a63e7af55e7f8..021323244f6e5a 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.AbstractClasses.NoKeptCtor.OverrideRemovalTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.AbstractClasses.NoKeptCtor.OverrideRemovalTests.g.cs @@ -4,64 +4,64 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance.AbstractClasses.NoKeptCtor { - public sealed partial class OverrideRemovalTests : LinkerTestBase - { + public sealed partial class OverrideRemovalTests : LinkerTestBase + { - protected override string TestSuiteName => "Inheritance.AbstractClasses.NoKeptCtor.OverrideRemoval"; + protected override string TestSuiteName => "Inheritance.AbstractClasses.NoKeptCtor.OverrideRemoval"; - [Fact] - public Task CanDisableOverrideRemoval () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CanDisableOverrideRemoval() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task OverrideOfAbstractIsKept () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task OverrideOfAbstractIsKept() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task OverrideOfAbstractIsKeptNonEmpty () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task OverrideOfAbstractIsKeptNonEmpty() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task OverrideOfVirtualCanBeRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task OverrideOfVirtualCanBeRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task OverrideOfVirtualCanBeRemoved2 () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task OverrideOfVirtualCanBeRemoved2() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task OverrideOfVirtualCanBeRemoved3 () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task OverrideOfVirtualCanBeRemoved3() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task OverrideThatAlsoFulfilsInterface () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task OverrideThatAlsoFulfilsInterface() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task PreservesOverriddenMethodOverrideOfUsedVirtualStillRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task PreservesOverriddenMethodOverrideOfUsedVirtualStillRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task PreservesOverriddenMethodOverrideOfUsedVirtualStillRemoved2 () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task PreservesOverriddenMethodOverrideOfUsedVirtualStillRemoved2() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.AbstractClasses.NotKeptCtorTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.AbstractClasses.NotKeptCtorTests.g.cs index 7b3464d10f4d26..0667abb1ed7714 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.AbstractClasses.NotKeptCtorTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.AbstractClasses.NotKeptCtorTests.g.cs @@ -4,46 +4,46 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance.AbstractClasses { - public sealed partial class NotKeptCtorTests : LinkerTestBase - { - - protected override string TestSuiteName => "Inheritance.AbstractClasses.NotKeptCtor"; - - [Fact] - public Task NeverInstantiatedTypeWithBaseInCopiedAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NeverInstantiatedTypeWithBaseInCopiedAssembly2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NeverInstantiatedTypeWithBaseInCopiedAssembly3 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NeverInstantiatedTypeWithBaseInCopiedAssembly4 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NeverInstantiatedTypeWithBaseInCopiedAssembly5 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NeverInstantiatedTypeWithBaseInCopiedAssembly6 () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class NotKeptCtorTests : LinkerTestBase + { + + protected override string TestSuiteName => "Inheritance.AbstractClasses.NotKeptCtor"; + + [Fact] + public Task NeverInstantiatedTypeWithBaseInCopiedAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NeverInstantiatedTypeWithBaseInCopiedAssembly2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NeverInstantiatedTypeWithBaseInCopiedAssembly3() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NeverInstantiatedTypeWithBaseInCopiedAssembly4() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NeverInstantiatedTypeWithBaseInCopiedAssembly5() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NeverInstantiatedTypeWithBaseInCopiedAssembly6() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.AbstractClassesTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.AbstractClassesTests.g.cs index 0c5c86f4eb06b4..c40e82652c95ec 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.AbstractClassesTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.AbstractClassesTests.g.cs @@ -4,70 +4,70 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance { - public sealed partial class AbstractClassesTests : LinkerTestBase - { + public sealed partial class AbstractClassesTests : LinkerTestBase + { - protected override string TestSuiteName => "Inheritance.AbstractClasses"; + protected override string TestSuiteName => "Inheritance.AbstractClasses"; - [Fact] - public Task TypeWithBaseInCopiedAssembly () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task TypeWithBaseInCopiedAssembly() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task TypeWithBaseInCopiedAssembly2 () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task TypeWithBaseInCopiedAssembly2() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task TypeWithBaseInCopiedAssembly3 () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task TypeWithBaseInCopiedAssembly3() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task TypeWithBaseInCopiedAssembly4 () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task TypeWithBaseInCopiedAssembly4() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task TypeWithBaseInCopiedAssembly5 () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task TypeWithBaseInCopiedAssembly5() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task TypeWithBaseInCopiedAssembly6 () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task TypeWithBaseInCopiedAssembly6() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UnusedAbstractMethodRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UnusedAbstractMethodRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UnusedVirtualMethodRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UnusedVirtualMethodRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UsedOverrideOfAbstractMethodIsKept () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UsedOverrideOfAbstractMethodIsKept() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UsedOverrideOfVirtualMethodIsKept () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UsedOverrideOfVirtualMethodIsKept() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Complex.NoKeptCtorTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Complex.NoKeptCtorTests.g.cs index 17bde96cc57041..d806d6b9648598 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Complex.NoKeptCtorTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Complex.NoKeptCtorTests.g.cs @@ -4,22 +4,22 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance.Complex { - public sealed partial class NoKeptCtorTests : LinkerTestBase - { + public sealed partial class NoKeptCtorTests : LinkerTestBase + { - protected override string TestSuiteName => "Inheritance.Complex.NoKeptCtor"; + protected override string TestSuiteName => "Inheritance.Complex.NoKeptCtor"; - [Fact] - public Task OverrideOfAbstractAndInterfaceMethodWhenInterfaceRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task OverrideOfAbstractAndInterfaceMethodWhenInterfaceRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task OverrideOfAbstractAndInterfaceMethodWhenInterfaceRemoved2 () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task OverrideOfAbstractAndInterfaceMethodWhenInterfaceRemoved2() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.BaseProvidesInterfaceEdgeCaseTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.BaseProvidesInterfaceEdgeCaseTests.g.cs index 541aeee031dedd..ce9e82a81c242a 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.BaseProvidesInterfaceEdgeCaseTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.BaseProvidesInterfaceEdgeCaseTests.g.cs @@ -4,16 +4,16 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance.Interfaces { - public sealed partial class BaseProvidesInterfaceEdgeCaseTests : LinkerTestBase - { + public sealed partial class BaseProvidesInterfaceEdgeCaseTests : LinkerTestBase + { - protected override string TestSuiteName => "Inheritance.Interfaces.BaseProvidesInterfaceEdgeCase"; + protected override string TestSuiteName => "Inheritance.Interfaces.BaseProvidesInterfaceEdgeCase"; - [Fact] - public Task BaseProvidesInterfaceMethodCircularReference () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task BaseProvidesInterfaceMethodCircularReference() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.DefaultInterfaceMethodsTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.DefaultInterfaceMethodsTests.g.cs index 19189bfcd01705..b12c24c773c6d1 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.DefaultInterfaceMethodsTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.DefaultInterfaceMethodsTests.g.cs @@ -4,76 +4,76 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance.Interfaces { - public sealed partial class DefaultInterfaceMethodsTests : LinkerTestBase - { + public sealed partial class DefaultInterfaceMethodsTests : LinkerTestBase + { - protected override string TestSuiteName => "Inheritance.Interfaces.DefaultInterfaceMethods"; + protected override string TestSuiteName => "Inheritance.Interfaces.DefaultInterfaceMethods"; - [Fact] - public Task DefaultInterfaceMethodCallIntoClass () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task DefaultInterfaceMethodCallIntoClass() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task DimProvidedByRecursiveInterface () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task DimProvidedByRecursiveInterface() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task GenericDefaultInterfaceMethods () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task GenericDefaultInterfaceMethods() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task InterfaceWithAttributeOnImplementation () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task InterfaceWithAttributeOnImplementation() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task MostSpecificDefaultImplementationKeptInstance () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task MostSpecificDefaultImplementationKeptInstance() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task MostSpecificDefaultImplementationKeptStatic () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task MostSpecificDefaultImplementationKeptStatic() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task MultipleDimsProvidedByRecursiveInterface () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task MultipleDimsProvidedByRecursiveInterface() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task SimpleDefaultInterfaceMethod () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task SimpleDefaultInterfaceMethod() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task StaticDefaultInterfaceMethodOnStruct () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task StaticDefaultInterfaceMethodOnStruct() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task StaticDimProvidedByUnreferencedIfaceInHierarchy () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task StaticDimProvidedByUnreferencedIfaceInHierarchy() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UnusedDefaultInterfaceImplementation () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UnusedDefaultInterfaceImplementation() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.BaseProvidesInterfaceMemberTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.BaseProvidesInterfaceMemberTests.g.cs index 80d525848b2153..56cb79b535609c 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.BaseProvidesInterfaceMemberTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.BaseProvidesInterfaceMemberTests.g.cs @@ -4,184 +4,184 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance.Interfaces.OnReferenceType { - public sealed partial class BaseProvidesInterfaceMemberTests : LinkerTestBase - { - - protected override string TestSuiteName => "Inheritance.Interfaces.OnReferenceType.BaseProvidesInterfaceMember"; - - [Fact] - public Task GenericInterfaceWithEvent () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithGenericBaseMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithGenericBaseMethodWithExplicit () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithGenericMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithGenericMethod2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithGenericMethod3 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithMethod2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithMethod3 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithMethodComplex () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithMethodComplex2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithMethodManyBaseInterfaces () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithMethodManyBases () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithMethodManyBases2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithMethodManyBases3 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithMethodManyVariations () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithMethodNested () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithMethodOnNoInstanceCtor () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithMethodOnNoInstanceCtor2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithPropertyGetter () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithPropertyGetter2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithPropertySetter () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericInterfaceWithPropertySetter2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceRemovedWhenMethodUsedDirectly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SimpleEvent () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SimpleMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SimpleMethodOnNoInstanceCtor () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SimpleMethodOnNoInstanceCtor2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SimpleProperty () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class BaseProvidesInterfaceMemberTests : LinkerTestBase + { + + protected override string TestSuiteName => "Inheritance.Interfaces.OnReferenceType.BaseProvidesInterfaceMember"; + + [Fact] + public Task GenericInterfaceWithEvent() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithGenericBaseMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithGenericBaseMethodWithExplicit() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithGenericMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithGenericMethod2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithGenericMethod3() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithMethod2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithMethod3() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithMethodComplex() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithMethodComplex2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithMethodManyBaseInterfaces() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithMethodManyBases() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithMethodManyBases2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithMethodManyBases3() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithMethodManyVariations() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithMethodNested() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithMethodOnNoInstanceCtor() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithMethodOnNoInstanceCtor2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithPropertyGetter() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithPropertyGetter2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithPropertySetter() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericInterfaceWithPropertySetter2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceRemovedWhenMethodUsedDirectly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SimpleEvent() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SimpleMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SimpleMethodOnNoInstanceCtor() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SimpleMethodOnNoInstanceCtor2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SimpleProperty() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.NoInstanceCtorTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.NoInstanceCtorTests.g.cs index c363a76e7abce9..c245d2a0a06c6f 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.NoInstanceCtorTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.NoInstanceCtorTests.g.cs @@ -4,52 +4,52 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance.Interfaces.OnReferenceType { - public sealed partial class NoInstanceCtorTests : LinkerTestBase - { - - protected override string TestSuiteName => "Inheritance.Interfaces.OnReferenceType.NoInstanceCtor"; - - [Fact] - public Task NoInstanceCtorAndAssemblyPreserveAll () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NoInstanceCtorAndTypePreserveAll () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NoInstanceCtorAndTypePreserveFields () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NoInstanceCtorAndTypePreserveFieldsWithInterfacesMarked () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NoInstanceCtorAndTypePreserveMethods () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NoInstanceCtorAndTypePreserveMethodsWithInterfacesMarked () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NoInstanceCtorAndTypePreserveNone () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class NoInstanceCtorTests : LinkerTestBase + { + + protected override string TestSuiteName => "Inheritance.Interfaces.OnReferenceType.NoInstanceCtor"; + + [Fact] + public Task NoInstanceCtorAndAssemblyPreserveAll() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NoInstanceCtorAndTypePreserveAll() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NoInstanceCtorAndTypePreserveFields() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NoInstanceCtorAndTypePreserveFieldsWithInterfacesMarked() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NoInstanceCtorAndTypePreserveMethods() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NoInstanceCtorAndTypePreserveMethodsWithInterfacesMarked() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NoInstanceCtorAndTypePreserveNone() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.NoKeptCtorButInterfaceNeededTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.NoKeptCtorButInterfaceNeededTests.g.cs index 92418533bf13db..664f3d06fb2f5c 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.NoKeptCtorButInterfaceNeededTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.NoKeptCtorButInterfaceNeededTests.g.cs @@ -4,148 +4,148 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance.Interfaces.OnReferenceType { - public sealed partial class NoKeptCtorButInterfaceNeededTests : LinkerTestBase - { - - protected override string TestSuiteName => "Inheritance.Interfaces.OnReferenceType.NoKeptCtorButInterfaceNeeded"; - - [Fact] - public Task ArrayWithIndexAssignedToReturnValue () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task FieldDowncastedToInterface () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericTypeWithConstraint () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericTypeWithConstraint2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericTypeWithConstraint3 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceOnMultipleBases () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task LocalAndNestedInterfaces () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task LocalArrayPassedAsParameter () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task LocalDowncastedToInterface () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task LocalPassedAsParameter () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task LocalPassedAsParameterToGeneric () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task LocalPassedAsParameterToGenericWithConstraint () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task LocalPassedAsParameterToGenericWithConstraint2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NestedInterfaces1 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NestedInterfaces2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NestedInterfaces3 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NestedInterfacesWithExplicit1 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NestedInterfacesWithExplicitAndNormal1 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ParameterAndLocal () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ParameterOutAndLocal () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ParameterRefAndLocal () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReturnValueDowncastedToInterface () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class NoKeptCtorButInterfaceNeededTests : LinkerTestBase + { + + protected override string TestSuiteName => "Inheritance.Interfaces.OnReferenceType.NoKeptCtorButInterfaceNeeded"; + + [Fact] + public Task ArrayWithIndexAssignedToReturnValue() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task FieldDowncastedToInterface() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericTypeWithConstraint() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericTypeWithConstraint2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericTypeWithConstraint3() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceOnMultipleBases() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task LocalAndNestedInterfaces() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task LocalArrayPassedAsParameter() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task LocalDowncastedToInterface() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task LocalPassedAsParameter() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task LocalPassedAsParameterToGeneric() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task LocalPassedAsParameterToGenericWithConstraint() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task LocalPassedAsParameterToGenericWithConstraint2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NestedInterfaces1() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NestedInterfaces2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NestedInterfaces3() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NestedInterfacesWithExplicit1() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NestedInterfacesWithExplicitAndNormal1() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ParameterAndLocal() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ParameterOutAndLocal() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ParameterRefAndLocal() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReturnValueDowncastedToInterface() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.NoKeptCtorTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.NoKeptCtorTests.g.cs index 042e0d0fa1ecdf..164840d835d7c4 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.NoKeptCtorTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceType.NoKeptCtorTests.g.cs @@ -4,124 +4,124 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance.Interfaces.OnReferenceType { - public sealed partial class NoKeptCtorTests : LinkerTestBase - { - - protected override string TestSuiteName => "Inheritance.Interfaces.OnReferenceType.NoKeptCtor"; - - [Fact] - public Task ComInterfaceTypeRemovedWhenOnlyUsedByClassWithOnlyStaticMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DynamicDependencyPreservesInterfaceMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ExplicitInterfaceCanBeRemovedFromClassWithOnlyStaticMethodUsed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task GenericWithConstraintDoesNotCauseOtherTypesToKeepInterface () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceCanBeRemovedFromClassWithOnlyStaticMethodUsed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceCanBeRemovedFromClassWithOnlyStaticMethodUsedWithCctor () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceFromCopiedAssemblyCanBeRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceTypeRemovedWhenOnlyUsedByClassWithOnlyStaticMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceTypeRemovedWhenOnlyUsedByClassWithOnlyStaticMethodMultiple () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task LocalDowncastDoesNotCuaseOtherTypesToKeepInterface () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ObjectHardCastedToInterface () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveDependencyPreservesInterfaceMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypeHasExplicitInterfaceMethodPreservedViaXml () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypeHasExplicitInterfacePropertyPreservedViaXml () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypeHasInterfaceMethodPreservedViaXml () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypeWithPreserveFields () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypeWithPreserveMethods () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypeWithPreserveMethodsAndInterfaceTypeMarked () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class NoKeptCtorTests : LinkerTestBase + { + + protected override string TestSuiteName => "Inheritance.Interfaces.OnReferenceType.NoKeptCtor"; + + [Fact] + public Task ComInterfaceTypeRemovedWhenOnlyUsedByClassWithOnlyStaticMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DynamicDependencyPreservesInterfaceMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ExplicitInterfaceCanBeRemovedFromClassWithOnlyStaticMethodUsed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task GenericWithConstraintDoesNotCauseOtherTypesToKeepInterface() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceCanBeRemovedFromClassWithOnlyStaticMethodUsed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceCanBeRemovedFromClassWithOnlyStaticMethodUsedWithCctor() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceFromCopiedAssemblyCanBeRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceTypeRemovedWhenOnlyUsedByClassWithOnlyStaticMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceTypeRemovedWhenOnlyUsedByClassWithOnlyStaticMethodMultiple() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task LocalDowncastDoesNotCuaseOtherTypesToKeepInterface() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ObjectHardCastedToInterface() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveDependencyPreservesInterfaceMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypeHasExplicitInterfaceMethodPreservedViaXml() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypeHasExplicitInterfacePropertyPreservedViaXml() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypeHasInterfaceMethodPreservedViaXml() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypeWithPreserveFields() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypeWithPreserveMethods() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypeWithPreserveMethodsAndInterfaceTypeMarked() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceTypeTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceTypeTests.g.cs index d87fcc06d688fe..1d09a7c1895c5a 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceTypeTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnReferenceTypeTests.g.cs @@ -4,184 +4,184 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance.Interfaces { - public sealed partial class OnReferenceTypeTests : LinkerTestBase - { - - protected override string TestSuiteName => "Inheritance.Interfaces.OnReferenceType"; - - [Fact] - public Task ClassImplementingInterfaceMethodsNested () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ClassImplementingInterfaceMethodsNested2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ClassImplemtingInterfaceMethodsThroughBaseClass2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ClassImplemtingInterfaceMethodsThroughBaseClass3 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ClassImplemtingInterfaceMethodsThroughBaseClass4 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ClassImplemtingInterfaceMethodsThroughBaseClass5 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ClassImplemtingInterfaceMethodsThroughBaseClass6 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ClassUsedFromConcreteTypeHasInterfaceMethodRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ClassUsedFromConcreteTypeHasInterfaceMethodRemoved2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ClassUsedFromInterfaceHasInterfaceMethodKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ExplicitInterfaceMethodWhichCreatesInstanceOfParentType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceMarkOrderingDoesNotMatter () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceMarkOrderingDoesNotMatter2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceMarkOrderingDoesNotMatter3 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceNeededOnUnrelatedInterfaceList () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceTypeInOtherUsedOnlyByCopiedAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceTypeInOtherUsedOnlyByCopiedAssemblyExplicit () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceTypeOnlyUsedHasInterfacesRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceUsedOnlyAsConstraintIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceWithInterfaceFromOtherAssemblyWhenExplicitMethodUsed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ObjectCastedToSecondInterfaceHasMemberRemovedButInterfaceKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task TypeGetsMarkedThatImplementsAlreadyMarkedInterfaceMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedComInterfaceIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedComInterfaceIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedExplicitInterfaceHasMethodPreservedViaXml () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedExplicitInterfaceIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedGenericInterfaceIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedInterfaceHasMethodPreservedViaXml () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedInterfaceTypeIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class OnReferenceTypeTests : LinkerTestBase + { + + protected override string TestSuiteName => "Inheritance.Interfaces.OnReferenceType"; + + [Fact] + public Task ClassImplementingInterfaceMethodsNested() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ClassImplementingInterfaceMethodsNested2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ClassImplemtingInterfaceMethodsThroughBaseClass2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ClassImplemtingInterfaceMethodsThroughBaseClass3() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ClassImplemtingInterfaceMethodsThroughBaseClass4() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ClassImplemtingInterfaceMethodsThroughBaseClass5() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ClassImplemtingInterfaceMethodsThroughBaseClass6() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ClassUsedFromConcreteTypeHasInterfaceMethodRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ClassUsedFromConcreteTypeHasInterfaceMethodRemoved2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ClassUsedFromInterfaceHasInterfaceMethodKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ExplicitInterfaceMethodWhichCreatesInstanceOfParentType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceMarkOrderingDoesNotMatter() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceMarkOrderingDoesNotMatter2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceMarkOrderingDoesNotMatter3() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceNeededOnUnrelatedInterfaceList() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceTypeInOtherUsedOnlyByCopiedAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceTypeInOtherUsedOnlyByCopiedAssemblyExplicit() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceTypeOnlyUsedHasInterfacesRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceUsedOnlyAsConstraintIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceWithInterfaceFromOtherAssemblyWhenExplicitMethodUsed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ObjectCastedToSecondInterfaceHasMemberRemovedButInterfaceKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task TypeGetsMarkedThatImplementsAlreadyMarkedInterfaceMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedComInterfaceIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedComInterfaceIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedExplicitInterfaceHasMethodPreservedViaXml() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedExplicitInterfaceIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedGenericInterfaceIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedInterfaceHasMethodPreservedViaXml() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedInterfaceTypeIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnValueType.NoKeptCtorTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnValueType.NoKeptCtorTests.g.cs index fc3a399179e487..df5a3bf3301475 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnValueType.NoKeptCtorTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnValueType.NoKeptCtorTests.g.cs @@ -4,34 +4,34 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance.Interfaces.OnValueType { - public sealed partial class NoKeptCtorTests : LinkerTestBase - { + public sealed partial class NoKeptCtorTests : LinkerTestBase + { - protected override string TestSuiteName => "Inheritance.Interfaces.OnValueType.NoKeptCtor"; + protected override string TestSuiteName => "Inheritance.Interfaces.OnValueType.NoKeptCtor"; - [Fact] - public Task InterfaceCanBeRemovedFromClassWithOnlyStaticMethodUsed () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task InterfaceCanBeRemovedFromClassWithOnlyStaticMethodUsed() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task InterfaceCanBeRemovedFromClassWithOnlyStaticMethodUsedWithCctor () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task InterfaceCanBeRemovedFromClassWithOnlyStaticMethodUsedWithCctor() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task InterfaceTypeRemovedWhenOnlyUsedByClassWithOnlyStaticMethod () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task InterfaceTypeRemovedWhenOnlyUsedByClassWithOnlyStaticMethod() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task InterfaceTypeRemovedWhenOnlyUsedByClassWithOnlyStaticMethodMultiple () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task InterfaceTypeRemovedWhenOnlyUsedByClassWithOnlyStaticMethodMultiple() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnValueTypeTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnValueTypeTests.g.cs index 6a2d53990c80e1..cbaedf1d6b723d 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnValueTypeTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.OnValueTypeTests.g.cs @@ -4,70 +4,70 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance.Interfaces { - public sealed partial class OnValueTypeTests : LinkerTestBase - { + public sealed partial class OnValueTypeTests : LinkerTestBase + { - protected override string TestSuiteName => "Inheritance.Interfaces.OnValueType"; + protected override string TestSuiteName => "Inheritance.Interfaces.OnValueType"; - [Fact] - public Task StructImplementingInterfaceMethodsNested () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task StructImplementingInterfaceMethodsNested() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task StructImplementingInterfaceMethodsNested2 () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task StructImplementingInterfaceMethodsNested2() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task StructUsedFromConcreteTypeHasInterfaceMethodRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task StructUsedFromConcreteTypeHasInterfaceMethodRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task StructUsedFromConcreteTypeHasInterfaceMethodRemoved2 () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task StructUsedFromConcreteTypeHasInterfaceMethodRemoved2() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task StructUsedFromInterfaceHasInterfaceMethodKept () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task StructUsedFromInterfaceHasInterfaceMethodKept() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task StructWithNestedStructImplementingInterface () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task StructWithNestedStructImplementingInterface() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UnusedExplicitInterfaceHasMethodPreservedViaXml () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UnusedExplicitInterfaceHasMethodPreservedViaXml() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UnusedExplicitInterfaceIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UnusedExplicitInterfaceIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UnusedInterfaceHasMethodPreservedViaXml () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UnusedInterfaceHasMethodPreservedViaXml() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UnusedInterfaceTypeIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UnusedInterfaceTypeIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.RecursiveInterfacesTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.RecursiveInterfacesTests.g.cs index 35cc0b65c0417b..87ef911ccc0b28 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.RecursiveInterfacesTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.RecursiveInterfacesTests.g.cs @@ -4,34 +4,34 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance.Interfaces { - public sealed partial class RecursiveInterfacesTests : LinkerTestBase - { + public sealed partial class RecursiveInterfacesTests : LinkerTestBase + { - protected override string TestSuiteName => "Inheritance.Interfaces.RecursiveInterfaces"; + protected override string TestSuiteName => "Inheritance.Interfaces.RecursiveInterfaces"; - [Fact] - public Task GenericInterfaceImplementedRecursively () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task GenericInterfaceImplementedRecursively() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task InterfaceImplementedRecursively () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task InterfaceImplementedRecursively() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task OverrideOfRecursiveInterfaceIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task OverrideOfRecursiveInterfaceIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task RecursiveInterfaceKept () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task RecursiveInterfaceKept() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.StaticInterfaceMethodsTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.StaticInterfaceMethodsTests.g.cs index 531c0cb0d7d08a..afacf94703e332 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.StaticInterfaceMethodsTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.Interfaces.StaticInterfaceMethodsTests.g.cs @@ -4,32 +4,32 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance.Interfaces { - public sealed partial class StaticInterfaceMethodsTests : LinkerTestBase - { + public sealed partial class StaticInterfaceMethodsTests : LinkerTestBase + { - [Fact] - public Task InstanceMethodsWithOverridesSwept () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task InstanceMethodsWithOverridesSwept() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task OverrideInCopyAssembly () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task OverrideInCopyAssembly() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task OverrideInSaveAssembly () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task OverrideInSaveAssembly() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task VarianceBasic () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task VarianceBasic() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.InterfacesTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.InterfacesTests.g.cs index 07680c1c9d5e6a..7b20f91cb7f566 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.InterfacesTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.InterfacesTests.g.cs @@ -4,46 +4,46 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance { - public sealed partial class InterfacesTests : LinkerTestBase - { - - protected override string TestSuiteName => "Inheritance.Interfaces"; - - [Fact] - public Task CanDisableUnusedInterfaces () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceImplementedThroughBaseInterface () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceOnUninstantiatedTypeRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceVariants () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceVariantsGeneric () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceWithoutNewSlot () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class InterfacesTests : LinkerTestBase + { + + protected override string TestSuiteName => "Inheritance.Interfaces"; + + [Fact] + public Task CanDisableUnusedInterfaces() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceImplementedThroughBaseInterface() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceOnUninstantiatedTypeRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceVariants() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceVariantsGeneric() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceWithoutNewSlot() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.VirtualMethods.NotKeptCtorTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.VirtualMethods.NotKeptCtorTests.g.cs index bf67ff17ef482a..d54a4afa9be4dc 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.VirtualMethods.NotKeptCtorTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.VirtualMethods.NotKeptCtorTests.g.cs @@ -4,16 +4,16 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance.VirtualMethods { - public sealed partial class NotKeptCtorTests : LinkerTestBase - { + public sealed partial class NotKeptCtorTests : LinkerTestBase + { - protected override string TestSuiteName => "Inheritance.VirtualMethods.NotKeptCtor"; + protected override string TestSuiteName => "Inheritance.VirtualMethods.NotKeptCtor"; - [Fact] - public Task NeverInstantiatedTypeWithBaseInCopiedAssembly () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task NeverInstantiatedTypeWithBaseInCopiedAssembly() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.VirtualMethodsTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.VirtualMethodsTests.g.cs index 8a7aab5c61b398..a8371a3f397432 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.VirtualMethodsTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Inheritance.VirtualMethodsTests.g.cs @@ -4,70 +4,70 @@ namespace ILLink.RoslynAnalyzer.Tests.Inheritance { - public sealed partial class VirtualMethodsTests : LinkerTestBase - { + public sealed partial class VirtualMethodsTests : LinkerTestBase + { - protected override string TestSuiteName => "Inheritance.VirtualMethods"; + protected override string TestSuiteName => "Inheritance.VirtualMethods"; - [Fact] - public Task BaseIsInSkipAssembly () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task BaseIsInSkipAssembly() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task HarderToDetectUnusedVirtualMethodGetsRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task HarderToDetectUnusedVirtualMethodGetsRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task NeverInstantiatedTypeWithBaseInCopiedAssembly () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task NeverInstantiatedTypeWithBaseInCopiedAssembly() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task OverrideOfAbstractInUnmarkedClassIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task OverrideOfAbstractInUnmarkedClassIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UnusedTypeWithOverrideOfVirtualMethodIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UnusedTypeWithOverrideOfVirtualMethodIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UnusedVirtualMethodRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UnusedVirtualMethodRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UsedOverrideOfVirtualMethodIsKept () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UsedOverrideOfVirtualMethodIsKept() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UsedTypeWithOverrideOfVirtualMethodHasOverrideKept () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UsedTypeWithOverrideOfVirtualMethodHasOverrideKept() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task VirtualMethodGetsPreservedIfBaseMethodGetsInvoked () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task VirtualMethodGetsPreservedIfBaseMethodGetsInvoked() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task VirtualMethodGetsStrippedIfImplementingMethodGetsInvokedDirectly () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task VirtualMethodGetsStrippedIfImplementingMethodGetsInvokedDirectly() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/InteropTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/InteropTests.g.cs index 7d83d81ef1e3ce..1ec6531b4cc36d 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/InteropTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/InteropTests.g.cs @@ -4,16 +4,16 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class InteropTests : LinkerTestBase - { + public sealed partial class InteropTests : LinkerTestBase + { - protected override string TestSuiteName => "Interop"; + protected override string TestSuiteName => "Interop"; - [Fact] - public Task ByteArrayCom () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task ByteArrayCom() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LibrariesTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LibrariesTests.g.cs index 03c76d0f1ee9de..efb3db6a2cdc4a 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LibrariesTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LibrariesTests.g.cs @@ -4,88 +4,88 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class LibrariesTests : LinkerTestBase - { - - protected override string TestSuiteName => "Libraries"; - - [Fact] - public Task CanLinkPublicApisOfLibrary () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CopyUsedAssemblyWithMainEntryRoot () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CopyUsedAssemblyWithPublicRoots () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DefaultLibraryLinkBehavior () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task LibraryWithUnresolvedInterfaces () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task RootAllLibraryBehavior () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task RootAllLibraryCopyBehavior () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task RootLibrary () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task RootLibraryInternalsWithIVT () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task RootLibraryVisibleAndDescriptor () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task RootLibraryVisibleForwarders () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task RootLibraryVisibleForwardersWithoutReference () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UserAssemblyActionWorks () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class LibrariesTests : LinkerTestBase + { + + protected override string TestSuiteName => "Libraries"; + + [Fact] + public Task CanLinkPublicApisOfLibrary() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CopyUsedAssemblyWithMainEntryRoot() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CopyUsedAssemblyWithPublicRoots() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DefaultLibraryLinkBehavior() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task LibraryWithUnresolvedInterfaces() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task RootAllLibraryBehavior() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task RootAllLibraryCopyBehavior() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task RootLibrary() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task RootLibraryInternalsWithIVT() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task RootLibraryVisibleAndDescriptor() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task RootLibraryVisibleForwarders() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task RootLibraryVisibleForwardersWithoutReference() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UserAssemblyActionWorks() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LinkAttributesTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LinkAttributesTests.g.cs index 909529f78229c3..242a95982f2615 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LinkAttributesTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LinkAttributesTests.g.cs @@ -4,56 +4,56 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class LinkAttributesTests : LinkerTestBase - { - - [Fact] - public Task AssemblyLevelLinkerAttributeRemoval () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task EmbeddedLinkAttributesInReferencedAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task EmbeddedLinkAttributesInReferencedAssembly_AssemblyLevel () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task FeatureAttributeRemovalInCopyAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task LinkAttributeErrorCases () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task LinkerAttributeRemovalAndPreserveAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OverrideAttributeRemoval () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task TypedArgumentsErrors () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class LinkAttributesTests : LinkerTestBase + { + + [Fact] + public Task AssemblyLevelLinkerAttributeRemoval() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task EmbeddedLinkAttributesInReferencedAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task EmbeddedLinkAttributesInReferencedAssembly_AssemblyLevel() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task FeatureAttributeRemovalInCopyAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task LinkAttributeErrorCases() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task LinkerAttributeRemovalAndPreserveAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OverrideAttributeRemoval() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task TypedArgumentsErrors() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LinkXmlTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LinkXmlTests.g.cs index 689072942e5bb0..b0c78fffd489ed 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LinkXmlTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LinkXmlTests.g.cs @@ -4,226 +4,226 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class LinkXmlTests : LinkerTestBase - { - - protected override string TestSuiteName => "LinkXml"; - - [Fact] - public Task AssemblyWithPreserveAll () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanPreserveAnExportedType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanPreserveExportedTypesUsingRegex () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanPreserveNamespace () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanPreserveTypesUsingRegex () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task EmbeddedLinkXmlFromCopyAssemblyIsProcessed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task EmbeddedLinkXmlPreservesAdditionalAssemblyWithOverriddenMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task EmbeddedLinkXmlUnresolvedReferencesAreReported () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task LinkXmlErrorCases () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveIndividualMembersOfNonRequiredType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveSecondLevelMethodsOfNonRequiredType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task TypeWithPreserveFieldsHasBackingFieldsOfPropertiesRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedAssemblyWithNoDefinedPreserveHasAllTypesPreserved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedEventPreservedByLinkXmlIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedFieldPreservedByLinkXmlIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedGenericTypeWithPreserveAllHasAllMembersPreserved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedInterfaceTypeOnTypeWithPreserveAllIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedInterfaceTypeOnTypeWithPreserveNothingIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedMethodPreservedByLinkXmlIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedNestedTypePreservedByLinkXmlIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedNonRequiredTypeIsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedPropertyPreservedByLinkXmlIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypeDeclarationPreservedByLinkXmlIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypeIsPresservedWhenEntireAssemblyIsPreserved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypePreservedByLinkXmlIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypePreservedByLinkXmlWithCommentIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypeWithNoDefinedPreserveHasAllMembersPreserved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypeWithPreserveAllHasAllMembersPreserved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypeWithPreserveFieldsHasMethodsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypeWithPreserveMethodsHasFieldsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypeWithPreserveNothingAndPreserveMembers () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedTypeWithPreserveNothingHasMembersRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedNonRequiredExportedTypeIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedNonRequiredExportedTypeIsKeptWhenRooted () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedNonRequiredTypeIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedNonRequiredTypeIsKeptWithSingleMethod () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class LinkXmlTests : LinkerTestBase + { + + protected override string TestSuiteName => "LinkXml"; + + [Fact] + public Task AssemblyWithPreserveAll() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanPreserveAnExportedType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanPreserveExportedTypesUsingRegex() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanPreserveNamespace() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanPreserveTypesUsingRegex() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task EmbeddedLinkXmlFromCopyAssemblyIsProcessed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task EmbeddedLinkXmlPreservesAdditionalAssemblyWithOverriddenMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task EmbeddedLinkXmlUnresolvedReferencesAreReported() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task LinkXmlErrorCases() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveIndividualMembersOfNonRequiredType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveSecondLevelMethodsOfNonRequiredType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task TypeWithPreserveFieldsHasBackingFieldsOfPropertiesRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedAssemblyWithNoDefinedPreserveHasAllTypesPreserved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedEventPreservedByLinkXmlIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedFieldPreservedByLinkXmlIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedGenericTypeWithPreserveAllHasAllMembersPreserved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedInterfaceTypeOnTypeWithPreserveAllIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedInterfaceTypeOnTypeWithPreserveNothingIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedMethodPreservedByLinkXmlIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedNestedTypePreservedByLinkXmlIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedNonRequiredTypeIsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedPropertyPreservedByLinkXmlIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypeDeclarationPreservedByLinkXmlIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypeIsPresservedWhenEntireAssemblyIsPreserved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypePreservedByLinkXmlIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypePreservedByLinkXmlWithCommentIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypeWithNoDefinedPreserveHasAllMembersPreserved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypeWithPreserveAllHasAllMembersPreserved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypeWithPreserveFieldsHasMethodsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypeWithPreserveMethodsHasFieldsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypeWithPreserveNothingAndPreserveMembers() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedTypeWithPreserveNothingHasMembersRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedNonRequiredExportedTypeIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedNonRequiredExportedTypeIsKeptWhenRooted() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedNonRequiredTypeIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedNonRequiredTypeIsKeptWithSingleMethod() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LinqExpressionsTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LinqExpressionsTests.g.cs index b3f6765c4e201d..72d95d766445fe 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LinqExpressionsTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LinqExpressionsTests.g.cs @@ -4,46 +4,46 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class LinqExpressionsTests : LinkerTestBase - { - - protected override string TestSuiteName => "LinqExpressions"; - - [Fact] - public Task CanDisableOperatorDiscovery () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanPreserveCustomOperators () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanPreserveNullableCustomOperators () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanRemoveMethodsNamedLikeCustomOperators () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanRemoveOperatorsWhenNotUsingLinqExpressions () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CustomOperatorsWithUnusedArgumentTypes () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class LinqExpressionsTests : LinkerTestBase + { + + protected override string TestSuiteName => "LinqExpressions"; + + [Fact] + public Task CanDisableOperatorDiscovery() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanPreserveCustomOperators() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanPreserveNullableCustomOperators() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanRemoveMethodsNamedLikeCustomOperators() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanRemoveOperatorsWhenNotUsingLinqExpressions() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CustomOperatorsWithUnusedArgumentTypes() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LoggingTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LoggingTests.g.cs index b5b68c0396102c..6c23cd96c0bdae 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LoggingTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/LoggingTests.g.cs @@ -4,22 +4,22 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class LoggingTests : LinkerTestBase - { + public sealed partial class LoggingTests : LinkerTestBase + { - protected override string TestSuiteName => "Logging"; + protected override string TestSuiteName => "Logging"; - [Fact] - public Task CommonLogs () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CommonLogs() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task SourceLines () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task SourceLines() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/MetadataTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/MetadataTests.g.cs index 9e958d384e9c52..e6c1dba134e596 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/MetadataTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/MetadataTests.g.cs @@ -4,52 +4,52 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class MetadataTests : LinkerTestBase - { - - protected override string TestSuiteName => "Metadata"; - - [Fact] - public Task DebuggerDisplayNamesAreKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NamesAreKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NamesAreRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task RootAllAssemblyNamesAreKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task RootDescriptorNamesAreKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task RootLibraryAssemblyNamesAreKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task RootVisibleAssemblyNamesAreKept () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class MetadataTests : LinkerTestBase + { + + protected override string TestSuiteName => "Metadata"; + + [Fact] + public Task DebuggerDisplayNamesAreKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NamesAreKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NamesAreRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task RootAllAssemblyNamesAreKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task RootDescriptorNamesAreKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task RootLibraryAssemblyNamesAreKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task RootVisibleAssemblyNamesAreKept() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/PreserveDependenciesTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/PreserveDependenciesTests.g.cs index 6643506028e531..9e03c3d390463c 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/PreserveDependenciesTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/PreserveDependenciesTests.g.cs @@ -4,100 +4,100 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class PreserveDependenciesTests : LinkerTestBase - { - - protected override string TestSuiteName => "PreserveDependencies"; - - [Fact] - public Task PreserveDependencyDeprecated () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveDependencyErrorCases () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveDependencyField () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveDependencyFromCopiedAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveDependencyKeptOption () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveDependencyMemberSignatureWildcard () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveDependencyMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveDependencyMethodInAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveDependencyMethodInNonReferencedAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveDependencyMethodInNonReferencedAssemblyChained () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveDependencyMethodInNonReferencedAssemblyChainedReference () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveDependencyMethodInNonReferencedAssemblyWithEmbeddedXml () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveDependencyOnUnusedMethodInNonReferencedAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveDependencyOnUnusedMethodInNonReferencedAssemblyWithCopyUsedAction () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task PreserveDependencyOnUnusedMethodInNonReferencedAssemblyWithEmbeddedXml () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class PreserveDependenciesTests : LinkerTestBase + { + + protected override string TestSuiteName => "PreserveDependencies"; + + [Fact] + public Task PreserveDependencyDeprecated() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveDependencyErrorCases() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveDependencyField() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveDependencyFromCopiedAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveDependencyKeptOption() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveDependencyMemberSignatureWildcard() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveDependencyMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveDependencyMethodInAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveDependencyMethodInNonReferencedAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveDependencyMethodInNonReferencedAssemblyChained() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveDependencyMethodInNonReferencedAssemblyChainedReference() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveDependencyMethodInNonReferencedAssemblyWithEmbeddedXml() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveDependencyOnUnusedMethodInNonReferencedAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveDependencyOnUnusedMethodInNonReferencedAssemblyWithCopyUsedAction() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task PreserveDependencyOnUnusedMethodInNonReferencedAssemblyWithEmbeddedXml() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/References.DependenciesTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/References.DependenciesTests.g.cs index 9b507cc19bbd5a..0d636806fdc360 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/References.DependenciesTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/References.DependenciesTests.g.cs @@ -4,16 +4,16 @@ namespace ILLink.RoslynAnalyzer.Tests.References { - public sealed partial class DependenciesTests : LinkerTestBase - { + public sealed partial class DependenciesTests : LinkerTestBase + { - protected override string TestSuiteName => "References.Dependencies"; + protected override string TestSuiteName => "References.Dependencies"; - [Fact] - public Task ReferenceWithEntryPoint_Lib () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task ReferenceWithEntryPoint_Lib() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/References.IndividualTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/References.IndividualTests.g.cs index dd5eb24e1a0ca8..bb0445b8cb777f 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/References.IndividualTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/References.IndividualTests.g.cs @@ -4,16 +4,16 @@ namespace ILLink.RoslynAnalyzer.Tests.References { - public sealed partial class IndividualTests : LinkerTestBase - { + public sealed partial class IndividualTests : LinkerTestBase + { - protected override string TestSuiteName => "References.Individual"; + protected override string TestSuiteName => "References.Individual"; - [Fact] - public Task CanSkipUnresolved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CanSkipUnresolved() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ReferencesTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ReferencesTests.g.cs index dc32f972824b72..adf7c618825ef8 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ReferencesTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ReferencesTests.g.cs @@ -4,88 +4,88 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class ReferencesTests : LinkerTestBase - { - - protected override string TestSuiteName => "References"; - - [Fact] - public Task AssemblyOnlyUsedByUsingSaveAction () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AssemblyOnlyUsedByUsingSaveActionWithSymbols () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AssemblyOnlyUsedByUsingWithCsc () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AssemblyReferenceIsRemovedWhenUnused () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CopyAreKeptFully () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CopyUsedAreKeptFully () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CopyWithLinkedWillHaveAttributeDepsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CopyWithLinkedWillHaveMethodDepsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MissingReferenceInUnusedCodePath () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MissingReferenceInUsedCodePath () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferencesAreRemovedWhenAllUsagesAreRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithEntryPoint () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UserAssembliesAreLinkedByDefault () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class ReferencesTests : LinkerTestBase + { + + protected override string TestSuiteName => "References"; + + [Fact] + public Task AssemblyOnlyUsedByUsingSaveAction() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AssemblyOnlyUsedByUsingSaveActionWithSymbols() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AssemblyOnlyUsedByUsingWithCsc() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AssemblyReferenceIsRemovedWhenUnused() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CopyAreKeptFully() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CopyUsedAreKeptFully() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CopyWithLinkedWillHaveAttributeDepsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CopyWithLinkedWillHaveMethodDepsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MissingReferenceInUnusedCodePath() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MissingReferenceInUsedCodePath() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferencesAreRemovedWhenAllUsagesAreRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithEntryPoint() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UserAssembliesAreLinkedByDefault() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ReflectionTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ReflectionTests.g.cs index 4e66e2225c1516..59a9a24c47527b 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ReflectionTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ReflectionTests.g.cs @@ -4,74 +4,74 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class ReflectionTests : LinkerTestBase - { + public sealed partial class ReflectionTests : LinkerTestBase + { - [Fact] - public Task AssemblyImportedViaReflection () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task AssemblyImportedViaReflection() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task AssemblyImportedViaReflectionWithDerivedType () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task AssemblyImportedViaReflectionWithDerivedType() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task AssemblyImportedViaReflectionWithReference () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task AssemblyImportedViaReflectionWithReference() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task AsType () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task AsType() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task CoreLibMessages () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CoreLibMessages() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task IsAssignableFrom () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task IsAssignableFrom() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task ParametersUsedViaReflection () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task ParametersUsedViaReflection() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task TypeMap () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task TypeMap() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UnderlyingSystemType () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UnderlyingSystemType() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UnsafeAccessor () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UnsafeAccessor() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task UsedViaReflectionIntegrationTest () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UsedViaReflectionIntegrationTest() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ReproTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ReproTests.g.cs index 2cd0c64c2fc3c7..4d233404cbb596 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ReproTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ReproTests.g.cs @@ -4,16 +4,16 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class ReproTests : LinkerTestBase - { + public sealed partial class ReproTests : LinkerTestBase + { - protected override string TestSuiteName => "Repro"; + protected override string TestSuiteName => "Repro"; - [Fact] - public Task Program () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task Program() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ResourcesTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ResourcesTests.g.cs index 00e80e2cafaaaa..9864a0eee25c57 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ResourcesTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/ResourcesTests.g.cs @@ -4,76 +4,76 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class ResourcesTests : LinkerTestBase - { + public sealed partial class ResourcesTests : LinkerTestBase + { - protected override string TestSuiteName => "Resources"; + protected override string TestSuiteName => "Resources"; - [Fact] - public Task EmbeddedLinkXmlFileInReferencedAssemblyIsNotProcessedIfActionIsCopy () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task EmbeddedLinkXmlFileInReferencedAssemblyIsNotProcessedIfActionIsCopy() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task EmbeddedLinkXmlFileInReferencedAssemblyIsNotProcessedIfNameDoesNotMatchAnAssembly () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task EmbeddedLinkXmlFileInReferencedAssemblyIsNotProcessedIfNameDoesNotMatchAnAssembly() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task EmbeddedLinkXmlFileInReferencedAssemblyIsProcessedIfActionIsLink () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task EmbeddedLinkXmlFileInReferencedAssemblyIsProcessedIfActionIsLink() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task EmbeddedLinkXmlFileIsNotProcessedIfNameDoesNotMatchAnAssembly () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task EmbeddedLinkXmlFileIsNotProcessedIfNameDoesNotMatchAnAssembly() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task EmbeddedLinkXmlFileIsNotProcessedWithIgnoreDescriptors () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task EmbeddedLinkXmlFileIsNotProcessedWithIgnoreDescriptors() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task EmbeddedLinkXmlFileIsNotProcessedWithIgnoreDescriptorsAndRemoved () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task EmbeddedLinkXmlFileIsNotProcessedWithIgnoreDescriptorsAndRemoved() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task EmbeddedLinkXmlFileIsProcessed () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task EmbeddedLinkXmlFileIsProcessed() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task EmbeddedLinkXmlFileIsProcessedAndKept () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task EmbeddedLinkXmlFileIsProcessedAndKept() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task EmbeddedLinkXmlFileIsProcessedIfNameMatchesAnAssembly () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task EmbeddedLinkXmlFileIsProcessedIfNameMatchesAnAssembly() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task EmbeddedLinkXmlFileWithTypePreserve () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task EmbeddedLinkXmlFileWithTypePreserve() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task NonLinkerEmbeddedResourceHasNoImpact () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task NonLinkerEmbeddedResourceHasNoImpact() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SealerTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SealerTests.g.cs index 0978942460b92b..949a15088c04c3 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SealerTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SealerTests.g.cs @@ -4,22 +4,22 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class SealerTests : LinkerTestBase - { + public sealed partial class SealerTests : LinkerTestBase + { - protected override string TestSuiteName => "Sealer"; + protected override string TestSuiteName => "Sealer"; - [Fact] - public Task MethodsDevirtualization () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task MethodsDevirtualization() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task TypesCanBeSealed () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task TypesCanBeSealed() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SerializationTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SerializationTests.g.cs index 127f40aa292599..55274cd48ca096 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SerializationTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SerializationTests.g.cs @@ -4,52 +4,52 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class SerializationTests : LinkerTestBase - { - - protected override string TestSuiteName => "Serialization"; - - [Fact] - public Task CanDisableSerializationDiscovery () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DataContractJsonSerialization () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DataContractSerialization () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DataContractSerializationUnused () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SerializationTypeRecursion () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task XmlSerialization () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task XmlSerializationUnused () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class SerializationTests : LinkerTestBase + { + + protected override string TestSuiteName => "Serialization"; + + [Fact] + public Task CanDisableSerializationDiscovery() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DataContractJsonSerialization() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DataContractSerialization() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DataContractSerializationUnused() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SerializationTypeRecursion() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task XmlSerialization() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task XmlSerializationUnused() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SingleFileTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SingleFileTests.g.cs index 62820e50c50b46..3a9d8b91c47a28 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SingleFileTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SingleFileTests.g.cs @@ -4,16 +4,16 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class SingleFileTests : LinkerTestBase - { + public sealed partial class SingleFileTests : LinkerTestBase + { - protected override string TestSuiteName => "SingleFile"; + protected override string TestSuiteName => "SingleFile"; - [Fact] - public Task SingleFileIntrinsics () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task SingleFileIntrinsics() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Statics.DisableBeforeFieldInitTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Statics.DisableBeforeFieldInitTests.g.cs index ff80319a1edb6f..93239d188c8255 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Statics.DisableBeforeFieldInitTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Statics.DisableBeforeFieldInitTests.g.cs @@ -4,16 +4,16 @@ namespace ILLink.RoslynAnalyzer.Tests.Statics { - public sealed partial class DisableBeforeFieldInitTests : LinkerTestBase - { + public sealed partial class DisableBeforeFieldInitTests : LinkerTestBase + { - protected override string TestSuiteName => "Statics.DisableBeforeFieldInit"; + protected override string TestSuiteName => "Statics.DisableBeforeFieldInit"; - [Fact] - public Task UnusedStaticFieldInitializer () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task UnusedStaticFieldInitializer() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/StaticsTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/StaticsTests.g.cs index 86e48c54209986..2f3dfeb8d6b53e 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/StaticsTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/StaticsTests.g.cs @@ -4,46 +4,46 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class StaticsTests : LinkerTestBase - { - - protected override string TestSuiteName => "Statics"; - - [Fact] - public Task ExplicitStaticCtor () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MixedStaticFieldInitializerAndCtor () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task StaticFieldInitializer () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedStaticConstructorGetsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedStaticFieldInitializer () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedStaticMethodGetsRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class StaticsTests : LinkerTestBase + { + + protected override string TestSuiteName => "Statics"; + + [Fact] + public Task ExplicitStaticCtor() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MixedStaticFieldInitializerAndCtor() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task StaticFieldInitializer() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedStaticConstructorGetsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedStaticFieldInitializer() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedStaticMethodGetsRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SubstitutionsTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SubstitutionsTests.g.cs index 93116fcb7541ba..35ec9a25061fa4 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SubstitutionsTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SubstitutionsTests.g.cs @@ -4,92 +4,92 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class SubstitutionsTests : LinkerTestBase - { - - [Fact] - public Task EmbeddedMethodSubstitutionsInReferencedAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task EmbeddedSubstitutions () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task EmbeddedSubstitutionsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task EmbeddedSubstitutionsNotProcessedWithIgnoreSubstitutions () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task EmbeddedSubstitutionsNotProcessedWithIgnoreSubstitutionsAndRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task FeatureGuardSubstitutionsDisabled () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task RemoveBody () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ResourceSubstitutions () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task StubBody () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task StubBodyInvalidSyntax () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task StubBodyUnsafe () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task StubBodyWithStaticCtor () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task StubBodyWithValue () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SubstitutionsErrorCases () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class SubstitutionsTests : LinkerTestBase + { + + [Fact] + public Task EmbeddedMethodSubstitutionsInReferencedAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task EmbeddedSubstitutions() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task EmbeddedSubstitutionsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task EmbeddedSubstitutionsNotProcessedWithIgnoreSubstitutions() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task EmbeddedSubstitutionsNotProcessedWithIgnoreSubstitutionsAndRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task FeatureGuardSubstitutionsDisabled() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task RemoveBody() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ResourceSubstitutions() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task StubBody() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task StubBodyInvalidSyntax() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task StubBodyUnsafe() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task StubBodyWithStaticCtor() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task StubBodyWithValue() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SubstitutionsErrorCases() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SymbolsTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SymbolsTests.g.cs index e208772d48f08a..3f688ebecd5a3e 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SymbolsTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/SymbolsTests.g.cs @@ -4,232 +4,232 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class SymbolsTests : LinkerTestBase - { - - protected override string TestSuiteName => "Symbols"; - - [Fact] - public Task AssemblyWithDefaultSymbols () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AssemblyWithDefaultSymbolsAndSymbolLinkingEnabled () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferencesWithMixedSymbolTypes () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferencesWithMixedSymbolTypesAndSymbolLinkingEnabled () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferencesWithMixedSymbolTypesWithMdbAndSymbolLinkingEnabled () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithEmbeddedPdb () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithEmbeddedPdbAndSymbolLinkingEnabled () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithEmbeddedPdbAndSymbolLinkingEnabledAndDeterministicMvid () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithEmbeddedPdbAndSymbolLinkingEnabledAndNewMvid () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithEmbeddedPdbCopyAction () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithEmbeddedPdbCopyActionAndSymbolLinkingEnabled () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithEmbeddedPdbDeleteAction () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithEmbeddedPdbDeleteActionAndSymbolLinkingEnabled () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithMdb () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithMdbAndSymbolLinkingEnabled () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithMdbAndSymbolLinkingEnabledAndDeterministicMvid () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithMdbAndSymbolLinkingEnabledAndNewMvid () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithMdbCopyAction () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithMdbCopyActionAndSymbolLinkingEnabled () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithMdbDeleteAction () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithMdbDeleteActionAndSymbolLinkingEnabled () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPdb () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPdbAndSymbolLinkingEnabled () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPdbAndSymbolLinkingEnabledAndDeterministicMvid () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPdbAndSymbolLinkingEnabledAndNewMvid () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPdbCopyAction () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPdbCopyActionAndSymbolLinkingEnabled () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPdbDeleteAction () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPdbDeleteActionAndSymbolLinkingEnabled () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPortablePdb () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPortablePdbAndSymbolLinkingEnabled () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPortablePdbAndSymbolLinkingEnabledAndDeterministicMvid () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPortablePdbAndSymbolLinkingEnabledAndNewMvid () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPortablePdbCopyAction () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPortablePdbCopyActionAndSymbolLinkingEnabled () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPortablePdbDeleteAction () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReferenceWithPortablePdbDeleteActionAndSymbolLinkingEnabled () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class SymbolsTests : LinkerTestBase + { + + protected override string TestSuiteName => "Symbols"; + + [Fact] + public Task AssemblyWithDefaultSymbols() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AssemblyWithDefaultSymbolsAndSymbolLinkingEnabled() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferencesWithMixedSymbolTypes() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferencesWithMixedSymbolTypesAndSymbolLinkingEnabled() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferencesWithMixedSymbolTypesWithMdbAndSymbolLinkingEnabled() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithEmbeddedPdb() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithEmbeddedPdbAndSymbolLinkingEnabled() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithEmbeddedPdbAndSymbolLinkingEnabledAndDeterministicMvid() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithEmbeddedPdbAndSymbolLinkingEnabledAndNewMvid() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithEmbeddedPdbCopyAction() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithEmbeddedPdbCopyActionAndSymbolLinkingEnabled() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithEmbeddedPdbDeleteAction() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithEmbeddedPdbDeleteActionAndSymbolLinkingEnabled() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithMdb() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithMdbAndSymbolLinkingEnabled() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithMdbAndSymbolLinkingEnabledAndDeterministicMvid() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithMdbAndSymbolLinkingEnabledAndNewMvid() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithMdbCopyAction() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithMdbCopyActionAndSymbolLinkingEnabled() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithMdbDeleteAction() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithMdbDeleteActionAndSymbolLinkingEnabled() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPdb() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPdbAndSymbolLinkingEnabled() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPdbAndSymbolLinkingEnabledAndDeterministicMvid() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPdbAndSymbolLinkingEnabledAndNewMvid() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPdbCopyAction() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPdbCopyActionAndSymbolLinkingEnabled() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPdbDeleteAction() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPdbDeleteActionAndSymbolLinkingEnabled() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPortablePdb() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPortablePdbAndSymbolLinkingEnabled() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPortablePdbAndSymbolLinkingEnabledAndDeterministicMvid() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPortablePdbAndSymbolLinkingEnabledAndNewMvid() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPortablePdbCopyAction() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPortablePdbCopyActionAndSymbolLinkingEnabled() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPortablePdbDeleteAction() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReferenceWithPortablePdbDeleteActionAndSymbolLinkingEnabled() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/TestFrameworkTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/TestFrameworkTests.g.cs index 744a6f3841ccc8..66b2eb3e70409a 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/TestFrameworkTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/TestFrameworkTests.g.cs @@ -4,106 +4,106 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class TestFrameworkTests : LinkerTestBase - { - - protected override string TestSuiteName => "TestFramework"; - - [Fact] - public Task CanCheckInitializersByIndex () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanCompileILAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanCompileReferencesUsingTypes () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanCompileReferencesWithResources () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanCompileReferencesWithResourcesWithCsc () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanCompileReferencesWithResourcesWithMcs () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanCompileTestCaseWithCsc () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanCompileTestCaseWithDebugPdbs () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanCompileTestCaseWithMcs () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanSandboxDependenciesUsingType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanVerifyInterfacesOnTypesInAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ILVerificationWorks () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task VerifyAttributesInAssemblyWorks () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task VerifyAttributesInAssemblyWorksWithStrings () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task VerifyDefineAttributeBehavior () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task VerifyResourceInAssemblyAttributesBehavior () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class TestFrameworkTests : LinkerTestBase + { + + protected override string TestSuiteName => "TestFramework"; + + [Fact] + public Task CanCheckInitializersByIndex() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanCompileILAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanCompileReferencesUsingTypes() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanCompileReferencesWithResources() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanCompileReferencesWithResourcesWithCsc() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanCompileReferencesWithResourcesWithMcs() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanCompileTestCaseWithCsc() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanCompileTestCaseWithDebugPdbs() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanCompileTestCaseWithMcs() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanSandboxDependenciesUsingType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanVerifyInterfacesOnTypesInAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ILVerificationWorks() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task VerifyAttributesInAssemblyWorks() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task VerifyAttributesInAssemblyWorksWithStrings() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task VerifyDefineAttributeBehavior() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task VerifyResourceInAssemblyAttributesBehavior() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/TopLevelStatementsTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/TopLevelStatementsTests.g.cs index 492352328447d2..385d01cf9e469a 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/TopLevelStatementsTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/TopLevelStatementsTests.g.cs @@ -4,14 +4,14 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class TopLevelStatementsTests : LinkerTestBase - { + public sealed partial class TopLevelStatementsTests : LinkerTestBase + { - [Fact] - public Task BasicKeptValidation () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task BasicKeptValidation() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Tracing.DependencyRecorderTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Tracing.DependencyRecorderTests.g.cs index 5545d319686169..a04c70479f6984 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Tracing.DependencyRecorderTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Tracing.DependencyRecorderTests.g.cs @@ -4,16 +4,16 @@ namespace ILLink.RoslynAnalyzer.Tests.Tracing { - public sealed partial class DependencyRecorderTests : LinkerTestBase - { + public sealed partial class DependencyRecorderTests : LinkerTestBase + { - protected override string TestSuiteName => "Tracing.DependencyRecorder"; + protected override string TestSuiteName => "Tracing.DependencyRecorder"; - [Fact] - public Task BasicDependencies () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task BasicDependencies() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Tracing.IndividualTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Tracing.IndividualTests.g.cs index 93a89fe9a13b38..af3da42b21d2ac 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Tracing.IndividualTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Tracing.IndividualTests.g.cs @@ -4,34 +4,34 @@ namespace ILLink.RoslynAnalyzer.Tests.Tracing { - public sealed partial class IndividualTests : LinkerTestBase - { + public sealed partial class IndividualTests : LinkerTestBase + { - protected override string TestSuiteName => "Tracing.Individual"; + protected override string TestSuiteName => "Tracing.Individual"; - [Fact] - public Task CanDumpDependenciesToUncompressedDgml () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CanDumpDependenciesToUncompressedDgml() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task CanDumpDependenciesToUncompressedXml () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CanDumpDependenciesToUncompressedXml() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task CanEnableDependenciesDump () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CanEnableDependenciesDump() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task CanEnableReducedTracing () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CanEnableReducedTracing() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/TypeForwardingTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/TypeForwardingTests.g.cs index d2b9d1ccb12aeb..fe1f556a88fcb3 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/TypeForwardingTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/TypeForwardingTests.g.cs @@ -4,262 +4,262 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class TypeForwardingTests : LinkerTestBase - { - - protected override string TestSuiteName => "TypeForwarding"; - - [Fact] - public Task AttributeArgumentForwarded () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeArgumentForwardedWithCopyAction () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeEnumArgumentForwarded () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributeEnumArgumentForwardedCopyUsedWithSweptForwarder () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task AttributesScopeUpdated () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MissingTargetReference () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MultiForwardedTypesWithCopyUsed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MultiForwardedTypesWithLink () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NestedTypeForwarder () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SecurityAttributeScope () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task TypeForwardedIsUpdatedForMissingType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task TypeForwarderOnlyAssembliesRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task TypeForwarderOnlyAssemblyCanBePreservedViaLinkXml () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task TypeForwardersModifiers () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task TypeForwardersRewrite () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedForwarderWithAssemblyCopyIsKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedForwarderWithAssemblyCopyUsed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedForwarderWithAssemblyLinked () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UnusedForwarderWithAssemblyLinkedAndFacadeCopy () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedAndUnusedForwarderReferencedFromCopyUsedAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedAndUnusedForwarderWithAssemblyCopy () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderAndUnusedReference () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderInCopyAssemblyKeptByPreserveDependency () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderInCopyAssemblyKeptByUsedCustomAttribute () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderInCopyAssemblyKeptByUsedField () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderInCopyAssemblyKeptByUsedInterface () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderInCopyAssemblyKeptByUsedMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderInCopyAssemblyKeptByUsedNestedType () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderInCopyAssemblyKeptByUsedProperty () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderInCopyAssemblyKeptByUsedTypeAsGenericArg () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderInGenericIsDynamicallyAccessedWithAssemblyCopyUsed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderIsDynamicallyAccessedWithAssemblyCopyUsed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderIsRemovedWhenLink () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderWithAssemblyCopy () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderWithAssemblyCopyUsed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderWithAssemblyCopyUsedAndForwarderLibraryKept () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedForwarderWithAssemblyCopyUsedAndUnusedReference () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedTransitiveForwarderInCopyAssemblyIsDynamicallyAccessed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedTransitiveForwarderInCopyUsedAssemblyIsDynamicallyAccessed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedTransitiveForwarderIsDynamicallyAccessed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedTransitiveForwarderIsResolvedAndFacadeRemoved () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UsedTransitiveForwarderIsResolvedAndFacadeRemovedInCopyAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class TypeForwardingTests : LinkerTestBase + { + + protected override string TestSuiteName => "TypeForwarding"; + + [Fact] + public Task AttributeArgumentForwarded() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeArgumentForwardedWithCopyAction() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeEnumArgumentForwarded() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributeEnumArgumentForwardedCopyUsedWithSweptForwarder() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task AttributesScopeUpdated() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MissingTargetReference() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MultiForwardedTypesWithCopyUsed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MultiForwardedTypesWithLink() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NestedTypeForwarder() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SecurityAttributeScope() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task TypeForwardedIsUpdatedForMissingType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task TypeForwarderOnlyAssembliesRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task TypeForwarderOnlyAssemblyCanBePreservedViaLinkXml() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task TypeForwardersModifiers() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task TypeForwardersRewrite() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedForwarderWithAssemblyCopyIsKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedForwarderWithAssemblyCopyUsed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedForwarderWithAssemblyLinked() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UnusedForwarderWithAssemblyLinkedAndFacadeCopy() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedAndUnusedForwarderReferencedFromCopyUsedAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedAndUnusedForwarderWithAssemblyCopy() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderAndUnusedReference() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderInCopyAssemblyKeptByPreserveDependency() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderInCopyAssemblyKeptByUsedCustomAttribute() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderInCopyAssemblyKeptByUsedField() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderInCopyAssemblyKeptByUsedInterface() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderInCopyAssemblyKeptByUsedMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderInCopyAssemblyKeptByUsedNestedType() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderInCopyAssemblyKeptByUsedProperty() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderInCopyAssemblyKeptByUsedTypeAsGenericArg() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderInGenericIsDynamicallyAccessedWithAssemblyCopyUsed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderIsDynamicallyAccessedWithAssemblyCopyUsed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderIsRemovedWhenLink() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderWithAssemblyCopy() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderWithAssemblyCopyUsed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderWithAssemblyCopyUsedAndForwarderLibraryKept() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedForwarderWithAssemblyCopyUsedAndUnusedReference() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedTransitiveForwarderInCopyAssemblyIsDynamicallyAccessed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedTransitiveForwarderInCopyUsedAssemblyIsDynamicallyAccessed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedTransitiveForwarderIsDynamicallyAccessed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedTransitiveForwarderIsResolvedAndFacadeRemoved() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UsedTransitiveForwarderIsResolvedAndFacadeRemovedInCopyAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/UnreachableBlockTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/UnreachableBlockTests.g.cs index 6d961d2c269e78..f9ce05416fcc8d 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/UnreachableBlockTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/UnreachableBlockTests.g.cs @@ -4,122 +4,122 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class UnreachableBlockTests : LinkerTestBase - { - - [Fact] - public Task BodiesWithSubstitutions () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ComplexConditions () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ComplexConditionsOptimized () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DataFlowRelated () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DeadVariables () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task EndScopeOnMethoEnd () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InstanceMethodSubstitutions () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MethodArgumentPropagation () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MethodWithParametersSubstitutions () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MultiStageRemoval () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReplacedJumpTarget () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ReplacedReturns () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ResultInliningNotPossible () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SimpleConditionalProperty () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SizeOfInConditions () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task TryCatchBlocks () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task TryFinallyBlocks () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task UninitializedLocals () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task WorksWithDynamicAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class UnreachableBlockTests : LinkerTestBase + { + + [Fact] + public Task BodiesWithSubstitutions() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ComplexConditions() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ComplexConditionsOptimized() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DataFlowRelated() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DeadVariables() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task EndScopeOnMethoEnd() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InstanceMethodSubstitutions() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MethodArgumentPropagation() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MethodWithParametersSubstitutions() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MultiStageRemoval() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReplacedJumpTarget() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ReplacedReturns() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ResultInliningNotPossible() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SimpleConditionalProperty() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SizeOfInConditions() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task TryCatchBlocks() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task TryFinallyBlocks() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task UninitializedLocals() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task WorksWithDynamicAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/UnreachableBodyTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/UnreachableBodyTests.g.cs index 076dbdbd0673f9..a34af627fda627 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/UnreachableBodyTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/UnreachableBodyTests.g.cs @@ -4,196 +4,196 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class UnreachableBodyTests : LinkerTestBase - { - - protected override string TestSuiteName => "UnreachableBody"; - - [Fact] - public Task BodyWithManyVariables () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task BodyWithManyVariablesWithSymbols () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanDisableLazyBodyMarking () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DoesNotApplyToCopiedAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DoesNotApplyToCopiedAssembly2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ExplicitInstructionCheck () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InterfaceMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task LinkedOtherIncludedLibrary () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task LinkedOtherIncludedLibraryNoInstanceCtor () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MixOfMethods () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NotWorthConvertingEmpty () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NotWorthConvertingReturnDouble () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NotWorthConvertingReturnFalse () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NotWorthConvertingReturnFloat () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NotWorthConvertingReturnInt () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NotWorthConvertingReturnLong () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NotWorthConvertingReturnNull () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NotWorthConvertingReturnTrue () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OverrideOfAbstractAndInterfaceMethodCalledFromLocal () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OverrideOfAbstractAndInterfaceMethodCalledFromLocal2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OverrideOfAbstractAndInterfaceMethodCalledFromLocal3 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OverrideOfAbstractAndInterfaceMethodWhenInterfaceRemoved2 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OverrideOfAbstractIsStubbed () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OverrideOfAbstractIsStubbedWithUnusedInterface () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task OverrideOfAVirtual () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SimpleGetter () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SimpleMethod () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SimpleSetter () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task WorksWithDynamicDependency () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task WorksWithLinkXml () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task WorksWithPreserveDependency () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class UnreachableBodyTests : LinkerTestBase + { + + protected override string TestSuiteName => "UnreachableBody"; + + [Fact] + public Task BodyWithManyVariables() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task BodyWithManyVariablesWithSymbols() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanDisableLazyBodyMarking() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DoesNotApplyToCopiedAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DoesNotApplyToCopiedAssembly2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ExplicitInstructionCheck() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InterfaceMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task LinkedOtherIncludedLibrary() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task LinkedOtherIncludedLibraryNoInstanceCtor() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MixOfMethods() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NotWorthConvertingEmpty() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NotWorthConvertingReturnDouble() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NotWorthConvertingReturnFalse() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NotWorthConvertingReturnFloat() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NotWorthConvertingReturnInt() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NotWorthConvertingReturnLong() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NotWorthConvertingReturnNull() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NotWorthConvertingReturnTrue() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OverrideOfAbstractAndInterfaceMethodCalledFromLocal() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OverrideOfAbstractAndInterfaceMethodCalledFromLocal2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OverrideOfAbstractAndInterfaceMethodCalledFromLocal3() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OverrideOfAbstractAndInterfaceMethodWhenInterfaceRemoved2() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OverrideOfAbstractIsStubbed() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OverrideOfAbstractIsStubbedWithUnusedInterface() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task OverrideOfAVirtual() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SimpleGetter() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SimpleMethod() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SimpleSetter() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task WorksWithDynamicDependency() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task WorksWithLinkXml() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task WorksWithPreserveDependency() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Warnings.DependenciesTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Warnings.DependenciesTests.g.cs index 6bb97b39338d03..be20e6b8abd48e 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Warnings.DependenciesTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Warnings.DependenciesTests.g.cs @@ -4,22 +4,22 @@ namespace ILLink.RoslynAnalyzer.Tests.Warnings { - public sealed partial class DependenciesTests : LinkerTestBase - { + public sealed partial class DependenciesTests : LinkerTestBase + { - protected override string TestSuiteName => "Warnings.Dependencies"; + protected override string TestSuiteName => "Warnings.Dependencies"; - [Fact] - public Task TriggerWarnings_Lib () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task TriggerWarnings_Lib() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task TriggerWarnings_TrimmableLib () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task TriggerWarnings_TrimmableLib() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Warnings.IndividualTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Warnings.IndividualTests.g.cs index 06ac6ebc2e8bf8..02688a7c205033 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Warnings.IndividualTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Warnings.IndividualTests.g.cs @@ -4,34 +4,34 @@ namespace ILLink.RoslynAnalyzer.Tests.Warnings { - public sealed partial class IndividualTests : LinkerTestBase - { + public sealed partial class IndividualTests : LinkerTestBase + { - protected override string TestSuiteName => "Warnings.Individual"; + protected override string TestSuiteName => "Warnings.Individual"; - [Fact] - public Task CanGenerateWarningSuppressionFileCSharp () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CanGenerateWarningSuppressionFileCSharp() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task CanGenerateWarningSuppressionFileXml () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CanGenerateWarningSuppressionFileXml() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task CustomStepWithWarnings () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task CustomStepWithWarnings() + { + return RunTest(allowMissingWarnings: true); + } - [Fact] - public Task WarningsAreSorted () - { - return RunTest (allowMissingWarnings: true); - } + [Fact] + public Task WarningsAreSorted() + { + return RunTest(allowMissingWarnings: true); + } - } + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Warnings.WarningSuppressionTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Warnings.WarningSuppressionTests.g.cs index ba9c98121fba3c..33d2b4739a619e 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Warnings.WarningSuppressionTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/Warnings.WarningSuppressionTests.g.cs @@ -4,128 +4,128 @@ namespace ILLink.RoslynAnalyzer.Tests.Warnings { - public sealed partial class WarningSuppressionTests : LinkerTestBase - { - - [Fact] - public Task AddSuppressionsBeforeAttributeRemoval () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DetectRedundantSuppressionsFeatureSubstitutions () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DetectRedundantSuppressionsFromXML () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DetectRedundantSuppressionsInAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DetectRedundantSuppressionsInCompilerGeneratedCode () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DetectRedundantSuppressionsInMembersAndTypes () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DetectRedundantSuppressionsInMembersAndTypesUsingTarget () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DetectRedundantSuppressionsInModule () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DetectRedundantSuppressionsSingleWarn () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task DetectRedundantSuppressionsTrimmedMembersTarget () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ModuleSuppressionWithMemberScopeNullTarget () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ModuleSuppressionWithModuleScopeNullTarget () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task ModuleSuppressionWithNullScopeNullTarget () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SuppressWarningsInAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SuppressWarningsInCopyAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SuppressWarningsInMembersAndTypes () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SuppressWarningsInModule () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SuppressWarningsUsingTargetViaXmlMono () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task SuppressWarningsUsingTargetViaXmlNetCore () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task TargettedModuleSuppressionWithUnmatchedScope () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class WarningSuppressionTests : LinkerTestBase + { + + [Fact] + public Task AddSuppressionsBeforeAttributeRemoval() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DetectRedundantSuppressionsFeatureSubstitutions() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DetectRedundantSuppressionsFromXML() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DetectRedundantSuppressionsInAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DetectRedundantSuppressionsInCompilerGeneratedCode() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DetectRedundantSuppressionsInMembersAndTypes() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DetectRedundantSuppressionsInMembersAndTypesUsingTarget() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DetectRedundantSuppressionsInModule() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DetectRedundantSuppressionsSingleWarn() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task DetectRedundantSuppressionsTrimmedMembersTarget() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ModuleSuppressionWithMemberScopeNullTarget() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ModuleSuppressionWithModuleScopeNullTarget() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task ModuleSuppressionWithNullScopeNullTarget() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SuppressWarningsInAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SuppressWarningsInCopyAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SuppressWarningsInMembersAndTypes() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SuppressWarningsInModule() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SuppressWarningsUsingTargetViaXmlMono() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task SuppressWarningsUsingTargetViaXmlNetCore() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task TargettedModuleSuppressionWithUnmatchedScope() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/WarningsTests.g.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/WarningsTests.g.cs index f9cd3f2cf8e263..f348c293c53b0d 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/WarningsTests.g.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/generated/ILLink.RoslynAnalyzer.Tests.Generator/ILLink.RoslynAnalyzer.Tests.TestCaseGenerator/WarningsTests.g.cs @@ -4,116 +4,116 @@ namespace ILLink.RoslynAnalyzer.Tests { - public sealed partial class WarningsTests : LinkerTestBase - { - - [Fact] - public Task CanDisableWarnAsError () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanDisableWarnings () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanNotSingleWarnPerAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanNotWarnAsErrorForDisabledVersion () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanSetWarningVersion0 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanSetWarningVersion5 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanSetWarningVersion9999 () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanSingleWarn () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanSingleWarnPerAssembly () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanSingleWarnWithIndividualWarnAsError () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanSingleWarnWithNoWarn () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanSingleWarnWithWarnAsError () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanWarnAsError () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task CanWarnAsErrorGlobal () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task InvalidWarningVersion () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task MultipleMethodsUseSameAsyncStateMachine () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task NoWarnRegardlessOfWarnAsError () - { - return RunTest (allowMissingWarnings: true); - } - - [Fact] - public Task WarningsFromTrimmableAssembliesCanSurviveSingleWarn () - { - return RunTest (allowMissingWarnings: true); - } - - } + public sealed partial class WarningsTests : LinkerTestBase + { + + [Fact] + public Task CanDisableWarnAsError() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanDisableWarnings() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanNotSingleWarnPerAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanNotWarnAsErrorForDisabledVersion() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanSetWarningVersion0() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanSetWarningVersion5() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanSetWarningVersion9999() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanSingleWarn() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanSingleWarnPerAssembly() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanSingleWarnWithIndividualWarnAsError() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanSingleWarnWithNoWarn() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanSingleWarnWithWarnAsError() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanWarnAsError() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task CanWarnAsErrorGlobal() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task InvalidWarningVersion() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task MultipleMethodsUseSameAsyncStateMachine() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task NoWarnRegardlessOfWarnAsError() + { + return RunTest(allowMissingWarnings: true); + } + + [Fact] + public Task WarningsFromTrimmableAssembliesCanSurviveSingleWarn() + { + return RunTest(allowMissingWarnings: true); + } + + } } diff --git a/src/tools/illink/test/ILLink.Tasks.Tests/CombineLinkerXmlFilesTests.cs b/src/tools/illink/test/ILLink.Tasks.Tests/CombineLinkerXmlFilesTests.cs index 3a1b0e1ee70250..82961ae31e5124 100644 --- a/src/tools/illink/test/ILLink.Tasks.Tests/CombineLinkerXmlFilesTests.cs +++ b/src/tools/illink/test/ILLink.Tasks.Tests/CombineLinkerXmlFilesTests.cs @@ -32,8 +32,8 @@ public void TestCombineLinkerXmlFiles() "doc2.xml"); var xmlFiles = new ITaskItem[] { - new TaskItem ("doc1.xml"), - new TaskItem ("doc2.xml"), + new TaskItem("doc1.xml"), + new TaskItem("doc2.xml"), }; var combiner = new CombineLinkerXmlFiles() diff --git a/src/tools/illink/test/ILLink.Tasks.Tests/ILLink.Tasks.Tests.cs b/src/tools/illink/test/ILLink.Tasks.Tests/ILLink.Tasks.Tests.cs index d555f0332bb5da..5e0380845930cb 100644 --- a/src/tools/illink/test/ILLink.Tasks.Tests/ILLink.Tasks.Tests.cs +++ b/src/tools/illink/test/ILLink.Tasks.Tests/ILLink.Tasks.Tests.cs @@ -20,38 +20,38 @@ public class TaskArgumentTests public static IEnumerable AssemblyPathsCases => new List { new object [] { new ITaskItem [] { - new TaskItem ("Assembly.dll", new Dictionary { { "trimmode", "copy" } }) + new TaskItem("Assembly.dll", new Dictionary { { "trimmode", "copy" } }) } }, new object [] { new ITaskItem [] { - new TaskItem ("Assembly.dll", new Dictionary { { "TrimMode", "Copy" } }) + new TaskItem("Assembly.dll", new Dictionary { { "TrimMode", "Copy" } }) } }, new object [] { new ITaskItem [] { - new TaskItem ("path with/spaces/Assembly.dll") + new TaskItem("path with/spaces/Assembly.dll") } }, new object [] { new ITaskItem [] { - // same path - new TaskItem ("path/to/Assembly1.dll"), - new TaskItem ("path/to/Assembly2.dll") + // same path + new TaskItem("path/to/Assembly1.dll"), + new TaskItem("path/to/Assembly2.dll") } }, new object [] { new ITaskItem [] { - // same assembly - new TaskItem ("path/to/Assembly.dll"), - new TaskItem ("path/to/Assembly.dll") + // same assembly + new TaskItem("path/to/Assembly.dll"), + new TaskItem("path/to/Assembly.dll") } }, new object [] { new ITaskItem [] { - // same assembly name, different paths - new TaskItem ("path1/Assembly.dll"), - new TaskItem ("path2/Assembly.dll") + // same assembly name, different paths + new TaskItem("path1/Assembly.dll"), + new TaskItem("path2/Assembly.dll") } } }; @@ -79,7 +79,7 @@ public void TrimModeAssemblyPaths(string trimMode) { var assemblyPaths = new ITaskItem[] { new TaskItem("Assembly1.dll", new Dictionary {{ "IsTrimmable", "true" }}), - new TaskItem("Assembly2.dll", new Dictionary ()), + new TaskItem("Assembly2.dll", new Dictionary()), new TaskItem("Assembly3.dll", new Dictionary {{ "IsTrimmable", "false" }}), }; var task = new MockTask() @@ -251,14 +251,14 @@ public static IEnumerable PerAssemblyOptimizationsCases() { yield return new object[] { new ITaskItem [] { - new TaskItem ("path/to/Assembly.dll", new Dictionary { + new TaskItem("path/to/Assembly.dll", new Dictionary { { optimization, "True" } }) } }; yield return new object[] { new ITaskItem [] { - new TaskItem ("path/to/Assembly.dll", new Dictionary { + new TaskItem("path/to/Assembly.dll", new Dictionary { { optimization, "False" } }) } @@ -267,11 +267,11 @@ public static IEnumerable PerAssemblyOptimizationsCases() // complex case with multiple optimizations, assemblies yield return new object[] { new ITaskItem [] { - new TaskItem ("path/to/Assembly1.dll", new Dictionary { + new TaskItem("path/to/Assembly1.dll", new Dictionary { { "Sealer", "True" }, { "BeforeFieldInit", "False" } }), - new TaskItem ("path/to/Assembly2.dll", new Dictionary { + new TaskItem("path/to/Assembly2.dll", new Dictionary { { "Sealer", "False" }, { "BeforeFieldInit", "True" } }) @@ -310,15 +310,15 @@ public void TestPerAssemblyOptimizations(ITaskItem[] assemblyPaths) new object[] { true, new ITaskItem [] { - new TaskItem ("AssemblyTrue.dll", new Dictionary { { "TrimmerSingleWarn", "true" } } ), - new TaskItem ("AssemblyFalse.dll", new Dictionary { { "TrimmerSingleWarn", "false" } } ) + new TaskItem("AssemblyTrue.dll", new Dictionary { { "TrimmerSingleWarn", "true" } } ), + new TaskItem("AssemblyFalse.dll", new Dictionary { { "TrimmerSingleWarn", "false" } } ) }, }, new object [] { false, new ITaskItem [] { - new TaskItem ("AssemblyTrue.dll", new Dictionary { { "TrimmerSingleWarn", "true" } } ), - new TaskItem ("AssemblyFalse.dll", new Dictionary { { "TrimmerSingleWarn", "false" } } ) + new TaskItem("AssemblyTrue.dll", new Dictionary { { "TrimmerSingleWarn", "true" } } ), + new TaskItem("AssemblyFalse.dll", new Dictionary { { "TrimmerSingleWarn", "false" } } ) } } }; @@ -349,7 +349,7 @@ public void TestInvalidPerAssemblyOptimizations() var task = new MockTask() { AssemblyPaths = new ITaskItem[] { - new TaskItem ("path/to/Assembly.dll", new Dictionary { + new TaskItem("path/to/Assembly.dll", new Dictionary { { "Sealer", "invalid" } }) } @@ -462,24 +462,24 @@ public void TestWarningsAsErrors(bool treatWarningsAsErrors, string? warningsAsE public static IEnumerable CustomDataCases => new List { new object [] { new ITaskItem [] { - new TaskItem ("DataName", new Dictionary { { "Value", "DataValue" } }) + new TaskItem("DataName", new Dictionary { { "Value", "DataValue" } }) }, }, new object [] { new ITaskItem [] { - new TaskItem ("DataName", new Dictionary { { "Value", "DataValue" } }), - new TaskItem ("DataName", new Dictionary { { "Value", "DataValue2" } }) + new TaskItem("DataName", new Dictionary { { "Value", "DataValue" } }), + new TaskItem("DataName", new Dictionary { { "Value", "DataValue2" } }) }, }, new object [] { new ITaskItem [] { - new TaskItem ("DataName1", new Dictionary { { "Value", "DataValue1" } }), - new TaskItem ("DataName2", new Dictionary { { "Value", "DataValue2" } }) + new TaskItem("DataName1", new Dictionary { { "Value", "DataValue1" } }), + new TaskItem("DataName2", new Dictionary { { "Value", "DataValue2" } }) }, }, new object [] { new ITaskItem [] { - new TaskItem ("DataName", new Dictionary { { "Value", "data value with spaces" } }) + new TaskItem("DataName", new Dictionary { { "Value", "data value with spaces" } }) }, }, }; @@ -506,19 +506,19 @@ public void TestCustomData(ITaskItem[] customData) public static IEnumerable FeatureSettingsCases => new List { new object [] { new ITaskItem [] { - new TaskItem ("FeatureName", new Dictionary { { "Value", "true" } }) + new TaskItem("FeatureName", new Dictionary { { "Value", "true" } }) }, }, new object [] { new ITaskItem [] { - new TaskItem ("FeatureName", new Dictionary { { "Value", "true" } }), - new TaskItem ("FeatureName", new Dictionary { { "Value", "false" } }) + new TaskItem("FeatureName", new Dictionary { { "Value", "true" } }), + new TaskItem("FeatureName", new Dictionary { { "Value", "false" } }) }, }, new object [] { new ITaskItem [] { - new TaskItem ("FeatureName1", new Dictionary { { "value", "true" } }), - new TaskItem ("FeatureName2", new Dictionary { { "value", "false" } }), + new TaskItem("FeatureName1", new Dictionary { { "value", "true" } }), + new TaskItem("FeatureName2", new Dictionary { { "value", "false" } }), }, }, }; @@ -731,14 +731,14 @@ public void TestInvalidDefaultAction() public static IEnumerable CustomStepsCases => new List { new object [] { new ITaskItem [] { - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockCustomStep" } }) }, }, new object [] { new ITaskItem [] { - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockCustomStep" }, { "BeforeStep", "MarkStep" } }) @@ -746,7 +746,7 @@ public void TestInvalidDefaultAction() }, new object [] { new ITaskItem [] { - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "type", "ILLink.Tasks.Tests.MockCustomStep" }, { "beforebtep", "MarkStep" } }) @@ -754,7 +754,7 @@ public void TestInvalidDefaultAction() }, new object [] { new ITaskItem [] { - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockCustomStep" }, { "AfterStep", "MarkStep" } }) @@ -762,11 +762,11 @@ public void TestInvalidDefaultAction() }, new object [] { new ITaskItem [] { - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockCustomStep" }, { "BeforeStep", "MarkStep" } }), - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockCustomStep" }, { "AfterStep", "MarkStep" } }) @@ -815,7 +815,7 @@ public void TestCustomSteps(ITaskItem[] customSteps) public void TestCustomStepsWithBeforeAndAfterSteps() { var customSteps = new ITaskItem[] { - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockCustomStep" }, { "BeforeStep", "MarkStep" }, { "AfterStep", "MarkStep" } @@ -832,40 +832,40 @@ public void TestCustomStepsWithBeforeAndAfterSteps() public void TestCustomStepOrdering() { var customSteps = new ITaskItem[] { - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockCustomStep" }, { "BeforeStep", "MarkStep" } }), - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockCustomStep2" }, { "BeforeStep", "MarkStep" } }), - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockCustomStep3" }, { "AfterStep", "MarkStep" } }), - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockCustomStep4" }, { "AfterStep", "MarkStep" } }), - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockCustomStep5" }, }), - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockCustomStep6" }, }), - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockMarkHandler" } }), - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockMarkHandler2" }, { "BeforeStep", "MockMarkHandler" } }), - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockMarkHandler3" }, { "AfterStep", "MockMarkHandler2" } }), - new TaskItem (Assembly.GetExecutingAssembly ().Location, new Dictionary { + new TaskItem(Assembly.GetExecutingAssembly().Location, new Dictionary { { "Type", "ILLink.Tasks.Tests.MockMarkHandler4" } }), }; @@ -901,7 +901,7 @@ public void TestCustomStepOrdering() public void TestCustomStepsMissingType() { var customSteps = new ITaskItem[] { - new TaskItem (Assembly.GetExecutingAssembly ().Location) + new TaskItem(Assembly.GetExecutingAssembly().Location) }; var task = new MockTask() { diff --git a/src/tools/illink/test/ILLink.Tasks.Tests/Mock.cs b/src/tools/illink/test/ILLink.Tasks.Tests/Mock.cs index 15dc51a72ac047..c4198109552f8b 100644 --- a/src/tools/illink/test/ILLink.Tasks.Tests/Mock.cs +++ b/src/tools/illink/test/ILLink.Tasks.Tests/Mock.cs @@ -185,7 +185,7 @@ public Dictionary GetCustomData() protected override List CreateDefaultResolvers() { return new List() { - new RootAssemblyInput (null, AssemblyRootMode.EntryPoint) + new RootAssemblyInput(null, AssemblyRootMode.EntryPoint) }; } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedOverrideAttribute.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedOverrideAttribute.cs index 4b630f40fbaf68..1b1fa671c11df7 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedOverrideAttribute.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedOverrideAttribute.cs @@ -8,7 +8,7 @@ namespace Mono.Linker.Tests.Cases.Expectations.Assertions /// /// Used to ensure that a method should remove an 'override' annotation for a method in the supplied base type. /// Fails in tests if the method has the override method in the linked assembly, - /// or if the override is not found in the original assembly + /// or if the override is not found in the original assembly /// /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Helpers/PlatformAssemblies.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Helpers/PlatformAssemblies.cs index 45b4ae863e9429..2fa8bbc73c2d47 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Helpers/PlatformAssemblies.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Helpers/PlatformAssemblies.cs @@ -8,7 +8,7 @@ public static class PlatformAssemblies #if NET public const string CoreLib = "System.Private.CoreLib.dll"; #else - public const string CoreLib = "mscorlib.dll"; + public const string CoreLib = "mscorlib.dll"; #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerArgumentAttribute.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerArgumentAttribute.cs index ce15de47bfed0f..4e461de65ac799 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerArgumentAttribute.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerArgumentAttribute.cs @@ -8,7 +8,7 @@ namespace Mono.Linker.Tests.Cases.Expectations.Metadata /// /// Used to define arguments to pass to ILLink. - /// + /// /// Don't use this attribute to setup single character flags. These flags do a poor job of communicating their purpose /// and although we need to continue to support the usages that exist today, that doesn't mean we need to make our tests harder to read /// diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Support/RemoveAttributeInstancesAttribute.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Support/RemoveAttributeInstancesAttribute.cs index 5fcec406159296..e66d6ac6f8ef3d 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Support/RemoveAttributeInstancesAttribute.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases.Expectations/Support/RemoveAttributeInstancesAttribute.cs @@ -6,7 +6,7 @@ namespace Mono.Linker { /// - /// This attribute name will be the name hardcoded in illink which will remove all + /// This attribute name will be the name hardcoded in illink which will remove all /// attribute usages but not the attribute definition /// [AttributeUsage( diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes.Debugger/KeepDebugMembers/DebuggerDisplayAttributeOnTypeWithNonExistentMethod.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes.Debugger/KeepDebugMembers/DebuggerDisplayAttributeOnTypeWithNonExistentMethod.cs index c830da9e542fd4..a84ca2a74de008 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes.Debugger/KeepDebugMembers/DebuggerDisplayAttributeOnTypeWithNonExistentMethod.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes.Debugger/KeepDebugMembers/DebuggerDisplayAttributeOnTypeWithNonExistentMethod.cs @@ -19,10 +19,10 @@ public static void Main() class Bar { #if !FLAG - public int Method () - { - return 1; - } + public int Method() + { + return 1; + } #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/AssemblyAttributeAccessesMembers.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/AssemblyAttributeAccessesMembers.cs index a7c1b8e6ef7f70..e81cc60806168e 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/AssemblyAttributeAccessesMembers.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/AssemblyAttributeAccessesMembers.cs @@ -57,8 +57,8 @@ public class AccessesMembersAttribute : Attribute { [Kept] public AccessesMembersAttribute( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.All)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/BoxedValues.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/BoxedValues.cs index 84b6f0d718b7d1..d0a9d34587234c 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/BoxedValues.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/BoxedValues.cs @@ -6,12 +6,12 @@ namespace Mono.Linker.Tests.Cases.Attributes public class BoxedValues { // mcs bug - // [TestAttribute ((object)typeof (Enum_2))] - // [Kept] - // [KeptAttributeAttribute (typeof (TestAttribute))] - // public void Test_1 () - // { - // } + // [TestAttribute((object)typeof(Enum_2))] + // [Kept] + // [KeptAttributeAttribute(typeof(TestAttribute))] + // public void Test_1() + // { + // } [TestAttribute(TestProperty = Enum_2.B)] [Kept] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/CoreLibraryAssemblyAttributesAreKept.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/CoreLibraryAssemblyAttributesAreKept.cs index 3bb24d962aee9d..3ed67c91b7dccd 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/CoreLibraryAssemblyAttributesAreKept.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/CoreLibraryAssemblyAttributesAreKept.cs @@ -14,8 +14,8 @@ namespace Mono.Linker.Tests.Cases.Attributes [KeptAttributeInAssembly(PlatformAssemblies.CoreLib, typeof(AssemblyDescriptionAttribute))] [KeptAttributeInAssembly(PlatformAssemblies.CoreLib, typeof(AssemblyCompanyAttribute))] #if !NET - [KeptAttributeInAssembly ("System.dll", typeof (AssemblyDescriptionAttribute))] - [KeptAttributeInAssembly ("System.dll", typeof (AssemblyCompanyAttribute))] + [KeptAttributeInAssembly("System.dll", typeof(AssemblyDescriptionAttribute))] + [KeptAttributeInAssembly("System.dll", typeof(AssemblyCompanyAttribute))] #endif public class CoreLibraryAssemblyAttributesAreKept { diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/Dependencies/IVTUnused_Lib.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/Dependencies/IVTUnused_Lib.cs index 93a680a2858962..ce385c26e037b6 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/Dependencies/IVTUnused_Lib.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/Dependencies/IVTUnused_Lib.cs @@ -1,6 +1,6 @@ #if IVT -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo ("missing")] -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo ("test-with-key, PublicKey=00240000")] +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("missing")] +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("test-with-key, PublicKey=00240000")] #endif namespace Mono.Linker.Tests.Cases.Attributes.Dependencies; diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/Dependencies/IVTUsed_Lib.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/Dependencies/IVTUsed_Lib.cs index 23ad8bb5d55c6f..6bb275254764f9 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/Dependencies/IVTUsed_Lib.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/Dependencies/IVTUsed_Lib.cs @@ -2,7 +2,7 @@ using System.Runtime.CompilerServices; #if IVT -[assembly: InternalsVisibleTo ("test")] +[assembly: InternalsVisibleTo("test")] #endif namespace Mono.Linker.Tests.Cases.Attributes.Dependencies diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/CoreLibraryUnusedAssemblyAttributesAreRemoved.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/CoreLibraryUnusedAssemblyAttributesAreRemoved.cs index 6f592be389e31d..527a0297d8f984 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/CoreLibraryUnusedAssemblyAttributesAreRemoved.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/CoreLibraryUnusedAssemblyAttributesAreRemoved.cs @@ -11,7 +11,7 @@ namespace Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed [SetupLinkerArgument("--used-attrs-only", "true")] [RemovedAttributeInAssembly(PlatformAssemblies.CoreLib, typeof(AssemblyDescriptionAttribute))] #if !NET - [RemovedAttributeInAssembly ("System.dll", typeof (AssemblyDescriptionAttribute))] + [RemovedAttributeInAssembly("System.dll", typeof(AssemblyDescriptionAttribute))] #endif public class CoreLibraryUnusedAssemblyAttributesAreRemoved { diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/CoreLibraryUsedAssemblyAttributesAreKept.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/CoreLibraryUsedAssemblyAttributesAreKept.cs index 1dd85b6be709d0..9fa964d1d6f646 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/CoreLibraryUsedAssemblyAttributesAreKept.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/CoreLibraryUsedAssemblyAttributesAreKept.cs @@ -11,7 +11,7 @@ namespace Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed [SetupLinkerArgument("--used-attrs-only", "true")] [KeptAttributeInAssembly(PlatformAssemblies.CoreLib, typeof(AssemblyDescriptionAttribute))] #if !NET - [KeptAttributeInAssembly ("System.dll", typeof (AssemblyDescriptionAttribute))] + [KeptAttributeInAssembly("System.dll", typeof(AssemblyDescriptionAttribute))] #endif public class CoreLibraryUsedAssemblyAttributesAreKept { diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/UnusedAttributeOnGenericParameterIsRemoved.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/UnusedAttributeOnGenericParameterIsRemoved.cs index 36376ce290846c..c5f3850a7060cc 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/UnusedAttributeOnGenericParameterIsRemoved.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/UnusedAttributeOnGenericParameterIsRemoved.cs @@ -13,8 +13,8 @@ public class UnusedAttributeOnGenericParameterIsRemoved static void Main() { #if IL_ASSEMBLY_AVAILABLE - var tmp = new Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed.Dependencies.GenericType (8).Method (); - var tmp2 = new Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed.Dependencies.TypeWithGenericMethod ().GenericMethod (9); + var tmp = new Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed.Dependencies.GenericType(8).Method(); + var tmp2 = new Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed.Dependencies.TypeWithGenericMethod().GenericMethod(9); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/UnusedAttributeOnReturnTypeIsRemoved.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/UnusedAttributeOnReturnTypeIsRemoved.cs index 34270bfb764ebb..582e4473a5e119 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/UnusedAttributeOnReturnTypeIsRemoved.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/UnusedAttributeOnReturnTypeIsRemoved.cs @@ -13,10 +13,10 @@ public class UnusedAttributeOnReturnTypeIsRemoved { static void Main() { -#if IL_ASSEMBLY_AVAILABLE - var tmp = new Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed.Dependencies.AssemblyWithUnusedAttributeOnReturnParameterDefinition ().Method (1); - var tmp2 = new Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed.Dependencies.AssemblyWithUnusedAttributeOnReturnParameterDefinition ().MethodWithoutParameters (); - var tmp3 = new Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed.Dependencies.AssemblyWithUnusedAttributeOnReturnParameterDefinition ().MethodWithoutParametersNonNestedAttribute (); +#if IL_ASSEMBLY_AVAIABLE + var tmp = new Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed.Dependencies.AssemblyWithUnusedAttributeOnReturnParameterDefinition().Method(1); + var tmp2 = new Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed.Dependencies.AssemblyWithUnusedAttributeOnReturnParameterDefinition().MethodWithoutParameters(); + var tmp3 = new Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed.Dependencies.AssemblyWithUnusedAttributeOnReturnParameterDefinition().MethodWithoutParametersNonNestedAttribute(); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/CommandLine/Dependencies/CustomStepDummy.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/CommandLine/Dependencies/CustomStepDummy.cs index 8e03eb21656ed3..2ca98c18f4c7b2 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/CommandLine/Dependencies/CustomStepDummy.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/CommandLine/Dependencies/CustomStepDummy.cs @@ -4,11 +4,11 @@ namespace CustomStep { - public class CustomStepDummy : IStep - { - public void Process (LinkContext context) - { - context.LogMessage (MessageContainer.CreateInfoMessage ("Custom step added.")); - } - } + public class CustomStepDummy : IStep + { + public void Process(LinkContext context) + { + context.LogMessage(MessageContainer.CreateInfoMessage("Custom step added.")); + } + } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/CommandLine/Dependencies/CustomStepUser.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/CommandLine/Dependencies/CustomStepUser.cs index b74c218c901647..37a0b62fcd02bb 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/CommandLine/Dependencies/CustomStepUser.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/CommandLine/Dependencies/CustomStepUser.cs @@ -4,12 +4,12 @@ namespace CustomStep { - public class CustomStepUser : IStep - { - public void Process (LinkContext context) - { - if (context.TryGetCustomData ("NewKey", out var value)) - context.LogMessage (MessageContainer.CreateInfoMessage ("Custom step added with custom data of " + value)); - } - } + public class CustomStepUser : IStep + { + public void Process(LinkContext context) + { + if (context.TryGetCustomData("NewKey", out var value)) + context.LogMessage(MessageContainer.CreateInfoMessage("Custom step added with custom data of " + value)); + } + } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/ComponentModel/TypeDescriptionProviderAttributeOnType.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/ComponentModel/TypeDescriptionProviderAttributeOnType.cs index e190e4cfc4332a..e92a008367a529 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/ComponentModel/TypeDescriptionProviderAttributeOnType.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/ComponentModel/TypeDescriptionProviderAttributeOnType.cs @@ -50,8 +50,8 @@ public class InterfaceTypeConverter : TypeConverter { [Kept] public static IInterface CreateVisual( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type visualType) { try diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/CppCLI/Dependencies/CallCppCLIFromManaged.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/CppCLI/Dependencies/CallCppCLIFromManaged.cs index 7b72517864ecc2..00cc1125baaeac 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/CppCLI/Dependencies/CallCppCLIFromManaged.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/CppCLI/Dependencies/CallCppCLIFromManaged.cs @@ -5,11 +5,11 @@ namespace Mono.Linker.Tests.Cases.CppCLI.Dependencies { - public static class CallCppCLIFromManaged - { - public static void TriggerWarning () - { - TestClass.TriggerWarningFromCppCLI (); - } - } + public static class CallCppCLIFromManaged + { + public static void TriggerWarning() + { + TestClass.TriggerWarningFromCppCLI(); + } + } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ArrayDataFlow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ArrayDataFlow.cs index b9b2defc6a44b2..780c5358e7993b 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ArrayDataFlow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ArrayDataFlow.cs @@ -654,15 +654,15 @@ static void TestInlineArrayElementReferenceAssignment(bool b = true) } // Inline array references are not allowed in conditionals, unlike array references. - // static void TestInlineArrayElementAssignment (bool b = true) + // static void TestInlineArrayElementAssignment(bool b = true) // { - // var arr1 = new InlineTypeArray (); - // arr1[0] = GetUnknownType (); - // var arr2 = new InlineTypeArray (); - // arr2[0] = GetTypeWithPublicConstructors (); - // (b ? arr1 : arr2)[0] = GetWithPublicMethods (); - // arr1[0].RequiresAll (); - // arr2[0].RequiresAll (); + // var arr1 = new InlineTypeArray(); + // arr1[0] = GetUnknownType(); + // var arr2 = new InlineTypeArray(); + // arr2[0] = GetTypeWithPublicConstructors(); + // (b ? arr1 : arr2)[0] = GetWithPublicMethods(); + // arr1[0].RequiresAll(); + // arr2[0].RequiresAll(); // } [ExpectedWarning("IL2087", nameof(T), nameof(DataFlowTypeExtensions.RequiresAll))] @@ -707,7 +707,7 @@ public static void Test() { TestArrayElementAssignment(); TestInlineArrayElementReferenceAssignment(); - // TestInlineArrayElementAssignment (); + // TestInlineArrayElementAssignment(); TestNullCoalesce(); TestNullCoalescingAssignment(); } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributeConstructorDataflow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributeConstructorDataflow.cs index 5e73d4bc708bec..ee857fb04d8c7e 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributeConstructorDataflow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/AttributeConstructorDataflow.cs @@ -53,8 +53,8 @@ class KeepsPublicMethodsAttribute : Attribute { [Kept] public KeepsPublicMethodsAttribute( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] string type) { } @@ -84,8 +84,8 @@ public class KeepsPublicPropertiesAttribute : Attribute { [Kept] public KeepsPublicPropertiesAttribute( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] Type type) { } @@ -141,8 +141,8 @@ class KeepsAllAttribute : Attribute { [Kept] public KeepsAllAttribute( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.All)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type) { } @@ -172,8 +172,8 @@ class AttributeRequiresTypeArrayAttribute : Attribute [Kept] [ExpectedWarning("IL2098")] public AttributeRequiresTypeArrayAttribute( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type[] types) { RequirePublicFields(types); @@ -182,8 +182,8 @@ public AttributeRequiresTypeArrayAttribute( [Kept] [ExpectedWarning("IL2098")] static void RequirePublicFields( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type[] types) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ByRefDataflow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ByRefDataflow.cs index f2b183aab7c893..89fa5d418b4cc8 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ByRefDataflow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ByRefDataflow.cs @@ -5,8 +5,8 @@ using System.Diagnostics.CodeAnalysis; using System.Reflection; using Mono.Linker.Tests.Cases.Expectations.Assertions; -using Mono.Linker.Tests.Cases.Expectations.Metadata; using Mono.Linker.Tests.Cases.Expectations.Helpers; +using Mono.Linker.Tests.Cases.Expectations.Metadata; namespace Mono.Linker.Tests.Cases.DataFlow { @@ -49,7 +49,7 @@ public static void Main() [ExpectedWarning("IL2077", nameof(ByRefDataflow) + "." + nameof(MethodWithRefParameter) + "(Type&)", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/linker/issues/2406")] [ExpectedWarning("IL2077", nameof(ByRefDataflow) + "." + nameof(MethodWithRefParameter) + "(ref Type)", Tool.Analyzer, "https://github.com/dotnet/linker/issues/2406")] [ExpectedWarning("IL2069", [nameof(s_typeWithPublicParameterlessConstructor), "parameter 'type'", nameof(MethodWithRefParameter)], Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/101955")] - // MethodWithRefParameter (ref x) + // MethodWithRefParameter(ref x) [ExpectedWarning("IL2077", nameof(ByRefDataflow) + "." + nameof(MethodWithRefParameter) + "(Type&)", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/linker/issues/2406")] [ExpectedWarning("IL2077", nameof(ByRefDataflow) + "." + nameof(MethodWithRefParameter) + "(ref Type)", Tool.Analyzer, "https://github.com/dotnet/linker/issues/2406")] public static void PassRefToField() @@ -169,11 +169,11 @@ class MultipleOutRefsToField [Kept] static void TwoOutRefs( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] out Type publicMethods, - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] out Type publicProperties) { publicMethods = null; @@ -215,11 +215,11 @@ static void TestFieldAssignment(bool b = true) [ExpectedWarning("IL2072", nameof(publicPropertiesParameter), nameof(GetUnknownType))] static void TestParameterAssignment( bool b = true, - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type publicMethodsParameter = null, - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] Type publicPropertiesParameter = null) { (b ? ref publicMethodsParameter : ref publicPropertiesParameter) = GetUnknownType(); @@ -280,8 +280,8 @@ static void TestNullCoalescingAssignmentComplex(bool b = true) [ExpectedWarning("IL2074", nameof(_publicPropertiesField), nameof(GetUnknownType))] static void TestDataFlowOnRightHandOfAssignment( bool b = true, - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors)] Type type = null) + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type = null) { (b ? ref _publicMethodsField : ref _publicPropertiesField) = (type = GetUnknownType()); } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ConstructedTypesDataFlow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ConstructedTypesDataFlow.cs index b2dd55515449e7..1a2093ca284866 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ConstructedTypesDataFlow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ConstructedTypesDataFlow.cs @@ -58,8 +58,8 @@ static void DeconstructVariablePropertyReference((Type type, object instance) in } record TypeAndInstance( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] - [property: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + [property: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type, object instance); @@ -97,14 +97,14 @@ static void DeconstructClassWithAnnotation(TypeAndInstanceManual value) } record TypeAndInstanceRecordManual( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] - [property: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + [property: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type, object instance) { // The generated property getter doesn't have the same attributes??? // The attributes are only propagated to the generated .ctor - so suppressing the warning the this.type doesn't have the matching annotations - //[UnconditionalSuppressMessage ("", "IL2072")] + //[UnconditionalSuppressMessage("", "IL2072")] public void Deconstruct([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] out Type type, out object instance) => (type, instance) = (this.type, this.instance); } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/DynamicObjects.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/DynamicObjects.cs index dd268bec92a9dd..054b57c08762ef 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/DynamicObjects.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/DynamicObjects.cs @@ -59,24 +59,24 @@ static void MethodWithDynamicParameter(dynamic arg) // Roslyn codegen no longer produces a call to Binder.InvokeConstructor. // [ExpectedSharedWarning ("IL2026", "Microsoft.CSharp.RuntimeBinder.Binder.InvokeConstructor")] // [ExpectedWarning ("IL3050", "System.Runtime.CompilerServices.CallSite", Tool.NativeAot, "https://github.com/dotnet/runtime/issues/94427")] - // static void ObjectCreationDynamicArgument () + // static void ObjectCreationDynamicArgument() // { - // dynamic dynamicObject = "Some string"; - // var x = new ClassWithDynamicCtor (dynamicObject); + // dynamic dynamicObject = "Some string"; + // var x = new ClassWithDynamicCtor(dynamicObject); // } // class ClassWithDynamicCtor // { - // public ClassWithDynamicCtor (dynamic arg) - // { - // } + // public ClassWithDynamicCtor(dynamic arg) + // { + // } // } public static void Test() { DynamicArgument(); DynamicParameter(); - // ObjectCreationDynamicArgument (); + // ObjectCreationDynamicArgument(); } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ExceptionalDataFlow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ExceptionalDataFlow.cs index 952b8177d3d254..02fefb3cadd253 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ExceptionalDataFlow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ExceptionalDataFlow.cs @@ -545,7 +545,7 @@ public static void CatchInTry() [ExpectedWarning("IL2072", nameof(RequireAll2) + "(Type)", nameof(GetWithPublicMethods) + "()")] [ExpectedWarning("IL2072", nameof(RequireAll2) + "(Type)", nameof(GetWithPublicFields) + "()")] // The bug was producing this warning: - // [ExpectedSharedWarning ("IL2072", nameof (RequireAll2) + "(Type)", nameof (GetWithPublicConstructors) + "()")] + // [ExpectedSharedWarning("IL2072", nameof(RequireAll2) + "(Type)", nameof(GetWithPublicConstructors) + "()")] // Trimmer merges branches going forward. [ExpectedWarning("IL2072", nameof(RequireAll1) + "(Type)", nameof(GetWithPublicMethods) + "()", Tool.Trimmer | Tool.NativeAot, "")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ExponentialDataFlow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ExponentialDataFlow.cs index 9686a6cc5463a4..bdfdd2467a271b 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ExponentialDataFlow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ExponentialDataFlow.cs @@ -123,26 +123,26 @@ class GenericTypeWithRequires< public static void Test() { Type[] types = new Type[20] { - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int), - typeof (int) + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int), + typeof(int) }; if (Condition) types[0] = typeof(T); if (Condition) types[1] = typeof(T); diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/FeatureGuardAttributeDataFlow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/FeatureGuardAttributeDataFlow.cs index 135c18cb31e2f8..afc8021d785615 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/FeatureGuardAttributeDataFlow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/FeatureGuardAttributeDataFlow.cs @@ -2,9 +2,9 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.Runtime.CompilerServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; using ILLink.RoslynAnalyzer; using Mono.Linker.Tests.Cases.Expectations.Assertions; using Mono.Linker.Tests.Cases.Expectations.Helpers; diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/FieldDataFlow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/FieldDataFlow.cs index a5383715ea0e2a..9a635d9a6acf78 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/FieldDataFlow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/FieldDataFlow.cs @@ -4,8 +4,8 @@ using System; using System.Diagnostics.CodeAnalysis; using Mono.Linker.Tests.Cases.Expectations.Assertions; -using Mono.Linker.Tests.Cases.Expectations.Metadata; using Mono.Linker.Tests.Cases.Expectations.Helpers; +using Mono.Linker.Tests.Cases.Expectations.Metadata; namespace Mono.Linker.Tests.Cases.DataFlow { @@ -262,7 +262,7 @@ public static void Test() } private static void RequirePublicMethods( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] string s) { } @@ -335,7 +335,7 @@ class UnsupportedType [ExpectedWarning("IL2098")] static void RequirePublicFields( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] UnsupportedType unsupportedTypeInstance) { } @@ -367,7 +367,7 @@ public StringRef(ref string s) [ExpectedWarning("IL2098")] static void RequirePublicFields( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] ref string s) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/GenericParameterDataFlow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/GenericParameterDataFlow.cs index a6902efc2062d8..1a39904824fde1 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/GenericParameterDataFlow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/GenericParameterDataFlow.cs @@ -714,7 +714,7 @@ public static void StaticPartialInstantiation() } [ExpectedWarning("IL2091", - [nameof (TOuter), + [nameof(TOuter), "Mono.Linker.Tests.Cases.DataFlow.GenericParameterDataFlow.TypeWithInstantiatedGenericMethodViaGenericParameter", "TMethods", "Mono.Linker.Tests.Cases.DataFlow.GenericParameterDataFlow.BaseTypeWithGenericMethod.StaticRequiresMultipleGenericParams()"], Tool.Analyzer, "")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/IReflectDataflow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/IReflectDataflow.cs index 0269e758967253..d4917e93c84179 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/IReflectDataflow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/IReflectDataflow.cs @@ -142,8 +142,8 @@ class MyReflectOverType : MyReflect [Kept] public MyReflectOverType( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] Type type) { _underlyingType = type; diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/LocalDataFlow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/LocalDataFlow.cs index c50d8b97c6be0e..86f966c3f872f8 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/LocalDataFlow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/LocalDataFlow.cs @@ -33,7 +33,7 @@ public static void Main() // that we might be able to lift in the future. // These are overly conservative (extraneous warnings) - // https://github.com/dotnet/linker/issues/2550 + // https://github.com/dotnet/linker/issues/2550 TestBranchGoto(); TestBranchIf(); TestBranchIfElse(); diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MemberTypes.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MemberTypes.cs index 883073760552c7..c0b6ebc50acb08 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MemberTypes.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MemberTypes.cs @@ -93,7 +93,7 @@ private PublicParameterlessConstructorType(int i, int j) { } // Not implied by the DynamicallyAccessedMemberTypes logic, but // explicit cctors would be kept by ILLink. // [Kept] - // static PublicParameterlessConstructorType () { } + // static PublicParameterlessConstructorType() { } public void Method1() { } public bool Property1 { get; set; } @@ -166,7 +166,7 @@ private PublicConstructorsType(int i, int j) { } // Not implied by the DynamicallyAccessedMemberTypes logic, but // explicit cctors would be kept by ILLink. // [Kept] - // static PublicConstructorsType () { } + // static PublicConstructorsType() { } public void Method1() { } public bool Property1 { get; set; } @@ -205,7 +205,7 @@ private PublicConstructorsWithInheritedType(int i, int j) { } // Not implied by the DynamicallyAccessedMemberTypes logic, but // explicit cctors would be kept by ILLink. // [Kept] - // static PublicConstructorsType () { } + // static PublicConstructorsType() { } public void Method1() { } public bool Property1 { get; set; } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MethodParametersDataFlow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MethodParametersDataFlow.cs index 8710898fbaced3..9e9d50d193ccb8 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MethodParametersDataFlow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MethodParametersDataFlow.cs @@ -247,7 +247,7 @@ class UnsupportedType [ExpectedWarning("IL2098", nameof(UnsupportedType))] static void RequirePublicMethods( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] UnsupportedType unsupportedTypeInstance) { RequirePublicFields(unsupportedTypeInstance); @@ -255,7 +255,7 @@ static void RequirePublicMethods( [ExpectedWarning("IL2098", nameof(UnsupportedType))] static void RequirePublicFields( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] UnsupportedType unsupportedTypeInstance) { } @@ -270,7 +270,7 @@ static void TestUnsupportedType() [ExpectedWarning("IL2098")] static void RequirePublicMethods( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type[] types) { RequirePublicFields(types); @@ -278,7 +278,7 @@ static void RequirePublicMethods( [ExpectedWarning("IL2098")] static void RequirePublicFields( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type[] types) { } @@ -293,7 +293,7 @@ static void TestTypeArray() [ExpectedWarning("IL2098")] static unsafe void RequirePublicMethods( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type* typePtr) { RequirePublicFields(typePtr); @@ -301,7 +301,7 @@ static unsafe void RequirePublicMethods( [ExpectedWarning("IL2098")] static unsafe void RequirePublicFields( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type* typePtr) { } @@ -316,7 +316,7 @@ static unsafe void TestTypePointer() [ExpectedWarning("IL2098")] static void RequirePublicMethods( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T t) where T : Type { RequirePublicFields(t); @@ -324,7 +324,7 @@ static void RequirePublicMethods( [ExpectedWarning("IL2098")] static void RequirePublicFields( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] T t) where T : Type { } @@ -339,7 +339,7 @@ static void TestTypeGenericParameter() [ExpectedWarning("IL2098")] static void RequirePublicMethods( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] ref string stringRef) { RequirePublicFields(ref stringRef); @@ -347,7 +347,7 @@ static void RequirePublicMethods( [ExpectedWarning("IL2098")] static void RequirePublicFields( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] ref string stringRef) { } @@ -375,14 +375,14 @@ class AnnotationOnByRefParameter [ExpectedWarning("IL2067")] [ExpectedWarning("IL2067", Tool.NativeAot | Tool.Trimmer, "https://github.com/dotnet/runtime/issues/101734")] static void RequirePublicMethods( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] ref Type typeRef) { RequirePublicFields(ref typeRef); } static void RequirePublicFields( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] ref Type typeRef) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MethodReturnParameterDataFlow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MethodReturnParameterDataFlow.cs index 58b7afba28008b..03c88ec3341fff 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MethodReturnParameterDataFlow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MethodReturnParameterDataFlow.cs @@ -51,7 +51,7 @@ Type ReturnPublicParameterlessConstructor( Type publicParameterlessConstructorType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type publicConstructorsType, - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.NonPublicConstructors)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type nonPublicConstructorsType) { switch (GetHashCode()) @@ -209,7 +209,7 @@ static UnsupportedType GetWithPublicMethods() [ExpectedWarning("IL2098")] static void RequirePublicFields( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] UnsupportedType unsupportedTypeInstance) { } @@ -234,7 +234,7 @@ class StringRefReturnValue [ExpectedWarning("IL2098")] static void RequirePublicFields( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] ref string s) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MethodThisDataFlow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MethodThisDataFlow.cs index a414a22aa87b5e..a6f5be0ba15bda 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MethodThisDataFlow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/MethodThisDataFlow.cs @@ -93,9 +93,9 @@ class AnnotationOnUnsupportedThisParameter class UnsupportedType { // The AttributeTargets don't support constructors. - // [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] - // public UnsupportedType () { - // RequirePublicFields (this); + // [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + // public UnsupportedType() { + // RequirePublicFields(this); // } [ExpectedWarning("IL2041")] @@ -119,7 +119,7 @@ public static void StaticMethod() [ExpectedWarning("IL2098")] static void RequirePublicFields( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] UnsupportedType unsupportedTypeInstance) { } @@ -129,14 +129,14 @@ static void TestMethodThisParameter() t.GetMethod("foo"); } - // static void TestConstructorThisParameter () { - // new UnsupportedType (); + // static void TestConstructorThisParameter() { + // new UnsupportedType(); // } public static void Test() { TestMethodThisParameter(); - // TestConstructorThisParameter (); + // TestConstructorThisParameter(); UnsupportedType.StaticMethod(); } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ModifierDataFlow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ModifierDataFlow.cs index fd7cb70adb249e..a40d9c2652f6e4 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ModifierDataFlow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/ModifierDataFlow.cs @@ -53,13 +53,13 @@ public static void Main() WriteVolatileType(); WriteVolatileTypeArray(); #if IL_ASSEMBLY_AVAILABLE - Library.ModifierDataFlow.WriteModReqType (); - Library.ModifierDataFlow.WriteMultipleModReqType (); - Library.ModifierDataFlow.WriteModOptType (); - Library.ModifierDataFlow.WriteModReqModOptType (); - Library.ModifierDataFlow.WriteModOptModReqType (); - Library.ModifierDataFlow.WriteModReqArrayType (); - Library.ModifierDataFlow.WriteArrayModReqType (); + Library.ModifierDataFlow.WriteModReqType(); + Library.ModifierDataFlow.WriteMultipleModReqType(); + Library.ModifierDataFlow.WriteModOptType(); + Library.ModifierDataFlow.WriteModReqModOptType(); + Library.ModifierDataFlow.WriteModOptModReqType(); + Library.ModifierDataFlow.WriteModReqArrayType(); + Library.ModifierDataFlow.WriteArrayModReqType(); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/NullableAnnotations.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/NullableAnnotations.cs index 67ae15ab46fbfb..84ca5fc83ee8b9 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/NullableAnnotations.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/NullableAnnotations.cs @@ -122,7 +122,7 @@ static void Field() static void Parameter( Type unannotated, [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] Type annotated) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type annotated) { typeof(Nullable<>).MakeGenericType(unannotated).GetMethods(); typeof(Nullable<>).MakeGenericType(annotated).GetMethods(); diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/PropertyDataFlow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/PropertyDataFlow.cs index 8adf581c6c5031..6b469c873b7272 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/PropertyDataFlow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/PropertyDataFlow.cs @@ -905,7 +905,7 @@ class StringRefProperty [ExpectedWarning("IL2098")] static void RequirePublicFields( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] ref string s) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/StaticInterfaceMethodDataflow.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/StaticInterfaceMethodDataflow.cs index eb2ad808cd501b..d2836f4a063d94 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/StaticInterfaceMethodDataflow.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/StaticInterfaceMethodDataflow.cs @@ -126,7 +126,7 @@ public static void AbstractMethod() { } [Kept] static void DamOnParam( [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/TypeInfoIntrinsics.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/TypeInfoIntrinsics.cs index 3f7b97531f256c..6cbf4c23455fa4 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/TypeInfoIntrinsics.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/TypeInfoIntrinsics.cs @@ -28,15 +28,15 @@ public class TypeInfoIntrinsics public static void Main() { #if IL_ASSEMBLY_AVAILABLE - Library.TypeInfoCalls.TestGetConstructors(typeof(string).GetTypeInfo()); - Library.TypeInfoCalls.TestGetMethods(typeof(string).GetTypeInfo()); - Library.TypeInfoCalls.TestGetFields(typeof(string).GetTypeInfo()); - Library.TypeInfoCalls.TestGetProperties(typeof(string).GetTypeInfo()); - Library.TypeInfoCalls.TestGetEvents(typeof(string).GetTypeInfo()); - Library.TypeInfoCalls.TestGetNestedTypes(typeof(string).GetTypeInfo()); - Library.TypeInfoCalls.TestGetField(typeof(string).GetTypeInfo()); - Library.TypeInfoCalls.TestGetProperty(typeof(string).GetTypeInfo()); - Library.TypeInfoCalls.TestGetEvent(typeof(string).GetTypeInfo()); + Library.TypeInfoCalls.TestGetConstructors(typeof(string).GetTypeInfo()); + Library.TypeInfoCalls.TestGetMethods(typeof(string).GetTypeInfo()); + Library.TypeInfoCalls.TestGetFields(typeof(string).GetTypeInfo()); + Library.TypeInfoCalls.TestGetProperties(typeof(string).GetTypeInfo()); + Library.TypeInfoCalls.TestGetEvents(typeof(string).GetTypeInfo()); + Library.TypeInfoCalls.TestGetNestedTypes(typeof(string).GetTypeInfo()); + Library.TypeInfoCalls.TestGetField(typeof(string).GetTypeInfo()); + Library.TypeInfoCalls.TestGetProperty(typeof(string).GetTypeInfo()); + Library.TypeInfoCalls.TestGetEvent(typeof(string).GetTypeInfo()); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/UnresolvedMembers.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/UnresolvedMembers.cs index 2e00aba0028307..df982c1d58e7bb 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/UnresolvedMembers.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/UnresolvedMembers.cs @@ -60,7 +60,7 @@ class AttributeWithRequirements : Attribute { [Kept] public AttributeWithRequirements( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) { } @@ -124,8 +124,8 @@ class EmptyType [Kept] static void RequirePublicMethods( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/VirtualMethodHierarchyDataflowAnnotationValidation.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/VirtualMethodHierarchyDataflowAnnotationValidation.cs index 0819c2c161f045..54415925f13342 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/VirtualMethodHierarchyDataflowAnnotationValidation.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/VirtualMethodHierarchyDataflowAnnotationValidation.cs @@ -76,12 +76,12 @@ class BaseClass // === Method parameters === // This does not check complicated inheritance cases as that is already validated by the return values public virtual void SingleParameterBaseWithDerivedWithout( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type p) { } public virtual void SingleParameterBaseWithDerivedWith_( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type p) { } @@ -90,15 +90,15 @@ public virtual void SingleParameterBaseWithoutDerivedWith_(Type p) { } public virtual void SingleParameterBaseWithoutDerivedWithout(Type p) { } public virtual void SingleParameterBaseWithDerivedWithDifferent( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type p) { } public virtual void MultipleParametersBaseWithDerivedWithout( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type p1BaseWithDerivedWithout, Type p2BaseWithoutDerivedWithout, - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type p3BaseWithDerivedWithout) { } @@ -109,18 +109,18 @@ public virtual void MultipleParametersBaseWithoutDerivedWith( { } public virtual void MultipleParametersBaseWithDerivedWithMatch( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type p1BaseWithDerivedWith, Type p2BaseWithoutDerivedWithout, - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type p3BaseWithDerivedWith) { } public virtual void MultipleParametersBaseWithDerivedWithMismatch( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type p1BaseWithDerivedWithMismatch, Type p2BaseWithoutDerivedWith, - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type p3BaseWithDerivedWithMatch, Type p4NoAnnotations) { } @@ -176,7 +176,7 @@ public override void SingleParameterBaseWithDerivedWithout(Type p) { } [LogDoesNotContain("DerivedClass.SingleParameterBaseWithDerivedWith_")] public override void SingleParameterBaseWithDerivedWith_( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type p) { } @@ -185,7 +185,7 @@ public override void SingleParameterBaseWithDerivedWith_( "don't match overridden parameter 'p' of method 'Mono.Linker.Tests.Cases.DataFlow.VirtualMethodHierarchyDataflowAnnotationValidation.BaseClass.SingleParameterBaseWithoutDerivedWith_(Type)'. " + "All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage.")] public override void SingleParameterBaseWithoutDerivedWith_( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type p) { } @@ -197,7 +197,7 @@ public override void SingleParameterBaseWithoutDerivedWithout(Type p) { } "don't match overridden parameter 'p' of method 'Mono.Linker.Tests.Cases.DataFlow.VirtualMethodHierarchyDataflowAnnotationValidation.BaseClass.SingleParameterBaseWithDerivedWithDifferent(Type)'. " + "All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage.")] public override void SingleParameterBaseWithDerivedWithDifferent( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type p) { } @@ -215,19 +215,19 @@ public override void MultipleParametersBaseWithDerivedWithout( [LogDoesNotContain(".*'p2BaseWithoutDerivedWithout'.*DerivedClass.*MultipleParametersBaseWithoutDerivedWith.*", regexMatch: true)] [LogContains(".*'p3BaseWithoutDerivedWith'.*DerivedClass.*MultipleParametersBaseWithoutDerivedWith.*", regexMatch: true)] public override void MultipleParametersBaseWithoutDerivedWith( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type p1BaseWithoutDerivedWith, Type p2BaseWithoutDerivedWithout, - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type p3BaseWithoutDerivedWith) { } [LogDoesNotContain("DerivedClass.MultipleParametersBaseWithDerivedWithMatch")] public override void MultipleParametersBaseWithDerivedWithMatch( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type p1BaseWithDerivedWith, Type p2BaseWithoutDerivedWithout, - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type p3BaseWithDerivedWith) { } @@ -236,11 +236,11 @@ public override void MultipleParametersBaseWithDerivedWithMatch( [LogDoesNotContain(".*'p3BaseWithDerivedWithMatch'.*DerivedClass.*MultipleParametersBaseWithDerivedWithMismatch.*", regexMatch: true)] [LogDoesNotContain(".*'p4NoAnnotations'.*DerivedClass.*MultipleParametersBaseWithDerivedWithMismatch.*", regexMatch: true)] public override void MultipleParametersBaseWithDerivedWithMismatch( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type p1BaseWithDerivedWithMismatch, - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type p2BaseWithoutDerivedWith, - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type p3BaseWithDerivedWithMatch, Type p4NoAnnotations) { } @@ -359,7 +359,7 @@ class DerivedOverNoAnnotations : BaseWithNoAnnotations // === Method parameters === [LogContains("DerivedOverNoAnnotations.SingleParameterBaseWithoutDerivedWith_")] public override void SingleParameterBaseWithoutDerivedWith_( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type p) { } @@ -393,12 +393,12 @@ abstract class BaseWithAnnotations // === Method parameters === public virtual void SingleParameterBaseWithDerivedWithout( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type p) { } public virtual void SingleParameterBaseWithDerivedWith_( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type p) { } @@ -433,7 +433,7 @@ public override void SingleParameterBaseWithDerivedWithout(Type p) { } [LogDoesNotContain("DerivedWithNoAnnotations.SingleParameterBaseWithDerivedWith_")] public override void SingleParameterBaseWithDerivedWith_( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type p) { } @@ -468,13 +468,13 @@ interface IBase // === Method parameters === void SingleParameterBaseWithImplementationWith_( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type p); void SingleParameterBaseWithoutImplementationWith_(Type p); void SingleParameterBaseWithImplementationWithout( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type p); void SingleParameterBaseWithoutImplementationWithout(Type p); @@ -526,7 +526,7 @@ abstract class ImplementationClass : IDerived // === Method parameters === [LogDoesNotContain("ImplementationClass.SingleParameterBaseWithImplementationWith_")] public void SingleParameterBaseWithImplementationWith_( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type p) { } @@ -535,7 +535,7 @@ public void SingleParameterBaseWithImplementationWithout(Type p) { } [LogContains("ImplementationClass.SingleParameterBaseWithoutImplementationWith_")] public void SingleParameterBaseWithoutImplementationWith_( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type p) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/Dependencies/DynamicDependencyFromAttributeXmlOnNonReferencedAssemblyLibrary.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/Dependencies/DynamicDependencyFromAttributeXmlOnNonReferencedAssemblyLibrary.cs index a4b24d50a459fc..0d5ac45ded4113 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/Dependencies/DynamicDependencyFromAttributeXmlOnNonReferencedAssemblyLibrary.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/Dependencies/DynamicDependencyFromAttributeXmlOnNonReferencedAssemblyLibrary.cs @@ -4,7 +4,7 @@ namespace Mono.Linker.Tests.Cases.DynamicDependencies.Dependencies { #if METHOD - public class DynamicDependencyFromAttributeXmlOnNonReferencedAssemblyLibrary_Method + public class DynamicDependencyFromAttributeXmlOnNonReferencedAssemblyLibrary_Method #else public class DynamicDependencyFromAttributeXmlOnNonReferencedAssemblyLibrary_Field #endif diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/Dependencies/FacadeAssembly.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/Dependencies/FacadeAssembly.cs index 128a6cbdbfba84..9d824d7f7f71e7 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/Dependencies/FacadeAssembly.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/Dependencies/FacadeAssembly.cs @@ -3,5 +3,5 @@ using System.Runtime.CompilerServices; -[assembly: TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.DynamicDependencies.Dependencies.ImplementationLibrary))] -[assembly: TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.DynamicDependencies.Dependencies.ImplementationLibraryGenericType<,>))] +[assembly: TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.DynamicDependencies.Dependencies.ImplementationLibrary))] +[assembly: TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.DynamicDependencies.Dependencies.ImplementationLibraryGenericType<,>))] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyFromAttributeXml.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyFromAttributeXml.cs index 001eab391d662d..3182afffeab990 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyFromAttributeXml.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyFromAttributeXml.cs @@ -10,7 +10,7 @@ namespace Mono.Linker.Tests.Cases.DynamicDependencies #if NET [SetupLinkAttributesFile("DynamicDependencyFromAttributeXml.netcore.Attributes.xml")] #else - [SetupLinkAttributesFile ("DynamicDependencyFromAttributeXml.mono.Attributes.xml")] + [SetupLinkAttributesFile("DynamicDependencyFromAttributeXml.mono.Attributes.xml")] #endif [IgnoreLinkAttributes(false)] [SetupLinkerArgument("--enable-opt", "unreachablebodies", "missing.dll")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyFromAttributeXmlOnNonReferencedAssembly.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyFromAttributeXmlOnNonReferencedAssembly.cs index c70f116c29e3f1..70aa297f3eb6f4 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyFromAttributeXmlOnNonReferencedAssembly.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyFromAttributeXmlOnNonReferencedAssembly.cs @@ -15,7 +15,7 @@ namespace Mono.Linker.Tests.Cases.DynamicDependencies #if NET [SetupLinkAttributesFile("DynamicDependencyFromAttributeXmlOnNonReferencedAssembly.netcore.Attributes.xml")] #else - [SetupLinkAttributesFile ("DynamicDependencyFromAttributeXmlOnNonReferencedAssembly.mono.Attributes.xml")] + [SetupLinkAttributesFile("DynamicDependencyFromAttributeXmlOnNonReferencedAssembly.mono.Attributes.xml")] #endif public class DynamicDependencyFromAttributeXmlOnNonReferencedAssembly { diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyMethod.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyMethod.cs index 33bc1797a85485..191b817e53b0e1 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyMethod.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyMethod.cs @@ -18,7 +18,7 @@ public static void Main() B.Broken(); B.Conditional(); #if NATIVEAOT - ReferenceViaReflection.Test (); + ReferenceViaReflection.Test(); #endif } @@ -182,42 +182,42 @@ internal void ConditionalTest() } } #if NATIVEAOT - abstract class ReferenceViaReflection - { - [Kept] - [DynamicDependency (nameof (TargetMethodViaReflection))] - public static void SourceMethodViaReflection () { } - - [Kept] - private static void TargetMethodViaReflection () { } - - - [Kept] - public static void Test () - { - var i = new Impl (); // Avoid removal of non-implemented abstract methods - - typeof (ReferenceViaReflection).RequiresPublicMethods (); - typeof (AbstractMethods).RequiresPublicMethods (); - } - - [KeptMember (".ctor()")] - private abstract class AbstractMethods - { - [Kept] - [DynamicDependency (nameof (TargetMethod))] - public abstract void SourceAbstractViaReflection (); - - [Kept] - private static void TargetMethod () { } - } - - [KeptMember (".ctor()")] - private class Impl : AbstractMethods - { - [Kept] - public override void SourceAbstractViaReflection () { } - } - } + abstract class ReferenceViaReflection + { + [Kept] + [DynamicDependency(nameof(TargetMethodViaReflection))] + public static void SourceMethodViaReflection() { } + + [Kept] + private static void TargetMethodViaReflection() { } + + + [Kept] + public static void Test() + { + var i = new Impl ); // Avoid removal of non-implemented abstract methods + + typeof(ReferenceViaReflection).RequiresPublicMethods(); + typeof(AbstractMethods).RequiresPublicMethods(); + } + + [KeptMember(".ctor()")] + private abstract class AbstractMethods + { + [Kept] + [DynamicDependency(nameof(TargetMethod))] + public abstract void SourceAbstractViaReflection(); + + [Kept] + private static void TargetMethod() { } + } + + [KeptMember(".ctor()")] + private class Impl : AbstractMethods + { + [Kept] + public override void SourceAbstractViaReflection() { } + } + } #endif } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyMethodInNonReferencedAssemblyWithSweptReferences.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyMethodInNonReferencedAssemblyWithSweptReferences.cs index e549e38cfa4183..05b2ed72ef9a45 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyMethodInNonReferencedAssemblyWithSweptReferences.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyMethodInNonReferencedAssemblyWithSweptReferences.cs @@ -10,7 +10,7 @@ namespace Mono.Linker.Tests.Cases.DynamicDependencies [SetupCompileBefore("reference.dll", new[] { "Dependencies/AssemblyDependency.cs" }, addAsReference: false)] [SetupCompileBefore("library.dll", new[] { "Dependencies/AssemblyDependencyWithMultipleReferences.cs" }, new[] { "reference.dll", "unusedreference.dll" }, addAsReference: false)] // TODO: keep library even if type is not found in it (https://github.com/dotnet/linker/issues/1795) - // [KeptAssembly ("library")] + // [KeptAssembly("library")] public class DynamicDependencyMethodInNonReferencedAssemblyWithSweptReferences { public static void Main() diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/CustomStepCanFixAbstractMethods.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/CustomStepCanFixAbstractMethods.cs index fdeb48d2961445..1ba3b41ef63d1e 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/CustomStepCanFixAbstractMethods.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/CustomStepCanFixAbstractMethods.cs @@ -1,6 +1,6 @@ -using Mono.Linker.Tests.Cases.Extensibility.Dependencies; using Mono.Linker.Tests.Cases.Expectations.Assertions; using Mono.Linker.Tests.Cases.Expectations.Metadata; +using Mono.Linker.Tests.Cases.Extensibility.Dependencies; namespace Mono.Linker.Tests.Cases.Extensibility { @@ -29,7 +29,7 @@ static void TestReflectionAccessToOtherAssembly() // to be created through reflection instead of a direct call to the constructor, otherwise we build the // TypeMapInfo cache too early for the custom step. - // var type = typeof (InterfaceImplementation); + // var type = typeof(InterfaceImplementation); var type = typeof(InterfaceImplementationInOtherAssembly); InterfaceType instance = (InterfaceType)System.Activator.CreateInstance(type); InterfaceType.UseInstance(instance); @@ -46,7 +46,7 @@ static void TestReflectionAccess() [Kept] [KeptMember(".ctor()")] [KeptInterface(typeof(InterfaceType))] - // [CreatedMember ("AbstractMethod()")] // https://github.com/dotnet/runtime/issues/104266 + // [CreatedMember("AbstractMethod()")] // https://github.com/dotnet/runtime/issues/104266 class InterfaceImplementationAccessedViaReflection : InterfaceType { } @@ -61,7 +61,7 @@ static void TestDirectAccess() [Kept] [KeptMember(".ctor()")] [KeptInterface(typeof(InterfaceType))] - // [CreatedMember ("AbstractMethod()")] // https://github.com/dotnet/runtime/issues/104266 + // [CreatedMember("AbstractMethod()")] // https://github.com/dotnet/runtime/issues/104266 class InterfaceImplementation : InterfaceType { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomMarkHandler.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomMarkHandler.cs index 7f257dc49c99de..7090ea5e3be80c 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomMarkHandler.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomMarkHandler.cs @@ -6,46 +6,46 @@ public class CustomMarkHandler : IMarkHandler { - LinkContext _context; - - public void Initialize (LinkContext context, MarkContext markContext) - { - _context = context; - markContext.RegisterMarkAssemblyAction (assembly => DiscoverTypesInAssembly (assembly)); - markContext.RegisterMarkTypeAction (type => DiscoverMethodsInType (type)); - markContext.RegisterMarkMethodAction (method => DiscoverMethodsOnDeclaringType (method)); - } - - void MarkTypeFoo (TypeDefinition type) - { - if (type.Name == "DiscoveredTypeForAssembly") - _context.Annotations.Mark (type); - - if (!type.HasNestedTypes) - return; - - foreach (var nested in type.NestedTypes) - MarkTypeFoo (nested); - } - - void DiscoverTypesInAssembly (AssemblyDefinition assembly) - { - foreach (var type in assembly.MainModule.Types) - MarkTypeFoo (type); - } - - void DiscoverMethodsInType (TypeDefinition type) - { - foreach (var method in type.Methods) { - if (method.Name == $"DiscoveredMethodForType_{type.Name}") - _context.Annotations.Mark (method); - } - } - - void DiscoverMethodsOnDeclaringType (MethodDefinition method) - { - foreach (var otherMethod in method.DeclaringType.Methods) - if (otherMethod.Name == $"DiscoveredMethodForMethod_{method.Name}") - _context.Annotations.Mark (otherMethod); - } + LinkContext _context; + + public void Initialize(LinkContext context, MarkContext markContext) + { + _context = context; + markContext.RegisterMarkAssemblyAction(assembly => DiscoverTypesInAssembly(assembly)); + markContext.RegisterMarkTypeAction(type => DiscoverMethodsInType(type)); + markContext.RegisterMarkMethodAction(method => DiscoverMethodsOnDeclaringType(method)); + } + + void MarkTypeFoo(TypeDefinition type) + { + if (type.Name == "DiscoveredTypeForAssembly") + _context.Annotations.Mark(type); + + if (!type.HasNestedTypes) + return; + + foreach (var nested in type.NestedTypes) + MarkTypeFoo(nested); + } + + void DiscoverTypesInAssembly(AssemblyDefinition assembly) + { + foreach (var type in assembly.MainModule.Types) + MarkTypeFoo(type); + } + + void DiscoverMethodsInType(TypeDefinition type) + { + foreach (var method in type.Methods) { + if (method.Name == $"DiscoveredMethodForType_{type.Name}") + _context.Annotations.Mark(method); + } + } + + void DiscoverMethodsOnDeclaringType(MethodDefinition method) + { + foreach (var otherMethod in method.DeclaringType.Methods) + if (otherMethod.Name == $"DiscoveredMethodForMethod_{method.Name}") + _context.Annotations.Mark(otherMethod); + } } \ No newline at end of file diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomStepsWithSharedState.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomStepsWithSharedState.cs index 8b6ba1d769bc88..f4804866f90ec5 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomStepsWithSharedState.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomStepsWithSharedState.cs @@ -4,58 +4,58 @@ public class SharedAnnotation { - public bool Mark { get; set; } + public bool Mark { get; set; } - public static void Set (LinkContext context, MethodDefinition method, SharedAnnotation value) - { - context.Annotations.SetCustomAnnotation (nameof (SharedAnnotation), method, value); - } + public static void Set(LinkContext context, MethodDefinition method, SharedAnnotation value) + { + context.Annotations.SetCustomAnnotation(nameof(SharedAnnotation), method, value); + } - public static SharedAnnotation Get (LinkContext context, MethodDefinition method) { - return context.Annotations.GetCustomAnnotation (nameof (SharedAnnotation), method) as SharedAnnotation; - } + public static SharedAnnotation Get(LinkContext context, MethodDefinition method) { + return context.Annotations.GetCustomAnnotation(nameof(SharedAnnotation), method) as SharedAnnotation; + } } public class SharedStateHandler1 : IMarkHandler { - LinkContext context; - - public void Initialize (LinkContext context, MarkContext markContext) - { - this.context = context; - markContext.RegisterMarkTypeAction (ProcessType); - } - - public void ProcessType (TypeDefinition type) - { - if (!type.HasMethods) - return; - - foreach (var method in type.Methods) { - if (method.Name == "MarkedMethod") - SharedAnnotation.Set (context, method, new SharedAnnotation () { Mark = true }); - } - } + LinkContext context; + + public void Initialize(LinkContext context, MarkContext markContext) + { + this.context = context; + markContext.RegisterMarkTypeAction(ProcessType); + } + + public void ProcessType(TypeDefinition type) + { + if (!type.HasMethods) + return; + + foreach (var method in type.Methods) { + if (method.Name == "MarkedMethod") + SharedAnnotation.Set(context, method, new SharedAnnotation() { Mark = true }); + } + } } public class SharedStateHandler2 : IMarkHandler { - LinkContext context; - - public void Initialize (LinkContext context, MarkContext markContext) - { - this.context = context; - markContext.RegisterMarkTypeAction (ProcessType); - } - - public void ProcessType (TypeDefinition type) - { - if (!type.HasMethods) - return; - - foreach (var method in type.Methods) { - if (SharedAnnotation.Get (context, method) is SharedAnnotation annotation && annotation.Mark) - context.Annotations.Mark (method); - } - } + LinkContext context; + + public void Initialize(LinkContext context, MarkContext markContext) + { + this.context = context; + markContext.RegisterMarkTypeAction(ProcessType); + } + + public void ProcessType(TypeDefinition type) + { + if (!type.HasMethods) + return; + + foreach (var method in type.Methods) { + if (SharedAnnotation.Get(context, method) is SharedAnnotation annotation && annotation.Mark) + context.Annotations.Mark(method); + } + } } \ No newline at end of file diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomSubStep.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomSubStep.cs index b03eab25ecfb1f..30648b0faa54dd 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomSubStep.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomSubStep.cs @@ -4,10 +4,10 @@ class CustomSubStep : BaseSubStep { - public override SubStepTargets Targets => SubStepTargets.Type; + public override SubStepTargets Targets => SubStepTargets.Type; - public override void ProcessType (TypeDefinition type) - { - Annotations.Mark (type); - } + public override void ProcessType(TypeDefinition type) + { + Annotations.Mark(type); + } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomSubStepFields.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomSubStepFields.cs index 6bb52cc5c05353..152a0a6ba74308 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomSubStepFields.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomSubStepFields.cs @@ -4,10 +4,10 @@ class CustomSubStep : BaseSubStep { - public override SubStepTargets Targets => SubStepTargets.Field; + public override SubStepTargets Targets => SubStepTargets.Field; - public override void ProcessField (FieldDefinition field) - { - Annotations.Mark (field); - } + public override void ProcessField(FieldDefinition field) + { + Annotations.Mark(field); + } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomWarning.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomWarning.cs index 9b35ce0d4f6a41..e933d717c7d6de 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomWarning.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/CustomWarning.cs @@ -6,17 +6,17 @@ public class CustomWarning : IMarkHandler { - LinkContext _context; + LinkContext _context; - public void Initialize (LinkContext context, MarkContext markContext) - { - _context = context; - markContext.RegisterMarkTypeAction (type => WarnOnKnownType (type)); - } + public void Initialize(LinkContext context, MarkContext markContext) + { + _context = context; + markContext.RegisterMarkTypeAction(type => WarnOnKnownType(type)); + } - void WarnOnKnownType (TypeDefinition type ) - { - if (type.Name == "KnownTypeThatShouldWarn") - _context.LogMessage (MessageContainer.CreateCustomWarningMessage (_context, "custom warning on type", 6200, new MessageOrigin (type), WarnVersion.ILLink5)); - } + void WarnOnKnownType(TypeDefinition type ) + { + if (type.Name == "KnownTypeThatShouldWarn") + _context.LogMessage(MessageContainer.CreateCustomWarningMessage(_context, "custom warning on type", 6200, new MessageOrigin(type), WarnVersion.ILLink5)); + } } \ No newline at end of file diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/FixAbstractMethods.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/FixAbstractMethods.cs index 99b936b64117a4..146334a81e9588 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/FixAbstractMethods.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/FixAbstractMethods.cs @@ -7,37 +7,37 @@ public class FixAbstractMethods : IMarkHandler { - LinkContext _context; + LinkContext _context; - public void Initialize (LinkContext context, MarkContext markContext) - { - _context = context; - markContext.RegisterMarkTypeAction (type => ProcessType (type)); - } + public void Initialize(LinkContext context, MarkContext markContext) + { + _context = context; + markContext.RegisterMarkTypeAction(type => ProcessType(type)); + } - void ProcessType (TypeDefinition type) - { - if (!type.Name.Contains ("InterfaceImplementation")) - return; + void ProcessType(TypeDefinition type) + { + if (!type.Name.Contains("InterfaceImplementation")) + return; - Assert (!type.IsAbstract && type.HasInterfaces); - var iface = type.Interfaces[0]; - Assert (iface.InterfaceType.Name == "InterfaceType"); - var interfaceType = iface.InterfaceType.Resolve (); - var method = interfaceType.Methods[0]; - Assert (method.Name == "AbstractMethod"); + Assert(!type.IsAbstract && type.HasInterfaces); + var iface = type.Interfaces[0]; + Assert(iface.InterfaceType.Name == "InterfaceType"); + var interfaceType = iface.InterfaceType.Resolve(); + var method = interfaceType.Methods[0]; + Assert(method.Name == "AbstractMethod"); - var newMethod = new MethodDefinition (method.Name, (method.Attributes | MethodAttributes.Final) & ~MethodAttributes.Abstract, method.ReturnType); - Assert (!method.HasParameters); - var ilProcessor = newMethod.Body.GetILProcessor (); - ilProcessor.Append (ilProcessor.Create (Mono.Cecil.Cil.OpCodes.Ret)); + var newMethod = new MethodDefinition(method.Name, (method.Attributes | MethodAttributes.Final) & ~MethodAttributes.Abstract, method.ReturnType); + Assert(!method.HasParameters); + var ilProcessor = newMethod.Body.GetILProcessor(); + ilProcessor.Append(ilProcessor.Create(Mono.Cecil.Cil.OpCodes.Ret)); - type.Methods.Add (newMethod); - } + type.Methods.Add(newMethod); + } - static void Assert (bool b) - { - if (!b) - throw new Exception (); - } + static void Assert(bool b) + { + if (!b) + throw new Exception(); + } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/InterfaceType.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/InterfaceType.cs index 9c1105ca4d57d6..0172175c0c2d6a 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/InterfaceType.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/InterfaceType.cs @@ -6,13 +6,13 @@ namespace Mono.Linker.Tests.Cases.Extensibility.Dependencies public interface InterfaceType { #if INCLUDE_ABSTRACT_METHOD - public abstract void AbstractMethod (); + public abstract void AbstractMethod(); #endif public static void UseInstance(InterfaceType instance) { #if INCLUDE_ABSTRACT_METHOD - instance.AbstractMethod (); + instance.AbstractMethod(); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/MyDispatcher.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/MyDispatcher.cs index fff1fc9881c440..a89c3e60d23a58 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/MyDispatcher.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/MyDispatcher.cs @@ -4,13 +4,13 @@ public class MyDispatcher : SubStepsDispatcher { - public MyDispatcher () - : base (GetSubSteps ()) - { - } + public MyDispatcher() + : base(GetSubSteps()) + { + } - static IEnumerable GetSubSteps () - { - yield return new CustomSubStep (); - } + static IEnumerable GetSubSteps() + { + yield return new CustomSubStep(); + } } \ No newline at end of file diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/MyMarkSubStepsDispatcher.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/MyMarkSubStepsDispatcher.cs index 9dab0d3feeec6c..87bc02ce424869 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/MyMarkSubStepsDispatcher.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/MyMarkSubStepsDispatcher.cs @@ -5,18 +5,18 @@ public class MyMarkSubStepsDispatcher : MarkSubStepsDispatcher { - public MyMarkSubStepsDispatcher () - : base (GetSubSteps ()) - { - } + public MyMarkSubStepsDispatcher() + : base(GetSubSteps()) + { + } - public override void Initialize (LinkContext context, MarkContext markContext) - { - base.Initialize (context, markContext); - } + public override void Initialize(LinkContext context, MarkContext markContext) + { + base.Initialize(context, markContext); + } - static IEnumerable GetSubSteps () - { - yield return new CustomSubStep (); - } + static IEnumerable GetSubSteps() + { + yield return new CustomSubStep(); + } } \ No newline at end of file diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/PreserveMethodsSubStep.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/PreserveMethodsSubStep.cs index f67df3119724e4..1b2004a371a9c8 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/PreserveMethodsSubStep.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/PreserveMethodsSubStep.cs @@ -5,38 +5,38 @@ class PreserveMethodsSubStep : BaseStep { - protected override void Process () - { - foreach (var assembly in Context.GetAssemblies ()) { - foreach (var type in assembly.MainModule.Types) - ProcessType (type); - } - } - - void ProcessType (TypeDefinition type) - { - if (type.HasNestedTypes) { - foreach (var nested in type.NestedTypes) - ProcessType (nested); - } - - - foreach (var method in type.Methods) { - if (method.Name == "PreservedForType") - Annotations.AddPreservedMethod (type, method); - - ProcessMethod (method); - } - } - - public void ProcessMethod (MethodDefinition method) - { - if (method.Name == "MarkedMethod") - Annotations.Mark (method); - - foreach (var m in method.DeclaringType.Methods) { - if (m.Name == $"PreservedForMethod_{method.Name}") - Annotations.AddPreservedMethod (method, m); - } - } + protected override void Process() + { + foreach (var assembly in Context.GetAssemblies()) { + foreach (var type in assembly.MainModule.Types) + ProcessType(type); + } + } + + void ProcessType(TypeDefinition type) + { + if (type.HasNestedTypes) { + foreach (var nested in type.NestedTypes) + ProcessType(nested); + } + + + foreach (var method in type.Methods) { + if (method.Name == "PreservedForType") + Annotations.AddPreservedMethod(type, method); + + ProcessMethod(method); + } + } + + public void ProcessMethod(MethodDefinition method) + { + if (method.Name == "MarkedMethod") + Annotations.Mark(method); + + foreach (var m in method.DeclaringType.Methods) { + if (m.Name == $"PreservedForMethod_{method.Name}") + Annotations.AddPreservedMethod(method, m); + } + } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/ResolveTypesSubStep.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/ResolveTypesSubStep.cs index 9327d2152dee1a..a7970314750a5f 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/ResolveTypesSubStep.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Extensibility/Dependencies/ResolveTypesSubStep.cs @@ -5,30 +5,30 @@ class ResolveTypesSubStep : BaseStep { - protected override void Process () - { - foreach (var assembly in Context.GetAssemblies ()) { - foreach (var type in assembly.MainModule.Types) - ProcessType (type); - } - } + protected override void Process() + { + foreach (var assembly in Context.GetAssemblies()) { + foreach (var type in assembly.MainModule.Types) + ProcessType(type); + } + } - void ProcessType (TypeDefinition type) - { - if (type.HasNestedTypes) { - foreach (var nested in type.NestedTypes) - ProcessType (nested); - } + void ProcessType(TypeDefinition type) + { + if (type.HasNestedTypes) { + foreach (var nested in type.NestedTypes) + ProcessType(nested); + } - if (type.Name == "TypeWithFields") { - foreach (var field in type.Fields) - ProcessField (field); - } - } + if (type.Name == "TypeWithFields") { + foreach (var field in type.Fields) + ProcessField(field); + } + } - public void ProcessField (FieldDefinition field) - { - if (field.FieldType.Resolve () == null) - throw new Exception($"Unresolved field type {field.FieldType} for field {field}!"); - } + public void ProcessField(FieldDefinition field) + { + if (field.FieldType.Resolve() == null) + throw new Exception($"Unresolved field type {field.FieldType} for field {field}!"); + } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/DimProvidedByRecursiveInterface.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/DimProvidedByRecursiveInterface.cs index 2ba25566d453e6..ba43a9abdd2686 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/DimProvidedByRecursiveInterface.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/DimProvidedByRecursiveInterface.cs @@ -12,22 +12,22 @@ namespace Mono.Linker.Tests.Cases.Inheritance.Interfaces.DefaultInterfaceMethods [SkipILVerify] #if IL_ASSEMBLY_AVAILABLE - [KeptMemberInAssembly ("library.dll", typeof(Program.IFoo), "Method()")] - [KeptTypeInAssembly ("library.dll", typeof(Program.IBar))] - [KeptMemberInAssembly ("library.dll", typeof(Program.IBar), "Program.IFoo.Method()")] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Program.IBar), "library.dll", typeof (Program.IFoo))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Program.MyFoo), "library.dll", typeof (Program.IBaz))] - [KeptTypeInAssembly ("library.dll", typeof(Program.IBaz))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Program.IBaz), "library.dll", typeof (Program.IBar))] - [KeptMemberInAssembly ("library.dll", typeof(Program), "CallMethod(Program/IFoo)")] + [KeptMemberInAssembly("library.dll", typeof(Program.IFoo), "Method()")] + [KeptTypeInAssembly("library.dll", typeof(Program.IBar))] + [KeptMemberInAssembly("library.dll", typeof(Program.IBar), "Program.IFoo.Method()")] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Program.IBar), "library.dll", typeof(Program.IFoo))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Program.MyFoo), "library.dll", typeof(Program.IBaz))] + [KeptTypeInAssembly("library.dll", typeof(Program.IBaz))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Program.IBaz), "library.dll", typeof(Program.IBar))] + [KeptMemberInAssembly("library.dll", typeof(Program), "CallMethod(Program/IFoo)")] #endif class DimProvidedByRecursiveInterface { static void Main() { #if IL_ASSEMBLY_AVAILABLE - Program.IFoo foo = new Program.MyFoo (); - Program.CallMethod(foo); + Program.IFoo foo = new Program.MyFoo(); + Program.CallMethod(foo); #endif } } @@ -37,31 +37,31 @@ static void Main() // public static class Program // { -// [Kept] -// interface IFoo -// { -// void Method(); -// } +// [Kept] +// interface IFoo +// { +// void Method(); +// } -// [Kept] -// interface IBar : IFoo -// { -// [Kept] -// void IFoo.Method() { } -// } +// [Kept] +// interface IBar : IFoo +// { +// [Kept] +// void IFoo.Method() { } +// } -// [Kept] -// interface IBaz: IBar /* not IFoo */ -// { -// } +// [Kept] +// interface IBaz: IBar /* not IFoo */ +// { +// } -// [Kept] -// [KeptInterface(typeof(IBaz))] -// class MyFoo : IBaz /* not IBar, not IFoo */ -// { } +// [Kept] +// [KeptInterface(typeof(IBaz))] +// class MyFoo : IBaz /* not IBar, not IFoo */ +// { } -// static void CallMethod(IFoo foo) -// { -// foo.Method(); -// } +// static void CallMethod(IFoo foo) +// { +// foo.Method(); +// } // } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/InterfaceWithAttributeOnImplementation.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/InterfaceWithAttributeOnImplementation.cs index 5a7edcdc42d17b..cb237acb8a4d55 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/InterfaceWithAttributeOnImplementation.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/InterfaceWithAttributeOnImplementation.cs @@ -12,7 +12,7 @@ class InterfaceWithAttributeOnImplementation static void Main() { #if IL_ASSEMBLY_AVAILABLE - ((IMyInterface)new MyClass ()).Frob (); + ((IMyInterface)new MyClass()).Frob(); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/MultipleDimsProvidedByRecursiveInterface.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/MultipleDimsProvidedByRecursiveInterface.cs index 1210f73d7b34ad..e6c2055b133160 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/MultipleDimsProvidedByRecursiveInterface.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/MultipleDimsProvidedByRecursiveInterface.cs @@ -12,36 +12,36 @@ namespace Mono.Linker.Tests.Cases.Inheritance.Interfaces.DefaultInterfaceMethods [SkipILVerify] #if IL_ASSEMBLY_AVAILABLE - // Both DIMs on I01 and I00 should be kept because one is not more specific than another. - [KeptMemberInAssembly ("library.dll", typeof(Program.I0), "Method()")] - [KeptTypeInAssembly ("library.dll", typeof(Program.I00))] - [KeptMemberInAssembly ("library.dll", typeof(Program.I00), "Program.I0.Method()")] - // Bug: DIM resolution doesn't look at recursive interfaces - //[KeptMemberInAssembly ("library.dll", typeof(Program.I01), "Program.I0.Method()")] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Program.I00), "library.dll", typeof (Program.I0))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Program.MyFoo), "library.dll", typeof (Program.I000))] - [KeptTypeInAssembly ("library.dll", typeof(Program.I000))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Program.I000), "library.dll", typeof (Program.I00))] - // Bug: DIM resolution doesn't look at recursive interfaces - //[KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Program.MyFoo), "library.dll", typeof (Program.I010))] - //[KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Program.I010), "library.dll", typeof (Program.I01))] - //[KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Program.I01), "library.dll", typeof (Program.I0))] + // Both DIMs on I01 and I00 should be kept because one is not more specific than another. + [KeptMemberInAssembly("library.dll", typeof(Program.I0), "Method()")] + [KeptTypeInAssembly("library.dll", typeof(Program.I00))] + [KeptMemberInAssembly("library.dll", typeof(Program.I00), "Program.I0.Method()")] + // Bug: DIM resolution doesn't look at recursive interfaces + //[KeptMemberInAssembly("library.dll", typeof(Program.I01), "Program.I0.Method()")] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Program.I00), "library.dll", typeof(Program.I0))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Program.MyFoo), "library.dll", typeof(Program.I000))] + [KeptTypeInAssembly("library.dll", typeof(Program.I000))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Program.I000), "library.dll", typeof(Program.I00))] + // Bug: DIM resolution doesn't look at recursive interfaces + //[KeptInterfaceOnTypeInAssembly("library.dll", typeof(Program.MyFoo), "library.dll", typeof(Program.I010))] + //[KeptInterfaceOnTypeInAssembly("library.dll", typeof(Program.I010), "library.dll", typeof(Program.I01))] + //[KeptInterfaceOnTypeInAssembly("library.dll", typeof(Program.I01), "library.dll", typeof(Program.I0))] #endif class MultipleDimsProvidedByRecursiveInterface { static void Main() { #if IL_ASSEMBLY_AVAILABLE - Program.I0 foo = new Program.MyFoo (); - CallMethod(foo); + Program.I0 foo = new Program.MyFoo(); + CallMethod(foo); #endif } #if IL_ASSEMBLY_AVAILABLE - [Kept] - static void CallMethod(Program.I0 foo) - { - foo.Method(); - } + [Kept] + static void CallMethod(Program.I0 foo) + { + foo.Method(); + } #endif } } @@ -50,39 +50,39 @@ static void CallMethod(Program.I0 foo) // public static class Program // { -// [Kept] -// interface I0 -// { -// void Method(); -// } +// [Kept] +// interface I0 +// { +// void Method(); +// } -// [Kept] -// interface I00 : I0 -// { -// [Kept] -// void I0.Method() { } -// } +// [Kept] +// interface I00 : I0 +// { +// [Kept] +// void I0.Method() { } +// } -// [Kept] -// interface I000: I00 /* not I0 */ -// { -// } +// [Kept] +// interface I000: I00 /* not I0 */ +// { +// } -// [Kept] -// interface I01 : I0 -// { -// [Kept] -// void I0.Method() { } -// } +// [Kept] +// interface I01 : I0 +// { +// [Kept] +// void I0.Method() { } +// } -// [Kept] -// interface I010: I01 /* not I0 */ -// { -// } +// [Kept] +// interface I010: I01 /* not I0 */ +// { +// } -// [Kept] -// [KeptInterface(typeof(I000))] -// class MyFoo : I000, I010 -// { } +// [Kept] +// [KeptInterface(typeof(I000))] +// class MyFoo : I000, I010 +// { } // } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/StaticDimProvidedByUnreferencedIfaceInHierarchy.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/StaticDimProvidedByUnreferencedIfaceInHierarchy.cs index 78425e248a49b1..7d894eb292d588 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/StaticDimProvidedByUnreferencedIfaceInHierarchy.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/DefaultInterfaceMethods/StaticDimProvidedByUnreferencedIfaceInHierarchy.cs @@ -12,23 +12,23 @@ namespace Mono.Linker.Tests.Cases.Inheritance.Interfaces.DefaultInterfaceMethods [SkipILVerify] #if IL_ASSEMBLY_AVAILABLE - [KeptMemberInAssembly ("library.dll", typeof(Program), "CallMethod<#1>()")] - [KeptTypeInAssembly ("library.dll", typeof(Program.IBase))] - [KeptMemberInAssembly ("library.dll", typeof(Program.IBase), "Method()")] - [KeptTypeInAssembly ("library.dll", typeof(Program.I4))] - [KeptTypeInAssembly ("library.dll", typeof(Program.I2))] - [KeptMemberInAssembly ("library.dll", typeof(Program.I2), "Program.IBase.Method()")] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Program.I2), "library.dll", typeof (Program.IBase))] - [KeptTypeInAssembly ("library.dll", typeof(Program.I3))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Program.I3), "library.dll", typeof (Program.I2))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Program.I4), "library.dll", typeof (Program.I3))] + [KeptMemberInAssembly("library.dll", typeof(Program), "CallMethod<#1>()")] + [KeptTypeInAssembly("library.dll", typeof(Program.IBase))] + [KeptMemberInAssembly("library.dll", typeof(Program.IBase), "Method()")] + [KeptTypeInAssembly("library.dll", typeof(Program.I4))] + [KeptTypeInAssembly("library.dll", typeof(Program.I2))] + [KeptMemberInAssembly("library.dll", typeof(Program.I2), "Program.IBase.Method()")] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Program.I2), "library.dll", typeof(Program.IBase))] + [KeptTypeInAssembly("library.dll", typeof(Program.I3))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Program.I3), "library.dll", typeof(Program.I2))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Program.I4), "library.dll", typeof(Program.I3))] #endif class StaticDimProvidedByUnreferencedIfaceInHierarchy { static void Main() { #if IL_ASSEMBLY_AVAILABLE - Program.CallMethod(); + Program.CallMethod(); #endif } } @@ -38,32 +38,32 @@ static void Main() // public static class Program // { -// [Kept] -// interface IBase -// { -// [Kept] -// static abstract void Method(); -// } +// [Kept] +// interface IBase +// { +// [Kept] +// static abstract void Method(); +// } -// [Kept] -// [KeptInterface(typeof(IBase)] -// interface I2 : IBase -// { -// [Kept] -// static void IBase.Method() { } -// } +// [Kept] +// [KeptInterface(typeof(IBase)] +// interface I2 : IBase +// { +// [Kept] +// static void IBase.Method() { } +// } -// [Kept] -// [KeptInterface(typeof(I2)] -// interface I3 : I2 { } +// [Kept] +// [KeptInterface(typeof(I2)] +// interface I3 : I2 { } -// [Kept] -// [KeptInterface(typeof(I3)] -// interface I4 : I3 { } +// [Kept] +// [KeptInterface(typeof(I3)] +// interface I4 : I3 { } -// [Kept] -// static void CallMethod() where T : IBase -// { -// T.Method(); -// } +// [Kept] +// static void CallMethod() where T : IBase +// { +// T.Method(); +// } // } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/InterfaceImplementedThroughBaseInterface.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/InterfaceImplementedThroughBaseInterface.cs index 786181d2c0f219..3c008ad2ef82a5 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/InterfaceImplementedThroughBaseInterface.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/InterfaceImplementedThroughBaseInterface.cs @@ -20,7 +20,7 @@ namespace Mono.Linker.Tests.Cases.Inheritance.Interfaces [SkipILVerify] #if IL_ASSEMBLY_AVAILABLE - [KeptMemberInAssembly ("library.dll", typeof(C), "IBase.M()")] + [KeptMemberInAssembly("library.dll", typeof(C), "IBase.M()")] #endif [KeptMember(".ctor()")] public class InterfaceImplementedThroughBaseInterface diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/OnReferenceType/NoInstanceCtor/NoInstanceCtorAndTypePreserveFieldsWithInterfacesMarked.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/OnReferenceType/NoInstanceCtor/NoInstanceCtorAndTypePreserveFieldsWithInterfacesMarked.cs index 1b05f7275518d9..19a80a761e0bce 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/OnReferenceType/NoInstanceCtor/NoInstanceCtorAndTypePreserveFieldsWithInterfacesMarked.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/OnReferenceType/NoInstanceCtor/NoInstanceCtorAndTypePreserveFieldsWithInterfacesMarked.cs @@ -31,7 +31,7 @@ public class NoInstanceCtorAndTypePreserveFieldsWithInterfacesMarked public static void Main() { #if IL_ASSEMBLY_COMPILED - var tmp = typeof (Mono.Linker.Tests.Cases.Inheritance.Interfaces.OnReferenceType.NoInstanceCtor.Dependencies.NoInstanceCtorAndAssemblyPreserveAll_Lib.IFoo).ToString (); + var tmp = typeof(Mono.Linker.Tests.Cases.Inheritance.Interfaces.OnReferenceType.NoInstanceCtor.Dependencies.NoInstanceCtorAndAssemblyPreserveAll_Lib.IFoo).ToString(); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/OnReferenceType/NoInstanceCtor/NoInstanceCtorAndTypePreserveMethodsWithInterfacesMarked.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/OnReferenceType/NoInstanceCtor/NoInstanceCtorAndTypePreserveMethodsWithInterfacesMarked.cs index b94e4c4ea498fd..88ea83bb4587d4 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/OnReferenceType/NoInstanceCtor/NoInstanceCtorAndTypePreserveMethodsWithInterfacesMarked.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/OnReferenceType/NoInstanceCtor/NoInstanceCtorAndTypePreserveMethodsWithInterfacesMarked.cs @@ -31,7 +31,7 @@ public static void Main() { // We'll mark one interface in code and one via xml, the end result should be the same #if IL_ASSEMBLY_COMPILED - var tmp = typeof (Mono.Linker.Tests.Cases.Inheritance.Interfaces.OnReferenceType.NoInstanceCtor.Dependencies.NoInstanceCtorAndAssemblyPreserveAll_Lib.IFoo).ToString (); + var tmp = typeof(Mono.Linker.Tests.Cases.Inheritance.Interfaces.OnReferenceType.NoInstanceCtor.Dependencies.NoInstanceCtorAndAssemblyPreserveAll_Lib.IFoo).ToString(); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/GenericInterfaceImplementedRecursively.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/GenericInterfaceImplementedRecursively.cs index b62d53e0992ed3..17f21597136428 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/GenericInterfaceImplementedRecursively.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/GenericInterfaceImplementedRecursively.cs @@ -17,13 +17,13 @@ namespace Mono.Linker.Tests.Cases.Inheritance.Interfaces.RecursiveInterfaces [SetupCompileBefore("library.dll", new[] { "Dependencies/GenericInterfaceImplementedRecursively.il" })] [SkipILVerify] #if IL_ASSEMBLY_AVAILABLE - [KeptTypeInAssembly ("library.dll", typeof(Program.IBase<>))] - [KeptTypeInAssembly ("library.dll", typeof(Program.IMiddle<>))] - [KeptInterfaceOnTypeInAssembly ("library.dll", "Program/IMiddle`1", "library.dll", "Program/IBase`1")] - [KeptTypeInAssembly ("library.dll", typeof(Program.IDerived<>))] - [KeptInterfaceOnTypeInAssembly ("library.dll", "Program/IDerived`1", "library.dll", "Program/IMiddle`1")] - [KeptTypeInAssembly ("library.dll", typeof(Program.C))] - [KeptInterfaceOnTypeInAssembly ("library.dll", "Program/C", "library.dll", "Program/IDerived`1")] + [KeptTypeInAssembly("library.dll", typeof(Program.IBase<>))] + [KeptTypeInAssembly("library.dll", typeof(Program.IMiddle<>))] + [KeptInterfaceOnTypeInAssembly("library.dll", "Program/IMiddle`1", "library.dll", "Program/IBase`1")] + [KeptTypeInAssembly("library.dll", typeof(Program.IDerived<>))] + [KeptInterfaceOnTypeInAssembly("library.dll", "Program/IDerived`1", "library.dll", "Program/IMiddle`1")] + [KeptTypeInAssembly("library.dll", typeof(Program.C))] + [KeptInterfaceOnTypeInAssembly("library.dll", "Program/C", "library.dll", "Program/IDerived`1")] #endif /// /// This test case is to verify that the linker will keep all the metadata necessary for C to implement IBase when an interfaceImpl isn't directly on C. @@ -34,8 +34,8 @@ public static void Main() { #if IL_ASSEMBLY_AVAILABLE - Program.IBase _ = null; - _ = new Program.C(); + Program.IBase _ = null; + _ = new Program.C(); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/InterfaceImplementedRecursively.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/InterfaceImplementedRecursively.cs index f3f819447761a5..3be089bf915dc9 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/InterfaceImplementedRecursively.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/InterfaceImplementedRecursively.cs @@ -17,13 +17,13 @@ namespace Mono.Linker.Tests.Cases.Inheritance.Interfaces.RecursiveInterfaces [SetupCompileBefore("library.dll", new[] { "Dependencies/InterfaceImplementedRecursively.il" })] [SkipILVerify] #if IL_ASSEMBLY_AVAILABLE - [KeptTypeInAssembly ("library.dll", typeof(Program.IBase))] - [KeptTypeInAssembly ("library.dll", typeof(Program.IMiddle))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Program.IMiddle), "library.dll", typeof (Program.IBase))] - [KeptTypeInAssembly ("library.dll", typeof(Program.IDerived))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Program.IDerived), "library.dll", typeof (Program.IMiddle))] - [KeptTypeInAssembly ("library.dll", typeof(Program.C))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Program.C), "library.dll", typeof (Program.IDerived))] + [KeptTypeInAssembly("library.dll", typeof(Program.IBase))] + [KeptTypeInAssembly("library.dll", typeof(Program.IMiddle))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Program.IMiddle), "library.dll", typeof(Program.IBase))] + [KeptTypeInAssembly("library.dll", typeof(Program.IDerived))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Program.IDerived), "library.dll", typeof(Program.IMiddle))] + [KeptTypeInAssembly("library.dll", typeof(Program.C))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Program.C), "library.dll", typeof(Program.IDerived))] #endif /// /// This test case is to verify that the linker will keep all the metadata necessary for C to implement IBase when an interfaceImpl isn't directly on C. @@ -34,8 +34,8 @@ public static void Main() { #if IL_ASSEMBLY_AVAILABLE - Program.IBase b = null; - object c = new Program.C(); + Program.IBase b = null; + object c = new Program.C(); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/OverrideOfRecursiveInterfaceIsRemoved.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/OverrideOfRecursiveInterfaceIsRemoved.cs index 0c9b36eb5d5a9d..55d16c74d0448b 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/OverrideOfRecursiveInterfaceIsRemoved.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/OverrideOfRecursiveInterfaceIsRemoved.cs @@ -36,8 +36,8 @@ public class OverrideOfRecursiveInterfaceIsRemoved public static void Main() { #if IL_ASSEMBLY_AVAILABLE - Program.MyTest(); - _ = typeof(Program.IBaseUnused); + Program.MyTest(); + _ = typeof(Program.IBaseUnused); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/RecursiveInterfaceKept.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/RecursiveInterfaceKept.cs index eddc6efae8879f..99b5191ff514c4 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/RecursiveInterfaceKept.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/RecursiveInterfaces/RecursiveInterfaceKept.cs @@ -15,21 +15,21 @@ namespace Mono.Linker.Tests.Cases.Inheritance.Interfaces.RecursiveInterfaces [SetupCompileBefore("library.dll", new[] { "Dependencies/RecursiveInterfaceTwoImplementationPaths.il" })] [SkipILVerify] #if IL_ASSEMBLY_AVAILABLE - [KeptTypeInAssembly ("library.dll", typeof(Library.MyClass))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Library.MyClass), "library.dll", typeof (Library.I0100))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Library.I0100), "library.dll", typeof (Library.I010))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Library.I010), "library.dll", typeof (Library.I01))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (Library.I01), "library.dll", typeof (Library.I0))] - [RemovedTypeInAssembly("library.dll", typeof(Library.I00))] - [RemovedTypeInAssembly("library.dll", typeof(Library.I000))] - [RemovedInterfaceOnTypeInAssembly("library.dll", typeof (Library.MyClass), "library.dll", typeof (Library.I000))] + [KeptTypeInAssembly("library.dll", typeof(Library.MyClass))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Library.MyClass), "library.dll", typeof(Library.I0100))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Library.I0100), "library.dll", typeof(Library.I010))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Library.I010), "library.dll", typeof(Library.I01))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(Library.I01), "library.dll", typeof(Library.I0))] + [RemovedTypeInAssembly("library.dll", typeof(Library.I00))] + [RemovedTypeInAssembly("library.dll", typeof(Library.I000))] + [RemovedInterfaceOnTypeInAssembly("library.dll", typeof(Library.MyClass), "library.dll", typeof(Library.I000))] #endif public class RecursiveInterfaceKept { public static void Main() { #if IL_ASSEMBLY_AVAILABLE - Library.I0 _ = new Library.MyClass(); + Library.I0 _ = new Library.MyClass(); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/Dependencies/CustomStepSaveAssembly.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/Dependencies/CustomStepSaveAssembly.cs index 031e4d69752b4b..a3558707c22661 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/Dependencies/CustomStepSaveAssembly.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/Dependencies/CustomStepSaveAssembly.cs @@ -5,9 +5,9 @@ public class CustomStepSaveAssembly : BaseStep { - protected override void ProcessAssembly (AssemblyDefinition assembly) + protected override void ProcessAssembly(AssemblyDefinition assembly) { if (assembly.Name.Name == "test") - Context.Annotations.SetAction (assembly, AssemblyAction.Save); + Context.Annotations.SetAction(assembly, AssemblyAction.Save); } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/InstanceMethodsWithOverridesSwept.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/InstanceMethodsWithOverridesSwept.cs index 54da4573175738..79563e1391dfad 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/InstanceMethodsWithOverridesSwept.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/InstanceMethodsWithOverridesSwept.cs @@ -22,38 +22,38 @@ namespace Mono.Linker.Tests.Cases.Inheritance.Interfaces.StaticInterfaceMethods [SetupCompileBefore("library.dll", new string[] { "Dependencies/InstanceMethods.il" })] [Kept] #if IL_ASSEMBLY_AVAILABLE - [KeptTypeInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodAccessedViaInterface))] - [KeptTypeInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodAccessedDirectly))] - [KeptTypeInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodAccessedViaReflection))] - [KeptTypeInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodKeptByDynamicDependency))] - [KeptTypeInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodCalledDirectlyAndInterfaceUnreferenced))] - [KeptTypeInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodCalledDirectlyAndRecursiveInterfaceUnreferenced))] - [KeptTypeInAssembly ("library.dll", typeof (InstanceMethods.IInt))] - [KeptTypeInAssembly ("library.dll", typeof (InstanceMethods.IIntUnreferenced))] // Kept only because of the .override on the public implementation method - [KeptTypeInAssembly ("library.dll", typeof (InstanceMethods.IIntBase))] - [KeptTypeInAssembly ("library.dll", typeof (InstanceMethods.IIntDerived))] - [KeptTypeInAssembly ("library.dll", typeof (InstanceMethods.IGeneric<>))] - [KeptTypeInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodCalledDirectlyAndTwoGenericInterfacesUnreferenced))] - [KeptMemberInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodAccessedViaInterface), ["GetInt()"])] - [KeptMemberInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodAccessedDirectly), ["GetInt()"])] - [KeptMemberInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodAccessedViaReflection), ["GetInt()"])] - [KeptMemberInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodKeptByDynamicDependency), ["GetInt()"])] - [KeptMemberInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodCalledDirectlyAndInterfaceUnreferenced), ["GetInt()"])] - [KeptMemberInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodCalledDirectlyAndRecursiveInterfaceUnreferenced), ["GetInt()"])] - [KeptMemberInAssembly ("library.dll", typeof (InstanceMethods.IInt), ["GetInt()"])] - [KeptMemberInAssembly ("library.dll", typeof (InstanceMethods.IIntUnreferenced), ["GetInt()"])] - [KeptMemberInAssembly ("library.dll", typeof (InstanceMethods.IIntBase), ["GetInt()"])] - [KeptMemberInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodCalledDirectlyAndTwoGenericInterfacesUnreferenced), ["GetIntInt()"])] - [KeptMemberInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodCalledDirectlyAndTwoGenericInterfacesUnreferenced), ["GetIntFloat()"])] // Could be removed - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodAccessedViaInterface), "library.dll", typeof (InstanceMethods.IInt))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodAccessedDirectly), "library.dll", typeof (InstanceMethods.IInt))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodAccessedViaReflection), "library.dll", typeof (InstanceMethods.IInt))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodKeptByDynamicDependency), "library.dll", typeof (InstanceMethods.IInt))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodCalledDirectlyAndInterfaceUnreferenced), "library.dll", typeof (InstanceMethods.IIntUnreferenced))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (InstanceMethods.TypeWithMethodCalledDirectlyAndRecursiveInterfaceUnreferenced), "library.dll", typeof (InstanceMethods.IIntDerived))] - [KeptInterfaceOnTypeInAssembly ("library.dll", typeof (InstanceMethods.IIntDerived), "library.dll", typeof (InstanceMethods.IIntBase))] - [KeptInterfaceOnTypeInAssembly ("library.dll", "InstanceMethods/TypeWithMethodCalledDirectlyAndTwoGenericInterfacesUnreferenced", "library.dll", "InstanceMethods/IGeneric`1")] - [KeptInterfaceOnTypeInAssembly ("library.dll", "InstanceMethods/TypeWithMethodCalledDirectlyAndTwoGenericInterfacesUnreferenced", "library.dll", "InstanceMethods/IGeneric`1")] + [KeptTypeInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodAccessedViaInterface))] + [KeptTypeInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodAccessedDirectly))] + [KeptTypeInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodAccessedViaReflection))] + [KeptTypeInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodKeptByDynamicDependency))] + [KeptTypeInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodCalledDirectlyAndInterfaceUnreferenced))] + [KeptTypeInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodCalledDirectlyAndRecursiveInterfaceUnreferenced))] + [KeptTypeInAssembly("library.dll", typeof(InstanceMethods.IInt))] + [KeptTypeInAssembly("library.dll", typeof(InstanceMethods.IIntUnreferenced))] // Kept only because of the .override on the public implementation method + [KeptTypeInAssembly("library.dll", typeof(InstanceMethods.IIntBase))] + [KeptTypeInAssembly("library.dll", typeof(InstanceMethods.IIntDerived))] + [KeptTypeInAssembly("library.dll", typeof(InstanceMethods.IGeneric<>))] + [KeptTypeInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodCalledDirectlyAndTwoGenericInterfacesUnreferenced))] + [KeptMemberInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodAccessedViaInterface), ["GetInt()"])] + [KeptMemberInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodAccessedDirectly), ["GetInt()"])] + [KeptMemberInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodAccessedViaReflection), ["GetInt()"])] + [KeptMemberInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodKeptByDynamicDependency), ["GetInt()"])] + [KeptMemberInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodCalledDirectlyAndInterfaceUnreferenced), ["GetInt()"])] + [KeptMemberInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodCalledDirectlyAndRecursiveInterfaceUnreferenced), ["GetInt()"])] + [KeptMemberInAssembly("library.dll", typeof(InstanceMethods.IInt), ["GetInt()"])] + [KeptMemberInAssembly("library.dll", typeof(InstanceMethods.IIntUnreferenced), ["GetInt()"])] + [KeptMemberInAssembly("library.dll", typeof(InstanceMethods.IIntBase), ["GetInt()"])] + [KeptMemberInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodCalledDirectlyAndTwoGenericInterfacesUnreferenced), ["GetIntInt()"])] + [KeptMemberInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodCalledDirectlyAndTwoGenericInterfacesUnreferenced), ["GetIntFloat()"])] // Could be removed + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodAccessedViaInterface), "library.dll", typeof(InstanceMethods.IInt))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodAccessedDirectly), "library.dll", typeof(InstanceMethods.IInt))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodAccessedViaReflection), "library.dll", typeof(InstanceMethods.IInt))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodKeptByDynamicDependency), "library.dll", typeof(InstanceMethods.IInt))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodCalledDirectlyAndInterfaceUnreferenced), "library.dll", typeof(InstanceMethods.IIntUnreferenced))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(InstanceMethods.TypeWithMethodCalledDirectlyAndRecursiveInterfaceUnreferenced), "library.dll", typeof(InstanceMethods.IIntDerived))] + [KeptInterfaceOnTypeInAssembly("library.dll", typeof(InstanceMethods.IIntDerived), "library.dll", typeof(InstanceMethods.IIntBase))] + [KeptInterfaceOnTypeInAssembly("library.dll", "InstanceMethods/TypeWithMethodCalledDirectlyAndTwoGenericInterfacesUnreferenced", "library.dll", "InstanceMethods/IGeneric`1")] + [KeptInterfaceOnTypeInAssembly("library.dll", "InstanceMethods/TypeWithMethodCalledDirectlyAndTwoGenericInterfacesUnreferenced", "library.dll", "InstanceMethods/IGeneric`1")] #endif public class InstanceMethodsWithOverridesSwept { @@ -61,17 +61,17 @@ public class InstanceMethodsWithOverridesSwept public static void Main() { #if IL_ASSEMBLY_AVAILABLE - InstanceMethods.Test (); - typeof (InstanceMethods.TypeWithMethodAccessedViaReflection).GetMethod ("GetInt").Invoke (null, null); - new InstanceMethods.TypeWithMethodCalledDirectlyAndInterfaceUnreferenced ().GetInt (); - new InstanceMethods.TypeWithMethodCalledDirectlyAndRecursiveInterfaceUnreferenced ().GetInt (); - new InstanceMethods.TypeWithMethodCalledDirectlyAndTwoGenericInterfacesUnreferenced ().GetIntInt (); + InstanceMethods.Test(); + typeof(InstanceMethods.TypeWithMethodAccessedViaReflection).GetMethod("GetInt").Invoke(null, null); + new InstanceMethods.TypeWithMethodCalledDirectlyAndInterfaceUnreferenced().GetInt(); + new InstanceMethods.TypeWithMethodCalledDirectlyAndRecursiveInterfaceUnreferenced().GetInt(); + new InstanceMethods.TypeWithMethodCalledDirectlyAndTwoGenericInterfacesUnreferenced().GetIntInt(); #endif KeepTypeThroughDynamicDependency(); } #if IL_ASSEMBLY_AVAILABLE - [DynamicDependency ("GetInt()", typeof (InstanceMethods.TypeWithMethodKeptByDynamicDependency))] + [DynamicDependency("GetInt()", typeof(InstanceMethods.TypeWithMethodKeptByDynamicDependency))] #endif [Kept] public static void KeepTypeThroughDynamicDependency() diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/OverrideInCopyAssembly.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/OverrideInCopyAssembly.cs index 6f7dd19342f9c5..57a420e2822051 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/OverrideInCopyAssembly.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/OverrideInCopyAssembly.cs @@ -13,12 +13,12 @@ namespace Mono.Linker.Tests.Cases.Inheritance.Interfaces.StaticInterfaceMethods [SetupLinkerAction("link", "library")] [SetupLinkerAction("copy", "test")] /// - /// Regression test for issue: https://github.com/dotnet/runtime/issues/81746 - /// OverridesStaticInterfaceMethods.Method() (and Property.set/get) has an entry in .overrides pointing to IStaticAbstractMethods.Method. - /// IStaticAbstractMethods.Method() isn't referenced anywhere else and isn't otherwise needed. - /// Usually the interface method could be removed, and the pointer to it in the .overrides metadata would be removed - /// However, since OverridesStaticInterfaceMethods is in a 'copy' assembly, the .overrides metadata isn't swept. If we remove the method from the interface, - /// we have a "dangling reference" which makes the metadata invalid. + /// Regression test for issue: https://github.com/dotnet/runtime/issues/81746 + /// OverridesStaticInterfaceMethods.Method() (and Property.set/get) has an entry in .overrides pointing to IStaticAbstractMethods.Method. + /// IStaticAbstractMethods.Method() isn't referenced anywhere else and isn't otherwise needed. + /// Usually the interface method could be removed, and the pointer to it in the .overrides metadata would be removed + /// However, since OverridesStaticInterfaceMethods is in a 'copy' assembly, the .overrides metadata isn't swept. If we remove the method from the interface, + /// we have a "dangling reference" which makes the metadata invalid. /// static class OverrideInCopyAssembly { diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/OverrideInSaveAssembly.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/OverrideInSaveAssembly.cs index 27d972ae9d677b..4bdae0d44fea9a 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/OverrideInSaveAssembly.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/OverrideInSaveAssembly.cs @@ -15,12 +15,12 @@ namespace Mono.Linker.Tests.Cases.Inheritance.Interfaces.StaticInterfaceMethods [SetupCompileBefore("library.dll", new[] { "Dependencies/Library.cs" })] [SetupLinkerAction("link", "library")] /// - /// Regression test for issue: https://github.com/dotnet/runtime/issues/86242 - /// OverridesStaticInterfaceMethods.Method() (and Property.set/get) has an entry in .overrides pointing to IStaticAbstractMethods.Method. - /// IStaticAbstractMethods.Method() isn't referenced anywhere else and isn't otherwise needed. - /// Usually the interface method could be removed, and the pointer to it in the .overrides metadata would be removed - /// However, since OverridesStaticInterfaceMethods is in a 'save' assembly, the .overrides metadata isn't swept. If we remove the method from the interface, - /// we have a "dangling reference" which makes the metadata invalid. + /// Regression test for issue: https://github.com/dotnet/runtime/issues/86242 + /// OverridesStaticInterfaceMethods.Method() (and Property.set/get) has an entry in .overrides pointing to IStaticAbstractMethods.Method. + /// IStaticAbstractMethods.Method() isn't referenced anywhere else and isn't otherwise needed. + /// Usually the interface method could be removed, and the pointer to it in the .overrides metadata would be removed + /// However, since OverridesStaticInterfaceMethods is in a 'save' assembly, the .overrides metadata isn't swept. If we remove the method from the interface, + /// we have a "dangling reference" which makes the metadata invalid. /// static class OverrideInSaveAssembly { diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/StaticAbstractInterfaceMethods.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/StaticAbstractInterfaceMethods.cs index cb20950059c1de..62f3a720afd2af 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/StaticAbstractInterfaceMethods.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.Interfaces/StaticInterfaceMethods/StaticAbstractInterfaceMethods.cs @@ -331,7 +331,7 @@ public class UnusedMethods : IStaticAndInstanceMethods //Bug //[Kept] - //[KeptOverride (typeof (IStaticAndInstanceMethods))] + //[KeptOverride(typeof(IStaticAndInstanceMethods))] static int IStaticAndInstanceMethods.StaticMethodExplicitImpl() => 0; public int InstanceMethod() => 0; @@ -474,7 +474,7 @@ public static void Test() [KeptInterface(typeof(IInheritsFromMultipleBases))] [KeptInterface(typeof(IBase1))] [KeptInterface(typeof(IBase2))] - // [RemovedInterface (typeof (IUnusedInterface))] + // [RemovedInterface(typeof(IUnusedInterface))] public class ImplementsIInheritsFromTwoBases : IInheritsFromMultipleBases { [Kept] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.VirtualMethods/VirtualMethodGetsStrippedIfImplementingMethodGetsInvokedDirectly.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.VirtualMethods/VirtualMethodGetsStrippedIfImplementingMethodGetsInvokedDirectly.cs index befb5fd257a9ea..57fd2912ea511c 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.VirtualMethods/VirtualMethodGetsStrippedIfImplementingMethodGetsInvokedDirectly.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Inheritance.VirtualMethods/VirtualMethodGetsStrippedIfImplementingMethodGetsInvokedDirectly.cs @@ -26,7 +26,7 @@ class A : B { // Bug: https://github.com/dotnet/linker/issues/3078 // ILLink should mark for DirectCall as well as OverrideOnInstantiatedType, not just OverrideOnInstantiatedType - //[KeptBy (typeof(A), nameof(Foo), DependencyKind.DirectCall)] + //[KeptBy(typeof(A), nameof(Foo), DependencyKind.DirectCall)] [KeptBy(typeof(A), "OverrideOnInstantiatedType")] public override void Foo() { diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/Dependencies/RootAllLibrary.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/Dependencies/RootAllLibrary.cs index b07212a04e1cd8..f779848dbe8b57 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/Dependencies/RootAllLibrary.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/Dependencies/RootAllLibrary.cs @@ -8,7 +8,7 @@ using Mono.Linker.Tests.Cases.Libraries.Dependencies; #if RootAllLibrary -[assembly: TypeForwardedTo (typeof (RootAllLibrary_ExportedType))] +[assembly: TypeForwardedTo(typeof(RootAllLibrary_ExportedType))] #endif namespace Mono.Linker.Tests.Cases.Libraries.Dependencies diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/RootLibraryInternalsWithIVT.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/RootLibraryInternalsWithIVT.cs index 1f63d79b9a99f0..dce9aca3084f58 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/RootLibraryInternalsWithIVT.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/RootLibraryInternalsWithIVT.cs @@ -3,9 +3,9 @@ using Mono.Linker.Tests.Cases.Expectations.Metadata; #if RootLibraryInternalsWithIVT -[assembly: InternalsVisibleToAttribute ("somename")] +[assembly: InternalsVisibleToAttribute("somename")] -[assembly: KeptAttributeAttribute (typeof (InternalsVisibleToAttribute))] +[assembly: KeptAttributeAttribute(typeof(InternalsVisibleToAttribute))] #endif namespace Mono.Linker.Tests.Cases.Libraries @@ -49,11 +49,11 @@ private void UnusedPrivateMethod() } #if RootLibraryInternalsWithIVT - [Kept] - internal interface InternalIface - { - [Kept] - void Foo (); - } + [Kept] + internal interface InternalIface + { + [Kept] + void Foo(); + } #endif } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/RootLibraryVisibleForwarders.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/RootLibraryVisibleForwarders.cs index 70e8c9f5999c03..1f03bd3bcf2b12 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/RootLibraryVisibleForwarders.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/RootLibraryVisibleForwarders.cs @@ -3,7 +3,7 @@ using Mono.Linker.Tests.Cases.Expectations.Metadata; #if RootLibraryVisibleForwarders -[assembly: TypeForwardedTo (typeof (ExternalPublic))] +[assembly: TypeForwardedTo(typeof(ExternalPublic))] #endif namespace Mono.Linker.Tests.Cases.Libraries diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/RootLibraryVisibleForwardersWithoutReference.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/RootLibraryVisibleForwardersWithoutReference.cs index a6546b342b385c..3335bfc2676a88 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/RootLibraryVisibleForwardersWithoutReference.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Libraries/RootLibraryVisibleForwardersWithoutReference.cs @@ -3,7 +3,7 @@ using Mono.Linker.Tests.Cases.Expectations.Metadata; #if RootLibraryVisibleForwarders -[assembly: TypeForwardedTo (typeof (ExternalPublic))] +[assembly: TypeForwardedTo(typeof(ExternalPublic))] #endif namespace Mono.Linker.Tests.Cases.Libraries diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkAttributes/LinkerAttributeRemoval.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkAttributes/LinkerAttributeRemoval.cs index 2fd85337b158d5..9a0e94df4b8917 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkAttributes/LinkerAttributeRemoval.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkAttributes/LinkerAttributeRemoval.cs @@ -18,8 +18,8 @@ namespace Mono.Linker.Tests.Cases.LinkAttributes [SetupCompileBefore("copyattribute.dll", new[] { "Dependencies/LinkerAttributeRemovalAttributeFromCopyAssembly.cs" })] [SetupLinkerAction("copy", "copyattribute")] #if !NET - [Reference ("System.dll")] - [SetupCompileBefore ("copyassembly.dll", new[] { "Dependencies/LinkerAttributeRemovalCopyAssembly.cs" }, references: new[] { "System.dll", "attribute.dll" })] + [Reference("System.dll")] + [SetupCompileBefore("copyassembly.dll", new[] { "Dependencies/LinkerAttributeRemovalCopyAssembly.cs" }, references: new[] { "System.dll", "attribute.dll" })] #else [SetupCompileBefore("copyassembly.dll", new[] { "Dependencies/LinkerAttributeRemovalCopyAssembly.cs" }, references: new[] { "attribute.dll" })] #endif @@ -51,7 +51,7 @@ namespace Mono.Linker.Tests.Cases.LinkAttributes [KeptTypeInAssembly("LinkerAttributeRemovalEmbeddedAndLazyLoad.dll", typeof(TypeWithEmbeddedAttributeToBeRemoved))] // This needs to fixed with lazy loading assembly refactoring - currently the assembly="*" only applies to assemblies in initial closure // The attribute should be removed and not kept as it is now - // [RemovedAttributeInAssembly ("LinkerAttributeRemovalEmbeddedAndLazyLoad.dll", typeof (EmbeddedAttributeToBeRemoved), typeof (TypeWithEmbeddedAttributeToBeRemoved))] + // [RemovedAttributeInAssembly("LinkerAttributeRemovalEmbeddedAndLazyLoad.dll", typeof(EmbeddedAttributeToBeRemoved), typeof(TypeWithEmbeddedAttributeToBeRemoved))] [KeptAttributeInAssembly("LinkerAttributeRemovalEmbeddedAndLazyLoad", typeof(EmbeddedAttributeToBeRemoved), typeof(TypeWithEmbeddedAttributeToBeRemoved))] [LogContains("IL2045: Mono.Linker.Tests.Cases.LinkAttributes.Dependencies.TypeOnCopyAssemblyWithAttributeUsage.TypeOnCopyAssemblyWithAttributeUsage(): Attribute 'Mono.Linker.Tests.Cases.LinkAttributes.Dependencies.TestAttributeReferencedAsTypeFromCopyAssemblyAttribute'")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkAttributes/LinkerAttributeRemovalConditional.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkAttributes/LinkerAttributeRemovalConditional.cs index 9d6cee63052043..b9b2b10635b504 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkAttributes/LinkerAttributeRemovalConditional.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkAttributes/LinkerAttributeRemovalConditional.cs @@ -124,7 +124,7 @@ public TestConditionalRemoveAttribute(string key, string value) { } - // Any usage with 100 key is removed + // Any usage with 100 key is removed // Any usage with "remove1" key is removed public TestConditionalRemoveAttribute(object key, char value, int ivalue) { diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkAttributes/OverrideAttributeRemoval.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkAttributes/OverrideAttributeRemoval.cs index 9ccb6aa533e811..8725352b440f48 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkAttributes/OverrideAttributeRemoval.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkAttributes/OverrideAttributeRemoval.cs @@ -29,8 +29,8 @@ public static void Main() [return: KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] private string methodWithCustomAttribute( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string parameterWithCustomAttribute) { return "this is a return value"; diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkXml/Dependencies/CanPreserveAnExportedType_Forwarder.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkXml/Dependencies/CanPreserveAnExportedType_Forwarder.cs index cb6f81e481d6fe..183e26ada80b6d 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkXml/Dependencies/CanPreserveAnExportedType_Forwarder.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkXml/Dependencies/CanPreserveAnExportedType_Forwarder.cs @@ -1,3 +1,3 @@ using System; -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.LinkXml.Dependencies.CanPreserveAnExportedType_Library))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.LinkXml.Dependencies.CanPreserveAnExportedType_Library))] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkXml/Dependencies/UsedNonRequiredExportedTypeIsKeptWhenRooted_fwd.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkXml/Dependencies/UsedNonRequiredExportedTypeIsKeptWhenRooted_fwd.cs index d323e7e63ebd90..f6f174fdb43e61 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkXml/Dependencies/UsedNonRequiredExportedTypeIsKeptWhenRooted_fwd.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkXml/Dependencies/UsedNonRequiredExportedTypeIsKeptWhenRooted_fwd.cs @@ -1,4 +1,4 @@ using System.Runtime.CompilerServices; using Mono.Linker.Tests.Cases.LinkXml; -[assembly: TypeForwardedTo (typeof (UsedNonRequiredExportedTypeIsKeptWhenRooted_Used))] +[assembly: TypeForwardedTo(typeof(UsedNonRequiredExportedTypeIsKeptWhenRooted_Used))] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkXml/Dependencies/UsedNonRequiredExportedTypeIsKept_fwd.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkXml/Dependencies/UsedNonRequiredExportedTypeIsKept_fwd.cs index ebda6ce2b6cbc8..e7f37e39ee30a4 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkXml/Dependencies/UsedNonRequiredExportedTypeIsKept_fwd.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/LinkXml/Dependencies/UsedNonRequiredExportedTypeIsKept_fwd.cs @@ -1,6 +1,6 @@ using System.Runtime.CompilerServices; using Mono.Linker.Tests.Cases.LinkXml; -[assembly: TypeForwardedTo (typeof (UsedNonRequiredExportedTypeIsKept_Used1))] -[assembly: TypeForwardedTo (typeof (UsedNonRequiredExportedTypeIsKept_Used2))] -[assembly: TypeForwardedTo (typeof (UsedNonRequiredExportedTypeIsKept_Used3))] +[assembly: TypeForwardedTo(typeof(UsedNonRequiredExportedTypeIsKept_Used1))] +[assembly: TypeForwardedTo(typeof(UsedNonRequiredExportedTypeIsKept_Used2))] +[assembly: TypeForwardedTo(typeof(UsedNonRequiredExportedTypeIsKept_Used3))] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Logging/Dependencies/LogStep.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Logging/Dependencies/LogStep.cs index 96799b5c0d19d5..bd0e205feb4b8f 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Logging/Dependencies/LogStep.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Logging/Dependencies/LogStep.cs @@ -4,18 +4,18 @@ namespace Log { - public class LogStep : IStep - { - public void Process (LinkContext context) - { - var msgError = MessageContainer.CreateCustomErrorMessage ("Error", 6001); - var msgWarning = MessageContainer.CreateCustomWarningMessage (context, "Warning", 6002, origin: new MessageOrigin ("logtest", 1, 1), version: WarnVersion.Latest); - var msgInfo = MessageContainer.CreateInfoMessage ("Info"); - var msgDiagnostics = MessageContainer.CreateDiagnosticMessage ("Diagnostics"); - context.LogMessage (msgError); - context.LogMessage (msgWarning); - context.LogMessage (msgInfo); - context.LogMessage (msgDiagnostics); - } - } + public class LogStep : IStep + { + public void Process(LinkContext context) + { + var msgError = MessageContainer.CreateCustomErrorMessage("Error", 6001); + var msgWarning = MessageContainer.CreateCustomWarningMessage(context, "Warning", 6002, origin: new MessageOrigin("logtest", 1, 1), version: WarnVersion.Latest); + var msgInfo = MessageContainer.CreateInfoMessage("Info"); + var msgDiagnostics = MessageContainer.CreateDiagnosticMessage("Diagnostics"); + context.LogMessage(msgError); + context.LogMessage(msgWarning); + context.LogMessage(msgInfo); + context.LogMessage(msgDiagnostics); + } + } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/PreserveDependencies/PreserveDependencyDeprecated.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/PreserveDependencies/PreserveDependencyDeprecated.cs index f6e7ef0992f7b2..97d01b65659295 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/PreserveDependencies/PreserveDependencyDeprecated.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/PreserveDependencies/PreserveDependencyDeprecated.cs @@ -32,10 +32,10 @@ void Method2(out sbyte arg) [Kept] [PreserveDependency("Dependency1()", "Mono.Linker.Tests.Cases.PreserveDependencies.D")] - [PreserveDependency("Dependency2`1 ( T[] , System.Int32 ) ", "Mono.Linker.Tests.Cases.PreserveDependencies.D")] + [PreserveDependency("Dependency2`1(T[],System.Int32)", "Mono.Linker.Tests.Cases.PreserveDependencies.D")] [PreserveDependency(".ctor()", "Mono.Linker.Tests.Cases.PreserveDependencies.D")] // To avoid lazy body marking stubbing [PreserveDependency("field", "Mono.Linker.Tests.Cases.PreserveDependencies.D")] - [PreserveDependency("NextOne (Mono.Linker.Tests.Cases.PreserveDependencies.PreserveDependencyDeprecated+Nested&)", "Mono.Linker.Tests.Cases.PreserveDependencies.PreserveDependencyDeprecated+Nested")] + [PreserveDependency("NextOne(Mono.Linker.Tests.Cases.PreserveDependencies.PreserveDependencyDeprecated+Nested&)", "Mono.Linker.Tests.Cases.PreserveDependencies.PreserveDependencyDeprecated+Nested")] [PreserveDependency(".cctor()", "Mono.Linker.Tests.Cases.PreserveDependencies.PreserveDependencyDeprecated+Nested")] // Dependency on a property itself should be expressed as a dependency on one or both accessor methods [PreserveDependency("get_Property()", "Mono.Linker.Tests.Cases.PreserveDependencies.D")] @@ -46,7 +46,7 @@ public static void Method() [Kept] [PreserveDependency("field")] - [PreserveDependency("Method2 (System.SByte&)")] + [PreserveDependency("Method2(System.SByte&)")] [ExpectedWarning("IL2033")] public static void SameContext() { @@ -55,7 +55,7 @@ public static void SameContext() [Kept] [PreserveDependency("MissingType", "Mono.Linker.Tests.Cases.PreserveDependencies.MissingType")] [PreserveDependency("MissingMethod", "Mono.Linker.Tests.Cases.PreserveDependencies.D")] - [PreserveDependency("Dependency2`1 (T, System.Int32, System.Object)", "Mono.Linker.Tests.Cases.PreserveDependencies.D")] + [PreserveDependency("Dependency2`1(T, System.Int32, System.Object)", "Mono.Linker.Tests.Cases.PreserveDependencies.D")] [PreserveDependency("")] [PreserveDependency(".ctor()", "Mono.Linker.Tests.Cases.PreserveDependencies.PreserveDependencyDeprecated+NestedStruct")] [PreserveDependency(".cctor()", "Mono.Linker.Tests.Cases.PreserveDependencies.D")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/PreserveDependencies/PreserveDependencyMethod.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/PreserveDependencies/PreserveDependencyMethod.cs index 4a5e43fef5c796..335b5d75b8c66f 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/PreserveDependencies/PreserveDependencyMethod.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/PreserveDependencies/PreserveDependencyMethod.cs @@ -40,10 +40,10 @@ void Method2(out sbyte arg) [Kept] [PreserveDependency("Dependency1()", "Mono.Linker.Tests.Cases.PreserveDependencies.C")] - [PreserveDependency("Dependency2`1 ( T[] , System.Int32 ) ", "Mono.Linker.Tests.Cases.PreserveDependencies.C")] + [PreserveDependency("Dependency2`1(T[],System.Int32)", "Mono.Linker.Tests.Cases.PreserveDependencies.C")] [PreserveDependency(".ctor()", "Mono.Linker.Tests.Cases.PreserveDependencies.C")] // To avoid lazy body marking stubbing [PreserveDependency("field", "Mono.Linker.Tests.Cases.PreserveDependencies.C")] - [PreserveDependency("NextOne (Mono.Linker.Tests.Cases.PreserveDependencies.PreserveDependencyMethod+Nested&)", "Mono.Linker.Tests.Cases.PreserveDependencies.PreserveDependencyMethod+Nested")] + [PreserveDependency("NextOne(Mono.Linker.Tests.Cases.PreserveDependencies.PreserveDependencyMethod+Nested&)", "Mono.Linker.Tests.Cases.PreserveDependencies.PreserveDependencyMethod+Nested")] [PreserveDependency(".cctor()", "Mono.Linker.Tests.Cases.PreserveDependencies.PreserveDependencyMethod+Nested")] // Dependency on a property itself should be expressed as a dependency on one or both accessor methods [PreserveDependency("get_Property()", "Mono.Linker.Tests.Cases.PreserveDependencies.C")] @@ -53,7 +53,7 @@ public static void Method() [Kept] [PreserveDependency("field")] - [PreserveDependency("Method2 (System.SByte&)")] + [PreserveDependency("Method2(System.SByte&)")] public static void SameContext() { } @@ -61,7 +61,7 @@ public static void SameContext() [Kept] [PreserveDependency("MissingType", "Mono.Linker.Tests.Cases.PreserveDependencies.MissingType")] [PreserveDependency("MissingMethod", "Mono.Linker.Tests.Cases.PreserveDependencies.C")] - [PreserveDependency("Dependency2`1 (T, System.Int32, System.Object)", "Mono.Linker.Tests.Cases.PreserveDependencies.C")] + [PreserveDependency("Dependency2`1(T, System.Int32, System.Object)", "Mono.Linker.Tests.Cases.PreserveDependencies.C")] [PreserveDependency("")] [PreserveDependency(".ctor()", "Mono.Linker.Tests.Cases.PreserveDependencies.PreserveDependencyMethod+NestedStruct")] [PreserveDependency(".cctor()", "Mono.Linker.Tests.Cases.PreserveDependencies.C")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/References/Dependencies/CustomMarkHandlerSaveAssembly.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/References/Dependencies/CustomMarkHandlerSaveAssembly.cs index c95bd8b54ba842..f25670a0b998a8 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/References/Dependencies/CustomMarkHandlerSaveAssembly.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/References/Dependencies/CustomMarkHandlerSaveAssembly.cs @@ -5,11 +5,11 @@ public class CustomMarkHandlerSaveAssembly : IMarkHandler { - public void Initialize (LinkContext context, MarkContext markContext) + public void Initialize(LinkContext context, MarkContext markContext) { - markContext.RegisterMarkAssemblyAction (assembly => { + markContext.RegisterMarkAssemblyAction(assembly => { if (assembly.Name.Name == "saved") - context.Annotations.SetAction (assembly, AssemblyAction.Save); + context.Annotations.SetAction(assembly, AssemblyAction.Save); }); } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/ActivatorCreateInstance.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/ActivatorCreateInstance.cs index 31ea1e2ef941ea..8cd6abcd436d19 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/ActivatorCreateInstance.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/ActivatorCreateInstance.cs @@ -623,8 +623,8 @@ private static void TestNullArgsOnKnownType() [Kept] private static void TestNullArgsOnAnnotatedType( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor), - KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] Type type) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor), + KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] Type type) { Activator.CreateInstance(type, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); } @@ -632,8 +632,8 @@ private static void TestNullArgsOnAnnotatedType( [Kept] [ExpectedWarning("IL2067", nameof(DynamicallyAccessedMemberTypes) + "." + nameof(DynamicallyAccessedMemberTypes.NonPublicConstructors))] private static void TestNullArgsNonPublicOnly( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor), - KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] Type type) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor), + KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] Type type) { Activator.CreateInstance(type, BindingFlags.NonPublic | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); } @@ -641,8 +641,8 @@ private static void TestNullArgsNonPublicOnly( [Kept] [ExpectedNoWarnings] private static void TestNullArgsNonPublicWithNonPublicAnnotation( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.NonPublicConstructors), - KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] Type type) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.NonPublicConstructors), + KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] Type type) { Activator.CreateInstance(type, nonPublic: true); } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/AssemblyImportedViaReflectionWithSweptReferences.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/AssemblyImportedViaReflectionWithSweptReferences.cs index fc19570f4abd14..029171f6bbc3b3 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/AssemblyImportedViaReflectionWithSweptReferences.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/AssemblyImportedViaReflectionWithSweptReferences.cs @@ -11,7 +11,7 @@ namespace Mono.Linker.Tests.Cases.Reflection [SetupCompileBefore("reference.dll", new[] { "Dependencies/AssemblyDependency.cs" }, addAsReference: false)] [SetupCompileBefore("library.dll", new[] { "Dependencies/AssemblyDependencyWithMultipleReferences.cs" }, new[] { "reference.dll", "unusedreference.dll" }, addAsReference: false)] // TODO: keep library even if type is not found in it (https://github.com/dotnet/linker/issues/1795) - // [KeptAssembly ("library")] + // [KeptAssembly("library")] public class AssemblyImportedViaReflectionWithSweptReferences { public static void Main() diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/ConstructorUsedViaReflection.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/ConstructorUsedViaReflection.cs index c8a8baee286d2a..c47145551875de 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/ConstructorUsedViaReflection.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/ConstructorUsedViaReflection.cs @@ -281,7 +281,7 @@ static void TestWithBindingFlagsAndTypes_EmptyTypes_DataFlow( [Kept] [ExpectedWarning("IL2070", nameof(Type.GetConstructor))] static void TestWithBindingFlagsAndTypes_NonEmptyTypes_DataFlow( - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] Type type) { diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/Dependencies/CoreLibEmulator.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/Dependencies/CoreLibEmulator.cs index 2c83bab3d128e5..d18bf88ac03cfc 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/Dependencies/CoreLibEmulator.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/Dependencies/CoreLibEmulator.cs @@ -11,12 +11,12 @@ public class CoreLibEmulator public static void Test() { #if INCLUDE_CORELIB_IMPL - Type t = new Type(); - t.GetConstructor (BindingFlags.Default, null, new Type[] {}, null); - t.GetMethod ("name", new Type[] {}); - t.GetProperty ("name", new Type[] {}); - t.GetField ("name"); - t.GetEvent ("name"); + Type t = new Type(); + t.GetConstructor(BindingFlags.Default, null, new Type[] {}, null); + t.GetMethod("name", new Type[] {}); + t.GetProperty("name", new Type[] {}); + t.GetField("name"); + t.GetEvent("name"); #endif } } @@ -25,38 +25,38 @@ public static void Test() #if INCLUDE_CORELIB_IMPL namespace System { - public class Type - { - public ConstructorInfo GetConstructor (BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) => GetConstructor (bindingAttr, binder, CallingConventions.Any, types, modifiers); - - public ConstructorInfo GetConstructor (BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) - { - return null; - } - - public MethodInfo GetMethod (string name, Type [] types) => GetMethod (name, types, null); - public MethodInfo GetMethod (string name, Type [] types, ParameterModifier [] modifiers) - { - return null; - } - - public PropertyInfo GetProperty (string name, Type [] types) => GetProperty (name, null, types); - public PropertyInfo GetProperty (string name, Type returnType, Type [] types) - { - return null; - } - - public FieldInfo GetField (string name) => GetField (name, BindingFlags.Default); - public FieldInfo GetField (string name, BindingFlags bindingAttr) - { - return null; - } - - public EventInfo GetEvent (string name) => GetEvent (name, BindingFlags.Default); - public EventInfo GetEvent (string name, BindingFlags bindingAttr) - { - return null; - } - } + public class Type + { + public ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) => GetConstructor(bindingAttr, binder, CallingConventions.Any, types, modifiers); + + public ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + { + return null; + } + + public MethodInfo GetMethod(string name, Type [] types) => GetMethod(name, types, null); + public MethodInfo GetMethod(string name, Type [] types, ParameterModifier [] modifiers) + { + return null; + } + + public PropertyInfo GetProperty(string name, Type [] types) => GetProperty(name, null, types); + public PropertyInfo GetProperty(string name, Type returnType, Type [] types) + { + return null; + } + + public FieldInfo GetField(string name) => GetField(name, BindingFlags.Default); + public FieldInfo GetField(string name, BindingFlags bindingAttr) + { + return null; + } + + public EventInfo GetEvent(string name) => GetEvent(name, BindingFlags.Default); + public EventInfo GetEvent(string name, BindingFlags bindingAttr) + { + return null; + } + } } #endif diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/EventHanderTypeGetInvokeMethod.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/EventHanderTypeGetInvokeMethod.cs index b92f9ec71a6695..223186b5fd03d9 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/EventHanderTypeGetInvokeMethod.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/EventHanderTypeGetInvokeMethod.cs @@ -7,91 +7,95 @@ namespace Mono.Linker.Tests.Cases.Reflection { - [ExpectedNoWarnings] - // Necessary to allow trimming unused EventInfo methods, - // making the test behavior more consistent with ILC. - [SetupLinkerTrimMode ("link")] - public class EventHanderTypeGetInvokeMethod - { - public static void Main () - { - EventDelegate.Test (); - NonDelegate.Test (); - } + [ExpectedNoWarnings] + // Necessary to allow trimming unused EventInfo methods, + // making the test behavior more consistent with ILC. + [SetupLinkerTrimMode("link")] + public class EventHanderTypeGetInvokeMethod + { + public static void Main() + { + EventDelegate.Test(); + NonDelegate.Test(); + } - class EventDelegate - { - [Kept] - [KeptBackingField] - [KeptEventAddMethod] - [KeptEventRemoveMethod] - public static event EventHandler MyEvent; + class EventDelegate + { + [Kept] + [KeptBackingField] + [KeptEventAddMethod] + [KeptEventRemoveMethod] + public static event EventHandler MyEvent; - [Kept] - public static void Test () - { - var eventInfo = typeof (EventDelegate).GetEvent (nameof (MyEvent)); - var invoke = eventInfo.EventHandlerType.GetMethod ("Invoke"); - } - } + [Kept] + public static void Test() + { + var eventInfo = typeof(EventDelegate).GetEvent(nameof(MyEvent)); + var invoke = eventInfo.EventHandlerType.GetMethod("Invoke"); + } + } - class NonDelegate - { - [Kept] - [KeptBaseType (typeof (EventInfo))] - [KeptMember (".ctor()")] - class CustomEventInfo : EventInfo - { - [Kept] - public override Type EventHandlerType { - [Kept] - get => typeof (NonDelegate); - } + class NonDelegate + { + [Kept] + [KeptBaseType(typeof(EventInfo))] + [KeptMember(".ctor()")] + class CustomEventInfo : EventInfo + { + [Kept] + public override Type EventHandlerType + { + [Kept] + get => typeof(NonDelegate); + } - // ILLink keeps more methods on MemberInfo due for stack trace support, - // but differences in this class are not important for this testcase. + // ILLink keeps more methods on MemberInfo due for stack trace support, + // but differences in this class are not important for this testcase. - [Kept (By = Tool.Trimmer)] - public override bool IsDefined (Type type, bool inherit) => throw null; - public override object[] GetCustomAttributes (bool inherit) => throw null; - [Kept (By = Tool.Trimmer)] - public override object[] GetCustomAttributes (Type attributeType, bool inherit) => throw null; - [Kept (By = Tool.Trimmer)] - public override string Name { - [Kept (By = Tool.Trimmer)] - get => throw null; - } - [Kept (By = Tool.Trimmer)] - public override Type ReflectedType { - [Kept (By = Tool.Trimmer)] - get => throw null; - } - [Kept (By = Tool.Trimmer)] - public override Type DeclaringType { - [Kept (By = Tool.Trimmer)] - get => throw null; - } - [Kept (By = Tool.Trimmer)] - public override MethodInfo GetAddMethod (bool nonPublic) => throw null; - public override MethodInfo GetRemoveMethod (bool nonPublic) => throw null; - public override MethodInfo GetRaiseMethod (bool nonPublic) => throw null; - public override EventAttributes Attributes => throw null; - } + [Kept(By = Tool.Trimmer)] + public override bool IsDefined(Type type, bool inherit) => throw null; + public override object[] GetCustomAttributes(bool inherit) => throw null; + [Kept(By = Tool.Trimmer)] + public override object[] GetCustomAttributes(Type attributeType, bool inherit) => throw null; + [Kept(By = Tool.Trimmer)] + public override string Name + { + [Kept(By = Tool.Trimmer)] + get => throw null; + } + [Kept(By = Tool.Trimmer)] + public override Type ReflectedType + { + [Kept(By = Tool.Trimmer)] + get => throw null; + } + [Kept(By = Tool.Trimmer)] + public override Type DeclaringType + { + [Kept(By = Tool.Trimmer)] + get => throw null; + } + [Kept(By = Tool.Trimmer)] + public override MethodInfo GetAddMethod(bool nonPublic) => throw null; + public override MethodInfo GetRemoveMethod(bool nonPublic) => throw null; + public override MethodInfo GetRaiseMethod(bool nonPublic) => throw null; + public override EventAttributes Attributes => throw null; + } - // Strictly speaking this should be kept, but trimmer doesn't see through the custom event info. - // See discussion at https://github.com/dotnet/runtime/issues/114113. - [RequiresUnreferencedCode (nameof (Invoke))] - public void Invoke () - { - } + // Strictly speaking this should be kept, but trimmer doesn't see through the custom event info. + // See discussion at https://github.com/dotnet/runtime/issues/114113. + [RequiresUnreferencedCode(nameof(Invoke))] + public void Invoke() + { + } - [Kept] - [ExpectedWarning ("IL2075", nameof (Type.GetMethod), Tool.Analyzer, - "ILLink/ILC intrinsic handling assumes EventHandlerType is a delegate: https://github.com/dotnet/runtime/issues/114113")] - public static void Test () - { - new CustomEventInfo ().EventHandlerType.GetMethod ("Invoke"); - } - } - } + [Kept] + [ExpectedWarning("IL2075", nameof(Type.GetMethod), Tool.Analyzer, + "ILLink/ILC intrinsic handling assumes EventHandlerType is a delegate: https://github.com/dotnet/runtime/issues/114113")] + public static void Test() + { + new CustomEventInfo().EventHandlerType.GetMethod("Invoke"); + } + } + } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/MemberUsedViaReflection.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/MemberUsedViaReflection.cs index bf8d0ccb6a4cbf..9199acc2ca1cd9 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/MemberUsedViaReflection.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/MemberUsedViaReflection.cs @@ -112,13 +112,13 @@ static void TestDataFlowType() } [Kept] - private static void TestDataFlowWithAnnotation([KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | - DynamicallyAccessedMemberTypes.PublicEvents | - DynamicallyAccessedMemberTypes.PublicFields | - DynamicallyAccessedMemberTypes.PublicMethods | - DynamicallyAccessedMemberTypes.PublicProperties | - DynamicallyAccessedMemberTypes.PublicNestedTypes)] Type type) + private static void TestDataFlowWithAnnotation([KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | + DynamicallyAccessedMemberTypes.PublicEvents | + DynamicallyAccessedMemberTypes.PublicFields | + DynamicallyAccessedMemberTypes.PublicMethods | + DynamicallyAccessedMemberTypes.PublicProperties | + DynamicallyAccessedMemberTypes.PublicNestedTypes)] Type type) { var members = type.GetMember("PrefixLookup*", BindingFlags.Public | BindingFlags.Static); } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/MembersUsedViaReflection.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/MembersUsedViaReflection.cs index 0f9db0c03a4276..1e6be694e47bdd 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/MembersUsedViaReflection.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/MembersUsedViaReflection.cs @@ -71,13 +71,13 @@ static void TestDataFlowType() } [Kept] - private static void TestDataFlowWithAnnotation([KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | - DynamicallyAccessedMemberTypes.PublicEvents | - DynamicallyAccessedMemberTypes.PublicFields | - DynamicallyAccessedMemberTypes.PublicMethods | - DynamicallyAccessedMemberTypes.PublicProperties | - DynamicallyAccessedMemberTypes.PublicNestedTypes)] Type type) + private static void TestDataFlowWithAnnotation([KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | + DynamicallyAccessedMemberTypes.PublicEvents | + DynamicallyAccessedMemberTypes.PublicFields | + DynamicallyAccessedMemberTypes.PublicMethods | + DynamicallyAccessedMemberTypes.PublicProperties | + DynamicallyAccessedMemberTypes.PublicNestedTypes)] Type type) { var properties = type.GetMembers(BindingFlags.Public | BindingFlags.Static); } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/ObjectGetType.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/ObjectGetType.cs index 4cee43eb033dfe..b4c445c2fc660b 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/ObjectGetType.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/ObjectGetType.cs @@ -2,9 +2,9 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.Reflection; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Reflection; using Mono.Linker.Tests.Cases.Expectations.Assertions; using Mono.Linker.Tests.Cases.Expectations.Helpers; diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeDelegator.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeDelegator.cs index 24e98461a0db2a..b48d985ff8b8f8 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeDelegator.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeDelegator.cs @@ -54,8 +54,8 @@ static void TestNoValue() [Kept] [ExpectedWarning("IL2067", nameof(DataFlowTypeExtensions.RequiresPublicFields))] static void TestDataFlowPropagation( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type typeWithPublicMethods = null) { var typeDelegator = new System.Reflection.TypeDelegator(typeWithPublicMethods); diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeHierarchyReflectionWarnings.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeHierarchyReflectionWarnings.cs index 02c8f5373b67e0..cfcbd53a7add57 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeHierarchyReflectionWarnings.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeHierarchyReflectionWarnings.cs @@ -122,8 +122,8 @@ public void RUCMethod() { } [Kept] [ExpectedWarning("IL2114", nameof(AnnotatedAll), nameof(DAMMethod))] public void DAMMethod( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t ) { } @@ -184,8 +184,8 @@ public void RUCMethod() { } [Kept] [ExpectedWarning("IL2114", nameof(AnnotatedPublicMethods), nameof(DAMMethod))] public void DAMMethod( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t ) { } @@ -199,8 +199,8 @@ Type t [Kept] [ExpectedWarning("IL2114", nameof(AnnotatedPublicMethods), nameof(DAMVirtualMethod))] public virtual void DAMVirtualMethod( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type ) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeHierarchySuppressions.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeHierarchySuppressions.cs index 0c06f9f8915a39..63fd8eb7b1c86b 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeHierarchySuppressions.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Reflection/TypeHierarchySuppressions.cs @@ -49,15 +49,15 @@ static void UseDerivedTypes() [Kept] static void RequireMethods( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) { } [Kept] static void RequireAll( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.All)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type) { } @@ -189,8 +189,8 @@ public static void RUCMethod() { } [KeptAttributeAttribute(typeof(UnconditionalSuppressMessageAttribute))] [UnconditionalSuppressMessage("TrimAnalysis", "IL2114")] public void DAMTMethod( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t ) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresInCompilerGeneratedCode.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresInCompilerGeneratedCode.cs index 47bb60d43babdd..424bc55a5649bc 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresInCompilerGeneratedCode.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresInCompilerGeneratedCode.cs @@ -86,7 +86,7 @@ static IEnumerable TestReflectionAccess() [ExpectedWarning("IL3002", "--MethodWithRequires--", Tool.NativeAot, "", CompilerGeneratedCode = true)] [ExpectedWarning("IL3050", "--MethodWithRequires--", Tool.NativeAot, "", CompilerGeneratedCode = true)] #else - // In release mode, the compiler optimizes away the unused Action (and reference to MethodWithRequires) + // In release mode, the compiler optimizes away the unused Action (and reference to MethodWithRequires) #endif [ExpectedWarning("IL2026", "--MethodWithRequires--", Tool.Analyzer, "")] [ExpectedWarning("IL3002", "--MethodWithRequires--", Tool.Analyzer, "")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresOnClass.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresOnClass.cs index 059b06ae3662a2..6cda065d4c364a 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresOnClass.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresOnClass.cs @@ -409,7 +409,7 @@ static void TestRequiresInParentClassAccesedByStaticMethod() [ExpectedWarning("IL2026", "RequiresOnClass.ClassWithRequires.StaticMethod()", "--ClassWithRequires--")] [ExpectedWarning("IL3050", "RequiresOnClass.ClassWithRequires.StaticMethod()", "--ClassWithRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT Specific Warnings")] - // Although we suppress the warning from RequiresOnMethod.MethodWithRequires () we still get a warning because we call CallRequiresMethod() which is an static method on a type with RUC + // Although we suppress the warning from RequiresOnMethod.MethodWithRequires() we still get a warning because we call CallRequiresMethod() which is an static method on a type with RUC [ExpectedWarning("IL2026", "RequiresOnClass.ClassWithRequires.CallMethodWithRequires()", "--ClassWithRequires--")] [ExpectedWarning("IL3050", "RequiresOnClass.ClassWithRequires.CallMethodWithRequires()", "--ClassWithRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT Specific Warnings")] [ExpectedWarning("IL2026", "ClassWithRequires.Instance", "--ClassWithRequires--")] @@ -480,7 +480,7 @@ static void TestStaticConstructorCalls() TestStaticCtorMarkingTriggeredOnSecondAccessWrite(); TestStaticRequiresFieldAccessSuppressedByRequiresOnMethod(); TestStaticCtorMarkingIsTriggeredByFieldAccessRead(); - //TestStaticCtorTriggeredByMethodCall (); + //TestStaticCtorTriggeredByMethodCall(); TestStaticCtorTriggeredByCtorCall(); TestInstanceFieldCallDontWarn(); } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresWithCopyAssembly.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresWithCopyAssembly.cs index 059566de39374c..1cacd58a861831 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresWithCopyAssembly.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresWithCopyAssembly.cs @@ -23,7 +23,7 @@ namespace Mono.Linker.Tests.Cases.RequiresCapability [LogDoesNotContain("--UnusedVirtualMethod2--")] [LogDoesNotContain("--IUnusedInterface.UnusedMethod--")] [LogDoesNotContain("--UnusedImplementationClass.UnusedMethod--")] - // [LogDoesNotContain ("UnusedVirtualMethod2")] // https://github.com/dotnet/linker/issues/2106 + // [LogDoesNotContain("UnusedVirtualMethod2")] // https://github.com/dotnet/linker/issues/2106 [ExpectedNoWarnings] class RequiresWithCopyAssembly diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Substitutions/Dependencies/TestFeatures.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Substitutions/Dependencies/TestFeatures.cs index 942c9f3586dd34..90961bfe1ee552 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Substitutions/Dependencies/TestFeatures.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Substitutions/Dependencies/TestFeatures.cs @@ -3,10 +3,10 @@ namespace ILLink.RoslynAnalyzer { - public class TestFeatures - { - public static bool IsUnreferencedCodeSupported => true; + public class TestFeatures + { + public static bool IsUnreferencedCodeSupported => true; - public static bool IsAssemblyFilesSupported => true; - } + public static bool IsAssemblyFilesSupported => true; + } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Substitutions/FeatureGuardSubstitutions.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Substitutions/FeatureGuardSubstitutions.cs index 16731f697fa9f5..4ae4d36e72d643 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Substitutions/FeatureGuardSubstitutions.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Substitutions/FeatureGuardSubstitutions.cs @@ -2,9 +2,9 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.Runtime.CompilerServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; using ILLink.RoslynAnalyzer; using Mono.Linker.Tests.Cases.Expectations.Assertions; using Mono.Linker.Tests.Cases.Expectations.Helpers; @@ -17,10 +17,10 @@ namespace Mono.Linker.Tests.Cases.Substitutions [SetupCompileResource("FeatureGuardSubstitutions.xml", "ILLink.Substitutions.xml")] [IgnoreSubstitutions(false)] #if NATIVEAOT - // ILC has different constant propagation behavior than ILLink, and we don't have - // the test infrastructure to check for different IL sequences between ILLink/ILC. - // Just validate the warning behavior instead. - [SkipKeptItemsValidation] + // ILC has different constant propagation behavior than ILLink, and we don't have + // the test infrastructure to check for different IL sequences between ILLink/ILC. + // Just validate the warning behavior instead. + [SkipKeptItemsValidation] #else // Tell linker to treat RequiresDynamicCodeAttribute as a disabled feature: [SetupLinkerArgument("--feature", "System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported", "false")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Substitutions/FeatureGuardSubstitutionsDisabled.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Substitutions/FeatureGuardSubstitutionsDisabled.cs index 4418137cd0f104..25a941233724aa 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Substitutions/FeatureGuardSubstitutionsDisabled.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Substitutions/FeatureGuardSubstitutionsDisabled.cs @@ -2,9 +2,9 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.Runtime.CompilerServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; using ILLink.RoslynAnalyzer; using Mono.Linker.Tests.Cases.Expectations.Assertions; using Mono.Linker.Tests.Cases.Expectations.Helpers; diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbAndSymbolLinkingEnabled.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbAndSymbolLinkingEnabled.cs index 07b8f73b7f088a..cfbcb5a42862ef 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbAndSymbolLinkingEnabled.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbAndSymbolLinkingEnabled.cs @@ -11,7 +11,7 @@ namespace Mono.Linker.Tests.Cases.Symbols [SetupLinkerLinkSymbols("true")] #if WIN32 - [KeptSymbols ("LibraryWithPdb.dll")] + [KeptSymbols("LibraryWithPdb.dll")] #else [RemovedSymbols("LibraryWithPdb.dll")] #endif diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbAndSymbolLinkingEnabledAndDeterministicMvid.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbAndSymbolLinkingEnabledAndDeterministicMvid.cs index 5b268930439833..a8f728356e097c 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbAndSymbolLinkingEnabledAndDeterministicMvid.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbAndSymbolLinkingEnabledAndDeterministicMvid.cs @@ -12,7 +12,7 @@ namespace Mono.Linker.Tests.Cases.Symbols [SetupLinkerArgument("--deterministic", "true")] #if WIN32 - [KeptSymbols ("LibraryWithPdb.dll")] + [KeptSymbols("LibraryWithPdb.dll")] #else [RemovedSymbols("LibraryWithPdb.dll")] #endif diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbAndSymbolLinkingEnabledAndNewMvid.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbAndSymbolLinkingEnabledAndNewMvid.cs index 6e47df80969f0f..080629f410b6a7 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbAndSymbolLinkingEnabledAndNewMvid.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbAndSymbolLinkingEnabledAndNewMvid.cs @@ -12,7 +12,7 @@ namespace Mono.Linker.Tests.Cases.Symbols [SetupLinkerArgument("--new-mvid", "true")] #if WIN32 - [KeptSymbols ("LibraryWithPdb.dll")] + [KeptSymbols("LibraryWithPdb.dll")] #else [RemovedSymbols("LibraryWithPdb.dll")] #endif diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbCopyActionAndSymbolLinkingEnabled.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbCopyActionAndSymbolLinkingEnabled.cs index 14d007bd6192cc..c3300d85260bf6 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbCopyActionAndSymbolLinkingEnabled.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferenceWithPdbCopyActionAndSymbolLinkingEnabled.cs @@ -11,7 +11,7 @@ namespace Mono.Linker.Tests.Cases.Symbols // typeforwarders). However, saving the native PDB is only // supported on windows. // Commented because the testcase is already ignored above. - // [IgnoreTestCase ("Only supported on Windows")] + // [IgnoreTestCase("Only supported on Windows")] #endif [TestCaseRequirements(TestRunCharacteristics.TargetingNetFramework, "Only supported on Windows on .NET Framework.")] [Reference("Dependencies/LibraryWithPdb/LibraryWithPdb.dll")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferencesWithMixedSymbolTypesAndSymbolLinkingEnabled.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferencesWithMixedSymbolTypesAndSymbolLinkingEnabled.cs index 3979630e21a472..8efc716a413b8f 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferencesWithMixedSymbolTypesAndSymbolLinkingEnabled.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferencesWithMixedSymbolTypesAndSymbolLinkingEnabled.cs @@ -18,7 +18,7 @@ namespace Mono.Linker.Tests.Cases.Symbols [KeptSymbols("test.exe")] #if WIN32 - [KeptSymbols ("LibraryWithPdb.dll")] + [KeptSymbols("LibraryWithPdb.dll")] #else [RemovedSymbols("LibraryWithPdb.dll")] #endif diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferencesWithMixedSymbolTypesWithMdbAndSymbolLinkingEnabled.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferencesWithMixedSymbolTypesWithMdbAndSymbolLinkingEnabled.cs index d3b2a7374e3a7b..a01aa0e80981a0 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferencesWithMixedSymbolTypesWithMdbAndSymbolLinkingEnabled.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Symbols/ReferencesWithMixedSymbolTypesWithMdbAndSymbolLinkingEnabled.cs @@ -26,7 +26,7 @@ namespace Mono.Linker.Tests.Cases.Symbols [KeptSymbols("test.exe")] [KeptSymbols("LibraryWithMdb.dll")] #if WIN32 - [KeptSymbols ("LibraryWithPdb.dll")] + [KeptSymbols("LibraryWithPdb.dll")] #else [RemovedSymbols("LibraryWithPdb.dll")] #endif diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/CanCompileILAssembly.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/CanCompileILAssembly.cs index 5f4613e2f64474..692dfdd5a98fd8 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/CanCompileILAssembly.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/CanCompileILAssembly.cs @@ -13,7 +13,7 @@ public class CanCompileILAssembly static void Main() { #if IL_ASSEMBLY_AVAILABLE - Console.WriteLine (new Mono.Linker.Tests.Cases.TestFramework.Dependencies.ILAssemblySample ().GiveMeAValue ()); + Console.WriteLine(new Mono.Linker.Tests.Cases.TestFramework.Dependencies.ILAssemblySample().GiveMeAValue()); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/CanCompileTestCaseWithCsc.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/CanCompileTestCaseWithCsc.cs index ed39a9e6ecf8da..2c28cfdabfc20b 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/CanCompileTestCaseWithCsc.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/CanCompileTestCaseWithCsc.cs @@ -22,7 +22,7 @@ class CanCompileTestCaseWithCsc static void Main() { #if VERIFY_DEFINE_WORKS - UsedByDefine (); + UsedByDefine(); #endif // Use something from System.dll so that we can verify the reference attribute works var timer = new System.Timers.Timer(); diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/CanCompileTestCaseWithMcs.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/CanCompileTestCaseWithMcs.cs index 8b02442abac100..781eb2b662a899 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/CanCompileTestCaseWithMcs.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/CanCompileTestCaseWithMcs.cs @@ -23,7 +23,7 @@ class CanCompileTestCaseWithMcs static void Main() { #if VERIFY_DEFINE_WORKS - UsedByDefine (); + UsedByDefine(); #endif // Use something from System.dll so that we can verify the reference attribute works var timer = new System.Timers.Timer(); diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/ILVerificationWorks.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/ILVerificationWorks.cs index 25d74d58d316bf..ce7b12e782521d 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/ILVerificationWorks.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/ILVerificationWorks.cs @@ -19,7 +19,7 @@ public class ILVerificationWorks public static void Main() { #if IL_ASSEMBLY_AVAILABLE - System.Console.WriteLine (new Mono.Linker.Tests.Cases.TestFramework.Dependencies.AssemblyWithInvalidIL ().GiveMeAValue ()); + System.Console.WriteLine(new Mono.Linker.Tests.Cases.TestFramework.Dependencies.AssemblyWithInvalidIL().GiveMeAValue()); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/VerifyDefineAttributeBehavior.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/VerifyDefineAttributeBehavior.cs index 6d4a6ce3e06f5c..2df3732ccc98d8 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/VerifyDefineAttributeBehavior.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TestFramework/VerifyDefineAttributeBehavior.cs @@ -14,7 +14,7 @@ public class VerifyDefineAttributeBehavior static void Main() { #if SOME_DEFINE - MethodThatIsUsedIfDefineIsWorkingProperly (); + MethodThatIsUsedIfDefineIsWorkingProperly(); #endif } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TopLevelStatements/BasicDataFlow/Program.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TopLevelStatements/BasicDataFlow/Program.cs index 02bd9606aae6d0..57f0d09ab4ff22 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TopLevelStatements/BasicDataFlow/Program.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TopLevelStatements/BasicDataFlow/Program.cs @@ -16,8 +16,8 @@ [Kept] static void RequirePublicFields( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] Type t) + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type t) { } class TopLevelClass @@ -32,7 +32,7 @@ class TopLevelClass [Kept] static void RequirePublicFields( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] Type t) + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type t) { } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TopLevelStatements/InvalidAnnotations/Program.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TopLevelStatements/InvalidAnnotations/Program.cs index a13b8b49b24001..9c960fdff702f7 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TopLevelStatements/InvalidAnnotations/Program.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TopLevelStatements/InvalidAnnotations/Program.cs @@ -17,8 +17,8 @@ static void Test() [ExpectedWarning("IL2098", Tool.Trimmer | Tool.NativeAot, "https://github.com/dotnet/runtime/issues/101215")] [Kept] static void RequireAll( - [KeptAttributeAttribute (typeof (DynamicallyAccessedMembersAttribute))] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.All)] UnsupportedType f) + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] UnsupportedType f) { } [Kept] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/AttributeArgumentForwarded.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/AttributeArgumentForwarded.cs index 9ee1fd8cb18b82..7149adb933b81d 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/AttributeArgumentForwarded.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/AttributeArgumentForwarded.cs @@ -82,12 +82,12 @@ public static void Test_Field_ArrayOfPointerTypeRef() } // This hits Roslyn bug https://github.com/dotnet/roslyn/issues/48765 - //[Kept] - //[KeptAttributeAttribute (typeof (TestTypeAttribute))] - //[TestType (TestField = new object[] { typeof (delegate*) })] - //public static void Test_Field_ArrayOfFunctionPointer () - //{ - //} + // [Kept] + // [KeptAttributeAttribute(typeof(TestTypeAttribute))] + // [TestType(TestField = new object[] { typeof(delegate*) })] + // public static void Test_Field_ArrayOfFunctionPointer() + // { + // } } [KeptBaseType(typeof(Attribute))] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/AnotherLibraryForwarder.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/AnotherLibraryForwarder.cs index 74b83ed7a975b5..310e86035e956d 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/AnotherLibraryForwarder.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/AnotherLibraryForwarder.cs @@ -1,3 +1,3 @@ using System; -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.AnotherLibrary<>))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.AnotherLibrary<>))] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/AnotherLibraryReferenceImplementation.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/AnotherLibraryReferenceImplementation.cs index e9aadc2e26ca21..6a2a1314934309 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/AnotherLibraryReferenceImplementation.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/AnotherLibraryReferenceImplementation.cs @@ -1,9 +1,9 @@ namespace Mono.Linker.Tests.Cases.TypeForwarding.Dependencies { #if INCLUDE_REFERENCE_IMPL - public class AnotherLibrary - { - public string Prop { get; set; } - } + public class AnotherLibrary + { + public string Prop { get; set; } + } #endif } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/AttributeWithEnumArgument.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/AttributeWithEnumArgument.cs index e9637be558cc38..e69d8d5f2fdce9 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/AttributeWithEnumArgument.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/AttributeWithEnumArgument.cs @@ -3,7 +3,7 @@ using Mono.Linker.Tests.Cases.TypeForwarding.Dependencies; #if INCLUDE_FORWARDER -[assembly: TypeForwardedTo (typeof (UsedToReferenceForwarderAssembly))] +[assembly: TypeForwardedTo(typeof(UsedToReferenceForwarderAssembly))] #endif namespace Mono.Linker.Tests.Cases.TypeForwarding.Dependencies diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwardedNestedTypeLibrary.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwardedNestedTypeLibrary.cs index be363bd6ddefdb..36921cbfd92c58 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwardedNestedTypeLibrary.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwardedNestedTypeLibrary.cs @@ -3,7 +3,7 @@ #if INCLUDE_FORWARDERS -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ForwardedNestedTypeLibrary))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ForwardedNestedTypeLibrary))] #endif #if INCLUDE_REFERENCE_IMPL @@ -11,14 +11,14 @@ namespace Mono.Linker.Tests.Cases.TypeForwarding.Dependencies; public class ForwardedNestedTypeLibrary { - public class NestedOne - { - public class NestedTwo - { - public class NestedThree - { - } - } - } + public class NestedOne + { + public class NestedTwo + { + public class NestedThree + { + } + } + } } #endif diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibrary.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibrary.cs index 57aee6ea8daa19..7938fa75681472 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibrary.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibrary.cs @@ -1,7 +1,7 @@ using System; -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ImplementationLibrary))] -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ImplementationStruct))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ImplementationLibrary))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ImplementationStruct))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ImplementationLibraryAttribute))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ImplementationLibraryImp))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ImplementationLibraryInterface))] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibraryWithUnusedReference.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibraryWithUnusedReference.cs index b6037e99b93b49..46bbe2572be31e 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibraryWithUnusedReference.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibraryWithUnusedReference.cs @@ -1,4 +1,4 @@ using System; -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ImplementationLibrary))] -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.UnusedImplementationLibrary))] \ No newline at end of file +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ImplementationLibrary))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.UnusedImplementationLibrary))] \ No newline at end of file diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibrary_2.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibrary_2.cs index 85af68d19fa394..ea84556f022a3b 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibrary_2.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibrary_2.cs @@ -1,4 +1,4 @@ using System; -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ImplementationLibrary))] -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.AnotherLibrary<>))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ImplementationLibrary))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.AnotherLibrary<>))] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibrary_3.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibrary_3.cs index d7aea07d7eed43..83cf3bc12c5093 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibrary_3.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ForwarderLibrary_3.cs @@ -1,11 +1,11 @@ using System; -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ImplementationLibrary3A))] -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ImplementationLibrary3B))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ImplementationLibrary3A))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.Dependencies.ImplementationLibrary3B))] namespace Mono.Linker.Tests.Cases.TypeForwarding.Dependencies { - public class RealClassInForwarder3 - { - } + public class RealClassInForwarder3 + { + } } \ No newline at end of file diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ImplementationLibrary.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ImplementationLibrary.cs index 4501cbb4b72c63..505246a160c67f 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ImplementationLibrary.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ImplementationLibrary.cs @@ -1,6 +1,6 @@ using System; -//[assembly: AssemblyVersion ("2.0")] +//[assembly: AssemblyVersion("2.0")] namespace Mono.Linker.Tests.Cases.TypeForwarding.Dependencies { diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ImplementationLibrary_3.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ImplementationLibrary_3.cs index 29223748b63b92..1d46ba76b07546 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ImplementationLibrary_3.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ImplementationLibrary_3.cs @@ -3,11 +3,11 @@ namespace Mono.Linker.Tests.Cases.TypeForwarding.Dependencies { - public class ImplementationLibrary3A - { - } + public class ImplementationLibrary3A + { + } - public class ImplementationLibrary3B - { - } + public class ImplementationLibrary3B + { + } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/MyEnumForwarder.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/MyEnumForwarder.cs index 03d4cf48420b43..550237260454cb 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/MyEnumForwarder.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/MyEnumForwarder.cs @@ -1,7 +1,7 @@ using System.Runtime.CompilerServices; using Mono.Linker.Tests.Cases.TypeForwarding.Dependencies; -[assembly: TypeForwardedTo (typeof (MyEnum))] +[assembly: TypeForwardedTo(typeof(MyEnum))] namespace Mono.Linker.Tests.Cases.TypeForwarding.Dependencies { diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ReferenceImplementationLibrary.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ReferenceImplementationLibrary.cs index 0f99b22a744bcd..8c782971173d78 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ReferenceImplementationLibrary.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ReferenceImplementationLibrary.cs @@ -9,51 +9,51 @@ public class ReferenceImplementationLibrary } #if INCLUDE_REFERENCE_IMPL - public interface ImplementationLibraryInterface - { - public int GetDefaultImplementation () - { - return 42; - } - } - - public class ImplementationLibraryImp : ImplementationLibraryInterface - { - } - - public class ImplementationLibrary { - public class ImplementationLibraryNestedType - { - public static int PropertyOnNestedType { get; set; } - } - - public class ForwardedNestedType - { - } - - public static int someField = 0; - - public string GetSomeValue () - { - return null; - } - } - - public class AnotherImplementationClass - { - public class ForwardedNestedType - { - } - } - - [AttributeUsage (AttributeTargets.All)] - public class ImplementationLibraryAttribute : Attribute - { - } - - public struct ImplementationStruct - { - public int Field; - } + public interface ImplementationLibraryInterface + { + public int GetDefaultImplementation() + { + return 42; + } + } + + public class ImplementationLibraryImp : ImplementationLibraryInterface + { + } + + public class ImplementationLibrary { + public class ImplementationLibraryNestedType + { + public static int PropertyOnNestedType { get; set; } + } + + public class ForwardedNestedType + { + } + + public static int someField = 0; + + public string GetSomeValue() + { + return null; + } + } + + public class AnotherImplementationClass + { + public class ForwardedNestedType + { + } + } + + [AttributeUsage(AttributeTargets.All)] + public class ImplementationLibraryAttribute : Attribute + { + } + + public struct ImplementationStruct + { + public int Field; + } #endif } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ReferenceImplementationUsedAndUnusedLibrary.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ReferenceImplementationUsedAndUnusedLibrary.cs index ce8f6f698832d2..209d6976af459a 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ReferenceImplementationUsedAndUnusedLibrary.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/ReferenceImplementationUsedAndUnusedLibrary.cs @@ -1,13 +1,13 @@ namespace Mono.Linker.Tests.Cases.TypeForwarding.Dependencies { #if INCLUDE_REFERENCE_IMPL - public class ImplementationLibrary - { - public string GetSomeValue () => null; - } + public class ImplementationLibrary + { + public string GetSomeValue() => null; + } - public class UnusedImplementationLibrary - { - } + public class UnusedImplementationLibrary + { + } #endif } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/TypeForwardedIsUpdatedForMissingTypeFwd.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/TypeForwardedIsUpdatedForMissingTypeFwd.cs index 7145725e44cd72..5a47a8b0984e33 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/TypeForwardedIsUpdatedForMissingTypeFwd.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/TypeForwardedIsUpdatedForMissingTypeFwd.cs @@ -1 +1 @@ -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.TypeForwarding.C1))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.C1))] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/TypeForwardersModifiersLibFwd.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/TypeForwardersModifiersLibFwd.cs index 374028aad4e7cf..657596c8069e00 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/TypeForwardersModifiersLibFwd.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/TypeForwardersModifiersLibFwd.cs @@ -1 +1 @@ -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (C))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/TypeForwardersRewriteForwarders.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/TypeForwardersRewriteForwarders.cs index cb79a2f0da8e21..6fbce770290597 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/TypeForwardersRewriteForwarders.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/Dependencies/TypeForwardersRewriteForwarders.cs @@ -1,4 +1,4 @@ -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.TypeForwarding.C))] -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.TypeForwarding.G<>))] -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.TypeForwarding.I))] -[assembly: System.Runtime.CompilerServices.TypeForwardedTo (typeof (Mono.Linker.Tests.Cases.TypeForwarding.S))] \ No newline at end of file +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.C))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.G<>))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.I))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(Mono.Linker.Tests.Cases.TypeForwarding.S))] \ No newline at end of file diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/MissingTargetReference.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/MissingTargetReference.cs index fdc56fa3dec4e6..c7568ca3d7f8fc 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/MissingTargetReference.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/MissingTargetReference.cs @@ -17,7 +17,7 @@ public class MissingTargetReference public static void Main() { #if IL_ASSEMBLY_AVAILABLE - Console.WriteLine (new DummyClass ()); + Console.WriteLine(new DummyClass()); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/SecurityAttributeScope.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/SecurityAttributeScope.cs index 2bbdbedc4cadbc..7ffe36146161b0 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/SecurityAttributeScope.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/SecurityAttributeScope.cs @@ -28,7 +28,7 @@ public class SecurityAttributeScope public static void Main() { #if IL_ASSEMBLY_AVAILABLE - new LibraryWithSecurityAttributes().OnAMethod (); + new LibraryWithSecurityAttributes().OnAMethod(); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/TypeForwardersModifiers.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/TypeForwardersModifiers.cs index 131e265ac47376..9a2c3efea03478 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/TypeForwardersModifiers.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/TypeForwardersModifiers.cs @@ -21,7 +21,7 @@ class TypeForwardersModifiers static void Main() { #if IL_ASSEMBLY_AVAILABLE - TestClass.TestAll (); + TestClass.TestAll(); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedForwarderInGenericIsDynamicallyAccessedWithAssemblyCopyUsed.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedForwarderInGenericIsDynamicallyAccessedWithAssemblyCopyUsed.cs index 1a36b72863b8bc..721a87e32b3b3d 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedForwarderInGenericIsDynamicallyAccessedWithAssemblyCopyUsed.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedForwarderInGenericIsDynamicallyAccessedWithAssemblyCopyUsed.cs @@ -34,7 +34,7 @@ static void Main() [Kept] static void PointToTypeInFacade( - [KeptAttributeAttribute (typeof(DynamicallyAccessedMembersAttribute))] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] string typeName) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedForwarderIsDynamicallyAccessedWithAssemblyCopyUsed.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedForwarderIsDynamicallyAccessedWithAssemblyCopyUsed.cs index 595541b55a12bd..5892a61d167cde 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedForwarderIsDynamicallyAccessedWithAssemblyCopyUsed.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedForwarderIsDynamicallyAccessedWithAssemblyCopyUsed.cs @@ -28,7 +28,7 @@ static void Main() [Kept] static void PointToTypeInFacade( - [KeptAttributeAttribute (typeof(DynamicallyAccessedMembersAttribute))] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] string typeName) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedTransitiveForwarderInCopyAssemblyIsDynamicallyAccessed.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedTransitiveForwarderInCopyAssemblyIsDynamicallyAccessed.cs index 286e6d73cea125..e3467f91711886 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedTransitiveForwarderInCopyAssemblyIsDynamicallyAccessed.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedTransitiveForwarderInCopyAssemblyIsDynamicallyAccessed.cs @@ -32,7 +32,7 @@ static void Main() [Kept] static void PointToTypeInFacade( - [KeptAttributeAttribute (typeof(DynamicallyAccessedMembersAttribute))] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] string typeName) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedTransitiveForwarderInCopyUsedAssemblyIsDynamicallyAccessed.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedTransitiveForwarderInCopyUsedAssemblyIsDynamicallyAccessed.cs index 293dcb89970af7..682c04815c1ff5 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedTransitiveForwarderInCopyUsedAssemblyIsDynamicallyAccessed.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedTransitiveForwarderInCopyUsedAssemblyIsDynamicallyAccessed.cs @@ -32,7 +32,7 @@ static void Main() [Kept] static void PointToTypeInFacade( - [KeptAttributeAttribute (typeof(DynamicallyAccessedMembersAttribute))] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] string typeName) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedTransitiveForwarderIsDynamicallyAccessed.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedTransitiveForwarderIsDynamicallyAccessed.cs index 6aacb8a1b97aac..8ab27190c746ed 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedTransitiveForwarderIsDynamicallyAccessed.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/TypeForwarding/UsedTransitiveForwarderIsDynamicallyAccessed.cs @@ -30,7 +30,7 @@ static void Main() [Kept] static void PointToTypeInFacade( - [KeptAttributeAttribute (typeof(DynamicallyAccessedMembersAttribute))] + [KeptAttributeAttribute(typeof(DynamicallyAccessedMembersAttribute))] [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] string typeName) { } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/ComplexConditions.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/ComplexConditions.cs index 7e3dfc63d87068..1d2c2e107fe6bc 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/ComplexConditions.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/ComplexConditions.cs @@ -22,7 +22,7 @@ public static void Main() [Kept] #if !NET - [ExpectBodyModified] + [ExpectBodyModified] #else [ExpectedInstructionSequence(new[] { "nop", @@ -55,7 +55,7 @@ static void Test_1(object type) [Kept] #if !NET - [ExpectBodyModified] + [ExpectBodyModified] #else [ExpectedInstructionSequence(new[] { "nop", diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/EndScopeOnMethoEnd.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/EndScopeOnMethoEnd.cs index 30e8778562ca48..37c21de319b250 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/EndScopeOnMethoEnd.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/EndScopeOnMethoEnd.cs @@ -14,8 +14,8 @@ public static void Main() { #if IL_ASSEMBLY_AVAILABLE // For now just have a method where the try/finally is the last thing in the method (no instruction after the - // end of finally - Roslyn doesn't seem to produce such method body. - Mono.Linker.Tests.Cases.UnreachableBlock.Dependencies.EndScopeOnMethod.TryFinally (); + // end of finally - Roslyn doesn't seem to produce such method body. + Mono.Linker.Tests.Cases.UnreachableBlock.Dependencies.EndScopeOnMethod.TryFinally(); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/MethodWithParametersSubstitutions.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/MethodWithParametersSubstitutions.cs index e386d3b03eae8f..3f73fb94b364b0 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/MethodWithParametersSubstitutions.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/MethodWithParametersSubstitutions.cs @@ -24,7 +24,7 @@ public static void Main() TestMethodWithComplexParams_4(); TestMethodWithComplexParams_5(); instance.TestMethodWithMultipleInParamsInstance(); - // TestMethodWithOutParam (); + // TestMethodWithOutParam(); TestMethodWithRefParam(); TestMethodWithMultipleRefParams(); TestMethodWithValueParamAndConstReturn_NoSubstitutions(); @@ -195,27 +195,27 @@ void MethodWithMultipleInParamsInstance_NeverReached() { } // CodeRewriterStep actually fails when asked to rewrite method body with an out parameter. // So no point in testing that the substitution works or not. - //[Kept] static bool _isEnabledWithOutParamField; - - //[Kept] - //static bool IsEnabledWithOutParam (out int param) - //{ - // param = 0; - // return _isEnabledWithOutParamField; - //} - - //[Kept] - //[LogDoesNotContain("IsEnabledWithOutParam")] - //static void TestMethodWithOutParam () - //{ - // if (IsEnabledWithOutParam (out var _)) - // MethodWithOutParam_Reached1 (); - // else - // MethodWithOutParam_Reached2 (); - //} - - //[Kept] static void MethodWithOutParam_Reached1 () { } - //[Kept] static void MethodWithOutParam_Reached2 () { } + // [Kept] static bool _isEnabledWithOutParamField; + + // [Kept] + // static bool IsEnabledWithOutParam(out int param) + // { + // param = 0; + // return _isEnabledWithOutParamField; + // } + + // [Kept] + // [LogDoesNotContain("IsEnabledWithOutParam")] + // static void TestMethodWithOutParam() + // { + // if (IsEnabledWithOutParam(out var _)) + // MethodWithOutParam_Reached1(); + // else + // MethodWithOutParam_Reached2(); + // } + + // [Kept] static void MethodWithOutParam_Reached1() { } + // [Kept] static void MethodWithOutParam_Reached2() { } static bool _isEnabledWithRefParamField; diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/SizeOfInConditions.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/SizeOfInConditions.cs index a2b82f7781bf92..c44690e0bf6a8b 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/SizeOfInConditions.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/SizeOfInConditions.cs @@ -7,7 +7,7 @@ namespace Mono.Linker.Tests.Cases.UnreachableBlock #if NET [SetupLinkerSubstitutionFile("SizeOfInConditions.netcore.xml")] #else - [SetupLinkerSubstitutionFile ("SizeOfInConditions.net_4_x.xml")] + [SetupLinkerSubstitutionFile("SizeOfInConditions.net_4_x.xml")] #endif [SetupCompileArgument("/unsafe")] [SetupLinkerArgument("--enable-opt", "ipconstprop")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/UninitializedLocals.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/UninitializedLocals.cs index bfc3a2600e825c..1d3363d46da65f 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/UninitializedLocals.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBlock/UninitializedLocals.cs @@ -22,8 +22,8 @@ public class UninitializedLocals public static void Main() { #if IL_ASSEMBLY_AVAILABLE - Mono.Linker.Tests.Cases.UnreachableBlock.Dependencies.ClassA.Method_1 (); - Mono.Linker.Tests.Cases.UnreachableBlock.Dependencies.ClassA.Method_2 (); + Mono.Linker.Tests.Cases.UnreachableBlock.Dependencies.ClassA.Method_1(); + Mono.Linker.Tests.Cases.UnreachableBlock.Dependencies.ClassA.Method_2(); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBody/DoesNotApplyToCopiedAssembly2.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBody/DoesNotApplyToCopiedAssembly2.cs index 1c0d5ca0cc0d6b..7144647a374e62 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBody/DoesNotApplyToCopiedAssembly2.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBody/DoesNotApplyToCopiedAssembly2.cs @@ -16,16 +16,16 @@ public class DoesNotApplyToCopiedAssembly2 public static void Main() { #if OTHER_INCLUDED - UsedToMarkMethod (null); + UsedToMarkMethod(null); #endif } #if OTHER_INCLUDED - [Kept] - static void UsedToMarkMethod (Mono.Linker.Tests.Cases.UnreachableBody.Dependencies.OtherAssemblyNoInstanceCtor.Foo f) - { - f.Method (); - } + [Kept] + static void UsedToMarkMethod(Mono.Linker.Tests.Cases.UnreachableBody.Dependencies.OtherAssemblyNoInstanceCtor.Foo f) + { + f.Method(); + } #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBody/LinkedOtherIncludedLibrary.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBody/LinkedOtherIncludedLibrary.cs index 0b4007a66a4136..49defd3721fe03 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBody/LinkedOtherIncludedLibrary.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBody/LinkedOtherIncludedLibrary.cs @@ -7,7 +7,7 @@ namespace Mono.Linker.Tests.Cases.UnreachableBody #if NET [SetupLinkerArgument("-a", "other2.dll")] #else - [SetupLinkerArgument ("-r", "other2")] + [SetupLinkerArgument("-r", "other2")] #endif [SetupCompileBefore("other2.dll", new[] { typeof(OtherAssembly) })] [KeptMemberInAssembly("other2.dll", typeof(OtherAssembly.Foo), "Method()")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBody/LinkedOtherIncludedLibraryNoInstanceCtor.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBody/LinkedOtherIncludedLibraryNoInstanceCtor.cs index 2d34f11024f30c..0a9af1a1a63e3c 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBody/LinkedOtherIncludedLibraryNoInstanceCtor.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/UnreachableBody/LinkedOtherIncludedLibraryNoInstanceCtor.cs @@ -8,7 +8,7 @@ namespace Mono.Linker.Tests.Cases.UnreachableBody #if NET [SetupLinkerArgument("-a", "other.dll", "visible")] #else - [SetupLinkerArgument ("-r", "other")] + [SetupLinkerArgument("-r", "other")] #endif [SetupCompileBefore("other.dll", new[] { "Dependencies/OtherAssemblyNoInstanceCtor.il" })] [KeptMemberInAssembly("other.dll", "Mono.Linker.Tests.Cases.UnreachableBody.Dependencies.OtherAssemblyNoInstanceCtor/Foo", "Method()")] @@ -20,16 +20,16 @@ public class LinkedOtherIncludedLibraryNoInstanceCtor public static void Main() { #if OTHER_INCLUDED - UsedToMarkMethod (null); + UsedToMarkMethod(null); #endif } #if OTHER_INCLUDED - [Kept] - static void UsedToMarkMethod (Mono.Linker.Tests.Cases.UnreachableBody.Dependencies.OtherAssemblyNoInstanceCtor.Foo f) - { - f.Method (); - } + [Kept] + static void UsedToMarkMethod(Mono.Linker.Tests.Cases.UnreachableBody.Dependencies.OtherAssemblyNoInstanceCtor.Foo f) + { + f.Method(); + } #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/CanDisableWarningsByCategory.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/CanDisableWarningsByCategory.cs index 82a2f73372455a..53188a07c65fee 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/CanDisableWarningsByCategory.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/CanDisableWarningsByCategory.cs @@ -11,7 +11,7 @@ namespace Mono.Linker.Tests.Cases.Warnings [SkipKeptItemsValidation] [SetupLinkerArgument("--notrimwarn")] #if NATIVEAOT - [SetupLinkerArgument ("--noaotwarn")] + [SetupLinkerArgument("--noaotwarn")] #endif public class CanDisableWarningsByCategory { diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/CanWarnAsErrorGlobal.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/CanWarnAsErrorGlobal.cs index ecfa2deb8c8dfe..da3be9e2d4494a 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/CanWarnAsErrorGlobal.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/CanWarnAsErrorGlobal.cs @@ -24,16 +24,16 @@ public static void Main() } #if IN_TEST_BUILD - public class CanWarnAsError - { - class HelperClass - { - private int helperField = 0; - int HelperMethod () - { - return 0; - } - } - } + public class CanWarnAsError + { + class HelperClass + { + private int helperField = 0; + int HelperMethod() + { + return 0; + } + } + } #endif } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Dependencies/CustomStep.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Dependencies/CustomStep.cs index 7c6edad55ec8ed..326af86ef8cfa0 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Dependencies/CustomStep.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Dependencies/CustomStep.cs @@ -7,35 +7,35 @@ namespace CustomStep { - public class CustomStep : IStep - { - public void Process (LinkContext context) - { - var warningMessage = MessageContainer.CreateCustomWarningMessage ( - context: context, - text: "Warning", - code: 6001, - origin: new MessageOrigin (fileName: "CustomStep.cs"), - version: WarnVersion.Latest); + public class CustomStep : IStep + { + public void Process(LinkContext context) + { + var warningMessage = MessageContainer.CreateCustomWarningMessage( + context: context, + text: "Warning", + code: 6001, + origin: new MessageOrigin(fileName: "CustomStep.cs"), + version: WarnVersion.Latest); - context.LogMessage (warningMessage); - } - } + context.LogMessage(warningMessage); + } + } - public class CustomStepWithInvalidWarningCode : IStep - { - public void Process (LinkContext context) - { - // All codes in the range [1000-6000] are reserved for trimming, single-file and nativeAOT - // errors and warnings and should not be used by external parties. - var invalidWarningMessage = MessageContainer.CreateCustomWarningMessage ( - context: context, - text: "Warning", - code: 2500, - origin: new MessageOrigin (fileName: "CustomStep.cs"), - version: WarnVersion.Latest); + public class CustomStepWithInvalidWarningCode : IStep + { + public void Process(LinkContext context) + { + // All codes in the range [1000-6000] are reserved for trimming, single-file and nativeAOT + // errors and warnings and should not be used by external parties. + var invalidWarningMessage = MessageContainer.CreateCustomWarningMessage( + context: context, + text: "Warning", + code: 2500, + origin: new MessageOrigin(fileName: "CustomStep.cs"), + version: WarnVersion.Latest); - context.LogMessage (invalidWarningMessage); - } - } + context.LogMessage(invalidWarningMessage); + } + } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Individual/CanGenerateWarningSuppressionFileCSharp.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Individual/CanGenerateWarningSuppressionFileCSharp.cs index c58571c859e04b..b44ec756b41c9f 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Individual/CanGenerateWarningSuppressionFileCSharp.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Individual/CanGenerateWarningSuppressionFileCSharp.cs @@ -9,8 +9,8 @@ namespace Mono.Linker.Tests.Cases.Warnings.Individual { [SetupLinkerTrimMode("skip")] #if !NET - [Reference ("System.Core.dll")] - [SetupCompileBefore ("library.dll", new[] { typeof (TriggerWarnings_Lib) }, new[] { "System.Core.dll" })] + [Reference("System.Core.dll")] + [SetupCompileBefore("library.dll", new[] { typeof(TriggerWarnings_Lib) }, new[] { "System.Core.dll" })] #else [SetupCompileBefore("library.dll", new[] { typeof(TriggerWarnings_Lib) })] #endif diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Individual/CanGenerateWarningSuppressionFileXml.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Individual/CanGenerateWarningSuppressionFileXml.cs index 0924de5ad991c4..82306bba13b6a3 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Individual/CanGenerateWarningSuppressionFileXml.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Individual/CanGenerateWarningSuppressionFileXml.cs @@ -6,7 +6,7 @@ namespace Mono.Linker.Tests.Cases.Warnings.Individual { [SetupLinkerTrimMode("skip")] #if !NET - [SetupCompileBefore ("library.dll", new[] { typeof (TriggerWarnings_Lib) }, new[] { "System.Core.dll" })] + [SetupCompileBefore("library.dll", new[] { typeof(TriggerWarnings_Lib) }, new[] { "System.Core.dll" })] #else [SetupCompileBefore("library.dll", new[] { typeof(TriggerWarnings_Lib) })] #endif diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Individual/WarningsAreSorted.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Individual/WarningsAreSorted.cs index f1ad9eaa1113d6..55f0fc0548560c 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Individual/WarningsAreSorted.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/Individual/WarningsAreSorted.cs @@ -13,7 +13,7 @@ namespace Mono.Linker.Tests.Cases.Warnings.Individual [SkipRemainingErrorsValidation] [SetupLinkerTrimMode("skip")] #if !NET - [SetupCompileBefore ("library.dll", new[] { typeof (TriggerWarnings_Lib) }, new[] { "System.Core.dll" })] + [SetupCompileBefore("library.dll", new[] { typeof(TriggerWarnings_Lib) }, new[] { "System.Core.dll" })] #else [SetupCompileBefore("library.dll", new[] { typeof(TriggerWarnings_Lib) })] #endif diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/MultipleMethodsUseSameAsyncStateMachine.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/MultipleMethodsUseSameAsyncStateMachine.cs index 8bfb22b953552d..9e7cc8e7375add 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/MultipleMethodsUseSameAsyncStateMachine.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/MultipleMethodsUseSameAsyncStateMachine.cs @@ -20,7 +20,7 @@ class MultipleMethodsUseSameAsyncStateMachine public static void Main() { #if IL_ASSEMBLY_AVAILABLE - Dependencies.MultipleMethodsUseSameAsyncStateMachine.M(); + Dependencies.MultipleMethodsUseSameAsyncStateMachine.M(); #endif } } diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInAssembly.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInAssembly.cs index 3f478301d6a7fc..2452a6e49ee98d 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInAssembly.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInAssembly.cs @@ -8,7 +8,7 @@ namespace Mono.Linker.Tests.Cases.Warnings.WarningSuppression { #if !NET - [Mono.Linker.Tests.Cases.Expectations.Metadata.Reference ("System.Core.dll")] + [Mono.Linker.Tests.Cases.Expectations.Metadata.Reference("System.Core.dll")] #endif [SkipKeptItemsValidation] [LogDoesNotContain("TriggerUnrecognizedPattern()")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInCopyAssembly.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInCopyAssembly.cs index 6e488e9696f0f1..0619aef770dc3d 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInCopyAssembly.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInCopyAssembly.cs @@ -8,7 +8,7 @@ namespace Mono.Linker.Tests.Cases.Warnings.WarningSuppression { #if !NET - [Reference ("System.Core.dll")] + [Reference("System.Core.dll")] #endif [SetupLinkerAction("copy", "test")] [SkipKeptItemsValidation] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInMembersAndTypes.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInMembersAndTypes.cs index 6cd7366d4096b3..c11ae832f80be5 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInMembersAndTypes.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInMembersAndTypes.cs @@ -7,7 +7,7 @@ namespace Mono.Linker.Tests.Cases.Warnings.WarningSuppression { #if !NET - [Mono.Linker.Tests.Cases.Expectations.Metadata.Reference ("System.Core.dll")] + [Mono.Linker.Tests.Cases.Expectations.Metadata.Reference("System.Core.dll")] #endif [SkipKeptItemsValidation] [LogDoesNotContain("TriggerUnrecognizedPattern()")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInMembersAndTypesUsingTarget.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInMembersAndTypesUsingTarget.cs index cbae89ba77f881..c045717227a4f5 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInMembersAndTypesUsingTarget.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInMembersAndTypesUsingTarget.cs @@ -13,7 +13,7 @@ namespace Mono.Linker.Tests.Cases.Warnings.WarningSuppression { #if !NET - [Mono.Linker.Tests.Cases.Expectations.Metadata.Reference ("System.Core.dll")] + [Mono.Linker.Tests.Cases.Expectations.Metadata.Reference("System.Core.dll")] #endif [SkipKeptItemsValidation] [LogDoesNotContain("TriggerUnrecognizedPattern()")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInModule.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInModule.cs index a0ee1f51b696c7..26d6571a564472 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInModule.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Warnings/WarningSuppression/SuppressWarningsInModule.cs @@ -10,7 +10,7 @@ namespace Mono.Linker.Tests.Cases.Warnings.WarningSuppression { #if !NET - [Mono.Linker.Tests.Cases.Expectations.Metadata.Reference ("System.Core.dll")] + [Mono.Linker.Tests.Cases.Expectations.Metadata.Reference("System.Core.dll")] #endif [SkipKeptItemsValidation] [LogDoesNotContain("TriggerUnrecognizedPattern()")] diff --git a/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/AssemblyChecker.cs b/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/AssemblyChecker.cs index 55bc29499cbeb3..fd430539705ae6 100644 --- a/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/AssemblyChecker.cs +++ b/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/AssemblyChecker.cs @@ -202,9 +202,9 @@ IEnumerable VerifyKeptByAttributes(ICustomAttributeProvider src, string IEnumerable VerifyKeptByAttribute(string keptAttributeProviderName, CustomAttribute attribute) { - // public KeptByAttribute (string dependencyProvider, string reason) { } - // public KeptByAttribute (Type dependencyProvider, string reason) { } - // public KeptByAttribute (Type dependencyProvider, string memberName, string reason) { } + // public KeptByAttribute(string dependencyProvider, string reason) { } + // public KeptByAttribute(Type dependencyProvider, string reason) { } + // public KeptByAttribute(Type dependencyProvider, string memberName, string reason) { } Assert.AreEqual(nameof(KeptByAttribute), attribute.AttributeType.Name); @@ -214,8 +214,8 @@ IEnumerable VerifyKeptByAttribute(string keptAttributeProviderName, Cust expectedDependency.Marked = true; if (attribute.ConstructorArguments.Count == 2) { - // public KeptByAttribute (string dependencyProvider, string reason) { } - // public KeptByAttribute (Type dependencyProvider, string reason) { } + // public KeptByAttribute(string dependencyProvider, string reason) { } + // public KeptByAttribute(Type dependencyProvider, string reason) { } if (attribute.ConstructorArguments[0].Type.IsTypeOf()) expectedDependency.Source = (string)attribute.ConstructorArguments[0].Value; else if (attribute.ConstructorArguments[0].Type.IsTypeOf()) @@ -227,7 +227,7 @@ IEnumerable VerifyKeptByAttribute(string keptAttributeProviderName, Cust } else if (attribute.ConstructorArguments.Count == 3) { - // public KeptByAttribute (Type dependencyProvider, string memberName, string reason) { } + // public KeptByAttribute(Type dependencyProvider, string memberName, string reason) { } if (!attribute.ConstructorArguments[0].Type.IsTypeOf()) throw new NotImplementedException("Unexpected KeptByAttribute ctor variant"); var type = (TypeDefinition)attribute.ConstructorArguments[0].Value; @@ -857,14 +857,14 @@ IEnumerable VerifyReferences(AssemblyDefinition original, AssemblyDefini .ToHashSet(); /* - - The test case will always need to have at least 1 reference. - - Forcing all tests to define their expected references seems tedious + - The test case will always need to have at least 1 reference. + - Forcing all tests to define their expected references seems tedious - Given the above, let's assume that when no [KeptReference] attributes are present, - the test case does not want to make any assertions regarding references. + Given the above, let's assume that when no [KeptReference] attributes are present, + the test case does not want to make any assertions regarding references. - Once 1 kept reference attribute is used, the test will need to define all of of it's expected references - */ + Once 1 kept reference attribute is used, the test will need to define all of of it's expected references + */ if (expected.Count == 0) yield break; diff --git a/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/ILCompiler.cs b/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/ILCompiler.cs index 4cdd7467506b21..84760a8cf5d8fa 100644 --- a/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/ILCompiler.cs +++ b/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/ILCompiler.cs @@ -54,8 +54,8 @@ private static string BuildArguments(CompilerOptions options) args.Append(options.OutputPath.ExtensionWithDot == ".dll" ? "-dll" : "-exe"); args.Append($" -out:{options.OutputPath.InQuotes()}"); #else - args.Append (options.OutputPath.ExtensionWithDot == ".dll" ? "/dll" : "/exe"); - args.Append ($" /out:{options.OutputPath.InQuotes ()}"); + args.Append(options.OutputPath.ExtensionWithDot == ".dll" ? "/dll" : "/exe"); + args.Append($" /out:{options.OutputPath.InQuotes()}"); #endif args.Append($" {options.SourceFiles.Aggregate(string.Empty, (buff, file) => $"{buff} {file.InQuotes()}")}"); return args.ToString(); @@ -74,7 +74,7 @@ protected virtual NPath LocateIlasm() throw new InvalidOperationException("ilasm not found at " + ilasmPath); #else - return Environment.OSVersion.Platform == PlatformID.Win32NT ? LocateIlasmOnWindows () : "ilasm".ToNPath (); + return Environment.OSVersion.Platform == PlatformID.Win32NT ? LocateIlasmOnWindows() : "ilasm".ToNPath(); #endif } diff --git a/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/ILVerification/ILChecker.cs b/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/ILVerification/ILChecker.cs index 66ffdfc9f24915..9f0b8fa5952dc9 100644 --- a/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/ILVerification/ILChecker.cs +++ b/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/ILVerification/ILChecker.cs @@ -176,7 +176,7 @@ protected virtual ILVerifier CreateILVerifier(NPath directory) return new ILVerifier(new[] { directory, - typeof (object).Assembly.Location.ToNPath ().Parent + typeof(object).Assembly.Location.ToNPath().Parent }, "System.Private.CoreLib"); } diff --git a/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/TestCaseCompiler.cs b/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/TestCaseCompiler.cs index 53a1946af7495d..d9828e9660df7c 100644 --- a/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/TestCaseCompiler.cs +++ b/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/TestCaseCompiler.cs @@ -236,7 +236,7 @@ protected virtual NPath CompileCSharpAssemblyWithDefaultCompiler(CompilerOptions #if NET return CompileCSharpAssemblyWithRoslyn(options); #else - return CompileCSharpAssemblyWithCsc (options); + return CompileCSharpAssemblyWithCsc(options); #endif } @@ -346,7 +346,7 @@ protected virtual NPath CompileCSharpAssemblyWithCsc(CompilerOptions options) #if NET return CompileCSharpAssemblyWithRoslyn(options); #else - return CompileCSharpAssemblyWithExternalCompiler (LocateCscExecutable (), options, "/shared "); + return CompileCSharpAssemblyWithExternalCompiler(LocateCscExecutable(), options, "/shared "); #endif } diff --git a/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/TrimmingArgumentBuilder.cs b/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/TrimmingArgumentBuilder.cs index 5596a9a71c846d..fa425b330d3d08 100644 --- a/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/TrimmingArgumentBuilder.cs +++ b/src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/TrimmingArgumentBuilder.cs @@ -71,8 +71,8 @@ public virtual void RootAssemblyVisible(string fileName) Append(fileName); Append("visible"); #else - Append ("-r"); - Append (fileName); + Append("-r"); + Append(fileName); #endif } @@ -225,8 +225,8 @@ public virtual void ProcessOptions(TestCaseLinkerOptions options) IgnoreLinkAttributes(options.IgnoreLinkAttributes); #if !NET - if (!string.IsNullOrEmpty (options.Il8n)) - AddIl8n (options.Il8n); + if (!string.IsNullOrEmpty options.Il8n)) + AddIl8n(options.Il8n); #endif if (!string.IsNullOrEmpty(options.LinkSymbols)) diff --git a/src/tools/illink/test/Mono.Linker.Tests/Tests/DocumentationSignatureParserTests.cs b/src/tools/illink/test/Mono.Linker.Tests/Tests/DocumentationSignatureParserTests.cs index 78c39b88c75e54..c126c9504b002c 100644 --- a/src/tools/illink/test/Mono.Linker.Tests/Tests/DocumentationSignatureParserTests.cs +++ b/src/tools/illink/test/Mono.Linker.Tests/Tests/DocumentationSignatureParserTests.cs @@ -194,7 +194,7 @@ public static void M(List a) } [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32,)")] - //[ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32,)")] + //[ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32,)")] // there's no way to reference this, since the parsing logic doesn't like it. public static void M(int abo, __arglist) { @@ -254,9 +254,9 @@ public int this[int i] public static implicit operator bool(A a) => false; // C# will not generate a return type for this method, but we will. - // [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] - // [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] - //public static int op_Implicit (A a) => 0; + // [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] + // [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] + //public static int op_Implicit(A a) => 0; [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_UnaryPlus(Mono.Linker.Tests.DocumentationSignatureParserTests.A)")] [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_UnaryPlus(Mono.Linker.Tests.DocumentationSignatureParserTests.A)")] From e2e9938897dc74d24e0607d45344814bc0a0a43f Mon Sep 17 00:00:00 2001 From: Sven Boemer Date: Mon, 7 Jul 2025 23:25:23 +0000 Subject: [PATCH 2/6] Update analyzer test expected warning locations --- ...DynamicallyAccessedMembersAnalyzerTests.cs | 164 ++++++------ .../DynamicallyAccessedMembersCodeFixTests.cs | 234 +++++++++--------- .../RequiresAssemblyFilesAnalyzerTests.cs | 116 ++++----- .../RequiresDynamicCodeAnalyzerTests.cs | 60 ++--- .../RequiresUnreferencedCodeAnalyzerTests.cs | 52 ++-- ...nconditionalSuppressMessageCodeFixTests.cs | 16 +- 6 files changed, 320 insertions(+), 322 deletions(-) diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersAnalyzerTests.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersAnalyzerTests.cs index 1cbd480d087265..2db6ae9f47800f 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersAnalyzerTests.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersAnalyzerTests.cs @@ -91,8 +91,8 @@ private static void M(Type type) // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetParameterWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter) - .WithSpan(21, 3, 21, 38) - .WithSpan(19, 24, 19, 33) + .WithSpan(21, 9, 21, 44) + .WithSpan(19, 27, 19, 36) .WithArguments("parameter", "C.NeedsPublicMethodsOnParameter(Type)", "type", @@ -131,8 +131,8 @@ private static Type M(Type type) // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetMethodReturnTypeWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsMethodReturnType) - .WithSpan(18, 10, 18, 14) - .WithSpan(16, 24, 16, 33) + .WithSpan(18, 16, 18, 20) + .WithSpan(16, 27, 16, 36) .WithArguments("C.M(Type)", "type", "C.M(Type)", @@ -172,8 +172,8 @@ private static void M(Type type) // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetFieldWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsField) - .WithSpan(17, 3, 17, 11) - .WithSpan(15, 24, 15, 33) + .WithSpan(17, 9, 17, 17) + .WithSpan(15, 27, 15, 36) .WithArguments("C.f", "type", "C.M(Type)", @@ -210,8 +210,8 @@ private static void M(Type type) // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetMethodWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsThisParameter) - .WithSpan(16, 3, 16, 24) - .WithSpan(14, 24, 14, 33) + .WithSpan(16, 9, 16, 30) + .WithSpan(14, 27, 14, 36) .WithArguments("System.Type.GetMethod(String)", "type", "C.M(Type)", @@ -250,13 +250,11 @@ private static Type GetT() } """; - // (12,3): warning IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethodsOnParameter(Type)'. - // The return value of method 'C.GetT()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + // (12,9): warning IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'C.NeedsPublicMethodsOnParameter(Type)'. The return value of method 'C.GetT()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetParameterWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter) - .WithSpan(12, 3, 12, 40) - .WithSpan(20, 2, 23, 3) + .WithSpan(12, 9, 12, 46) + .WithSpan(20, 5, 23, 6) .WithArguments("type", "C.NeedsPublicMethodsOnParameter(Type)", "C.GetT()", "'DynamicallyAccessedMemberTypes.PublicMethods'")); } @@ -291,13 +289,11 @@ private static Type GetFoo() } """; - // (18,10): warning IL2073: 'C.M()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. - // The return value of method 'C.GetT()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + // (18,16): warning IL2073: 'C.M()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The return value of method 'C.GetT()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetMethodReturnTypeWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsMethodReturnType) - .WithSpan(18, 10, 18, 18) - .WithSpan(21, 2, 24, 3) + .WithSpan(18, 16, 18, 24) + .WithSpan(21, 5, 24, 6) .WithArguments("C.M()", "C.GetFoo()", "'DynamicallyAccessedMemberTypes.PublicMethods'")); } @@ -329,13 +325,11 @@ private static Type M() } """; - // (12,3): warning IL2074: value stored in field 'C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. - // The return value of method 'C.M()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + // (12,9): warning IL2074: value stored in field 'C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The return value of method 'C.M()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetFieldWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsField) - .WithSpan(12, 3, 12, 10) - .WithSpan(15, 2, 18, 3) + .WithSpan(12, 9, 12, 16) + .WithSpan(15, 5, 18, 6) .WithArguments("C.f", "C.M()", "'DynamicallyAccessedMemberTypes.PublicMethods'")); @@ -367,15 +361,14 @@ private static Type GetFoo() """; // The warning will be generated once dataflow is able to handle GetMethod intrinsic - // (11,3): warning IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. - // The return value of method 'C.GetT()' does not have matching annotations. - // The source value must declare at least the same requirements as those declared on the target location it is assigned to. + // (11,9): warning IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethod(String)'. The return value of method 'C.GetT()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetMethodWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter) - .WithSpan(11, 3, 11, 28) - .WithSpan(15, 2, 18, 3) + .WithSpan(11, 9, 11, 34) + .WithSpan(15, 5, 18, 6) .WithArguments("System.Type.GetMethod(String)", "C.GetFoo()", "'DynamicallyAccessedMemberTypes.PublicMethods'")); } + #endregion #region SourceField @@ -411,8 +404,8 @@ private static void NeedsPublicMethods( // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetParameterWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsParameter) - .WithSpan(14, 3, 14, 24) - .WithSpan(10, 22, 10, 37) + .WithSpan(14, 9, 14, 30) + .WithSpan(10, 25, 10, 40) .WithArguments("type", "C.NeedsPublicMethods(Type)", "C.f", @@ -452,8 +445,8 @@ private static Type M() // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetMethodReturnTypeWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsMethodReturnType) - .WithSpan(20, 10, 20, 11) - .WithSpan(10, 22, 10, 37) + .WithSpan(20, 16, 20, 17) + .WithSpan(10, 25, 10, 40) .WithArguments("C.M()", "C.f", "'DynamicallyAccessedMemberTypes.PublicMethods'")); } @@ -487,8 +480,8 @@ public static void Main() // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetFieldWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsField) - .WithSpan(17, 3, 17, 10) - .WithSpan(10, 22, 10, 38) + .WithSpan(17, 9, 17, 16) + .WithSpan(10, 25, 10, 41) .WithArguments("C.f2", "C.f1", "'DynamicallyAccessedMemberTypes.PublicMethods'")); @@ -521,8 +514,8 @@ public static void Main() // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetMethodWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsThisParameter) - .WithSpan(13, 3, 13, 21) - .WithSpan(9, 22, 9, 37) + .WithSpan(13, 9, 13, 27) + .WithSpan(9, 25, 9, 40) .WithArguments("System.Type.GetMethod(String)", "C.f", "'DynamicallyAccessedMemberTypes.PublicMethods'")); @@ -751,13 +744,13 @@ private static void M2( } """; - // (198,4): warning IL2082: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. + // (198,13): warning IL2082: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(string.Concat(GetSystemTypeBase(), TargetParameterWithAnnotations), consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter) - .WithSpan(198, 4, 198, 12) - .WithSpan(196, 3, 199, 4) + .WithSpan(198, 13, 198, 21) + .WithSpan(196, 9, 199, 10) .WithArguments("type", "System.C.M2(Type)", "System.C.M1()", "'DynamicallyAccessedMemberTypes.PublicMethods'")); } @@ -794,14 +787,13 @@ private static void M2( """; return VerifyDynamicallyAccessedMembersAnalyzer(string.Concat(GetSystemTypeBase(), ConversionOperation), consoleApplication: false, - // (203,4): warning IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. The return value of method 'System.ConvertsToType.implicit operator Type(ConvertsToType)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. + // (203,13): warning IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. The return value of method 'System.ConvertsToType.implicit operator Type(ConvertsToType)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter) - .WithSpan(203, 4, 203, 28) - .WithSpan(191, 3, 191, 89) + .WithSpan(203, 13, 203, 37) + .WithSpan(191, 9, 191, 94) .WithArguments("type", "System.C.M2(Type)", "System.ConvertsToType.implicit operator Type(ConvertsToType)", "'DynamicallyAccessedMemberTypes.PublicMethods'")); } - [Fact] public Task ConversionOperationAnnotationDoesNotMatch() { @@ -837,9 +829,9 @@ private static void M2( """; return VerifyDynamicallyAccessedMembersAnalyzer(string.Concat(GetSystemTypeBase(), AnnotatedConversionOperation), consoleApplication: false, - // (205,4): warning IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. The return value of method 'System.ConvertsToType.implicit operator Type(ConvertsToType)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. + // (205,13): warning IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.C.M2(Type)'. The return value of method 'System.ConvertsToType.implicit operator Type(ConvertsToType)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter) - .WithSpan(205, 4, 205, 28) + .WithSpan(205, 13, 205, 37) .WithArguments("type", "System.C.M2(Type)", "System.ConvertsToType.implicit operator Type(ConvertsToType)", "'DynamicallyAccessedMemberTypes.PublicMethods'")); } @@ -904,13 +896,13 @@ private Type M() } """; - // (200,11): warning IL2083: 'System.C.M()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. + // (200,20): warning IL2083: 'System.C.M()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. // The implicit 'this' argument of method 'System.C.M()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(string.Concat(GetSystemTypeBase(), TargetMethodReturnTypeWithAnnotations), consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsMethodReturnType) - .WithSpan(200, 11, 200, 15) - .WithSpan(196, 3, 201, 4) + .WithSpan(200, 20, 200, 24) + .WithSpan(196, 9, 201, 10) .WithArguments("System.C.M()", "System.C.M()", "'DynamicallyAccessedMemberTypes.PublicMethods'")); } @@ -939,13 +931,13 @@ private void M() } """; - // (198,4): warning IL2084: value stored in field 'System.C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. + // (198,13): warning IL2084: value stored in field 'System.C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. // The implicit 'this' argument of method 'System.C.M()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(string.Concat(GetSystemTypeBase(), TargetFieldWithAnnotations), consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsField) - .WithSpan(198, 4, 198, 12) - .WithSpan(196, 3, 199, 4) + .WithSpan(198, 13, 198, 21) + .WithSpan(196, 9, 199, 10) .WithArguments("System.C.f", "System.C.M()", "'DynamicallyAccessedMemberTypes.PublicMethods'")); @@ -972,13 +964,13 @@ private void M() } """; - // (198,4): warning IL2085: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethods()'. + // (198,13): warning IL2085: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethods()'. // The implicit 'this' argument of method 'System.C.M()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(string.Concat(GetSystemTypeBase(), TargetMethodWithAnnotations), consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsThisParameter) - .WithSpan(198, 4, 198, 21) - .WithSpan(196, 3, 199, 4) + .WithSpan(198, 13, 198, 30) + .WithSpan(196, 9, 199, 10) .WithArguments("System.Type.GetMethods()", "System.C.M()", "'DynamicallyAccessedMemberTypes.PublicMethods'")); } #endregion @@ -1014,8 +1006,8 @@ private static void M2() // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetParameterWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsParameter) - .WithSpan(18, 3, 18, 16) - .WithSpan(16, 25, 16, 26) + .WithSpan(18, 9, 18, 22) + .WithSpan(16, 28, 16, 29) .WithArguments("type", "C.M1(Type)", "T", "C.M2()", "'DynamicallyAccessedMemberTypes.PublicMethods'")); } @@ -1046,8 +1038,8 @@ private static Type M() // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetMethodReturnTypeWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsMethodReturnType) - .WithSpan(14, 10, 14, 19) - .WithSpan(12, 24, 12, 25) + .WithSpan(14, 16, 14, 25) + .WithSpan(12, 27, 12, 28) .WithArguments("C.M()", "T", "C.M()", "'DynamicallyAccessedMemberTypes.PublicConstructors'")); } @@ -1080,8 +1072,8 @@ private static void M() // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetFieldWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsField) - .WithSpan(16, 3, 16, 16) - .WithSpan(14, 24, 14, 25) + .WithSpan(16, 9, 16, 22) + .WithSpan(14, 27, 14, 28) .WithArguments("C.f", "T", "C.M()", @@ -1117,8 +1109,8 @@ private static void M2() // The source value must declare at least the same requirements as those declared on the target location it is assigned to. return VerifyDynamicallyAccessedMembersAnalyzer(TargetGenericParameterWithAnnotations, consoleApplication: false, VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsGenericParameter) - .WithSpan(16, 3, 16, 10) - .WithSpan(14, 25, 14, 26) + .WithSpan(16, 9, 16, 16) + .WithSpan(14, 28, 14, 29) .WithArguments("T", "C.M1()", "S", "C.M2()", "'DynamicallyAccessedMemberTypes.PublicMethods'")); } @@ -1284,8 +1276,8 @@ static void RequireAll([DynamicallyAccessedMembers(DynamicallyAccessedMemberType """; return VerifyDynamicallyAccessedMembersAnalyzer(Source, consoleApplication: false, - // (8,14): error CS0103: The name 'type' does not exist in the current context - DiagnosticResult.CompilerError("CS0103").WithSpan(8, 14, 8, 18).WithArguments("type")); + // (8,20): error CS0103: The name 'type' does not exist in the current context + DiagnosticResult.CompilerError("CS0103").WithSpan(8, 20, 8, 24).WithArguments("type")); } [Fact] @@ -1308,10 +1300,10 @@ public static void Main() """; return VerifyDynamicallyAccessedMembersAnalyzer(Source, consoleApplication: false, - // (12,34): error CS0103: The name 'type' does not exist in the current context - DiagnosticResult.CompilerError("CS0103").WithSpan(12, 34, 12, 38).WithArguments("type"), - // (12,34): warning IL2063: Value returned from method 'C.GetTypeWithAll()' can not be statically determined and may not meet 'DynamicallyAccessedMembersAttribute' requirements. - VerifyCS.Diagnostic(DiagnosticId.MethodReturnValueCannotBeStaticallyDetermined).WithSpan(12, 34, 12, 38).WithArguments("C.GetTypeWithAll()")); + // (12,37): error CS0103: The name 'type' does not exist in the current context + DiagnosticResult.CompilerError("CS0103").WithSpan(12, 37, 12, 41).WithArguments("type"), + // (12,37): warning IL2063: Value returned from method 'C.GetTypeWithAll()' can not be statically determined and may not meet 'DynamicallyAccessedMembersAttribute' requirements. + VerifyCS.Diagnostic(DiagnosticId.MethodReturnValueCannotBeStaticallyDetermined).WithSpan(12, 37, 12, 41).WithArguments("C.GetTypeWithAll()")); } [Fact] @@ -1334,10 +1326,10 @@ public static void Main() """; return VerifyDynamicallyAccessedMembersAnalyzer(Source, consoleApplication: false, - // (8,22): error CS0103: The name 'type' does not exist in the current context - DiagnosticResult.CompilerError("CS0103").WithSpan(8, 22, 8, 26).WithArguments("type"), - // (8,3): warning IL2064: Value assigned to C.fieldRequiresAll can not be statically determined and may not meet 'DynamicallyAccessedMembersAttribute' requirements. - VerifyCS.Diagnostic(DiagnosticId.FieldValueCannotBeStaticallyDetermined).WithSpan(8, 3, 8, 26).WithArguments("C.fieldRequiresAll")); + // (8,28): error CS0103: The name 'type' does not exist in the current context + DiagnosticResult.CompilerError("CS0103").WithSpan(8, 28, 8, 32).WithArguments("type"), + // (8,9): warning IL2064: Value assigned to C.fieldRequiresAll can not be statically determined and may not meet 'DynamicallyAccessedMembersAttribute' requirements. + VerifyCS.Diagnostic(DiagnosticId.FieldValueCannotBeStaticallyDetermined).WithSpan(8, 9, 8, 32).WithArguments("C.fieldRequiresAll")); } [Fact] @@ -1361,7 +1353,7 @@ public static void Main() return VerifyDynamicallyAccessedMembersAnalyzer(Source, consoleApplication: false, // (8,9): error CS0103: The name 'type' does not exist in the current context - DiagnosticResult.CompilerError("CS0103").WithSpan(8, 3, 8, 7).WithArguments("type")); + DiagnosticResult.CompilerError("CS0103").WithSpan(8, 9, 8, 13).WithArguments("type")); } [Fact] @@ -1384,8 +1376,8 @@ public static void Main() """; return VerifyDynamicallyAccessedMembersAnalyzer(Source, consoleApplication: false, - // (8,3): error CS0103: The name 'type' does not exist in the current context - DiagnosticResult.CompilerError("CS0103").WithSpan(8, 3, 8, 7).WithArguments("type")); + // (8,9): error CS0103: The name 'type' does not exist in the current context + DiagnosticResult.CompilerError("CS0103").WithSpan(8, 9, 8, 13).WithArguments("type")); } [Fact] @@ -1398,12 +1390,12 @@ public Task AssignmentTargetHasNestedInvalidOperation() """; return VerifyDynamicallyAccessedMembersAnalyzer(Source, consoleApplication: true, - // (2,6): error CS1525: Invalid expression term '=' - DiagnosticResult.CompilerError("CS1525").WithSpan(2, 6, 2, 7).WithArguments("="), - // (2,2): error CS0165: Use of unassigned local variable 'a' - DiagnosticResult.CompilerError("CS0165").WithSpan(2, 2, 2, 3).WithArguments("a"), - // (1,9): warning CS0219: The variable 'b' is assigned but its value is never used - DiagnosticResult.CompilerWarning("CS0219").WithSpan(1, 9, 1, 10).WithArguments("b") + // (2,9): error CS1525: Invalid expression term '=' + DiagnosticResult.CompilerError("CS1525").WithSpan(2, 9, 2, 10).WithArguments("="), + // (2,5): error CS0165: Use of unassigned local variable 'a' + DiagnosticResult.CompilerError("CS0165").WithSpan(2, 5, 2, 6).WithArguments("a"), + // (1,12): warning CS0219: The variable 'b' is assigned but its value is never used + DiagnosticResult.CompilerWarning("CS0219").WithSpan(1, 12, 1, 13).WithArguments("b") ); } @@ -1428,8 +1420,14 @@ class CRequires<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Publi // The actual usage (ctor call) should warn, about missing annotation, but the cref should not. return VerifyDynamicallyAccessedMembersAnalyzer(Source, consoleApplication: false, - // (10,36): warning IL2091: 'TInner' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in 'CRequires'. The generic parameter 'TOuter' of 'C' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. - VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsGenericParameter).WithSpan(10, 36, 10, 60).WithSpan(3, 9, 3, 15).WithArguments("TInner", "CRequires", "TOuter", "C", "'DynamicallyAccessedMemberTypes.PublicMethods'")); + // (10,60): error CS1526: A new expression requires an argument list or (), [], or {} after type + DiagnosticResult.CompilerError("CS1526").WithSpan(10, 60, 10, 61), + // (10,60): error CS1002: ; expected + DiagnosticResult.CompilerError("CS1002").WithSpan(10, 60, 10, 61), + // (10,60): error CS1519: Invalid token ')' in a member declaration + DiagnosticResult.CompilerError("CS1519").WithSpan(10, 60, 10, 61).WithArguments(")"), + // (10,39): warning IL2091: 'TInner' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in 'CRequires'. The generic parameter 'TOuter' of 'C' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. + VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsGenericParameter).WithSpan(10, 39, 10, 60).WithSpan(3, 9, 3, 15).WithArguments("TInner", "CRequires", "TOuter", "C", "'DynamicallyAccessedMemberTypes.PublicMethods'")); } [Fact] diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersCodeFixTests.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersCodeFixTests.cs index 7f3fcb16951a89..481d539fb2c89a 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersCodeFixTests.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/DynamicallyAccessedMembersCodeFixTests.cs @@ -80,8 +80,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The parameter 't' of method 'C.M(Type)' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter) - .WithSpan(7, 3, 7, 8) - .WithSpan(6, 16, 6, 22) + .WithSpan(7, 9, 7, 14) + .WithSpan(6, 19, 6, 25) .WithArguments("t", "C.M2(Type)", "t", @@ -134,8 +134,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The parameter 't' of method 'C.M(Type)' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter) - .WithSpan(8, 3, 8, 8) - .WithSpan(7, 18, 7, 24) + .WithSpan(8, 9, 8, 14) + .WithSpan(7, 21, 7, 27) .WithArguments("t", "C.M2(Type)", "t", @@ -166,8 +166,8 @@ static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Public // The parameter 't' of method 'C.M(Type)' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter) - .WithSpan(7, 3, 7, 8) - .WithSpan(6, 16, 6, 22) + .WithSpan(7, 9, 7, 14) + .WithSpan(6, 19, 6, 25) .WithArguments("t", "C.M2(Type)", "t", @@ -201,7 +201,7 @@ static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Public // The parameter 't' of method 'C.M(Type)' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter) - .WithSpan(8, 3, 8, 8) + .WithSpan(8, 9, 8, 14) .WithArguments("t", "C.M2(Type)", "t", @@ -246,8 +246,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( baselineExpected: new[] { // /0/Test0.cs(8,10): warning IL2068: 'C.M(Type)' method return value does not satisfy 'DynamicallyAccessedMemberTypes.All' requirements. The parameter 't' of method 'C.M(Type)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsMethodReturnType) - .WithSpan(8, 10, 8, 11) - .WithSpan(7, 9, 7, 15) + .WithSpan(8, 16, 8, 17) + .WithSpan(7, 12, 7, 18) .WithArguments("C.M(Type)", "t", "C.M(Type)", @@ -274,7 +274,7 @@ Type M([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.None)] Type t) var diag = new[] { // /0/Test0.cs(8,10): warning IL2068: 'C.M(Type)' method return value does not satisfy 'DynamicallyAccessedMemberTypes.All' requirements. The parameter 't' of method 'C.M(Type)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsMethodReturnType) - .WithSpan(8, 10, 8, 11) + .WithSpan(8, 16, 8, 17) .WithArguments("C.M(Type)", "t", "C.M(Type)", @@ -335,8 +335,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( //The parameter 'type' of method 'C.M(Type)' does not have matching annotations. //The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsField) - .WithSpan(13, 3, 13, 11) - .WithSpan(11, 24, 11, 33) + .WithSpan(13, 9, 13, 17) + .WithSpan(11, 27, 11, 36) .WithArguments("C.f", "type", "C.M(Type)", @@ -386,8 +386,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( baselineExpected: new[] { // /0/Test0.cs(12,3): warning IL2070: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' in call to 'System.Type.GetMethods()'. The parameter 't' of method 'C.M(Type)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsThisParameter) - .WithSpan(12, 3, 12, 17) - .WithSpan(10, 16, 10, 22) + .WithSpan(12, 9, 12, 23) + .WithSpan(10, 19, 10, 25) .WithArguments("System.Type.GetMethods()", "t", "C.M(Type)", @@ -442,8 +442,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The parameter 't' of method 'C.M(Type)' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsThisParameter) - .WithSpan(13, 3, 13, 39) - .WithSpan(11, 16, 11, 22) + .WithSpan(13, 9, 13, 45) + .WithSpan(11, 19, 11, 25) .WithArguments("System.Type.GetMethods(BindingFlags)", "t", "C.M(Type)", @@ -453,7 +453,7 @@ await VerifyDynamicallyAccessedMembersCodeFix( // /0/Test0.cs(9,3): warning IL2111: Method 'C.M(Type)' with parameters or return value with `DynamicallyAccessedMembersAttribute` is accessed via reflection. // Trimmer can't guarantee availability of the requirements of the method. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMethodAccessedViaReflection) - .WithSpan(9, 3, 9, 15) + .WithSpan(9, 9, 9, 21) .WithArguments("C.M(Type)") }); } @@ -509,8 +509,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The parameter 't' of method 'System.C.Main(Type)' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsThisParameter) - .WithSpan(10, 27, 10, 41) - .WithSpan(8, 20, 8, 26) + .WithSpan(10, 36, 10, 50) + .WithSpan(8, 26, 8, 32) .WithArguments("System.Type.GetMethods()", "t", "System.C.Main(Type)", @@ -577,8 +577,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The return value of method 'C.GetT()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter) - .WithSpan(8, 3, 8, 40) - .WithSpan(16, 2, 19, 3) + .WithSpan(8, 9, 8, 46) + .WithSpan(16, 5, 19, 6) .WithArguments("type", "C.NeedsPublicMethodsOnParameter(Type)", "C.GetC()", @@ -645,8 +645,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The return value of method 'C.GetC(Type)' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter) - .WithSpan(8, 3, 8, 49) - .WithSpan(16, 2, 19, 3) + .WithSpan(8, 9, 8, 55) + .WithSpan(16, 5, 19, 6) .WithArguments("t", "C.NeedsPublicMethodsOnParameter(Type)", "C.GetC(Type)", @@ -686,7 +686,7 @@ private static Type GetC() // The return value of method 'C.GetT()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter) - .WithSpan(8, 3, 8, 40) + .WithSpan(8, 9, 8, 46) .WithArguments("type", "C.NeedsPublicMethodsOnParameter(Type)", "C.GetC()", @@ -726,7 +726,7 @@ private static Type GetT() // The return value of method 'C.GetT()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter) - .WithSpan(8, 3, 8, 40) + .WithSpan(8, 9, 8, 46) .WithArguments("type", "C.NeedsPublicMethodsOnParameter(Type)", "C.GetT()", @@ -777,8 +777,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The return value of method 'C.Main(Type)' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsMethodReturnType) - .WithSpan(11, 10, 11, 25) - .WithSpan(5, 2, 7, 3) + .WithSpan(11, 16, 11, 31) + .WithSpan(5, 5, 7, 6) .WithArguments("C.M()", "C.Main(Type)", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -828,8 +828,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The return value of method 'C.Main(Type)' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsMethodReturnType) - .WithSpan(11, 10, 11, 17) - .WithSpan(5, 2, 7, 3) + .WithSpan(11, 16, 11, 23) + .WithSpan(5, 5, 7, 6) .WithArguments("C.M(Type)", "C.Main(Type)", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -889,8 +889,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The return value of method 'C.M()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsField) - .WithSpan(8, 3, 8, 10) - .WithSpan(11, 2, 14, 3) + .WithSpan(8, 9, 8, 16) + .WithSpan(11, 5, 14, 6) .WithArguments("C.f", "C.M()", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -931,7 +931,7 @@ public static void Main() } [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - private static Type GetC) + private static Type GetC() { return typeof(C); } @@ -945,8 +945,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( //The return value of method 'C.GetFoo()' does not have matching annotations. //The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter) - .WithSpan(8, 3, 8, 26) - .WithSpan(11, 2, 14, 3) + .WithSpan(8, 9, 8, 32) + .WithSpan(11, 5, 14, 6) .WithArguments("System.Type.GetMethod(String)", "C.GetC()", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -968,7 +968,7 @@ public static void Main() GetC().GetMethod("Foo"); } - private static Type GetC) + private static Type GetC() { return typeof(int); } @@ -1002,8 +1002,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( //The return value of method 'C.GetFoo()' does not have matching annotations. //The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter) - .WithSpan(194, 4, 194, 27) - .WithSpan(197, 3, 200, 4) + .WithSpan(194, 13, 194, 36) + .WithSpan(197, 9, 200, 10) .WithArguments("System.Type.GetMethod(String)", "System.C.GetC()", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -1059,8 +1059,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( //The return value of method 'C.GetFoo()' does not have matching annotations. //The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter) - .WithSpan(193, 4, 193, 27) - .WithSpan(196, 3, 200, 4) + .WithSpan(193, 13, 193, 36) + .WithSpan(196, 9, 200, 10) .WithArguments("System.Type.GetMethod(String)", "System.C.GetC()", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -1118,8 +1118,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( //The return value of method 'C.GetFoo()' does not have matching annotations. //The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter) - .WithSpan(194, 4, 194, 27) - .WithSpan(198, 3, 201, 4) + .WithSpan(194, 13, 194, 36) + .WithSpan(198, 9, 201, 10) .WithArguments("System.Type.GetMethod(String)", "System.C.GetC()", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -1177,8 +1177,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The field 'C.f' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsParameter) - .WithSpan(10, 3, 10, 24) - .WithSpan(6, 22, 6, 35) + .WithSpan(10, 9, 10, 30) + .WithSpan(6, 25, 6, 38) .WithArguments("type", "C.NeedsPublicMethods(Type)", "C.f", @@ -1216,7 +1216,7 @@ private static void NeedsPublicMethods( // The field 'C.f' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsParameter) - .WithSpan(11, 3, 11, 24) + .WithSpan(11, 9, 11, 30) .WithArguments("type", "C.NeedsPublicMethods(Type)", "C.f", @@ -1265,8 +1265,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The field 'C.f' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsMethodReturnType) - .WithSpan(9, 10, 9, 11) - .WithSpan(12, 22, 12, 23) + .WithSpan(9, 16, 9, 17) + .WithSpan(12, 25, 12, 26) .WithArguments("C.Main()", "C.f", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -1298,7 +1298,7 @@ public static Type Main() // The field 'C.f' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsMethodReturnType) - .WithSpan(9, 10, 9, 11) + .WithSpan(9, 16, 9, 17) .WithArguments("C.Main()", "C.f", "'DynamicallyAccessedMemberTypes.PublicMethods'")}; @@ -1350,8 +1350,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The field 'C.f1' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsField) - .WithSpan(13, 3, 13, 10) - .WithSpan(6, 22, 6, 36) + .WithSpan(13, 9, 13, 16) + .WithSpan(6, 25, 6, 39) .WithArguments("C.f2", "C.f1", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -1385,7 +1385,7 @@ public static void Main() // The field 'C.f1' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsField) - .WithSpan(14, 3, 14, 10) + .WithSpan(14, 9, 14, 16) .WithArguments("C.f2", "C.f1", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -1433,8 +1433,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The field 'C.f' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsThisParameter) - .WithSpan(10, 3, 10, 21) - .WithSpan(6, 22, 6, 35) + .WithSpan(10, 9, 10, 27) + .WithSpan(6, 25, 6, 38) .WithArguments("System.Type.GetMethod(String)", "C.f", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -1482,8 +1482,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The field 'C.f' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsThisParameter) - .WithSpan(10, 3, 10, 21) - .WithSpan(6, 21, 6, 34) + .WithSpan(10, 9, 10, 27) + .WithSpan(6, 24, 6, 37) .WithArguments("System.Type.GetMethod(String)", "C.f", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -1514,7 +1514,7 @@ public static void Main() // The field 'C.f' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsThisParameter) - .WithSpan(11, 3, 11, 21) + .WithSpan(11, 9, 11, 27) .WithArguments("System.Type.GetMethod(String)", "C.f", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -1577,18 +1577,18 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter) - .WithSpan(198, 4, 198, 12) - .WithSpan(196, 3, 199, 4) + .WithSpan(198, 13, 198, 21) + .WithSpan(196, 9, 199, 10) .WithArguments("t", "System.C.M2(Type)", "System.C.M1()", "'DynamicallyAccessedMemberTypes.PublicMethods'") }, fixedExpected: new[] { - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined + // /0/Test0.cs(193,13): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) - .WithSpan(193, 4, 193, 16) + .WithSpan(193, 13, 193, 25) .WithArguments("System.C.M1()") }); } @@ -1652,18 +1652,18 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter) - .WithSpan(199, 4, 199, 12) - .WithSpan(196, 3, 201, 4) + .WithSpan(199, 13, 199, 21) + .WithSpan(196, 9, 201, 10) .WithArguments("t", "System.C.M2(Type)", "System.C.M1()", "'DynamicallyAccessedMemberTypes.PublicMethods'") }, fixedExpected: new[] { - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined + // /0/Test0.cs(193,13): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) - .WithSpan(193, 4, 193, 16) + .WithSpan(193, 13, 193, 25) .WithArguments("System.C.M1()") }); } @@ -1727,18 +1727,18 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter) - .WithSpan(199, 4, 199, 12) - .WithSpan(196, 3, 201, 4) + .WithSpan(199, 13, 199, 21) + .WithSpan(196, 9, 201, 10) .WithArguments("t", "System.C.M2(Type)", "System.C.M1(String)", "'DynamicallyAccessedMemberTypes.PublicMethods'") }, fixedExpected: new[] { - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined + // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1(String)' can not be statically determined // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) - .WithSpan(193, 4, 193, 21) + .WithSpan(193, 13, 193, 30) .WithArguments("System.C.M1(String)") }); } @@ -1773,15 +1773,15 @@ private static void M2([DynamicallyAccessedMembers(DynamicallyAccessedMemberType // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter) - .WithSpan(199, 4, 199, 12) + .WithSpan(199, 13, 199, 21) .WithArguments("t", "System.C.M2(Type)", "System.C.M1()", "'DynamicallyAccessedMemberTypes.PublicMethods'"), - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined + // /0/Test0.cs(193,13): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) - .WithSpan(193, 4, 193, 16) + .WithSpan(193, 13, 193, 25) .WithArguments("System.C.M1()") }; await VerifyDynamicallyAccessedMembersCodeFix(string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), test), @@ -1835,8 +1835,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( baselineExpected: new[] { // /0/Test0.cs(199,11): warning IL2083: 'System.C.M1()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsMethodReturnType) - .WithSpan(199, 11, 199, 15) - .WithSpan(196, 3, 200, 4) + .WithSpan(199, 20, 199, 24) + .WithSpan(196, 9, 200, 10) .WithArguments("System.C.M1()", "System.C.M1()", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -1845,7 +1845,7 @@ await VerifyDynamicallyAccessedMembersCodeFix( // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) - .WithSpan(193, 4, 193, 16) + .WithSpan(193, 13, 193, 25) .WithArguments("System.C.M1()") }); } @@ -1899,8 +1899,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( baselineExpected: new[] { // /0/Test0.cs(199,11): warning IL2083: 'System.C.M1()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsMethodReturnType) - .WithSpan(200, 11, 200, 15) - .WithSpan(196, 3, 201, 4) + .WithSpan(200, 20, 200, 24) + .WithSpan(196, 9, 201, 10) .WithArguments("System.C.M1(String)", "System.C.M1(String)", "'DynamicallyAccessedMemberTypes.PublicMethods'") @@ -1909,7 +1909,7 @@ await VerifyDynamicallyAccessedMembersCodeFix( // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) - .WithSpan(193, 4, 193, 21) + .WithSpan(193, 13, 193, 30) .WithArguments("System.C.M1(String)") }); } @@ -1939,14 +1939,14 @@ private Type M1() var diag = new[] { // /0/Test0.cs(200,11): warning IL2083: 'System.C.M1()' method return value does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsMethodReturnType) - .WithSpan(200, 11, 200, 15) + .WithSpan(200, 20, 200, 24) .WithArguments("System.C.M1()", "System.C.M1()", "'DynamicallyAccessedMemberTypes.PublicMethods'"), - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined + // /0/Test0.cs(193,13): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) - .WithSpan(193, 4, 193, 16) + .WithSpan(193, 13, 193, 25) .WithArguments("System.C.M1()") }; await VerifyDynamicallyAccessedMembersCodeFix(string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), test), @@ -2007,17 +2007,17 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The implicit 'this' argument of method 'System.C.M()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsField) - .WithSpan(198, 4, 198, 12) - .WithSpan(196, 3, 199, 4) + .WithSpan(198, 13, 198, 21) + .WithSpan(196, 9, 199, 10) .WithArguments("System.C.f", "System.C.M()", "'DynamicallyAccessedMemberTypes.PublicMethods'") }, fixedExpected: new[] { - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M()' can not be statically determined + // /0/Test0.cs(193,13): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M()' can not be statically determined // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) - .WithSpan(193, 4, 193, 15) + .WithSpan(193, 13, 193, 24) .WithArguments("System.C.M()") }); } @@ -2079,17 +2079,17 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsThisParameter) - .WithSpan(198, 4, 198, 13) - .WithSpan(196, 3, 199, 4) + .WithSpan(198, 13, 198, 22) + .WithSpan(196, 9, 199, 10) .WithArguments("System.C.M2()", "System.C.M1()", "'DynamicallyAccessedMemberTypes.PublicMethods'") }, fixedExpected: new[] { - // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined + // /0/Test0.cs(193,13): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) - .WithSpan(193, 4, 193, 16) + .WithSpan(193, 13, 193, 25) .WithArguments("System.C.M1()") }); } @@ -2125,14 +2125,14 @@ private void M2() // The implicit 'this' argument of method 'System.C.M1()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsThisParameter) - .WithSpan(199, 4, 199, 13) + .WithSpan(199, 13, 199, 22) .WithArguments("System.C.M2()", "System.C.M1()", "'DynamicallyAccessedMemberTypes.PublicMethods'"), // /0/Test0.cs(193,4): warning IL2065: Value passed to implicit 'this' parameter of method 'System.C.M1()' can not be statically determined // and may not meet 'DynamicallyAccessedMembersAttribute' requirements. VerifyCS.Diagnostic(DiagnosticId.ImplicitThisCannotBeStaticallyDetermined) - .WithSpan(193, 4, 193, 16) + .WithSpan(193, 13, 193, 25) .WithArguments("System.C.M1()") }; await VerifyDynamicallyAccessedMembersCodeFix(string.Concat(DynamicallyAccessedMembersAnalyzerTests.GetSystemTypeBase(), test), @@ -2194,8 +2194,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The generic parameter 'T' of 'C.M2()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsParameter) - .WithSpan(18, 3, 18, 16) - .WithSpan(16, 25, 16, 26) + .WithSpan(18, 9, 18, 22) + .WithSpan(16, 28, 16, 29) .WithArguments("type", "C.M1(Type)", "T", @@ -2252,8 +2252,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The generic parameter 'T' of 'C.M()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsMethodReturnType) - .WithSpan(14, 10, 14, 19) - .WithSpan(12, 24, 12, 25) + .WithSpan(14, 16, 14, 25) + .WithSpan(12, 27, 12, 28) .WithArguments("C.M()", "T", "C.M()", @@ -2288,7 +2288,7 @@ public static void Main() // The generic parameter 'T' of 'C.M()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsMethodReturnType) - .WithSpan(14, 10, 14, 19) + .WithSpan(14, 16, 14, 25) .WithArguments("C.M()", "T", "C.M()", @@ -2336,8 +2336,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( baselineExpected: new[] { // /0/Test0.cs(8,3): warning IL2089: value stored in field 'C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The generic parameter 'T' of 'C.Main()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsField) - .WithSpan(8, 3, 8, 16) - .WithSpan(6, 26, 6, 27) + .WithSpan(8, 9, 8, 22) + .WithSpan(6, 29, 6, 30) .WithArguments("C.f", "T", "C.Main()", @@ -2367,7 +2367,7 @@ class C var diag = new[] { // /0/Test0.cs(8,3): warning IL2089: value stored in field 'C.f' does not satisfy 'DynamicallyAccessedMemberTypes.PublicMethods' requirements. The generic parameter 'T' of 'C.Main()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsField) - .WithSpan(8, 3, 8, 16) + .WithSpan(8, 9, 8, 22) .WithArguments("C.f", "T", "C.Main()", @@ -2412,7 +2412,7 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The generic parameter 'T' of 'C' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsThisParameter) - .WithSpan(8, 3, 8, 25) + .WithSpan(8, 9, 8, 31) .WithSpan(4, 9, 4, 10) .WithArguments("System.Type.GetMethods()", "T", @@ -2441,7 +2441,7 @@ void M() // The generic parameter 'T' of 'C' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsThisParameter) - .WithSpan(8, 3, 8, 25) + .WithSpan(8, 9, 8, 31) .WithArguments("System.Type.GetMethods()", "T", "C", @@ -2470,7 +2470,7 @@ void M() // The generic parameter 'T' of 'C' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsThisParameter) - .WithSpan(8, 3, 8, 25) + .WithSpan(8, 9, 8, 31) .WithArguments("System.Type.GetMethods()", "T", "C", @@ -2530,8 +2530,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // The generic parameter 'S' of 'C.M2()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsGenericParameter) - .WithSpan(16, 3, 16, 10) - .WithSpan(14, 25, 14, 26) + .WithSpan(16, 9, 16, 16) + .WithSpan(14, 28, 14, 29) .WithArguments("T", "C.M1()", "S", @@ -2569,7 +2569,7 @@ public static void Main() // The generic parameter 'S' of 'C.M2()' does not have matching annotations. // The source value must declare at least the same requirements as those declared on the target location it is assigned to. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsGenericParameter) - .WithSpan(16, 3, 16, 10) + .WithSpan(16, 9, 16, 16) .WithArguments("T", "C.M1()", "S", @@ -2621,8 +2621,8 @@ await VerifyDynamicallyAccessedMembersCodeFix(test, fixtest, new[] { // don't match overridden parameter 't' of method 'Base.M(Type)'. // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides) - .WithSpan(11, 30, 11, 31) - .WithSpan(11, 30, 11, 31) + .WithSpan(11, 33, 11, 34) + .WithSpan(11, 33, 11, 34) .WithArguments("t", "C.M(Type)", "t", @@ -2677,8 +2677,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // don't match overridden parameter 't' of method 'Base.M(Type)'. // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides) - .WithSpan(11, 108, 11, 109) - .WithSpan(6, 29, 6, 30) + .WithSpan(11, 111, 11, 112) + .WithSpan(6, 32, 6, 33) .WithArguments("t", "C.M(Type)", "t", @@ -2713,7 +2713,7 @@ public static void Main() { // don't match overridden parameter 't' of method 'Base.M(Type)'. // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides) - .WithSpan(11, 108, 11, 109) + .WithSpan(11, 111, 11, 112) .WithArguments("t", "C.M(Type)", "t", @@ -2748,8 +2748,8 @@ public static void Main() { // don't match overridden parameter 't' of method 'Base.M(Type)'. // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides) - .WithSpan(11, 30, 11, 31) - .WithSpan(11, 30, 11, 31) + .WithSpan(11, 33, 11, 34) + .WithSpan(11, 33, 11, 34) .WithArguments("t", "C.M(Type)", "t", @@ -2784,7 +2784,7 @@ public static void Main() { // don't match overridden parameter 't' of method 'Base.M(Type)'. // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides) - .WithSpan(11, 108, 11, 109) + .WithSpan(11, 111, 11, 112) .WithArguments("t", "C.M(Type)", "t", @@ -2849,8 +2849,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // don't match overridden return value of method 'Base.M(Type)'. // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides) - .WithSpan(14, 23, 14, 24) - .WithSpan(14, 23, 14, 24) + .WithSpan(14, 26, 14, 27) + .WithSpan(14, 26, 14, 27) .WithArguments("C.M(Type)", "Base.M(Type)") }, @@ -2913,8 +2913,8 @@ await VerifyDynamicallyAccessedMembersCodeFix( // don't match overridden return value of method 'Base.M(Type)'. // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides) - .WithSpan(14, 23, 14, 24) - .WithSpan(6, 22, 6, 23) + .WithSpan(14, 26, 14, 27) + .WithSpan(6, 25, 6, 26) .WithArguments("C.M(Type)", "Base.M(Type)") }, @@ -2952,7 +2952,7 @@ public static void Main() { // don't match overridden return value of method 'Base.M(Type)'. // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides) - .WithSpan(15, 23, 15, 24) + .WithSpan(15, 26, 15, 27) .WithArguments("C.M(Type)", "Base.M(Type)") }; @@ -2990,7 +2990,7 @@ public static void Main() { // don't match overridden return value of method 'Base.M(Type)'. // All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage. VerifyCS.Diagnostic(DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides) - .WithSpan(15, 23, 15, 24) + .WithSpan(15, 26, 15, 27) .WithArguments("C.M(Type)", "Base.M(Type)") }; diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresAssemblyFilesAnalyzerTests.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresAssemblyFilesAnalyzerTests.cs index 326ddf9588251b..d5b0d230742e69 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresAssemblyFilesAnalyzerTests.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresAssemblyFilesAnalyzerTests.cs @@ -146,8 +146,8 @@ void M() } """; return VerifyRequiresAssemblyFilesAnalyzer(TestRequiresAssemblyFieldsOnEvent, - // (11,17): warning IL3002: Using member 'C.E' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(11, 3, 11, 26).WithArguments("C.E.add", "", "")); + // (11,9): warning IL3002: Using member 'C.E.add' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(11, 9, 11, 32).WithArguments("C.E.add", "", "")); } [Fact] @@ -170,10 +170,10 @@ void M() } """; return VerifyRequiresAssemblyFilesAnalyzer(TestRequiresAssemblyFilesOnProperty, - // (11,3): warning IL3002: Using member 'C.P' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(11, 3, 11, 12).WithArguments("C.P.set", "", ""), - // (12,35): warning IL3002: Using member 'C.P' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(12, 35, 12, 36).WithArguments("C.P.get", "", "")); + // (11,9): warning IL3002: Using member 'C.P.set' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(11, 9, 11, 18).WithArguments("C.P.set", "", ""), + // (12,41): warning IL3002: Using member 'C.P.get' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(12, 41, 12, 42).WithArguments("C.P.get", "", "")); } [Fact] @@ -207,8 +207,8 @@ void M() } """; return VerifyRequiresAssemblyFilesAnalyzer(TestRequiresAssemblyFilesOnMethodInsideProperty, - // (23,3): warning IL3002: Using member 'C.P' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(23, 3, 23, 12).WithArguments("C.P.set", "", "")); + // (23,9): warning IL3002: Using member 'C.P.set' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(23, 9, 23, 18).WithArguments("C.P.set", "", "")); } [Fact] @@ -231,8 +231,8 @@ void M2() } """; return VerifyRequiresAssemblyFilesAnalyzer(TestRequiresAssemblyFilesWithMessageAndUrl, - // (12,3): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. https://helpurl - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(12, 3, 12, 5).WithArguments("C.M1()", "", " https://helpurl")); + // (12,9): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. https://helpurl + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(12, 9, 12, 11).WithArguments("C.M1()", "", " https://helpurl")); } [Fact] @@ -263,7 +263,7 @@ void M1() M2(); } - [RequiresAssemblyFile("Warn from M2")] + [RequiresAssemblyFiles("Warn from M2")] void M2() { M3(); @@ -276,8 +276,8 @@ void M3() } """; return VerifyRequiresAssemblyFilesAnalyzer(TestNoDiagnosticIsProducedIfCallerIsAnnotated, - // (7,3): warning IL3002: Using member 'C.M2()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. Warn from M2. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(7, 3, 7, 5).WithArguments("C.M2()", " Warn from M2.", "")); + // (7,9): warning IL3002: Using member 'C.M2()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. Warn from M2. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(7, 9, 7, 11).WithArguments("C.M2()", " Warn from M2.", "")); } [Fact] @@ -293,7 +293,7 @@ class C return VerifyRequiresAssemblyFilesAnalyzer(src, // (5,26): warning IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. - VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(4, 23, 4, 63).WithArguments("System.Reflection.Assembly.Location.get")); + VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(4, 26, 4, 66).WithArguments("System.Reflection.Assembly.Location.get")); } [Fact] @@ -314,8 +314,8 @@ public void M() } """; return VerifyRequiresAssemblyFilesAnalyzer(src, - // (7,7): warning IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. - VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(7, 7, 7, 17).WithArguments("System.Reflection.Assembly.Location.get") + // (7,13): warning IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. + VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(7, 13, 7, 23).WithArguments("System.Reflection.Assembly.Location.get") ); } @@ -335,10 +335,10 @@ public void M() } """; return VerifyRequiresAssemblyFilesAnalyzer(src, - // (7,7): warning IL3001: Assemblies embedded in a single-file app cannot have additional files in the manifest. - VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyGetFilesInSingleFile).WithSpan(7, 7, 7, 16).WithArguments("System.Reflection.Assembly.GetFile(String)"), - // (8,7): warning IL3001: Assemblies embedded in a single-file app cannot have additional files in the manifest. - VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyGetFilesInSingleFile).WithSpan(8, 7, 8, 17).WithArguments("System.Reflection.Assembly.GetFiles()") + // (7,13): warning IL3001: Assemblies embedded in a single-file app cannot have additional files in the manifest. + VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyGetFilesInSingleFile).WithSpan(7, 13, 7, 22).WithArguments("System.Reflection.Assembly.GetFile(String)"), + // (8,13): warning IL3001: Assemblies embedded in a single-file app cannot have additional files in the manifest. + VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyGetFilesInSingleFile).WithSpan(8, 13, 8, 23).WithArguments("System.Reflection.Assembly.GetFiles()") ); } @@ -358,14 +358,14 @@ public void M() } """; return VerifyRequiresAssemblyFilesAnalyzer(src, - // (7,7): warning SYSLIB0044: 'AssemblyName.CodeBase' is obsolete: 'AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported.' - DiagnosticResult.CompilerWarning("SYSLIB0044").WithSpan(7, 7, 7, 17).WithArguments("System.Reflection.AssemblyName.CodeBase", "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported."), - // (8,7): warning SYSLIB0044: 'AssemblyName.EscapedCodeBase' is obsolete: 'AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported.' - DiagnosticResult.CompilerWarning("SYSLIB0044").WithSpan(8, 7, 8, 24).WithArguments("System.Reflection.AssemblyName.EscapedCodeBase", "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported."), - // (7,7): warning IL3000: 'System.Reflection.AssemblyName.CodeBase' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. - VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(7, 7, 7, 17).WithArguments("System.Reflection.AssemblyName.CodeBase.get"), - // (8,7): warning IL3000: 'System.Reflection.AssemblyName.EscapedCodeBase' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. - VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(8, 7, 8, 24).WithArguments("System.Reflection.AssemblyName.EscapedCodeBase.get") + // (7,13): warning SYSLIB0044: 'AssemblyName.CodeBase' is obsolete: 'AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported.' + DiagnosticResult.CompilerWarning("SYSLIB0044").WithSpan(7, 13, 7, 23).WithArguments("System.Reflection.AssemblyName.CodeBase", "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported."), + // (8,13): warning SYSLIB0044: 'AssemblyName.EscapedCodeBase' is obsolete: 'AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported.' + DiagnosticResult.CompilerWarning("SYSLIB0044").WithSpan(8, 13, 8, 30).WithArguments("System.Reflection.AssemblyName.EscapedCodeBase", "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported."), + // (7,13): warning IL3000: 'System.Reflection.AssemblyName.CodeBase' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. + VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(7, 13, 7, 23).WithArguments("System.Reflection.AssemblyName.CodeBase.get"), + // (8,13): warning IL3000: 'System.Reflection.AssemblyName.EscapedCodeBase' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. + VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(8, 13, 8, 30).WithArguments("System.Reflection.AssemblyName.EscapedCodeBase.get") ); } @@ -387,10 +387,10 @@ public void M() } """; return VerifyRequiresAssemblyFilesAnalyzer(src, - // (7,7): warning IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. - VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(7, 7, 7, 17).WithArguments("System.Reflection.Assembly.Location.get"), - // (8,7): warning IL3001: Assemblies embedded in a single-file app cannot have additional files in the manifest. - VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyGetFilesInSingleFile).WithSpan(8, 7, 8, 17).WithArguments("System.Reflection.Assembly.GetFiles()") + // (7,13): warning IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. + VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(7, 13, 7, 23).WithArguments("System.Reflection.Assembly.Location.get"), + // (8,13): warning IL3001: Assemblies embedded in a single-file app cannot have additional files in the manifest. + VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyGetFilesInSingleFile).WithSpan(8, 13, 8, 23).WithArguments("System.Reflection.Assembly.GetFiles()") ); } @@ -494,14 +494,14 @@ public class F source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(6,14): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(6, 14, 6, 16).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(10,24): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(10, 24, 10, 28).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(13,25): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(13, 25, 13, 29).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(20,25): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(20, 25, 20, 29).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(6,17): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(6, 17, 6, 19).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(10,27): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(10, 27, 10, 31).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(13,31): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(13, 31, 13, 35).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(20,31): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(20, 31, 20, 35).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } @@ -541,10 +541,10 @@ public void M2() { source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(6,24): warning IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. - VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(6, 24, 6, 41).WithArguments("System.Reflection.Assembly.Location.get", "", ""), - // /0/Test0.cs(8,7): warning IL3001: 'System.Reflection.Assembly.GetFiles()' will throw for assemblies embedded in a single-file app - VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyGetFilesInSingleFile).WithSpan(8, 7, 8, 24).WithArguments("System.Reflection.Assembly.GetFiles()", "", ""), + // /0/Test0.cs(6,27): warning IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. + VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyLocationInSingleFile).WithSpan(6, 27, 6, 44).WithArguments("System.Reflection.Assembly.Location.get"), + // /0/Test0.cs(8,13): warning IL3001: 'System.Reflection.Assembly.GetFiles()' will throw for assemblies embedded in a single-file app + VerifyCS.Diagnostic(DiagnosticId.AvoidAssemblyGetFilesInSingleFile).WithSpan(8, 13, 8, 30).WithArguments("System.Reflection.Assembly.GetFiles()"), }, fixedExpected: Array.Empty()); } @@ -581,8 +581,8 @@ public class C source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(9,12): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(9, 12, 9, 14).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(9,15): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(9, 15, 9, 17).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } @@ -628,10 +628,10 @@ private int M2 { } """; var diag = new[] { - // /0/Test0.cs(12,16): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(12, 16, 12, 18).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(13,17): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(13, 17, 13, 19).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(12,22): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(12, 22, 12, 24).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(13,23): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(13, 23, 13, 25).WithArguments("C.M1()", " message.", "") }; return VerifyRequiresAssemblyFilesCodeFix(src, fix, diag, Array.Empty()); } @@ -656,8 +656,8 @@ public static C InitC() { """; var diag = new[] { - // /0/Test0.cs(5,47): warning IL3002: Using member 'C.InitC()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(5, 47, 5, 52).WithArguments("C.InitC()", "", ""), + // /0/Test0.cs(5,50): warning IL3002: Using member 'C.InitC()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(5, 50, 5, 55).WithArguments("C.InitC()", "", ""), }; return VerifyRequiresAssemblyFilesCodeFix(src, src, diag, diag); } @@ -703,8 +703,8 @@ Action M2() source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(11,22): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(11, 22, 11, 24).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(11,27): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(11, 27, 11, 29).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty(), numberOfIterations: 2); @@ -742,8 +742,8 @@ public class C source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(9,17): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(9, 17, 9, 19).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(9,19): warning IL3002: Using member 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when embedded in a single-file app. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(9, 19, 9, 21).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } @@ -794,8 +794,8 @@ public event EventHandler E1 source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(13,12): warning IL3002: Using method 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(13, 12, 13, 14).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(13,21): warning IL3002: Using method 'C.M1()' which has 'RequiresAssemblyFilesAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresAssemblyFiles).WithSpan(13, 21, 13, 23).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresDynamicCodeAnalyzerTests.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresDynamicCodeAnalyzerTests.cs index ca27be84603296..ac3706f82e00ee 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresDynamicCodeAnalyzerTests.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresDynamicCodeAnalyzerTests.cs @@ -142,14 +142,14 @@ await VerifyRequiresDynamicCodeCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(8,14): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(8, 14, 8, 16).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(12,24): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(12, 24, 12, 28).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(16,25): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(16, 25, 16, 29).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(23,25): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(23, 25, 23, 29).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(8,17): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(8, 17, 8, 19).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(12,27): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(12, 27, 12, 31).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(16,31): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(16, 31, 16, 35).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(23,28): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(23, 31, 23, 35).WithArguments("C.M1()", " message.", "") }, fixedExpected: new[] { // /0/Test0.cs(26,10): error CS7036: There is no argument given that corresponds to the required formal parameter 'message' of 'RequiresDynamicCodeAttribute.RequiresDynamicCodeAttribute(string)' @@ -177,8 +177,8 @@ Action M2() } """; var diag = new[] { - // /0/Test0.cs(11,16): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(11, 16, 11, 18).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(11,22): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(11, 22, 11, 24).WithArguments("C.M1()", " message.", "") }; // No fix available inside a lambda, requires manual code change since attribute cannot // be applied @@ -226,8 +226,8 @@ Action M2() source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(11,22): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(11, 22, 11, 24).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(11,27): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(11, 27, 11, 29).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty(), // The default iterations for the codefix is the number of diagnostics (1 in this case) @@ -269,8 +269,8 @@ public class C source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(9,16): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(9, 16, 9, 18).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(9,19): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(9, 19, 9, 21).WithArguments("C.M1()", " message.", "") }, fixedExpected: new[] { // /0/Test0.cs(9,6): error CS7036: There is no argument given that corresponds to the required formal parameter 'message' of 'RequiresDynamicCodeAttribute.RequiresDynamicCodeAttribute(string)' @@ -294,8 +294,8 @@ public class C } """; var diag = new[] { - // /0/Test0.cs(9,12): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(9, 12, 9, 14).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(9,15): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(9, 15, 9, 17).WithArguments("C.M1()", " message.", "") }; // Can't apply RDC on properties at the moment return VerifyRequiresDynamicCodeCodeFix(src, src, diag, diag); @@ -342,10 +342,10 @@ private int M2 { } """; var diag = new[] { - // /0/Test0.cs(12,16): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(12, 16, 12, 18).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(13,17): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(13, 17, 13, 19).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(12,22): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(12, 22, 12, 24).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(13,23): warning IL3050: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(13, 23, 13, 25).WithArguments("C.M1()", " message.", "") }; return VerifyRequiresDynamicCodeCodeFix(src, fix, diag, Array.Empty()); } @@ -381,8 +381,8 @@ public class C """; return VerifyRequiresDynamicCodeCodeFix(src, fix, baselineExpected: new[] { - // /0/Test0.cs(9,21,9,25): warning IL2026: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(9, 21, 9, 23).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(9,24,9,26): warning IL2026: Using member 'C.M1()' which has 'RequiresDynamicCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(9, 24, 9, 26).WithArguments("C.M1()", " message.", ""), }, fixedExpected: new[] { // /0/Test0.cs(4,2): error CS7036: There is no argument given that corresponds to the required parameter 'message' of 'RequiresDynamicCodeAttribute.RequiresDynamicCodeAttribute(string)' @@ -448,8 +448,8 @@ class Gen { } """; return VerifyRequiresDynamicCodeAnalyzer(src, - // (4,21): warning IL3050: Using member 'System.Type.MakeGenericType(params Type[])' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The native code for this instantiation might not be available at runtime. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(4, 21, 4, 52).WithArguments("System.Type.MakeGenericType(params Type[])", " The native code for this instantiation might not be available at runtime.", "")); + // (4,24): warning IL3050: Using member 'System.Type.MakeGenericType(params Type[])' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The native code for this instantiation might not be available at runtime. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(4, 24, 4, 55).WithArguments("System.Type.MakeGenericType(params Type[])", " The native code for this instantiation might not be available at runtime.", "")); } [Fact] @@ -466,8 +466,8 @@ class Gen { } """; return VerifyRequiresDynamicCodeAnalyzer(src, - // (4,21): warning IL3050: Using member 'System.Type.MakeGenericType(params Type[])' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The native code for this instantiation might not be available at runtime. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(4, 21, 4, 50).WithArguments("System.Type.MakeGenericType(params Type[])", " The native code for this instantiation might not be available at runtime.", "")); + // (4,24): warning IL3050: Using member 'System.Type.MakeGenericType(params Type[])' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The native code for this instantiation might not be available at runtime. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(4, 24, 4, 53).WithArguments("System.Type.MakeGenericType(params Type[])", " The native code for this instantiation might not be available at runtime.", "")); } [Fact] @@ -528,8 +528,8 @@ public void N() { } """; return VerifyRequiresDynamicCodeAnalyzer(src, - // (4,21): warning IL3050: Using member 'System.Reflection.MethodInfo.MakeGenericMethod(params Type[])' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The native code for this instantiation might not be available at runtime. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(4, 21, 4, 54).WithArguments("System.Reflection.MethodInfo.MakeGenericMethod(params Type[])", " The native code for this instantiation might not be available at runtime.", "")); + // (4,24): warning IL3050: Using member 'System.Reflection.MethodInfo.MakeGenericMethod(params Type[])' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The native code for this instantiation might not be available at runtime. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(4, 24, 4, 57).WithArguments("System.Reflection.MethodInfo.MakeGenericMethod(params Type[])", " The native code for this instantiation might not be available at runtime.", "")); } [Fact] @@ -546,8 +546,8 @@ public void N() { } """; return VerifyRequiresDynamicCodeAnalyzer(src, - // (4,21): warning IL3050: Using member 'System.Reflection.MethodInfo.MakeGenericMethod(params Type[])' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The native code for this instantiation might not be available at runtime. - VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(4, 21, 4, 69).WithArguments("System.Reflection.MethodInfo.MakeGenericMethod(params Type[])", " The native code for this instantiation might not be available at runtime.", "")); + // (4,24): warning IL3050: Using member 'System.Reflection.MethodInfo.MakeGenericMethod(params Type[])' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The native code for this instantiation might not be available at runtime. + VerifyCS.Diagnostic(DiagnosticId.RequiresDynamicCode).WithSpan(4, 24, 4, 72).WithArguments("System.Reflection.MethodInfo.MakeGenericMethod(params Type[])", " The native code for this instantiation might not be available at runtime.", "")); } } } diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresUnreferencedCodeAnalyzerTests.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresUnreferencedCodeAnalyzerTests.cs index 015403bf16497a..b0cf31595cd40e 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresUnreferencedCodeAnalyzerTests.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/RequiresUnreferencedCodeAnalyzerTests.cs @@ -90,8 +90,8 @@ await VerifyRequiresUnreferencedCodeCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(9,25): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 25, 9, 27).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(9,28): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 28, 9, 30).WithArguments("C.M1()", " message.", ""), }, fixedExpected: new[] { // /0/Test0.cs(10,3): error CS7036: There is no argument given that corresponds to the required formal parameter 'message' of 'RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)' @@ -166,14 +166,14 @@ await VerifyRequiresUnreferencedCodeCodeFix( source: test, fixedSource: fixtest, baselineExpected: new[] { - // /0/Test0.cs(8,14): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(8, 14, 8, 16).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(12,24): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(12, 24, 12, 28).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(16,25): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(16, 25, 16, 29).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(23,25): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(23, 25, 23, 29).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(8,17): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(8, 17, 8, 19).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(12,27): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(12, 27, 12, 31).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(16,31): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(16, 31, 16, 35).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(23,28): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(23, 31, 23, 35).WithArguments("C.M1()", " message.", "") }, fixedExpected: new[] { // /0/Test0.cs(26,10): error CS7036: There is no argument given that corresponds to the required formal parameter 'message' of 'RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)' @@ -200,8 +200,8 @@ Action M2() } """; var diag = new[] { - // /0/Test0.cs(11,16): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(11, 16, 11, 18).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(11,22): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(11, 22, 11, 24).WithArguments("C.M1()", " message.", "") }; // No fix available inside a lambda, requires manual code change since attribute cannot // be applied @@ -249,8 +249,8 @@ Action M2() source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(11,22): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(11, 22, 11, 24).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(11,27): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(11, 27, 11, 29).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty(), // The default iterations for the codefix is the number of diagnostics (1 in this case) @@ -292,8 +292,8 @@ public class C source: src, fixedSource: fix, baselineExpected: new[] { - // /0/Test0.cs(9,16): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 16, 9, 18).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(9,19): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 19, 9, 21).WithArguments("C.M1()", " message.", "") }, fixedExpected: new[] { // /0/Test0.cs(9,3): error CS7036: There is no argument given that corresponds to the required formal parameter 'message' of 'RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)' @@ -317,8 +317,8 @@ public class C } """; var diag = new[] { - // /0/Test0.cs(10,15): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 12, 9, 14).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(9,15): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 15, 9, 17).WithArguments("C.M1()", " message.", "") }; // Can't apply RUC on properties at the moment return VerifyRequiresUnreferencedCodeCodeFix(src, src, diag, diag); @@ -365,10 +365,10 @@ private int M2 { } """; var diag = new[] { - // /0/Test0.cs(12,16): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(12, 16, 12, 18).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(13,17): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(13, 17, 13, 19).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(12,22): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(12, 22, 12, 24).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(13,23): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(13, 23, 13, 25).WithArguments("C.M1()", " message.", "") }; return VerifyRequiresUnreferencedCodeCodeFix(src, fix, diag, Array.Empty()); } @@ -404,8 +404,8 @@ public class C """; return VerifyRequiresUnreferencedCodeCodeFix(src, fix, baselineExpected: new[] { - // /0/Test0.cs(9,21): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 21, 9, 23).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(9,24): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCS.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(9, 24, 9, 26).WithArguments("C.M1()", " message.", "") }, fixedExpected: new[] { // /0/Test0.cs(4,2): error CS7036: There is no argument given that corresponds to the required parameter 'message' of 'RequiresUnreferencedCodeAttribute.RequiresUnreferencedCodeAttribute(string)' @@ -436,8 +436,8 @@ static void M2(MethodInfo methodInfo) """; return VerifyRequiresUnreferencedCodeAnalyzer(source, - // (8,3): warning IL2060: Call to 'System.Reflection.MethodInfo.MakeGenericMethod(params Type[])' can not be statically analyzed. It's not possible to guarantee the availability of requirements of the generic method. - VerifyCS.Diagnostic(DiagnosticId.MakeGenericMethod).WithSpan(8, 3, 8, 44).WithArguments("System.Reflection.MethodInfo.MakeGenericMethod(params Type[])")); + // (8,9): warning IL2060: Call to 'System.Reflection.MethodInfo.MakeGenericMethod(params Type[])' can not be statically analyzed. It's not possible to guarantee the availability of requirements of the generic method. + VerifyCS.Diagnostic(DiagnosticId.MakeGenericMethod).WithSpan(8, 9, 8, 48).WithArguments("System.Reflection.MethodInfo.MakeGenericMethod(params Type[])")); } [Fact] diff --git a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/UnconditionalSuppressMessageCodeFixTests.cs b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/UnconditionalSuppressMessageCodeFixTests.cs index 071e10a5bb5161..7813a902709d8b 100644 --- a/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/UnconditionalSuppressMessageCodeFixTests.cs +++ b/src/tools/illink/test/ILLink.RoslynAnalyzer.Tests/UnconditionalSuppressMessageCodeFixTests.cs @@ -304,10 +304,10 @@ private int M2 { } """; var diag = new[] { - // /0/Test0.cs(12,16): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(12, 16, 12, 18).WithArguments("C.M1()", " message.", ""), - // /0/Test0.cs(13,17): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(13, 17, 13, 19).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(12,22): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(12, 22, 12, 24).WithArguments("C.M1()", " message.", ""), + // /0/Test0.cs(13,23): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(13, 23, 13, 25).WithArguments("C.M1()", " message.", "") }; return VerifyUnconditionalSuppressMessageCodeFixWithRUC(src, fix, diag, Array.Empty()); } @@ -392,8 +392,8 @@ Action M2() src, fix, baselineExpected: new[] { - // /0/Test0.cs(12,28): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(12, 28, 12, 30).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(12,27): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(12, 27, 12, 29).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } @@ -428,8 +428,8 @@ public class C src, fix, baselineExpected: new[] { - // /0/Test0.cs(10,15): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. - VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(10, 20, 10, 22).WithArguments("C.M1()", " message.", "") + // /0/Test0.cs(10,19): warning IL2026: Using member 'C.M1()' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. message. + VerifyCSUSM.Diagnostic(DiagnosticId.RequiresUnreferencedCode).WithSpan(10, 19, 10, 21).WithArguments("C.M1()", " message.", "") }, fixedExpected: Array.Empty()); } From 39c0263ba586d3fa2fa4c310e76018f6da1fb452 Mon Sep 17 00:00:00 2001 From: Sven Boemer Date: Tue, 8 Jul 2025 08:04:32 -0700 Subject: [PATCH 3/6] Update src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/UnusedAttributeOnReturnTypeIsRemoved.cs Co-authored-by: Jackson Schuster <36744439+jtschuster@users.noreply.github.com> --- .../OnlyKeepUsed/UnusedAttributeOnReturnTypeIsRemoved.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/UnusedAttributeOnReturnTypeIsRemoved.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/UnusedAttributeOnReturnTypeIsRemoved.cs index 582e4473a5e119..159f45ad6a4b73 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/UnusedAttributeOnReturnTypeIsRemoved.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/UnusedAttributeOnReturnTypeIsRemoved.cs @@ -13,7 +13,7 @@ public class UnusedAttributeOnReturnTypeIsRemoved { static void Main() { -#if IL_ASSEMBLY_AVAIABLE +#if IL_ASSEMBLY_AVAILABLE var tmp = new Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed.Dependencies.AssemblyWithUnusedAttributeOnReturnParameterDefinition().Method(1); var tmp2 = new Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed.Dependencies.AssemblyWithUnusedAttributeOnReturnParameterDefinition().MethodWithoutParameters(); var tmp3 = new Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed.Dependencies.AssemblyWithUnusedAttributeOnReturnParameterDefinition().MethodWithoutParametersNonNestedAttribute(); From d00f935367e482e63bd9308680b4f8a42e20f4eb Mon Sep 17 00:00:00 2001 From: Sven Boemer Date: Tue, 8 Jul 2025 15:07:26 +0000 Subject: [PATCH 4/6] A couple more fixes --- .../illink/external/Mono.Options/Options.cs | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/tools/illink/external/Mono.Options/Options.cs b/src/tools/illink/external/Mono.Options/Options.cs index 20b48797870563..cf1e5b1f54d047 100644 --- a/src/tools/illink/external/Mono.Options/Options.cs +++ b/src/tools/illink/external/Mono.Options/Options.cs @@ -507,7 +507,7 @@ protected static T Parse(string value, OptionContext c) { Type tt = typeof(T); #if PCL - TypeInfo ti = tt.GetTypeInfo (); + TypeInfo ti = tt.GetTypeInfo(); #else Type ti = tt; #endif @@ -517,7 +517,7 @@ protected static T Parse(string value, OptionContext c) !ti.IsGenericTypeDefinition && ti.GetGenericTypeDefinition() == typeof(Nullable<>); #if PCL - Type targetType = nullable ? tt.GenericTypeArguments [0] : tt; + Type targetType = nullable ? tt.GenericTypeArguments [0] : tt; #else Type targetType = nullable ? tt.GetGenericArguments()[0] : tt; #endif @@ -527,10 +527,10 @@ protected static T Parse(string value, OptionContext c) if (value != null) { #if PCL - if (targetType.GetTypeInfo ().IsEnum) - t = (T) Enum.Parse (targetType, value, true); - else - t = (T) Convert.ChangeType (value, targetType); + if (targetType.GetTypeInfo().IsEnum) + t = (T)Enum.Parse(targetType, value, true); + else + t = (T)Convert.ChangeType(value, targetType); #else TypeConverter conv = TypeDescriptor.GetConverter(targetType); t = (T)conv.ConvertFromString(value); @@ -794,13 +794,13 @@ public string OptionName #if !PCL && !NET #pragma warning disable 618 // SecurityPermissionAttribute is obsolete - [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)] + [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)] #pragma warning restore 618 - public override void GetObjectData (SerializationInfo info, StreamingContext context) - { - base.GetObjectData (info, context); - info.AddValue ("OptionName", option); - } + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue("OptionName", option); + } #endif } From 0857aa160e30638e42b1eb81ebe2c935f12a2b81 Mon Sep 17 00:00:00 2001 From: Sven Boemer Date: Tue, 8 Jul 2025 21:09:31 +0000 Subject: [PATCH 5/6] Fix typo --- .../DynamicDependencies/DynamicDependencyMethod.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyMethod.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyMethod.cs index 191b817e53b0e1..25275722088438 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyMethod.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DynamicDependencies/DynamicDependencyMethod.cs @@ -195,7 +195,7 @@ private static void TargetMethodViaReflection() { } [Kept] public static void Test() { - var i = new Impl ); // Avoid removal of non-implemented abstract methods + var i = new Impl(); // Avoid removal of non-implemented abstract methods typeof(ReferenceViaReflection).RequiresPublicMethods(); typeof(AbstractMethods).RequiresPublicMethods(); From 602fd98c6591dc16220e78ba387dd6b66de5a597 Mon Sep 17 00:00:00 2001 From: Sven Boemer Date: Wed, 9 Jul 2025 20:34:52 +0000 Subject: [PATCH 6/6] More formatting fixes --- .../Compiler/Dataflow/ArrayValue.cs | 6 +- .../Dataflow/CompilerGeneratedState.cs | 8 +- .../Compiler/Dataflow/HandleCallAction.cs | 32 +- .../Compiler/Dataflow/HoistedLocalKey.cs | 2 +- .../Compiler/Dataflow/InterproceduralState.cs | 4 +- .../Compiler/Dataflow/MethodBodyScanner.cs | 24 +- .../Dataflow/TrimAnalysisAssignmentPattern.cs | 4 +- .../TestCases/TestCase.cs | 2 +- .../TestCasesRunner/AssemblyChecker.cs | 678 +++++++++--------- .../TestCasesRunner/ILInputCompiler.cs | 6 +- .../TestCasesRunner/ResultChecker.cs | 33 +- .../TestCasesRunner/TestCaseCompiler.cs | 4 +- .../TestCasesRunner/TestCaseSandbox.cs | 2 +- .../TrimmingArgumentBuilder.cs | 4 +- .../DocumentationSignatureParserTests.cs | 18 +- ...odHierarchyDataflowAnnotationValidation.cs | 492 ++++++------- .../RequiresCapability/RequiresOnAttribute.cs | 120 ++-- 17 files changed, 728 insertions(+), 711 deletions(-) diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ArrayValue.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ArrayValue.cs index beb0d60d4799af..cab9d351cf6bb2 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ArrayValue.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ArrayValue.cs @@ -19,7 +19,7 @@ internal partial record ArrayValue public static MultiValue Create(MultiValue size, TypeDesc elementType) { MultiValue result = MultiValueLattice.Top; - foreach (var sizeValue in size.AsEnumerable ()) + foreach (var sizeValue in size.AsEnumerable()) { result = MultiValueLattice.Meet(result, new MultiValue(new ArrayValue(sizeValue, elementType))); } @@ -92,7 +92,7 @@ public override SingleValue DeepCopy() // Since it's possible to store a reference to array as one of its own elements // simple deep copy could lead to endless recursion. // So instead we simply disallow arrays as element values completely - and treat that case as "too complex to analyze". - foreach (SingleValue v in kvp.Value.Value.AsEnumerable ()) + foreach (SingleValue v in kvp.Value.Value.AsEnumerable()) { System.Diagnostics.Debug.Assert(v is not ArrayValue); } @@ -123,7 +123,7 @@ public override string ToString() result.Append(element.Key); result.Append(",("); bool firstValue = true; - foreach (var v in element.Value.Value.AsEnumerable ()) + foreach (var v in element.Value.Value.AsEnumerable()) { if (firstValue) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedState.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedState.cs index 24707c75f8c293..a96ccdcf5e94ee 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedState.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedState.cs @@ -346,15 +346,15 @@ referencedMethod.OwningType is MetadataType generatedType && /// Attempts to reverse the process of the compiler's alpha renaming. So if the original code was /// something like this: /// - /// void M<T> () { - /// Action a = () => { Console.WriteLine (typeof (T)); }; + /// void M<T>() { + /// Action a = () => { Console.WriteLine(typeof(T)); }; /// } /// /// The compiler will generate a nested class like this: /// /// class <>c__DisplayClass0<T> { - /// public void <M>b__0 () { - /// Console.WriteLine (typeof (T)); + /// public void <M>b__0() { + /// Console.WriteLine(typeof(T)); /// } /// } /// diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HandleCallAction.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HandleCallAction.cs index 870a969c7e2b90..9c5927a7532c03 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HandleCallAction.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HandleCallAction.cs @@ -48,7 +48,7 @@ public HandleCallAction( _requireDynamicallyAccessedMembersAction = new(reflectionMarker, diagnosticContext, reason); } - private partial bool TryHandleIntrinsic ( + private partial bool TryHandleIntrinsic( MethodProxy calledMethod, MultiValue instanceValue, IReadOnlyList argumentValues, @@ -221,7 +221,7 @@ private partial bool TryHandleIntrinsic ( // // System.Array // - // CreateInstance (Type, Int32) + // CreateInstance(Type, Int32) // case IntrinsicId.Array_CreateInstance: { @@ -234,7 +234,7 @@ private partial bool TryHandleIntrinsic ( // // System.Enum // - // static GetValues (Type) + // static GetValues(Type) // case IntrinsicId.Enum_GetValues: { @@ -243,7 +243,7 @@ private partial bool TryHandleIntrinsic ( // type instead). // // At least until we have shared enum code, this needs extra handling to get it right. - foreach (var value in argumentValues[0].AsEnumerable ()) + foreach (var value in argumentValues[0].AsEnumerable()) { if (value is SystemTypeValue systemTypeValue && !systemTypeValue.RepresentedType.Type.IsGenericDefinition @@ -263,10 +263,10 @@ private partial bool TryHandleIntrinsic ( // // System.Runtime.InteropServices.Marshal // - // static SizeOf (Type) - // static PtrToStructure (IntPtr, Type) - // static DestroyStructure (IntPtr, Type) - // static OffsetOf (Type, string) + // static SizeOf(Type) + // static PtrToStructure(IntPtr, Type) + // static DestroyStructure(IntPtr, Type) + // static OffsetOf(Type, string) // case IntrinsicId.Marshal_SizeOf: case IntrinsicId.Marshal_PtrToStructure: @@ -278,7 +278,7 @@ private partial bool TryHandleIntrinsic ( ? 0 : 1; // We need the data to do struct marshalling. - foreach (var value in argumentValues[paramIndex].AsEnumerable ()) + foreach (var value in argumentValues[paramIndex].AsEnumerable()) { if (value is SystemTypeValue systemTypeValue && !systemTypeValue.RepresentedType.Type.IsGenericDefinition @@ -304,12 +304,12 @@ private partial bool TryHandleIntrinsic ( // // System.Runtime.InteropServices.Marshal // - // static GetDelegateForFunctionPointer (IntPtr, Type) + // static GetDelegateForFunctionPointer(IntPtr, Type) // case IntrinsicId.Marshal_GetDelegateForFunctionPointer: { // We need the data to do delegate marshalling. - foreach (var value in argumentValues[1].AsEnumerable ()) + foreach (var value in argumentValues[1].AsEnumerable()) { if (value is SystemTypeValue systemTypeValue && !systemTypeValue.RepresentedType.Type.IsGenericDefinition @@ -329,11 +329,11 @@ private partial bool TryHandleIntrinsic ( // // System.Delegate // - // get_Method () + // get_Method() // // System.Reflection.RuntimeReflectionExtensions // - // GetMethodInfo (System.Delegate) + // GetMethodInfo(System.Delegate) // case IntrinsicId.RuntimeReflectionExtensions_GetMethodInfo: case IntrinsicId.Delegate_get_Method: @@ -373,12 +373,12 @@ private partial bool TryHandleIntrinsic ( // case IntrinsicId.Object_GetType: { - if (instanceValue.IsEmpty ()) { - AddReturnValue (MultiValueLattice.Top); + if (instanceValue.IsEmpty()) { + AddReturnValue(MultiValueLattice.Top); break; } - foreach (var valueNode in instanceValue.AsEnumerable ()) + foreach (var valueNode in instanceValue.AsEnumerable()) { // Note that valueNode can be statically typed in IL as some generic argument type. // For example: diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HoistedLocalKey.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HoistedLocalKey.cs index 76b3fd499086cb..908381d9a7600e 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HoistedLocalKey.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HoistedLocalKey.cs @@ -29,7 +29,7 @@ public HoistedLocalKey(FieldDesc field) public override int GetHashCode() => Field.GetHashCode(); - public static bool operator ==(HoistedLocalKey left, HoistedLocalKey right) => left.Equals (right); + public static bool operator ==(HoistedLocalKey left, HoistedLocalKey right) => left.Equals(right); public static bool operator !=(HoistedLocalKey left, HoistedLocalKey right) => !(left == right); } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/InterproceduralState.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/InterproceduralState.cs index 7627312e81550a..71e3518a42bd81 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/InterproceduralState.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/InterproceduralState.cs @@ -67,8 +67,8 @@ public void TrackMethod(MethodIL methodBody) methodBody = GetInstantiatedMethodIL(methodBody); // Work around the fact that ValueSet is readonly - Debug.Assert (!MethodBodies.IsUnknown ()); - var methodsList = new List(MethodBodies.GetKnownValues ()); + Debug.Assert(!MethodBodies.IsUnknown()); + var methodsList = new List(MethodBodies.GetKnownValues()); methodsList.Add(new MethodBodyValue(methodBody)); // For state machine methods, also scan the state machine members. diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodBodyScanner.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodBodyScanner.cs index eef3878c24461b..77de311145e890 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodBodyScanner.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodBodyScanner.cs @@ -207,7 +207,7 @@ private static void ValidateNoReferenceToReference(ValueBasicBlockPair?[] locals continue; MultiValue localValue = localVariable.Value.Value; - foreach (var val in localValue.AsEnumerable ()) + foreach (var val in localValue.AsEnumerable()) { if (val is LocalVariableReferenceValue localReference && localReference.ReferencedType.IsByRefOrPointer()) { @@ -306,8 +306,8 @@ public virtual void InterproceduralScan(MethodIL startingMethodBody) // Flow state through all methods encountered so far, as long as there // are changes discovered in the hoisted local state on entry to any method. - Debug.Assert (!oldInterproceduralState.MethodBodies.IsUnknown ()); - foreach (var methodBodyValue in oldInterproceduralState.MethodBodies.GetKnownValues ()) + Debug.Assert(!oldInterproceduralState.MethodBodies.IsUnknown()); + foreach (var methodBodyValue in oldInterproceduralState.MethodBodies.GetKnownValues()) Scan(methodBodyValue.MethodBody, ref interproceduralState); } @@ -319,14 +319,14 @@ public virtual void InterproceduralScan(MethodIL startingMethodBody) var calleeMethods = compilerGeneratedCallees.OfType(); // https://github.com/dotnet/linker/issues/2845 // Disabled asserts due to a bug - // Debug.Assert (interproceduralState.Count == 1 + calleeMethods.Count ()); + // Debug.Assert(interproceduralState.Count == 1 + calleeMethods.Count()); // foreach (var method in calleeMethods) - // Debug.Assert (interproceduralState.Any (kvp => kvp.Key.Method == method)); + // Debug.Assert(interproceduralState.Any(kvp => kvp.Key.Method == method)); } else { - Debug.Assert (!interproceduralState.MethodBodies.IsUnknown ()); - Debug.Assert(interproceduralState.MethodBodies.GetKnownValues ().Count() == 1); + Debug.Assert(!interproceduralState.MethodBodies.IsUnknown()); + Debug.Assert(interproceduralState.MethodBodies.GetKnownValues().Count() == 1); } #endif } @@ -1020,7 +1020,7 @@ private void ScanIndirectStore( /// Throws if is not a valid target for an indirect store. protected void StoreInReference(MultiValue target, MultiValue source, MethodIL method, int offset, ValueBasicBlockPair?[] locals, int curBasicBlock, ref InterproceduralState ipState, int? parameterIndex) { - foreach (var value in target.AsEnumerable ()) + foreach (var value in target.AsEnumerable()) { switch (value) { @@ -1139,7 +1139,7 @@ private void ScanStfld( return; } - foreach (var value in HandleGetField(methodBody, offset, field).AsEnumerable ()) + foreach (var value in HandleGetField(methodBody, offset, field).AsEnumerable()) { // GetFieldValue may return different node types, in which case they can't be stored to. // At least not yet. @@ -1187,7 +1187,7 @@ internal MultiValue DereferenceValue( ref InterproceduralState interproceduralState) { MultiValue dereferencedValue = MultiValueLattice.Top; - foreach (var value in maybeReferenceValue.AsEnumerable ()) + foreach (var value in maybeReferenceValue.AsEnumerable()) { switch (value) { @@ -1299,7 +1299,7 @@ private void HandleCall( foreach (var param in methodArguments) { - foreach (var v in param.AsEnumerable ()) + foreach (var v in param.AsEnumerable()) { if (v is ArrayValue arr) { @@ -1344,7 +1344,7 @@ private void ScanStelem( StackSlot indexToStoreAt = PopUnknown(currentStack, 1, methodBody, offset); StackSlot arrayToStoreIn = PopUnknown(currentStack, 1, methodBody, offset); int? indexToStoreAtInt = indexToStoreAt.Value.AsConstInt(); - foreach (var array in arrayToStoreIn.Value.AsEnumerable ()) + foreach (var array in arrayToStoreIn.Value.AsEnumerable()) { if (array is ArrayValue arrValue) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TrimAnalysisAssignmentPattern.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TrimAnalysisAssignmentPattern.cs index 2f44acb76c90b6..89cebd2e73586b 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TrimAnalysisAssignmentPattern.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TrimAnalysisAssignmentPattern.cs @@ -55,9 +55,9 @@ public void MarkAndProduceDiagnostics(ReflectionMarker reflectionMarker, Logger logger.ShouldSuppressAnalysisWarningsForRequires(Origin.MemberDefinition, DiagnosticUtilities.RequiresAssemblyFilesAttribute), logger); - foreach (var sourceValue in Source.AsEnumerable ()) + foreach (var sourceValue in Source.AsEnumerable()) { - foreach (var targetValue in Target.AsEnumerable ()) + foreach (var targetValue in Target.AsEnumerable()) { if (targetValue is not ValueWithDynamicallyAccessedMembers targetWithDynamicallyAccessedMembers) throw new NotImplementedException(); diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestCase.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestCase.cs index a306238fffe03f..09965c24c30dda 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestCase.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCases/TestCase.cs @@ -28,7 +28,7 @@ public TestCase(NPath sourceFile, NPath rootCasesDirectory, NPath originalTestCa // A little hacky, but good enough for name. No reason why namespace & type names // should not follow the directory structure - //ReconstructedFullTypeName = $"{sourceFile.Parent.RelativeTo (rootCasesDirectory.Parent).ToString (SlashMode.Forward).Replace ('/', '.')}.{sourceFile.FileNameWithoutExtension}"; + // ReconstructedFullTypeName = $"{sourceFile.Parent.RelativeTo(rootCasesDirectory.Parent).ToString(SlashMode.Forward).Replace('/', '.')}.{sourceFile.FileNameWithoutExtension}"; reconstructedFullTypeName = $"Mono.Linker.Tests.Cases.{fullyRelative.Parent.ToString(SlashMode.Forward).Replace('/', '.')}.{sourceFile.FileNameWithoutExtension}"; var firstParentRelativeToRoot = SourceFile.RelativeTo(rootCasesDirectory).Elements.First(); diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyChecker.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyChecker.cs index a8e02c0a024cac..6bf18640886d4a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyChecker.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/AssemblyChecker.cs @@ -51,18 +51,18 @@ class LinkedMethodEntity : LinkedEntity // Note: It's enough to exclude the type name, all of its members will also be excluded then private static readonly HashSet ExcludeDisplayNames = new() { - // Ignore compiler injected attributes to describe language version - "Microsoft.CodeAnalysis.EmbeddedAttribute", - "System.Runtime.CompilerServices.RefSafetyRulesAttribute", + // Ignore compiler injected attributes to describe language version + "Microsoft.CodeAnalysis.EmbeddedAttribute", + "System.Runtime.CompilerServices.RefSafetyRulesAttribute", - // Ignore NativeAOT injected members - ".StartupCodeMain(Int32,IntPtr)", - ".MainMethodWrapper()", - ".MainMethodWrapper(String[])", + // Ignore NativeAOT injected members + ".StartupCodeMain(Int32,IntPtr)", + ".MainMethodWrapper()", + ".MainMethodWrapper(String[])", - // Ignore compiler generated code which can't be reasonably matched to the source method - "", - }; + // Ignore compiler generated code which can't be reasonably matched to the source method + "", + }; public AssemblyChecker( BaseAssemblyResolver originalsResolver, @@ -94,21 +94,21 @@ public void Verify() IEnumerable VerifyImpl() { // There are no type forwarders left after compilation in Native AOT - // VerifyExportedTypes (originalAssembly, linkedAssembly); + // VerifyExportedTypes(originalAssembly, linkedAssembly); // TODO - // VerifyCustomAttributes (originalAssembly, linkedAssembly); - // VerifySecurityAttributes (originalAssembly, linkedAssembly); + // VerifyCustomAttributes(originalAssembly, linkedAssembly); + // VerifySecurityAttributes(originalAssembly, linkedAssembly); // TODO - this is mostly attribute verification // foreach (var originalModule in originalAssembly.Modules) - // VerifyModule (originalModule, linkedAssembly.Modules.FirstOrDefault (m => m.Name == originalModule.Name)); + // VerifyModule(originalModule, linkedAssembly.Modules.FirstOrDefault(m => m.Name == originalModule.Name)); // TODO - // VerifyResources (originalAssembly, linkedAssembly); + // VerifyResources(originalAssembly, linkedAssembly); // There are no assembly reference in Native AOT - // VerifyReferences (originalAssembly, linkedAssembly); + // VerifyReferences(originalAssembly, linkedAssembly); PopulateLinkedMembers(); @@ -395,15 +395,16 @@ IEnumerable VerifyTypeDefinition(TypeDefinition original, LinkedEntity? // For now always fail on this attribute since we don't know how to validate it throw new NotSupportedException("CreatedMemberAttribute is not yet supported by the test infra"); #if false - foreach (var attr in original.CustomAttributes.Where (l => l.AttributeType.Name == nameof (CreatedMemberAttribute))) { - var newName = original.FullName + "::" + attr.ConstructorArguments[0].Value.ToString (); + foreach (var attr in original.CustomAttributes.Where(l => l.AttributeType.Name == nameof(CreatedMemberAttribute))) + { + var newName = original.FullName + "::" + attr.ConstructorArguments[0].Value.ToString(); - var linkedMemberName = linkedMembers.Keys.FirstOrDefault (l => l.Contains (newName)); - if (linkedMemberName == null) - yield return $"Newly created member '{newName}' was not found"; + var linkedMemberName = linkedMembers.Keys.FirstOrDefault(l => l.Contains(newName)); + if (linkedMemberName == null) + yield return $"Newly created member '{newName}' was not found"; - linkedMembers.Remove (linkedMemberName); - } + linkedMembers.Remove(linkedMemberName); + } #endif } } @@ -423,29 +424,30 @@ protected virtual IEnumerable VerifyTypeDefinitionKept(TypeDefinition or } #if false - if (!SkipKeptItemsValidation (original)) { - foreach(var err in VerifyKeptByAttributes (original, linked)) - yield return err; - if (!original.IsInterface) - { - foreach(var err in VerifyBaseType (original, linked)) - yield return err; - } - - foreach(var err in VerifyInterfaces (original, linked)) - yield return err; - foreach(var err in VerifyPseudoAttributes (original, linked)) - yield return err; - foreach(var err in VerifyGenericParameters (original, linked, skipKeptItemsValidation: false)) - yield return err; - foreach(var err in VerifyCustomAttributes (original, linked)) - yield return err; - foreach(var err in VerifySecurityAttributes (original, linked)) - yield return err; - - foreach(var err in VerifyFixedBufferFields (original, linked)) - yield return err; - } + if (!SkipKeptItemsValidation(original)) + { + foreach (var err in VerifyKeptByAttributes(original, linked)) + yield return err; + if (!original.IsInterface) + { + foreach (var err in VerifyBaseType(original, linked)) + yield return err; + } + + foreach (var err in VerifyInterfaces(original, linked)) + yield return err; + foreach (var err in VerifyPseudoAttributes(original, linked)) + yield return err; + foreach (var err in VerifyGenericParameters(original, linked, skipKeptItemsValidation: false)) + yield return err; + foreach (var err in VerifyCustomAttributes(original, linked)) + yield return err; + foreach (var err in VerifySecurityAttributes(original, linked)) + yield return err; + + foreach (var err in VerifyFixedBufferFields(original, linked)) + yield return err; + } #endif foreach (var td in original.NestedTypes) @@ -486,15 +488,16 @@ protected virtual IEnumerable VerifyTypeDefinitionKept(TypeDefinition or } #if false - // Need to check delegate cache fields before the normal field check - VerifyDelegateBackingFields (original, linked); - - foreach (var f in original.Fields) { - if (verifiedGeneratedFields.Contains (f.FullName)) - continue; - VerifyField (f, linked.Fields.FirstOrDefault (l => f.Name == l.Name)); - linkedMembers.Remove (f.FullName); - } + // Need to check delegate cache fields before the normal field check + VerifyDelegateBackingFields(original, linked); + + foreach (var f in original.Fields) + { + if (verifiedGeneratedFields.Contains(f.FullName)) + continue; + VerifyField(f, linked.Fields.FirstOrDefault(l => f.Name == l.Name)); + linkedMembers.Remove(f.FullName); + } #endif foreach (var m in original.Methods) @@ -612,17 +615,17 @@ private static IEnumerable VerifyFieldKept(FieldDefinition src, FieldDes if (src.HasConstant) throw new NotImplementedException("Constant value for a field is not yet supported by the test infra."); #if false - if (!Equals (src.Constant, linked.Constant)) { - yield return $"Field '{src}' value doesn's match. Expected {src.Constant}, actual {linked.Constant}"; - } + if (!Equals(src.Constant, linked.Constant)) { + yield return $"Field '{src}' value doesn's match. Expected {src.Constant}, actual {linked.Constant}"; + } #endif #if false - foreach(var err in VerifyPseudoAttributes (src, linked)) - yield return err; - if (!skipKeptItemsValidation) - foreach(var err in VerifyCustomAttributes (src, linked)) - yield return err; + foreach (var err in VerifyPseudoAttributes (src, linked)) + yield return err; + if (!skipKeptItemsValidation) + foreach (var err in VerifyCustomAttributes (src, linked)) + yield return err; #endif } @@ -651,19 +654,20 @@ private IEnumerable VerifyProperty(PropertyDefinition src, LinkedEntity? if (src.HasConstant) throw new NotSupportedException("Constant value for a property is not yet supported by the test infra."); #if false - if (src.Constant != linked.Constant) { - yield return $"Property '{src}' value doesn's match. Expected {src.Constant}, actual {linked.Constant}"; - } + if (src.Constant != linked.Constant) + { + yield return $"Property '{src}' value doesn's match. Expected {src.Constant}, actual {linked.Constant}"; + } #endif #if false - foreach(var err in VerifyPseudoAttributes (src, linked)) - yield return err; - if (!skipKeptItemsValidation) - { - foreach(var err in VerifyCustomAttributes (src, linked)) - yield return err; - } + foreach (var err in VerifyPseudoAttributes(src, linked)) + yield return err; + if (!skipKeptItemsValidation) + { + foreach (var err in VerifyCustomAttributes(src, linked)) + yield return err; + } #endif } @@ -711,13 +715,13 @@ private IEnumerable VerifyEvent(EventDefinition src, LinkedEntity? linke } #if false - foreach(var err in VerifyPseudoAttributes (src, linked)) - yield return err; - if (!skipKeptItemsValidation) - { - foreach(var err in VerifyCustomAttributes (src, linned)) - yield return err; - } + foreach (var err in VerifyPseudoAttributes(src, linked)) + yield return err; + if (!skipKeptItemsValidation) + { + foreach (var err in VerifyCustomAttributes(src, linned)) + yield return err; + } #endif } @@ -788,30 +792,31 @@ IEnumerable VerifyMethodKept(MethodDefinition src, LinkedMethodEntity? l } #if false - foreach(var err in VerifyPseudoAttributes (src, linked)) - yield return err; - foreach(var err in VerifyGenericParameters (src, linked, skipKeptItemsValidation)) - yield return err; - if (!skipKeptItemsValidation) { - foreach(var err in VerifyCustomAttributes (src, linked)) - yield return err; - foreach(var err in VerifyCustomAttributes (src.MethodReturnType, linked.MethodReturnType)) - yield return err; - } + foreach (var err in VerifyPseudoAttributes(src, linked)) + yield return err; + foreach (var err in VerifyGenericParameters(src, linked, skipKeptItemsValidation)) + yield return err; + if (!skipKeptItemsValidation) + { + foreach (var err in VerifyCustomAttributes(src, linked)) + yield return err; + foreach (var err in VerifyCustomAttributes(src.MethodReturnType, linked.MethodReturnType)) + yield return err; + } #endif foreach (var err in VerifyParameters(src, linked, skipKeptItemsValidation)) yield return err; #if false - foreach(var err in VerifySecurityAttributes (src, linked)) - yield return err; - foreach(var err in VerifyArrayInitializers (src, linked)) - yield return err; - - // Method bodies are not very different in Native AOT - foreach(var err in VerifyMethodBody (src, linked)) - yield return err; - foreach(var err in VerifyKeptByAttributes (src, linked)) - yield return err; + foreach (var err in VerifySecurityAttributes(src, linked)) + yield return err; + foreach (var err in VerifyArrayInitializers(src, linked)) + yield return err; + + // Method bodies are not very different in Native AOT + foreach (var err in VerifyMethodBody (src, linked)) + yield return err; + foreach (var err in VerifyKeptByAttributes (src, linked)) + yield return err; #endif } @@ -1014,14 +1019,14 @@ private IEnumerable VerifyReferences(AssemblyDefinition original, Assemb .ToArray(); /* - - The test case will always need to have at least 1 reference. - - Forcing all tests to define their expected references seems tedious + - The test case will always need to have at least 1 reference. + - Forcing all tests to define their expected references seems tedious - Given the above, let's assume that when no [KeptReference] attributes are present, - the test case does not want to make any assertions regarding references. + Given the above, let's assume that when no [KeptReference] attributes are present, + the test case does not want to make any assertions regarding references. - Once 1 kept reference attribute is used, the test will need to define all of of it's expected references - */ + Once 1 kept reference attribute is used, the test will need to define all of of it's expected references + */ if (expected.Length == 0) yield break; @@ -1152,74 +1157,81 @@ protected virtual IEnumerable VerifySecurityAttributes(ICustomAttributeP } #if false - protected virtual IEnumerable VerifyArrayInitializers (MethodDefinition src, MethodDefinition linked) - { - var expectedIndices = GetCustomAttributeCtorValues (src, nameof (KeptInitializerData)) - .Cast () - .ToArray (); - - var expectKeptAll = src.CustomAttributes.Any (attr => attr.AttributeType.Name == nameof (KeptInitializerData) && !attr.HasConstructorArguments); - - if (expectedIndices.Length == 0 && !expectKeptAll) - return; - - if (!src.HasBody) - yield return $"`{nameof (KeptInitializerData)}` cannot be used on methods that don't have bodies"; - - var srcImplementationDetails = src.Module.Types.FirstOrDefault (t => string.IsNullOrEmpty (t.Namespace) && t.Name.StartsWith ("")); - - if (srcImplementationDetails == null) { - yield return "Could not locate in the original assembly. Does your test use initializers?"; - return; - } - - var linkedImplementationDetails = linked.Module.Types.FirstOrDefault (t => string.IsNullOrEmpty (t.Namespace) && t.Name.StartsWith ("")); - - if (linkedImplementationDetails == null) { - yield return "Could not locate in the linked assembly"; - return; - } - - var possibleInitializerFields = src.Body.Instructions - .Where (ins => IsLdtokenOnPrivateImplementationDetails (srcImplementationDetails, ins)) - .Select (ins => ((FieldReference) ins.Operand).Resolve ()) - .ToArray (); - - if (possibleInitializerFields.Length == 0) - yield return $"`{src}` does not make use of any initializers"; - - if (expectKeptAll) { - foreach (var srcField in possibleInitializerFields) { - var linkedField = linkedImplementationDetails.Fields.FirstOrDefault (f => f.InitialValue.SequenceEqual (srcField.InitialValue)); - foreach(var err in VerifyInitializerField (srcField, linkedField)) - yield return err; - } - } else { - foreach (var index in expectedIndices) { - if (index < 0 || index > possibleInitializerFields.Length) - yield return $"Invalid expected index `{index}` in {src}. Value must be between 0 and {expectedIndices.Length}"; - - var srcField = possibleInitializerFields[index]; - var linkedField = linkedImplementationDetails.Fields.FirstOrDefault (f => f.InitialValue.SequenceEqual (srcField.InitialValue)); - - foreach(var err in VerifyInitializerField (srcField, linkedField)) - yield return err; - } - } - } - - private IEnumerable VerifyInitializerField (FieldDefinition src, FieldDefinition? linked) - { - foreach(var err in VerifyFieldKept (src, linked, skipKeptItemsValidation: true)) - yield return err; - verifiedGeneratedFields.Add (linked!.FullName); - linkedMembers.Remove (new (linked)); - // foreach(var err in VerifyTypeDefinitionKept (src.FieldType.Resolve (), linked.FieldType.Resolve ())) - // yield return err; - linkedMembers.Remove (new (linked.FieldType.Resolve ())); - linkedMembers.Remove (new (linked.DeclaringType.Resolve ())); - verifiedGeneratedTypes.Add (linked.DeclaringType.FullName); - } + protected virtual IEnumerable VerifyArrayInitializers(MethodDefinition src, MethodDefinition linked) + { + var expectedIndices = GetCustomAttributeCtorValues(src, nameof(KeptInitializerData)) + .Cast() + .ToArray(); + + var expectKeptAll = src.CustomAttributes.Any(attr => attr.AttributeType.Name == nameof(KeptInitializerData) && !attr.HasConstructorArguments); + + if (expectedIndices.Length == 0 && !expectKeptAll) + return; + + if (!src.HasBody) + yield return $"`{nameof(KeptInitializerData)}` cannot be used on methods that don't have bodies"; + + var srcImplementationDetails = src.Module.Types.FirstOrDefault(t => string.IsNullOrEmpty(t.Namespace) && t.Name.StartsWith("")); + + if (srcImplementationDetails == null) + { + yield return "Could not locate in the original assembly. Does your test use initializers?"; + return; + } + + var linkedImplementationDetails = linked.Module.Types.FirstOrDefault(t => string.IsNullOrEmpty(t.Namespace) && t.Name.StartsWith("")); + + if (linkedImplementationDetails == null) + { + yield return "Could not locate in the linked assembly"; + return; + } + + var possibleInitializerFields = src.Body.Instructions + .Where(ins => IsLdtokenOnPrivateImplementationDetails(srcImplementationDetails, ins)) + .Select(ins => ((FieldReference)ins.Operand).Resolve()) + .ToArray(); + + if (possibleInitializerFields.Length == 0) + yield return $"`{src}` does not make use of any initializers"; + + if (expectKeptAll) + { + foreach (var srcField in possibleInitializerFields) + { + var linkedField = linkedImplementationDetails.Fields.FirstOrDefault(f => f.InitialValue.SequenceEqual(srcField.InitialValue)); + foreach (var err in VerifyInitializerField(srcField, linkedField)) + yield return err; + } + } + else + { + foreach (var index in expectedIndices) + { + if (index < 0 || index > possibleInitializerFields.Length) + yield return $"Invalid expected index `{index}` in {src}. Value must be between 0 and {expectedIndices.Length}"; + + var srcField = possibleInitializerFields[index]; + var linkedField = linkedImplementationDetails.Fields.FirstOrDefault(f => f.InitialValue.SequenceEqual(srcField.InitialValue)); + + foreach (var err in VerifyInitializerField(srcField, linkedField)) + yield return err; + } + } + } + + private IEnumerable VerifyInitializerField(FieldDefinition src, FieldDefinition? linked) + { + foreach (var err in VerifyFieldKept(src, linked, skipKeptItemsValidation: true)) + yield return err; + verifiedGeneratedFields.Add(linked!.FullName); + linkedMembers.Remove(new(linked)); + // foreach (var err in VerifyTypeDefinitionKept(src.FieldType.Resolve(), linked.FieldType.Resolve())) + // yield return err; + linkedMembers.Remove(new(linked.FieldType.Resolve())); + linkedMembers.Remove(new(linked.DeclaringType.Reolve())); + verifiedGeneratedTypes.Add(linked.DeclaringType.FullName); + } #endif private static bool IsLdtokenOnPrivateImplementationDetails(TypeDefinition privateImplementationDetails, Instruction instruction) @@ -1294,65 +1306,69 @@ protected virtual IEnumerable FilterLinkedSecurityAttributes(ISecurityDe } #if false - private IEnumerable VerifyFixedBufferFields (TypeDefinition src, TypeDefinition linked) - { - var fields = src.Fields.Where (f => f.CustomAttributes.Any (attr => attr.AttributeType.Name == nameof (KeptFixedBufferAttribute))); - - foreach (var field in fields) { - // The name of the generated fixed buffer type is a little tricky. - // Some versions of csc name it `e__FixedBuffer0` - // while mcs and other versions of csc name it `__FixedBuffer0` - var originalCompilerGeneratedBufferType = src.NestedTypes.FirstOrDefault (t => t.FullName.Contains ($"<{field.Name}>") && t.FullName.Contains ("__FixedBuffer")); - if (originalCompilerGeneratedBufferType == null) { - yield return $"Could not locate original compiler generated fixed buffer type for field {field}"; - yield break; - } - - var linkedCompilerGeneratedBufferType = linked.NestedTypes.FirstOrDefault (t => t.Name == originalCompilerGeneratedBufferType.Name); - if (linkedCompilerGeneratedBufferType == null) { - yield return $"Missing expected type {originalCompilerGeneratedBufferType}"; - yield break; - } - - // Have to verify the field before the type - var originalElementField = originalCompilerGeneratedBufferType.Fields.FirstOrDefault (); - if (originalElementField == null) { - yield return $"Could not locate original compiler generated FixedElementField on {originalCompilerGeneratedBufferType}"; - yield break; - } - - var linkedField = linkedCompilerGeneratedBufferType?.Fields.FirstOrDefault (); - foreach(var err in VerifyFieldKept (originalElementField, linkedField, skipKeptItemsValidation: true)) - yield return err; - verifiedGeneratedFields.Add (originalElementField.FullName); - linkedMembers.Remove (new (linkedField!)); - - // foreach(var err in VerifyTypeDefinitionKept (originalCompilerGeneratedBufferType, linkedCompilerGeneratedBufferType)) - // yield return err; - verifiedGeneratedTypes.Add (originalCompilerGeneratedBufferType.FullName); - } - } - - private IEnumerable VerifyDelegateBackingFields (TypeDefinition src, TypeDefinition linked) - { - var expectedFieldNames = GetCustomAttributeCtorValues (src, nameof (KeptDelegateCacheFieldAttribute)) - .Select (unique => $"<>f__mg$cache{unique}") - .ToList (); - - if (expectedFieldNames.Count == 0) - yield break; - - foreach (var srcField in src.Fields) { - if (!expectedFieldNames.Contains (srcField.Name)) - continue; - - var linkedField = linked?.Fields.FirstOrDefault (l => l.Name == srcField.Name); - foreach(var err in VerifyFieldKept (srcField, linkedField, skipKeptItemsValidation: true)) - yield return err; - verifiedGeneratedFields.Add (srcField.FullName); - linkedMembers.Remove (new (srcField)); - } - } + private IEnumerable VerifyFixedBufferFields(TypeDefinition src, TypeDefinition linked) + { + var fields = src.Fields.Where(f => f.CustomAttributes.Any(attr => attr.AttributeType.Name == nameof(KeptFixedBufferAttribute))); + + foreach (var field in fields) + { + // The name of the generated fixed buffer type is a little tricky. + // Some versions of csc name it `e__FixedBuffer0` + // while mcs and other versions of csc name it `__FixedBuffer0` + var originalCompilerGeneratedBufferType = src.NestedTypes.FirstOrDefault(t => t.FullName.Contains($"<{field.Name}>") && t.FullName.Contains("__FixedBuffer")); + if (originalCompilerGeneratedBufferType == null) + { + yield return $"Could not locate original compiler generated fixed buffer type for field {field}"; + yield break; + } + + var linkedCompilerGeneratedBufferType = linked.NestedTypes.FirstOrDefault(t => t.Name == originalCompilerGeneratedBufferType.Name); + if (linkedCompilerGeneratedBufferType == null) + { + yield return $"Missing expected type {originalCompilerGeneratedBufferType}"; + yield break; + } + + // Have to verify the field before the type + var originalElementField = originalCompilerGeneratedBufferType.Fields.FirstOrDefault(); + if (originalElementField == null) + { + yield return $"Could not locate original compiler generated FixedElementField on {originalCompilerGeneratedBufferType}"; + yield break; + } + + var linkedField = linkedCompilerGeneratedBufferType?.Fields.FirstOrDefault(); + foreach (var err in VerifyFieldKept(originalElementField, linkedField, skipKeptItemsValidation: true)) + yield return err; + verifiedGeneratedFields.Add(originalElementField.FullName); + linkedMembers.Remove(new(linkedField!)); + + // foreach (var err in VerifyTypeDefinitionKept(originalCompilerGeneratedBufferType, linkedCompilerGeneratedBufferType)) + // yield return err; + verifiedGeneratedTypes.Add(originalCompilerGeneratedBufferType.FullName); + } + } + + private IEnumerable VerifyDelegateBackingFields(TypeDefinition src, TypeDefinition linked) + { + var expectedFieldNames = GetCustomAttributeCtorValues(src, nameof(KeptDelegateCacheFieldAttribute)) + .Select(unique => $"<>f__mg$cache{unique}") + .ToList(); + + if (expectedFieldNames.Count == 0) + yield break; + + foreach (var srcField in src.Fields) { + if (!expectedFieldNames.Contains(srcField.Name)) + continue; + + var linkedField = linked?.Fields.FirstOrDefault(l => l.Name == srcField.Name); + foreach (var err in VerifyFieldKept(srcField, linkedField, skipKeptItemsValidation: true)) + yield return err; + verifiedGeneratedFields.Add(srcField.FullName); + linkedMembers.Remove(new(srcField)); + } + } #endif private IEnumerable VerifyGenericParameters(IGenericParameterProvider src, IGenericParameterProvider linked, bool skipKeptItemsValidation) @@ -1406,8 +1422,8 @@ private IEnumerable VerifyParameters(IMethodSignature src, LinkedMethodE #if false if (!skipKeptItemsValidation) { - foreach(var err in VerifyCustomAttributes (srcp, lnkp)) - yield return err; + foreach (var err in VerifyCustomAttributes(srcp, lnkp)) + yield return err; } #endif @@ -1545,10 +1561,10 @@ internal IEnumerable VerifyLinkingOfOtherAssemblies(AssemblyDefinition o errs.AddRange(VerifyKeptAllTypesAndMembersInAssembly(assemblyName, linkedMembersInAssembly)); continue; case nameof(KeptAttributeInAssemblyAttribute): - // errs.AddRange(VerifyKeptAttributeInAssembly (checkAttrInAssembly, linkedAssembly)) + // errs.AddRange(VerifyKeptAttributeInAssembly(checkAttrInAssembly, linkedAssembly)) continue; case nameof(RemovedAttributeInAssembly): - // errs.AddRange(VerifyRemovedAttributeInAssembly (checkAttrInAssembly, linkedAssembly)) + // errs.AddRange(VerifyRemovedAttributeInAssembly(checkAttrInAssembly, linkedAssembly)) continue; default: break; @@ -1562,18 +1578,18 @@ internal IEnumerable VerifyLinkingOfOtherAssemblies(AssemblyDefinition o MetadataType? linkedType = linkedTypeEntity?.Entity as MetadataType; #if false - if (linkedType == null && linkedAssembly.MainModule.HasExportedTypes) { - ExportedType? exportedType = linkedAssembly.MainModule.ExportedTypes - .FirstOrDefault (exported => exported.FullName == expectedTypeName); - - // Note that copied assemblies could have dangling references. - if (exportedType != null && original.EntryPoint.DeclaringType.CustomAttributes.FirstOrDefault ( - ca => ca.AttributeType.Name == nameof (RemovedAssemblyAttribute) - && ca.ConstructorArguments[0].Value.ToString () == exportedType.Scope.Name + ".dll") != null) - continue; - - linkedType = exportedType?.Resolve (); - } + if (linkedType == null && linkedAssembly.MainModule.HasExportedTypes) { + ExportedType? exportedType = linkedAssembly.MainModule.ExportedTypes + .FirstOrDefault(exported => exported.FullName == expectedTypeName); + + // Note that copied assemblies could have dangling references. + if (exportedType != null && original.EntryPoint.DeclaringType.CustomAttributes.FirstOrDefault( + ca => ca.AttributeType.Name == nameof(RemovedAssemblyAttribute) + && ca.ConstructorArguments[0].Value.ToString() == exportedType.Scope.Name + ".dll") != null) + continue; + + linkedType = exportedType?.Resolve(); + } #endif switch (attributeTypeName) @@ -1588,76 +1604,76 @@ internal IEnumerable VerifyLinkingOfOtherAssemblies(AssemblyDefinition o errs.Add($"Type `{expectedTypeName}' should have been kept in assembly {assemblyName}"); break; #if false - case nameof (RemovedInterfaceOnTypeInAssemblyAttribute): - if (linkedType == null) - { - errs.Add($"Type `{expectedTypeName}' should have been kept in assembly {assemblyName}"); - break; - } - errs.AddRange(VerifyRemovedInterfaceOnTypeInAssembly (checkAttrInAssembly, linkedType)); - break; - case nameof (KeptInterfaceOnTypeInAssemblyAttribute): - if (linkedType == null) - { - errs.Add($"Type `{expectedTypeName}' should have been kept in assembly {assemblyName}"); - break; - } - errs.AddRange(VerifyKeptInterfaceOnTypeInAssembly (checkAttrInAssembly, linkedType)); - break; - case nameof (RemovedMemberInAssemblyAttribute): - if (linkedType == null) - continue; - - errs.AddRange(VerifyRemovedMemberInAssembly (checkAttrInAssembly, linkedType)); - break; - case nameof (KeptBaseOnTypeInAssemblyAttribute): - if (linkedType == null) - { - errs.Add($"Type `{expectedTypeName}' should have been kept in assembly {assemblyName}"); - break; - } - errs.AddRange(VerifyKeptBaseOnTypeInAssembly (checkAttrInAssembly, linkedType)); - break; - case nameof (KeptMemberInAssemblyAttribute): - if (linkedType == null) - { - errs.Add($"Type `{expectedTypeName}' should have been kept in assembly {assemblyName}"); - break; - } - - errs.AddRange(VerifyKeptMemberInAssembly (checkAttrInAssembly, linkedType)); - break; - case nameof (RemovedForwarderAttribute): - if (linkedAssembly.MainModule.ExportedTypes.Any (l => l.Name == expectedTypeName)) - errs.Add($"Forwarder `{expectedTypeName}' should have been removed from assembly {assemblyName}"); - - break; - - case nameof (RemovedAssemblyReferenceAttribute): - if (linkedAssembly.MainModule.AssemblyReferences.Any (l => l.Name == expectedTypeName) != false) - errs.Add($"AssemblyRef '{expectedTypeName}' should have been removed from assembly {assemblyName}"); - break; - - case nameof (KeptResourceInAssemblyAttribute): - errs.AddRange(VerifyKeptResourceInAssembly (checkAttrInAssembly)); - break; - case nameof (RemovedResourceInAssemblyAttribute): - errs.AddRange(VerifyRemovedResourceInAssembly (checkAttrInAssembly)); - break; - case nameof (KeptReferencesInAssemblyAttribute): - errs.AddRange(VerifyKeptReferencesInAssembly (checkAttrInAssembly)) - break; - case nameof (ExpectedInstructionSequenceOnMemberInAssemblyAttribute): - if (linkedType == null) - { - errs.Add($"Type `{expectedTypeName}` should have been kept in assembly {assemblyName}"); - break; - } - errs.AddRange(VerifyExpectedInstructionSequenceOnMemberInAssembly (checkAttrInAssembly, linkedType)); - break; - default: - UnhandledOtherAssemblyAssertion (expectedTypeName, checkAttrInAssembly, linkedType); - break; + case nameof(RemovedInterfaceOnTypeInAssemblyAttribute): + if (linkedType == null) + { + errs.Add($"Type `{expectedTypeName}' should have been kept in assembly {assemblyName}"); + break; + } + errs.AddRange(VerifyRemovedInterfaceOnTypeInAssembly(checkAttrInAssembly, linkedType)); + break; + case nameof(KeptInterfaceOnTypeInAssemblyAttribute): + if (linkedType == null) + { + errs.Add($"Type `{expectedTypeName}' should have been kept in assembly {assemblyName}"); + break; + } + errs.AddRange(VerifyKeptInterfaceOnTypeInAssembly(checkAttrInAssembly, linkedType)); + break; + case nameof(RemovedMemberInAssemblyAttribute): + if (linkedType == null) + continue; + + errs.AddRange(VerifyRemovedMemberInAssembly(checkAttrInAssembly, linkedType)); + break; + case nameof(KeptBaseOnTypeInAssemblyAttribute): + if (linkedType == null) + { + errs.Add($"Type `{expectedTypeName}' should have been kept in assembly {assemblyName}"); + break; + } + errs.AddRange(VerifyKeptBaseOnTypeInAssembly(checkAttrInAssembly, linkedType)); + break; + case nameof(KeptMemberInAssemblyAttribute): + if (linkedType == null) + { + errs.Add($"Type `{expectedTypeName}' should have been kept in assembly {assemblyName}"); + break; + } + + errs.AddRange(VerifyKeptMemberInAssembly(checkAttrInAssembly, linkedType)); + break; + case nameof(RemovedForwarderAttribute): + if (linkedAssembly.MainModule.ExportedTypes.Any(l => l.Name == expectedTypeName)) + errs.Add($"Forwarder `{expectedTypeName}' should have been removed from assembly {assemblyName}"); + + break; + + case nameof(RemovedAssemblyReferenceAttribute): + if (linkedAssembly.MainModule.AssemblyReferences.Any(l => l.Name == expectedTypeName) != false) + errs.Add($"AssemblyRef '{expectedTypeName}' should have been removed from assembly {assemblyName}"); + break; + + case nameof(KeptResourceInAssemblyAttribute): + errs.AddRange(VerifyKeptResourceInAssembly(checkAttrInAssembly)); + break; + case nameof(RemovedResourceInAssemblyAttribute): + errs.AddRange(VerifyRemovedResourceInAssembly(checkAttrInAssembly)); + break; + case nameof(KeptReferencesInAssemblyAttribute): + errs.AddRange(VerifyKeptReferencesInAssembly(checkAttrInAssembly)) + break; + case nameof(ExpectedInstructionSequenceOnMemberInAssemblyAttribute): + if (linkedType == null) + { + errs.Add($"Type `{expectedTypeName}` should have been kept in assembly {assemblyName}"); + break; + } + errs.AddRange(VerifyExpectedInstructionSequenceOnMemberInAssembly checkAttrInAssembly, linkedType)); + break; + default: + UnhandledOtherAssemblyAssertion(expectedTypeName, checkAttrInAssembly, linkedType); + break; #else default: break; @@ -1994,13 +2010,13 @@ protected virtual bool TryVerifyKeptMemberInAssemblyAsMethod(string memberName, private IEnumerable VerifyKeptReferencesInAssembly(CustomAttribute inAssemblyAttribute) { #if false - var assembly = ResolveLinkedAssembly (inAssemblyAttribute.ConstructorArguments[0].Value.ToString ()!); - var expectedReferenceNames = ((CustomAttributeArgument[]) inAssemblyAttribute.ConstructorArguments[1].Value).Select (attr => (string) attr.Value).ToList (); - for (int i = 0; i < expectedReferenceNames.Count; i++) - if (expectedReferenceNames[i].EndsWith (".dll")) - expectedReferenceNames[i] = expectedReferenceNames[i].Substring (0, expectedReferenceNames[i].LastIndexOf (".")); + var assembly = ResolveLinkedAssembly(inAssemblyAttribute.ConstructorArguments[0].Value.ToString()!); + var expectedReferenceNames = ((CustomAttributeArgument[]) inAssemblyAttribute.ConstructorArguments[1].Value).Select(attr => (string) attr.Value).ToList(); + for (int i = 0; i < expectedReferenceNames.Count; i++) + if (expectedReferenceNames[i].EndsWith(".dll")) + expectedReferenceNames[i] = expectedReferenceNames[i].Substring(0, expectedReferenceNames[i].LastIndexOf(".")); - Assert.Equal (assembly.MainModule.AssemblyReferences.Select (asm => asm.Name), expectedReferenceNames); + Assert.Equal(assembly.MainModule.AssemblyReferences.Select(asm => asm.Name), expectedReferenceNames); #endif yield break; } @@ -2008,10 +2024,10 @@ private IEnumerable VerifyKeptReferencesInAssembly(CustomAttribute inAss private IEnumerable VerifyKeptResourceInAssembly(CustomAttribute inAssemblyAttribute) { #if false - var assembly = ResolveLinkedAssembly (inAssemblyAttribute.ConstructorArguments[0].Value.ToString ()!); - var resourceName = inAssemblyAttribute.ConstructorArguments[1].Value.ToString (); + var assembly = ResolveLinkedAssembly(inAssemblyAttribute.ConstructorArguments[0].Value.ToString()!); + var resourceName = inAssemblyAttribute.ConstructorArguments[1].Value.ToString(); - Assert.Contains (resourceName, assembly.MainModule.Resources.Select (r => r.Name)); + Assert.Contains(resourceName, assembly.MainModule.Resources.Select(r => r.Name)); #endif yield break; } @@ -2019,10 +2035,10 @@ private IEnumerable VerifyKeptResourceInAssembly(CustomAttribute inAssem private IEnumerable VerifyRemovedResourceInAssembly(CustomAttribute inAssemblyAttribute) { #if false - var assembly = ResolveLinkedAssembly (inAssemblyAttribute.ConstructorArguments[0].Value.ToString ()!); - var resourceName = inAssemblyAttribute.ConstructorArguments[1].Value.ToString (); + var assembly = ResolveLinkedAssembly(inAssemblyAttribute.ConstructorArguments[0].Value.ToString()!); + var resourceName = inAssemblyAttribute.ConstructorArguments[1].Value.ToString(); - Assert.DoesNotContain (resourceName, assembly.MainModule.Resources.Select (r => r.Name)); + Assert.DoesNotContain(resourceName, assembly.MainModule.Resources.Select(r => r.Name)); #endif yield break; } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILInputCompiler.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILInputCompiler.cs index 86b93e02b5ad34..c9d00414694f0c 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILInputCompiler.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ILInputCompiler.cs @@ -50,8 +50,8 @@ private static string BuildArguments(CompilerOptions options) args.Append(options.OutputPath.ExtensionWithDot == ".dll" ? "-dll" : "-exe"); args.Append($" -out:{options.OutputPath.InQuotes()}"); #else - args.Append (options.OutputPath.ExtensionWithDot == ".dll" ? "/dll" : "/exe"); - args.Append ($" /out:{options.OutputPath.InQuotes ()}"); + args.Append(options.OutputPath.ExtensionWithDot == ".dll" ? "/dll" : "/exe"); + args.Append($" /out:{options.OutputPath.InQuotes()}"); #endif args.Append($" {options.SourceFiles.Aggregate(string.Empty, (buff, file) => $"{buff} {file.InQuotes()}")}"); return args.ToString(); @@ -70,7 +70,7 @@ protected virtual NPath LocateIlasm() throw new InvalidOperationException("ilasm not found at " + ilasmPath); #else - return Environment.OSVersion.Platform == PlatformID.Win32NT ? LocateIlasmOnWindows () : "ilasm".ToNPath (); + return Environment.OSVersion.Platform == PlatformID.Win32NT ? LocateIlasmOnWindows() : "ilasm".ToNPath(); #endif } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ResultChecker.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ResultChecker.cs index 06411420c5fddd..186ea1d3c69b96 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ResultChecker.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/ResultChecker.cs @@ -58,8 +58,8 @@ public virtual void Check(TrimmedTestCaseResult testResult) // TODO Validate presence of the main assembly - if it makes sense (reflection only somehow) // IL verification is impossible for NativeAOT since there's no IL output - // if (ShouldValidateIL (original)) - // VerifyIL (); + // if (ShouldValidateIL(original)) + // VerifyIL(); InitialChecking(testResult, original); @@ -121,33 +121,34 @@ private static void PerformOutputAssemblyChecks(AssemblyDefinition original, Tri name = Path.GetFileNameWithoutExtension(name); #if false - if (assemblyAttr.AttributeType.Name == nameof (RemovedAssemblyAttribute)) - Assert.IsFalse (expectedPath.FileExists (), $"Expected the assembly {name} to not exist in {outputDirectory}, but it did"); - else if (assemblyAttr.AttributeType.Name == nameof (KeptAssemblyAttribute)) - Assert.IsTrue (expectedPath.FileExists (), $"Expected the assembly {name} to exist in {outputDirectory}, but it did not"); - else if (assemblyAttr.AttributeType.Name == nameof (SetupLinkerActionAttribute)) { + if (assemblyAttr.AttributeType.Name == nameof(RemovedAssemblyAttribute)) + Assert.IsFalse(expectedPath.FileExists(), $"Expected the assembly {name} to not exist in {outputDirectory}, but it did"); + else if (assemblyAttr.AttributeType.Name == nameof(KeptAssemblyAttribute)) + Assert.IsTrue(expectedPath.FileExists(), $"Expected the assembly {name} to exist in {outputDirectory}, but it did not"); + else if (assemblyAttr.AttributeType.Name == nameof(SetupLinkerActionAttribute)) { string assemblyName = (string) assemblyAttr.ConstructorArguments[1].Value; if ((string) assemblyAttr.ConstructorArguments[0].Value == "copy") { - VerifyCopyAssemblyIsKeptUnmodified (outputDirectory, assemblyName + (assemblyName == "test" ? ".exe" : ".dll")); + VerifyCopyAssemblyIsKeptUnmodified(outputDirectory, assemblyName + (assemblyName == "test" ? ".exe" : ".dll")); } - actionAssemblies.Add (assemblyName); - } else if (assemblyAttr.AttributeType.Name == nameof (SetupLinkerTrimModeAttribute)) { + actionAssemblies.Add(assemblyName); + } else if (assemblyAttr.AttributeType.Name == nameof(SetupLinkerTrimModeAttribute)) { // We delay checking that everything was copied after processing all assemblies // with a specific action, since assembly action wins over trim mode. if ((string) assemblyAttr.ConstructorArguments[0].Value == "copy") trimModeIsCopy = true; } else - throw new NotImplementedException ($"Unknown assembly assertion of type {assemblyAttr.AttributeType}"); + throw new NotImplementedException($"Unknown assembly assertion of type {assemblyAttr.AttributeType}"); #endif } #if false - if (trimModeIsCopy) { - foreach (string assemblyName in Directory.GetFiles (Directory.GetParent (outputDirectory).ToString (), "input")) { - var fileInfo = new FileInfo (assemblyName); - if (fileInfo.Extension == ".dll" && !actionAssemblies.Contains (assemblyName)) - VerifyCopyAssemblyIsKeptUnmodified (outputDirectory, assemblyName + (assemblyName == "test" ? ".exe" : ".dll")); + if (trimModeIsCopy) + { + foreach (string assemblyName in Directory.GetFiles(Directory.GetParent(outputDirectory).ToString(), "input")) { + var fileInfo = new FileInfo(assemblyName); + if (fileInfo.Extension == ".dll" && !actionAssemblies.Contains(assemblyName)) + VerifyCopyAssemblyIsKeptUnmodified(outputDirectory, assemblyName + (assemblyName == "test" ? ".exe" : ".dll")); } } #endif diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCompiler.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCompiler.cs index feaed7f0f69c9d..8acfd278c40ffc 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCompiler.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseCompiler.cs @@ -236,7 +236,7 @@ protected virtual NPath CompileCSharpAssemblyWithDefaultCompiler(CompilerOptions #if NET return CompileCSharpAssemblyWithRoslyn(options); #else - return CompileCSharpAssemblyWithCsc (options); + return CompileCSharpAssemblyWithCsc(options); #endif } @@ -349,7 +349,7 @@ protected virtual NPath CompileCSharpAssemblyWithCsc(CompilerOptions options) #if NET return CompileCSharpAssemblyWithRoslyn(options); #else - return CompileCSharpAssemblyWithExternalCompiler (LocateCscExecutable (), options, "/shared "); + return CompileCSharpAssemblyWithExternalCompiler(LocateCscExecutable(), options, "/shared "); #endif } diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseSandbox.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseSandbox.cs index 13e696a879c4e0..49f8c79da90ee6 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseSandbox.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TestCaseSandbox.cs @@ -12,7 +12,7 @@ namespace Mono.Linker.Tests.TestCasesRunner { partial class TestCaseSandbox { - private const string _linkerAssemblyPath = "";//typeof (Trimmer).Assembly.Location; + private const string _linkerAssemblyPath = ""; // typeof(Trimmer).Assembly.Location; private static partial NPath GetArtifactsTestPath() { diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingArgumentBuilder.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingArgumentBuilder.cs index 8bd67f51877520..4d32c0e13f2bb7 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingArgumentBuilder.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/TestCasesRunner/TrimmingArgumentBuilder.cs @@ -232,8 +232,8 @@ public virtual void ProcessOptions(TestCaseLinkerOptions options) IgnoreLinkAttributes(options.IgnoreLinkAttributes); #if !NET - if (!string.IsNullOrEmpty (options.Il8n)) - AddIl8n (options.Il8n); + if (!string.IsNullOrEmpty(options.Il8n)) + AddIl8n(options.Il8n); #endif if (!string.IsNullOrEmpty(options.KeepTypeForwarderOnlyAssemblies)) diff --git a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Tests/DocumentationSignatureParserTests.cs b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Tests/DocumentationSignatureParserTests.cs index a06b08ebc2ff8e..14adc5da7a68e6 100644 --- a/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Tests/DocumentationSignatureParserTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.Trimming.Tests/Tests/DocumentationSignatureParserTests.cs @@ -29,7 +29,7 @@ public void TestSignatureParsing(TypeSystemEntity member, MemberAssertionsCollec CheckUniqueParsedString(member, attributeString); break; case nameof(ExpectGeneratedDocumentationSignatureAttribute): - // CheckGeneratedString (member, attributeString); + // CheckGeneratedString(member, attributeString); break; case nameof(ExpectResolvedDocumentationSignatureAttribute): CheckParsedString(member, attributeString); @@ -76,11 +76,11 @@ private static void CheckUniqueParsedString(TypeSystemEntity member, string inpu // Currently NativeAOT has only a partial implementation of the generator since it doesn't need it for anything // other than signature parsing (which uses the generator for certain parts). #if false - private static void CheckGeneratedString (TypeSystemEntity member, string expected) + private static void CheckGeneratedString(TypeSystemEntity member, string expected) { - var builder = new StringBuilder (); - DocumentationSignatureGenerator.PartVisitor.Instance.AppendName (builder, type); - Assert.Equal (expected, builder.ToString ()); + var builder = new StringBuilder(); + DocumentationSignatureGenerator.PartVisitor.Instance.AppendName(builder, type); + Assert.Equal(expected, builder.ToString()); } #endif @@ -235,7 +235,7 @@ public static void M(List a) } [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32,)")] - //[ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32,)")] + //[ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.M(System.Int32,)")] // there's no way to reference this, since the parsing logic doesn't like it. public static void M(int abo, __arglist) { @@ -295,9 +295,9 @@ public int this[int i] public static implicit operator bool(A a) => false; // C# will not generate a return type for this method, but we will. - // [ExpectGeneratedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] - // [ExpectExactlyResolvedDocumentationSignature ("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] - //public static int op_Implicit (A a) => 0; + // [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] + // [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_Implicit(Mono.Linker.Tests.DocumentationSignatureParserTests.A)~System.Boolean")] + //public static int op_Implicit(A a) => 0; [ExpectGeneratedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_UnaryPlus(Mono.Linker.Tests.DocumentationSignatureParserTests.A)")] [ExpectExactlyResolvedDocumentationSignature("M:Mono.Linker.Tests.DocumentationSignatureParserTests.A.op_UnaryPlus(Mono.Linker.Tests.DocumentationSignatureParserTests.A)")] diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/VirtualMethodHierarchyDataflowAnnotationValidation.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/VirtualMethodHierarchyDataflowAnnotationValidation.cs index 52661f91ed1524..ba31e3bbf60b14 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/VirtualMethodHierarchyDataflowAnnotationValidation.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/DataFlow/VirtualMethodHierarchyDataflowAnnotationValidation.cs @@ -870,252 +870,252 @@ public override void Param(Type t) { } public override Type Return() => typeof(int); } - public static void Test () - { - // https://github.com/dotnet/linker/issues/3133 - // Access the interfaces as well - otherwise NativeAOT can decide - // to not look for overrides since it knows it's making a direct access - // to a method and it doesn't need to know about the base method - // which leads to some warnings not being generated. - // The goal of this test is to validate the generated diagnostics - // so we're forcing the checks to happen with this. - typeof (Library.IAnnotatedMethods).RequiresAll (); - typeof (Library.IUnannotatedMethods).RequiresAll (); - - typeof (ImplIUnannotatedMethodsMismatch).RequiresPublicMethods (); - typeof (ImplIAnnotatedMethodsMismatch).RequiresPublicMethods (); - typeof (DerivedFromAnnotatedMismatch).RequiresPublicMethods (); - typeof (DerivedFromUnannotatedMismatch).RequiresPublicMethods (); - typeof (ImplIUnannotatedMethodsMatch).RequiresPublicMethods (); - typeof (ImplIAnnotatedMethodsMatch).RequiresPublicMethods (); - typeof (DerivedFromAnnotatedMatch).RequiresPublicMethods (); - typeof (DerivedFromUnannotatedMatch).RequiresPublicMethods (); - } - } - - // This is mostly for Native AOT - in that compiler it matters how a method - // is referenced as it will take a different code path to do some of these validations - // The above tests all rely on reflection marking so this test also uses direct calls - class DirectCall - { - abstract class Base - { - [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] - public abstract Type NonGenericAbstract ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] Type type); - - [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] - public virtual Type NonGenericVirtual ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] Type type) => type; - - public abstract void GenericAbstract<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] T> (); - - public virtual void GenericVirtual<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] T> () { } - - public abstract Type UnannotatedAbstract (Type type); - - public abstract void UnannotatedGenericAbstract (); - } - - class Derived : Base - { - [ExpectedWarning ("IL2092")] - [ExpectedWarning ("IL2093")] - public override Type NonGenericAbstract ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] Type type) => null; - - [ExpectedWarning ("IL2092")] - [ExpectedWarning ("IL2093")] - [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] - public override Type NonGenericVirtual (Type type) => null; - - [ExpectedWarning ("IL2095")] - public override void GenericAbstract () { } - - [ExpectedWarning ("IL2095")] - public override void GenericVirtual<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] T> () { } - - [ExpectedWarning ("IL2092")] - [ExpectedWarning ("IL2093")] - [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] - public override Type UnannotatedAbstract ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] Type type) => null; - - [ExpectedWarning ("IL2095")] - public override void UnannotatedGenericAbstract<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] T> () { } - } - - interface IBaseWithDefault - { - void DefaultMethod (Type type); - } - - interface IDerivedWithDefault : IBaseWithDefault - { - [ExpectedWarning ("IL2092")] - [UnexpectedWarning ("IL2092", Tool.Analyzer, "https://github.com/dotnet/linker/issues/3121")] - void IBaseWithDefault.DefaultMethod ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] Type type) { } - } - - class ImplDerivedWithDefault : IDerivedWithDefault - { - } - - interface IGvmBase - { - Type UnannotatedGvm (Type type); - Type UnannotatedGvmCalledThroughBase (Type type); - - [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] - static abstract Type AnnotatedStaticGvm<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] T> ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] Type type); - - static virtual Type UnannotatedStaticGvm (Type type) => null; - } - - class ImplIGvmBase : IGvmBase - { - // NativeAOT doesn't validate overrides when it can resolve them as direct calls - [ExpectedWarning ("IL2092", Tool.Trimmer | Tool.Analyzer, "")] - [ExpectedWarning ("IL2093", Tool.Trimmer | Tool.Analyzer, "")] - [ExpectedWarning ("IL2095", Tool.Trimmer | Tool.Analyzer, "")] - [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] - public Type UnannotatedGvm<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] T> ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] Type type) => null; - - [ExpectedWarning ("IL2092")] - [ExpectedWarning ("IL2093")] - [ExpectedWarning ("IL2095")] - [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] - public Type UnannotatedGvmCalledThroughBase<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] T> ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] Type type) => null; - - [ExpectedWarning ("IL2092")] - [ExpectedWarning ("IL2093")] - [ExpectedWarning ("IL2095")] - public static Type AnnotatedStaticGvm (Type type) => null; - - [ExpectedWarning ("IL2092")] - [ExpectedWarning ("IL2093")] - [ExpectedWarning ("IL2095")] - [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] - public static Type UnannotatedStaticGvm<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] T> ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] Type type) => null; - } - - static void CallStaticGvm () where TGvmBase : IGvmBase - { - TGvmBase.AnnotatedStaticGvm (typeof (string)); - TGvmBase.UnannotatedStaticGvm (typeof (string)); - } - - public static void Test () - { - Base instance = new Derived (); - instance.NonGenericAbstract (typeof (string)); - instance.NonGenericVirtual (typeof (string)); - instance.GenericAbstract (); - instance.GenericVirtual (); - instance.UnannotatedAbstract (typeof (string)); - instance.UnannotatedGenericAbstract (); - - ((IBaseWithDefault) (new ImplDerivedWithDefault ())).DefaultMethod (typeof (string)); - - ImplIGvmBase impl = new ImplIGvmBase (); - impl.UnannotatedGvm (typeof (string)); - - IGvmBase ibase = (IGvmBase) impl; - ibase.UnannotatedGvmCalledThroughBase (typeof (string)); - - CallStaticGvm (); - } - } - - class RequiresAndDynamicallyAccessedMembersValidation - { - // These tests have both DynamicallyAccessedMembers annotations and Requires annotations. - // This is to reproduce a bug where the virtual method annotations would be validated due to - // the presence of DynamicallyAccessedMembers, but the logic for checking Requires annotations - // was incorrect. The bug didn't manifest with just Requires annotations because the methods wouldn't - // be validated at all for Requires on type. - - class BaseMethodWithRequires - { - [RequiresUnreferencedCode (nameof (MethodWithRequires))] - [RequiresDynamicCode (nameof (MethodWithRequires))] - public virtual void MethodWithRequires ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.All)] Type t) {} - } - - [RequiresUnreferencedCode (nameof (DerivedTypeWithRequires_BaseMethodWithRequires))] - [RequiresDynamicCode (nameof (DerivedTypeWithRequires_BaseMethodWithRequires))] - class DerivedTypeWithRequires_BaseMethodWithRequires : BaseMethodWithRequires - { - public override void MethodWithRequires ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.All)] Type t) {} - } - - [ExpectedWarning ("IL2026", nameof (DerivedTypeWithRequires_BaseMethodWithRequires))] - [ExpectedWarning ("IL2026", nameof (DerivedTypeWithRequires_BaseMethodWithRequires.MethodWithRequires))] - [ExpectedWarning ("IL3050", nameof (DerivedTypeWithRequires_BaseMethodWithRequires), Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL3050", nameof (DerivedTypeWithRequires_BaseMethodWithRequires.MethodWithRequires), Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - static void Test_DerivedTypeWithRequires_BaseMethodWithRequires () - { - new DerivedTypeWithRequires_BaseMethodWithRequires ().MethodWithRequires (typeof (int)); - } - - class BaseMethodWithoutRequires - { - public virtual void MethodWithoutRequires ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.All)] Type t) {} - } - - [RequiresUnreferencedCode (nameof (DerivedTypeWithRequires_BaseMethodWithoutRequires))] - class DerivedTypeWithRequires_BaseMethodWithoutRequires : BaseMethodWithoutRequires - { - public override void MethodWithoutRequires ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.All)] Type t) {} - } - - [ExpectedWarning ("IL2026", nameof (DerivedTypeWithRequires_BaseMethodWithoutRequires))] - static void Test_DerivedTypeWithRequires_BaseMethodWithoutRequires () - { - new DerivedTypeWithRequires_BaseMethodWithoutRequires ().MethodWithoutRequires (typeof (int)); - } - - public static void Test () - { - Test_DerivedTypeWithRequires_BaseMethodWithRequires (); - Test_DerivedTypeWithRequires_BaseMethodWithoutRequires (); - } - } - - class InstantiatedGeneric - { - class GenericBase { - [ExpectedWarning ("IL2106")] - [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] - public virtual T ReturnValue () => default; - } - - class InstantiatedDerived : GenericBase { - public override Type ReturnValue () => null; - } - - public static void Test () - { - new InstantiatedDerived ().ReturnValue (); - } - } - - class AnnotationOnUnsupportedType - { - class UnsupportedType { - [ExpectedWarning ("IL2041")] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] - public virtual void UnsupportedAnnotationMismatch () { } - } - - class DerivedUnsupportedType : UnsupportedType { - [ExpectedWarning ("IL2041")] - [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] - public override void UnsupportedAnnotationMismatch () { } - } - - public static void Test () - { - new DerivedUnsupportedType ().UnsupportedAnnotationMismatch (); - } - } - } + public static void Test () + { + // https://github.com/dotnet/linker/issues/3133 + // Access the interfaces as well - otherwise NativeAOT can decide + // to not look for overrides since it knows it's making a direct access + // to a method and it doesn't need to know about the base method + // which leads to some warnings not being generated. + // The goal of this test is to validate the generated diagnostics + // so we're forcing the checks to happen with this. + typeof (Library.IAnnotatedMethods).RequiresAll (); + typeof (Library.IUnannotatedMethods).RequiresAll (); + + typeof (ImplIUnannotatedMethodsMismatch).RequiresPublicMethods (); + typeof (ImplIAnnotatedMethodsMismatch).RequiresPublicMethods (); + typeof (DerivedFromAnnotatedMismatch).RequiresPublicMethods (); + typeof (DerivedFromUnannotatedMismatch).RequiresPublicMethods (); + typeof (ImplIUnannotatedMethodsMatch).RequiresPublicMethods (); + typeof (ImplIAnnotatedMethodsMatch).RequiresPublicMethods (); + typeof (DerivedFromAnnotatedMatch).RequiresPublicMethods (); + typeof (DerivedFromUnannotatedMatch).RequiresPublicMethods (); + } + } + + // This is mostly for Native AOT - in that compiler it matters how a method + // is referenced as it will take a different code path to do some of these validations + // The above tests all rely on reflection marking so this test also uses direct calls + class DirectCall + { + abstract class Base + { + [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + public abstract Type NonGenericAbstract ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] Type type); + + [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + public virtual Type NonGenericVirtual ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] Type type) => type; + + public abstract void GenericAbstract<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] T> (); + + public virtual void GenericVirtual<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] T> () { } + + public abstract Type UnannotatedAbstract (Type type); + + public abstract void UnannotatedGenericAbstract (); + } + + class Derived : Base + { + [ExpectedWarning ("IL2092")] + [ExpectedWarning ("IL2093")] + public override Type NonGenericAbstract ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] Type type) => null; + + [ExpectedWarning ("IL2092")] + [ExpectedWarning ("IL2093")] + [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] + public override Type NonGenericVirtual (Type type) => null; + + [ExpectedWarning ("IL2095")] + public override void GenericAbstract () { } + + [ExpectedWarning ("IL2095")] + public override void GenericVirtual<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] T> () { } + + [ExpectedWarning ("IL2092")] + [ExpectedWarning ("IL2093")] + [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + public override Type UnannotatedAbstract ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] Type type) => null; + + [ExpectedWarning ("IL2095")] + public override void UnannotatedGenericAbstract<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] T> () { } + } + + interface IBaseWithDefault + { + void DefaultMethod (Type type); + } + + interface IDerivedWithDefault : IBaseWithDefault + { + [ExpectedWarning ("IL2092")] + [UnexpectedWarning ("IL2092", Tool.Analyzer, "https://github.com/dotnet/linker/issues/3121")] + void IBaseWithDefault.DefaultMethod ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] Type type) { } + } + + class ImplDerivedWithDefault : IDerivedWithDefault + { + } + + interface IGvmBase + { + Type UnannotatedGvm (Type type); + Type UnannotatedGvmCalledThroughBase (Type type); + + [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + static abstract Type AnnotatedStaticGvm<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] T> ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] Type type); + + static virtual Type UnannotatedStaticGvm (Type type) => null; + } + + class ImplIGvmBase : IGvmBase + { + // NativeAOT doesn't validate overrides when it can resolve them as direct calls + [ExpectedWarning ("IL2092", Tool.Trimmer | Tool.Analyzer, "")] + [ExpectedWarning ("IL2093", Tool.Trimmer | Tool.Analyzer, "")] + [ExpectedWarning ("IL2095", Tool.Trimmer | Tool.Analyzer, "")] + [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + public Type UnannotatedGvm<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] T> ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] Type type) => null; + + [ExpectedWarning ("IL2092")] + [ExpectedWarning ("IL2093")] + [ExpectedWarning ("IL2095")] + [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + public Type UnannotatedGvmCalledThroughBase<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] T> ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] Type type) => null; + + [ExpectedWarning ("IL2092")] + [ExpectedWarning ("IL2093")] + [ExpectedWarning ("IL2095")] + public static Type AnnotatedStaticGvm (Type type) => null; + + [ExpectedWarning ("IL2092")] + [ExpectedWarning ("IL2093")] + [ExpectedWarning ("IL2095")] + [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + public static Type UnannotatedStaticGvm<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] T> ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicProperties)] Type type) => null; + } + + static void CallStaticGvm () where TGvmBase : IGvmBase + { + TGvmBase.AnnotatedStaticGvm (typeof (string)); + TGvmBase.UnannotatedStaticGvm (typeof (string)); + } + + public static void Test () + { + Base instance = new Derived (); + instance.NonGenericAbstract (typeof (string)); + instance.NonGenericVirtual (typeof (string)); + instance.GenericAbstract (); + instance.GenericVirtual (); + instance.UnannotatedAbstract (typeof (string)); + instance.UnannotatedGenericAbstract (); + + ((IBaseWithDefault) (new ImplDerivedWithDefault ())).DefaultMethod (typeof (string)); + + ImplIGvmBase impl = new ImplIGvmBase (); + impl.UnannotatedGvm (typeof (string)); + + IGvmBase ibase = (IGvmBase) impl; + ibase.UnannotatedGvmCalledThroughBase (typeof (string)); + + CallStaticGvm (); + } + } + + class RequiresAndDynamicallyAccessedMembersValidation + { + // These tests have both DynamicallyAccessedMembers annotations and Requires annotations. + // This is to reproduce a bug where the virtual method annotations would be validated due to + // the presence of DynamicallyAccessedMembers, but the logic for checking Requires annotations + // was incorrect. The bug didn't manifest with just Requires annotations because the methods wouldn't + // be validated at all for Requires on type. + + class BaseMethodWithRequires + { + [RequiresUnreferencedCode (nameof (MethodWithRequires))] + [RequiresDynamicCode (nameof (MethodWithRequires))] + public virtual void MethodWithRequires ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.All)] Type t) {} + } + + [RequiresUnreferencedCode (nameof (DerivedTypeWithRequires_BaseMethodWithRequires))] + [RequiresDynamicCode (nameof (DerivedTypeWithRequires_BaseMethodWithRequires))] + class DerivedTypeWithRequires_BaseMethodWithRequires : BaseMethodWithRequires + { + public override void MethodWithRequires ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.All)] Type t) {} + } + + [ExpectedWarning ("IL2026", nameof (DerivedTypeWithRequires_BaseMethodWithRequires))] + [ExpectedWarning ("IL2026", nameof (DerivedTypeWithRequires_BaseMethodWithRequires.MethodWithRequires))] + [ExpectedWarning ("IL3050", nameof (DerivedTypeWithRequires_BaseMethodWithRequires), Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL3050", nameof (DerivedTypeWithRequires_BaseMethodWithRequires.MethodWithRequires), Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + static void Test_DerivedTypeWithRequires_BaseMethodWithRequires () + { + new DerivedTypeWithRequires_BaseMethodWithRequires ().MethodWithRequires (typeof (int)); + } + + class BaseMethodWithoutRequires + { + public virtual void MethodWithoutRequires ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.All)] Type t) {} + } + + [RequiresUnreferencedCode (nameof (DerivedTypeWithRequires_BaseMethodWithoutRequires))] + class DerivedTypeWithRequires_BaseMethodWithoutRequires : BaseMethodWithoutRequires + { + public override void MethodWithoutRequires ([DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.All)] Type t) {} + } + + [ExpectedWarning ("IL2026", nameof (DerivedTypeWithRequires_BaseMethodWithoutRequires))] + static void Test_DerivedTypeWithRequires_BaseMethodWithoutRequires () + { + new DerivedTypeWithRequires_BaseMethodWithoutRequires ().MethodWithoutRequires (typeof (int)); + } + + public static void Test () + { + Test_DerivedTypeWithRequires_BaseMethodWithRequires (); + Test_DerivedTypeWithRequires_BaseMethodWithoutRequires (); + } + } + + class InstantiatedGeneric + { + class GenericBase { + [ExpectedWarning ("IL2106")] + [return: DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + public virtual T ReturnValue () => default; + } + + class InstantiatedDerived : GenericBase { + public override Type ReturnValue () => null; + } + + public static void Test () + { + new InstantiatedDerived ().ReturnValue (); + } + } + + class AnnotationOnUnsupportedType + { + class UnsupportedType { + [ExpectedWarning ("IL2041")] + [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicMethods)] + public virtual void UnsupportedAnnotationMismatch () { } + } + + class DerivedUnsupportedType : UnsupportedType { + [ExpectedWarning ("IL2041")] + [DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicFields)] + public override void UnsupportedAnnotationMismatch () { } + } + + public static void Test () + { + new DerivedUnsupportedType ().UnsupportedAnnotationMismatch (); + } + } + } } namespace System diff --git a/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresOnAttribute.cs b/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresOnAttribute.cs index e91f18174b32f0..6654a03a21bd89 100644 --- a/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresOnAttribute.cs +++ b/src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresOnAttribute.cs @@ -64,18 +64,18 @@ public bool PropertyWhichRequires } } - [ExpectedWarning ("IL2026", "--AttributeWhichRequiresAttribute.ctor--")] - [ExpectedWarning ("IL3002", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL3050", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - class GenericTypeWithAttributedParameter<[AttributeWhichRequires] T> - { - public static void TestMethod () { } - } - - [ExpectedWarning ("IL2026", "--AttributeWhichRequiresAttribute.ctor--")] - [ExpectedWarning ("IL3002", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL3050", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - static void GenericMethodWithAttributedParameter<[AttributeWhichRequires] T> () { } + [ExpectedWarning ("IL2026", "--AttributeWhichRequiresAttribute.ctor--")] + [ExpectedWarning ("IL3002", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL3050", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + class GenericTypeWithAttributedParameter<[AttributeWhichRequires] T> + { + public static void TestMethod () { } + } + + [ExpectedWarning ("IL2026", "--AttributeWhichRequiresAttribute.ctor--")] + [ExpectedWarning ("IL3002", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL3050", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + static void GenericMethodWithAttributedParameter<[AttributeWhichRequires] T> () { } static void TestRequiresOnAttributeOnGenericParameter() { @@ -83,47 +83,47 @@ static void TestRequiresOnAttributeOnGenericParameter() GenericMethodWithAttributedParameter(); } - [ExpectedWarning ("IL2026", "--AttributeWhichRequiresAttribute.ctor--")] - [ExpectedWarning ("IL3002", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL3050", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL2026", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--")] - [ExpectedWarning ("IL3002", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL3050", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [AttributeWhichRequires] - [AttributeWhichRequiresOnProperty (PropertyWhichRequires = true)] - class TypeWithAttributeWhichRequires - { - } - - [ExpectedWarning ("IL2026", "--AttributeWhichRequiresAttribute.ctor--")] - [ExpectedWarning ("IL3002", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL3050", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL2026", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--")] - [ExpectedWarning ("IL3002", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL3050", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [AttributeWhichRequires] - [AttributeWhichRequiresOnProperty (PropertyWhichRequires = true)] - static void MethodWithAttributeWhichRequires () { } - - [ExpectedWarning ("IL2026", "--AttributeWhichRequiresAttribute.ctor--")] - [ExpectedWarning ("IL3002", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL3050", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL2026", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--")] - [ExpectedWarning ("IL3002", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL3050", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [AttributeWhichRequires] - [AttributeWhichRequiresOnProperty (PropertyWhichRequires = true)] - static int _fieldWithAttributeWhichRequires; - - [ExpectedWarning ("IL2026", "--AttributeWhichRequiresAttribute.ctor--")] - [ExpectedWarning ("IL3002", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL3050", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL2026", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--")] - [ExpectedWarning ("IL3002", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL3050", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [AttributeWhichRequires] - [AttributeWhichRequiresOnProperty (PropertyWhichRequires = true)] - static bool PropertyWithAttributeWhichRequires { get; set; } + [ExpectedWarning ("IL2026", "--AttributeWhichRequiresAttribute.ctor--")] + [ExpectedWarning ("IL3002", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL3050", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL2026", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--")] + [ExpectedWarning ("IL3002", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL3050", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [AttributeWhichRequires] + [AttributeWhichRequiresOnProperty (PropertyWhichRequires = true)] + class TypeWithAttributeWhichRequires + { + } + + [ExpectedWarning ("IL2026", "--AttributeWhichRequiresAttribute.ctor--")] + [ExpectedWarning ("IL3002", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL3050", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL2026", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--")] + [ExpectedWarning ("IL3002", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL3050", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [AttributeWhichRequires] + [AttributeWhichRequiresOnProperty (PropertyWhichRequires = true)] + static void MethodWithAttributeWhichRequires () { } + + [ExpectedWarning ("IL2026", "--AttributeWhichRequiresAttribute.ctor--")] + [ExpectedWarning ("IL3002", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL3050", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL2026", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--")] + [ExpectedWarning ("IL3002", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL3050", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [AttributeWhichRequires] + [AttributeWhichRequiresOnProperty (PropertyWhichRequires = true)] + static int _fieldWithAttributeWhichRequires; + + [ExpectedWarning ("IL2026", "--AttributeWhichRequiresAttribute.ctor--")] + [ExpectedWarning ("IL3002", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL3050", "--AttributeWhichRequiresAttribute.ctor--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL2026", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--")] + [ExpectedWarning ("IL3002", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL3050", "--AttributeWhichRequiresOnPropertyAttribute.PropertyWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [AttributeWhichRequires] + [AttributeWhichRequiresOnProperty (PropertyWhichRequires = true)] + static bool PropertyWithAttributeWhichRequires { get; set; } [AttributeWhichRequires] [AttributeWhichRequiresOnProperty(PropertyWhichRequires = true)] @@ -132,13 +132,13 @@ static void MethodWithAttributeWhichRequires () { } [RequiresDynamicCode("--MethodWhichRequiresWithAttributeWhichRequires--")] static void MethodWhichRequiresWithAttributeWhichRequires() { } - [ExpectedWarning ("IL2026", "--MethodWhichRequiresWithAttributeWhichRequires--")] - [ExpectedWarning ("IL3002", "--MethodWhichRequiresWithAttributeWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - [ExpectedWarning ("IL3050", "--MethodWhichRequiresWithAttributeWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] - static void TestMethodWhichRequiresWithAttributeWhichRequires () - { - MethodWhichRequiresWithAttributeWhichRequires (); - } + [ExpectedWarning ("IL2026", "--MethodWhichRequiresWithAttributeWhichRequires--")] + [ExpectedWarning ("IL3002", "--MethodWhichRequiresWithAttributeWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + [ExpectedWarning ("IL3050", "--MethodWhichRequiresWithAttributeWhichRequires--", Tool.Analyzer | Tool.NativeAot, "NativeAOT-specific warning")] + static void TestMethodWhichRequiresWithAttributeWhichRequires () + { + MethodWhichRequiresWithAttributeWhichRequires (); + } class RequiresTriggeredByAttributeUsage {