repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/CSharp/Impl/Interactive/CSharpVsInteractiveWindowCommandProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.InteractiveWindow.Commands; using Microsoft.VisualStudio.InteractiveWindow.Shell; using Microsoft.VisualStudio.LanguageServices.Interactive; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Interactive { [Export(typeof(IVsInteractiveWindowOleCommandTargetProvider))] [ContentType(ContentTypeNames.CSharpContentType)] [ContentType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName)] internal sealed class CSharpVsInteractiveWindowCommandProvider : IVsInteractiveWindowOleCommandTargetProvider { private readonly System.IServiceProvider _serviceProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpVsInteractiveWindowCommandProvider( SVsServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public IOleCommandTarget GetCommandTarget(IWpfTextView textView, IOleCommandTarget nextTarget) { var target = new ScriptingOleCommandTarget(textView, (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel))); target.NextCommandTarget = nextTarget; return target; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.InteractiveWindow.Commands; using Microsoft.VisualStudio.InteractiveWindow.Shell; using Microsoft.VisualStudio.LanguageServices.Interactive; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Interactive { [Export(typeof(IVsInteractiveWindowOleCommandTargetProvider))] [ContentType(ContentTypeNames.CSharpContentType)] [ContentType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName)] internal sealed class CSharpVsInteractiveWindowCommandProvider : IVsInteractiveWindowOleCommandTargetProvider { private readonly System.IServiceProvider _serviceProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpVsInteractiveWindowCommandProvider( SVsServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public IOleCommandTarget GetCommandTarget(IWpfTextView textView, IOleCommandTarget nextTarget) { var target = new ScriptingOleCommandTarget(textView, (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel))); target.NextCommandTarget = nextTarget; return target; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/Test/Debugging/DebugInformationReaderProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Debugging.UnitTests { public class DebugInformationReaderProviderTests { [Fact] public void CreateFrom_Errors() { Assert.Throws<ArgumentException>(() => DebugInformationReaderProvider.CreateFromStream(new TestStream(canRead: false, canSeek: true, canWrite: true))); Assert.Throws<ArgumentException>(() => DebugInformationReaderProvider.CreateFromStream(new TestStream(canRead: true, canSeek: false, canWrite: true))); Assert.Throws<ArgumentNullException>(() => DebugInformationReaderProvider.CreateFromStream(null)); Assert.Throws<ArgumentNullException>(() => DebugInformationReaderProvider.CreateFromMetadataReader(null)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Debugging.UnitTests { public class DebugInformationReaderProviderTests { [Fact] public void CreateFrom_Errors() { Assert.Throws<ArgumentException>(() => DebugInformationReaderProvider.CreateFromStream(new TestStream(canRead: false, canSeek: true, canWrite: true))); Assert.Throws<ArgumentException>(() => DebugInformationReaderProvider.CreateFromStream(new TestStream(canRead: true, canSeek: false, canWrite: true))); Assert.Throws<ArgumentNullException>(() => DebugInformationReaderProvider.CreateFromStream(null)); Assert.Throws<ArgumentNullException>(() => DebugInformationReaderProvider.CreateFromMetadataReader(null)); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ITypeSymbolExtensions { /// <summary> /// Returns the corresponding symbol in this type or a base type that implements /// interfaceMember (either implicitly or explicitly), or null if no such symbol exists /// (which might be either because this type doesn't implement the container of /// interfaceMember, or this type doesn't supply a member that successfully implements /// interfaceMember). /// </summary> public static async Task<ImmutableArray<ISymbol>> FindImplementationsForInterfaceMemberAsync( this ITypeSymbol typeSymbol, ISymbol interfaceMember, Solution solution, CancellationToken cancellationToken) { // This method can return multiple results. Consider the case of: // // interface IGoo<X> { void Goo(X x); } // // class C : IGoo<int>, IGoo<string> { void Goo(int x); void Goo(string x); } // // If you're looking for the implementations of IGoo<X>.Goo then you want to find both // results in C. using var _ = ArrayBuilder<ISymbol>.GetInstance(out var builder); // TODO(cyrusn): Implement this using the actual code for // TypeSymbol.FindImplementationForInterfaceMember if (typeSymbol == null || interfaceMember == null) return ImmutableArray<ISymbol>.Empty; if (interfaceMember.Kind != SymbolKind.Event && interfaceMember.Kind != SymbolKind.Method && interfaceMember.Kind != SymbolKind.Property) { return ImmutableArray<ISymbol>.Empty; } // WorkItem(4843) // // 'typeSymbol' has to at least implement the interface containing the member. note: // this just means that the interface shows up *somewhere* in the inheritance chain of // this type. However, this type may not actually say that it implements it. For // example: // // interface I { void Goo(); } // // class B { } // // class C : B, I { } // // class D : C { } // // D does implement I transitively through C. However, even if D has a "Goo" method, it // won't be an implementation of I.Goo. The implementation of I.Goo must be from a type // that actually has I in it's direct interface chain, or a type that's a base type of // that. in this case, that means only classes C or B. var interfaceType = interfaceMember.ContainingType; if (!typeSymbol.ImplementsIgnoringConstruction(interfaceType)) return ImmutableArray<ISymbol>.Empty; // We've ascertained that the type T implements some constructed type of the form I<X>. // However, we're not precisely sure which constructions of I<X> are being used. For // example, a type C might implement I<int> and I<string>. If we're searching for a // method from I<X> we might need to find several methods that implement different // instantiations of that method. var originalInterfaceType = interfaceMember.ContainingType.OriginalDefinition; var originalInterfaceMember = interfaceMember.OriginalDefinition; var constructedInterfaces = typeSymbol.AllInterfaces.Where(i => SymbolEquivalenceComparer.Instance.Equals(i.OriginalDefinition, originalInterfaceType)); foreach (var constructedInterface in constructedInterfaces) { cancellationToken.ThrowIfCancellationRequested(); // OriginalSymbolMatch allows types to be matched across different assemblies if they are considered to // be the same type, which provides a more accurate implementations list for interfaces. var constructedInterfaceMember = await constructedInterface.GetMembers(interfaceMember.Name).FirstOrDefaultAsync( typeSymbol => SymbolFinder.OriginalSymbolsMatchAsync(solution, typeSymbol, interfaceMember, cancellationToken)).ConfigureAwait(false); if (constructedInterfaceMember == null) { continue; } // Now we need to walk the base type chain, but we start at the first type that actually // has the interface directly in its interface hierarchy. var seenTypeDeclaringInterface = false; for (var currentType = typeSymbol; currentType != null; currentType = currentType.BaseType) { seenTypeDeclaringInterface = seenTypeDeclaringInterface || currentType.GetOriginalInterfacesAndTheirBaseInterfaces().Contains(interfaceType.OriginalDefinition); if (seenTypeDeclaringInterface) { var result = currentType.FindImplementations(constructedInterfaceMember, solution.Workspace); if (result != null) { builder.Add(result); break; } } } } return builder.ToImmutable(); } public static ISymbol? FindImplementations(this ITypeSymbol typeSymbol, ISymbol constructedInterfaceMember, Workspace workspace) => constructedInterfaceMember switch { IEventSymbol eventSymbol => typeSymbol.FindImplementations(eventSymbol, workspace), IMethodSymbol methodSymbol => typeSymbol.FindImplementations(methodSymbol, workspace), IPropertySymbol propertySymbol => typeSymbol.FindImplementations(propertySymbol, workspace), _ => null, }; private static ISymbol? FindImplementations<TSymbol>( this ITypeSymbol typeSymbol, TSymbol constructedInterfaceMember, Workspace workspace) where TSymbol : class, ISymbol { // Check the current type for explicit interface matches. Otherwise, check // the current type and base types for implicit matches. var explicitMatches = from member in typeSymbol.GetMembers().OfType<TSymbol>() from explicitInterfaceMethod in member.ExplicitInterfaceImplementations() where SymbolEquivalenceComparer.Instance.Equals(explicitInterfaceMethod, constructedInterfaceMember) select member; var provider = workspace.Services.GetLanguageServices(typeSymbol.Language); var semanticFacts = provider.GetRequiredService<ISemanticFactsService>(); // Even if a language only supports explicit interface implementation, we // can't enforce it for types from metadata. For example, a VB symbol // representing System.Xml.XmlReader will say it implements IDisposable, but // the XmlReader.Dispose() method will not be an explicit implementation of // IDisposable.Dispose() if ((!semanticFacts.SupportsImplicitInterfaceImplementation && typeSymbol.Locations.Any(location => location.IsInSource)) || typeSymbol.TypeKind == TypeKind.Interface) { return explicitMatches.FirstOrDefault(); } var syntaxFacts = provider.GetRequiredService<ISyntaxFactsService>(); var implicitMatches = from baseType in typeSymbol.GetBaseTypesAndThis() from member in baseType.GetMembers(constructedInterfaceMember.Name).OfType<TSymbol>() where member.DeclaredAccessibility == Accessibility.Public && SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(member, constructedInterfaceMember, syntaxFacts.IsCaseSensitive) select member; return explicitMatches.FirstOrDefault() ?? implicitMatches.FirstOrDefault(); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? RemoveUnavailableTypeParameters( this ITypeSymbol? type, Compilation compilation, IEnumerable<ITypeParameterSymbol> availableTypeParameters) { return type?.RemoveUnavailableTypeParameters(compilation, availableTypeParameters.Select(t => t.Name).ToSet()); } [return: NotNullIfNotNull(parameterName: "type")] private static ITypeSymbol? RemoveUnavailableTypeParameters( this ITypeSymbol? type, Compilation compilation, ISet<string> availableTypeParameterNames) { return type?.Accept(new UnavailableTypeParameterRemover(compilation, availableTypeParameterNames)); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? RemoveAnonymousTypes( this ITypeSymbol? type, Compilation compilation) { return type?.Accept(new AnonymousTypeRemover(compilation)); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? RemoveUnnamedErrorTypes( this ITypeSymbol? type, Compilation compilation) { return type?.Accept(new UnnamedErrorTypeRemover(compilation)); } public static IList<ITypeParameterSymbol> GetReferencedMethodTypeParameters( this ITypeSymbol? type, IList<ITypeParameterSymbol>? result = null) { result ??= new List<ITypeParameterSymbol>(); type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: true)); return result; } public static IList<ITypeParameterSymbol> GetReferencedTypeParameters( this ITypeSymbol? type, IList<ITypeParameterSymbol>? result = null) { result ??= new List<ITypeParameterSymbol>(); type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: false)); return result; } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? SubstituteTypes<TType1, TType2>( this ITypeSymbol? type, IDictionary<TType1, TType2> mapping, Compilation compilation) where TType1 : ITypeSymbol where TType2 : ITypeSymbol { return type.SubstituteTypes(mapping, new CompilationTypeGenerator(compilation)); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? SubstituteTypes<TType1, TType2>( this ITypeSymbol? type, IDictionary<TType1, TType2> mapping, ITypeGenerator typeGenerator) where TType1 : ITypeSymbol where TType2 : ITypeSymbol { return type?.Accept(new SubstituteTypesVisitor<TType1, TType2>(mapping, typeGenerator)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ITypeSymbolExtensions { /// <summary> /// Returns the corresponding symbol in this type or a base type that implements /// interfaceMember (either implicitly or explicitly), or null if no such symbol exists /// (which might be either because this type doesn't implement the container of /// interfaceMember, or this type doesn't supply a member that successfully implements /// interfaceMember). /// </summary> public static async Task<ImmutableArray<ISymbol>> FindImplementationsForInterfaceMemberAsync( this ITypeSymbol typeSymbol, ISymbol interfaceMember, Solution solution, CancellationToken cancellationToken) { // This method can return multiple results. Consider the case of: // // interface IGoo<X> { void Goo(X x); } // // class C : IGoo<int>, IGoo<string> { void Goo(int x); void Goo(string x); } // // If you're looking for the implementations of IGoo<X>.Goo then you want to find both // results in C. using var _ = ArrayBuilder<ISymbol>.GetInstance(out var builder); // TODO(cyrusn): Implement this using the actual code for // TypeSymbol.FindImplementationForInterfaceMember if (typeSymbol == null || interfaceMember == null) return ImmutableArray<ISymbol>.Empty; if (interfaceMember.Kind != SymbolKind.Event && interfaceMember.Kind != SymbolKind.Method && interfaceMember.Kind != SymbolKind.Property) { return ImmutableArray<ISymbol>.Empty; } // WorkItem(4843) // // 'typeSymbol' has to at least implement the interface containing the member. note: // this just means that the interface shows up *somewhere* in the inheritance chain of // this type. However, this type may not actually say that it implements it. For // example: // // interface I { void Goo(); } // // class B { } // // class C : B, I { } // // class D : C { } // // D does implement I transitively through C. However, even if D has a "Goo" method, it // won't be an implementation of I.Goo. The implementation of I.Goo must be from a type // that actually has I in it's direct interface chain, or a type that's a base type of // that. in this case, that means only classes C or B. var interfaceType = interfaceMember.ContainingType; if (!typeSymbol.ImplementsIgnoringConstruction(interfaceType)) return ImmutableArray<ISymbol>.Empty; // We've ascertained that the type T implements some constructed type of the form I<X>. // However, we're not precisely sure which constructions of I<X> are being used. For // example, a type C might implement I<int> and I<string>. If we're searching for a // method from I<X> we might need to find several methods that implement different // instantiations of that method. var originalInterfaceType = interfaceMember.ContainingType.OriginalDefinition; var originalInterfaceMember = interfaceMember.OriginalDefinition; var constructedInterfaces = typeSymbol.AllInterfaces.Where(i => SymbolEquivalenceComparer.Instance.Equals(i.OriginalDefinition, originalInterfaceType)); foreach (var constructedInterface in constructedInterfaces) { cancellationToken.ThrowIfCancellationRequested(); // OriginalSymbolMatch allows types to be matched across different assemblies if they are considered to // be the same type, which provides a more accurate implementations list for interfaces. var constructedInterfaceMember = await constructedInterface.GetMembers(interfaceMember.Name).FirstOrDefaultAsync( typeSymbol => SymbolFinder.OriginalSymbolsMatchAsync(solution, typeSymbol, interfaceMember, cancellationToken)).ConfigureAwait(false); if (constructedInterfaceMember == null) { continue; } // Now we need to walk the base type chain, but we start at the first type that actually // has the interface directly in its interface hierarchy. var seenTypeDeclaringInterface = false; for (var currentType = typeSymbol; currentType != null; currentType = currentType.BaseType) { seenTypeDeclaringInterface = seenTypeDeclaringInterface || currentType.GetOriginalInterfacesAndTheirBaseInterfaces().Contains(interfaceType.OriginalDefinition); if (seenTypeDeclaringInterface) { var result = currentType.FindImplementations(constructedInterfaceMember, solution.Workspace); if (result != null) { builder.Add(result); break; } } } } return builder.ToImmutable(); } public static ISymbol? FindImplementations(this ITypeSymbol typeSymbol, ISymbol constructedInterfaceMember, Workspace workspace) => constructedInterfaceMember switch { IEventSymbol eventSymbol => typeSymbol.FindImplementations(eventSymbol, workspace), IMethodSymbol methodSymbol => typeSymbol.FindImplementations(methodSymbol, workspace), IPropertySymbol propertySymbol => typeSymbol.FindImplementations(propertySymbol, workspace), _ => null, }; private static ISymbol? FindImplementations<TSymbol>( this ITypeSymbol typeSymbol, TSymbol constructedInterfaceMember, Workspace workspace) where TSymbol : class, ISymbol { // Check the current type for explicit interface matches. Otherwise, check // the current type and base types for implicit matches. var explicitMatches = from member in typeSymbol.GetMembers().OfType<TSymbol>() from explicitInterfaceMethod in member.ExplicitInterfaceImplementations() where SymbolEquivalenceComparer.Instance.Equals(explicitInterfaceMethod, constructedInterfaceMember) select member; var provider = workspace.Services.GetLanguageServices(typeSymbol.Language); var semanticFacts = provider.GetRequiredService<ISemanticFactsService>(); // Even if a language only supports explicit interface implementation, we // can't enforce it for types from metadata. For example, a VB symbol // representing System.Xml.XmlReader will say it implements IDisposable, but // the XmlReader.Dispose() method will not be an explicit implementation of // IDisposable.Dispose() if ((!semanticFacts.SupportsImplicitInterfaceImplementation && typeSymbol.Locations.Any(location => location.IsInSource)) || typeSymbol.TypeKind == TypeKind.Interface) { return explicitMatches.FirstOrDefault(); } var syntaxFacts = provider.GetRequiredService<ISyntaxFactsService>(); var implicitMatches = from baseType in typeSymbol.GetBaseTypesAndThis() from member in baseType.GetMembers(constructedInterfaceMember.Name).OfType<TSymbol>() where member.DeclaredAccessibility == Accessibility.Public && SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(member, constructedInterfaceMember, syntaxFacts.IsCaseSensitive) select member; return explicitMatches.FirstOrDefault() ?? implicitMatches.FirstOrDefault(); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? RemoveUnavailableTypeParameters( this ITypeSymbol? type, Compilation compilation, IEnumerable<ITypeParameterSymbol> availableTypeParameters) { return type?.RemoveUnavailableTypeParameters(compilation, availableTypeParameters.Select(t => t.Name).ToSet()); } [return: NotNullIfNotNull(parameterName: "type")] private static ITypeSymbol? RemoveUnavailableTypeParameters( this ITypeSymbol? type, Compilation compilation, ISet<string> availableTypeParameterNames) { return type?.Accept(new UnavailableTypeParameterRemover(compilation, availableTypeParameterNames)); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? RemoveAnonymousTypes( this ITypeSymbol? type, Compilation compilation) { return type?.Accept(new AnonymousTypeRemover(compilation)); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? RemoveUnnamedErrorTypes( this ITypeSymbol? type, Compilation compilation) { return type?.Accept(new UnnamedErrorTypeRemover(compilation)); } public static IList<ITypeParameterSymbol> GetReferencedMethodTypeParameters( this ITypeSymbol? type, IList<ITypeParameterSymbol>? result = null) { result ??= new List<ITypeParameterSymbol>(); type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: true)); return result; } public static IList<ITypeParameterSymbol> GetReferencedTypeParameters( this ITypeSymbol? type, IList<ITypeParameterSymbol>? result = null) { result ??= new List<ITypeParameterSymbol>(); type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: false)); return result; } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? SubstituteTypes<TType1, TType2>( this ITypeSymbol? type, IDictionary<TType1, TType2> mapping, Compilation compilation) where TType1 : ITypeSymbol where TType2 : ITypeSymbol { return type.SubstituteTypes(mapping, new CompilationTypeGenerator(compilation)); } [return: NotNullIfNotNull(parameterName: "type")] public static ITypeSymbol? SubstituteTypes<TType1, TType2>( this ITypeSymbol? type, IDictionary<TType1, TType2> mapping, ITypeGenerator typeGenerator) where TType1 : ITypeSymbol where TType2 : ITypeSymbol { return type?.Accept(new SubstituteTypesVisitor<TType1, TType2>(mapping, typeGenerator)); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.fr.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../Resources.resx"> <body> <trans-unit id="DynamicView"> <source>Dynamic View</source> <target state="translated">Affichage dynamique</target> <note>IDynamicMetaObjectProvider and System.__ComObject expansion</note> </trans-unit> <trans-unit id="DynamicViewNotDynamic"> <source>Only COM or Dynamic objects can have Dynamic View</source> <target state="translated">Seuls les objets COM ou dynamiques peuvent avoir un affichage dynamique</target> <note>Cannot use "dynamic" format specifier on a non-dynamic type</note> </trans-unit> <trans-unit id="DynamicViewValueWarning"> <source>Expanding the Dynamic View will get the dynamic members for the object</source> <target state="translated">Le développement de l'affichage dynamique permet d'obtenir les membres dynamiques pour l'objet</target> <note>Warning reported in Dynamic View value</note> </trans-unit> <trans-unit id="ErrorName"> <source>Error</source> <target state="translated">Erreur</target> <note>Error result name</note> </trans-unit> <trans-unit id="ExceptionThrown"> <source>'{0}' threw an exception of type '{1}'</source> <target state="translated">'{0}' a levé une exception de type '{1}'</target> <note>Threw an exception while evaluating a value.</note> </trans-unit> <trans-unit id="HostValueNotFound"> <source>Cannot provide the value: host value not found</source> <target state="translated">Impossible de fournir la valeur : valeur d'hôte introuvable</target> <note /> </trans-unit> <trans-unit id="InvalidPointerDereference"> <source>Cannot dereference '{0}'. The pointer is not valid.</source> <target state="translated">Impossible de déréférencer '{0}'. Le pointeur n'est pas valide.</target> <note>Invalid pointer dereference</note> </trans-unit> <trans-unit id="NativeView"> <source>Native View</source> <target state="translated">Vue native</target> <note>Native COM object expansion</note> </trans-unit> <trans-unit id="NativeViewNotNativeDebugging"> <source>To inspect the native object, enable native code debugging.</source> <target state="translated">Pour inspecter l'objet natif, activez le débogage du code natif.</target> <note>Display value of Native View node when native debugging is not enabled</note> </trans-unit> <trans-unit id="NonPublicMembers"> <source>Non-Public members</source> <target state="translated">Membres non publics</target> <note>Non-public type members</note> </trans-unit> <trans-unit id="RawView"> <source>Raw View</source> <target state="translated">Affichage brut</target> <note>DebuggerTypeProxy "Raw View"</note> </trans-unit> <trans-unit id="ResultsView"> <source>Results View</source> <target state="translated">Affichage des résultats</target> <note>IEnumerable results expansion</note> </trans-unit> <trans-unit id="ResultsViewNoSystemCore"> <source>Results View requires System.Core.dll to be referenced</source> <target state="translated">L'affichage des résultats nécessite le référencement de System.Core.dll</target> <note>"results" format specifier requires System.Core.dll</note> </trans-unit> <trans-unit id="ResultsViewNotEnumerable"> <source>Only Enumerable types can have Results View</source> <target state="translated">Seuls les types énumérables peuvent avoir un affichage des résultats</target> <note>Cannot use "results" format specifier on non-enumerable type</note> </trans-unit> <trans-unit id="ResultsViewValueWarning"> <source>Expanding the Results View will enumerate the IEnumerable</source> <target state="translated">Le développement de l'affichage des résultats permet d'énumérer IEnumerable</target> <note>Warning reported in Results View value</note> </trans-unit> <trans-unit id="SharedMembers"> <source>Shared members</source> <target state="translated">Membres partagés</target> <note>Shared type members (VB only)</note> </trans-unit> <trans-unit id="StaticMembers"> <source>Static members</source> <target state="translated">Membres statiques</target> <note>Static type members (C# only)</note> </trans-unit> <trans-unit id="TypeVariablesName"> <source>Type variables</source> <target state="translated">Variables de type</target> <note>Type variables result name</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../Resources.resx"> <body> <trans-unit id="DynamicView"> <source>Dynamic View</source> <target state="translated">Affichage dynamique</target> <note>IDynamicMetaObjectProvider and System.__ComObject expansion</note> </trans-unit> <trans-unit id="DynamicViewNotDynamic"> <source>Only COM or Dynamic objects can have Dynamic View</source> <target state="translated">Seuls les objets COM ou dynamiques peuvent avoir un affichage dynamique</target> <note>Cannot use "dynamic" format specifier on a non-dynamic type</note> </trans-unit> <trans-unit id="DynamicViewValueWarning"> <source>Expanding the Dynamic View will get the dynamic members for the object</source> <target state="translated">Le développement de l'affichage dynamique permet d'obtenir les membres dynamiques pour l'objet</target> <note>Warning reported in Dynamic View value</note> </trans-unit> <trans-unit id="ErrorName"> <source>Error</source> <target state="translated">Erreur</target> <note>Error result name</note> </trans-unit> <trans-unit id="ExceptionThrown"> <source>'{0}' threw an exception of type '{1}'</source> <target state="translated">'{0}' a levé une exception de type '{1}'</target> <note>Threw an exception while evaluating a value.</note> </trans-unit> <trans-unit id="HostValueNotFound"> <source>Cannot provide the value: host value not found</source> <target state="translated">Impossible de fournir la valeur : valeur d'hôte introuvable</target> <note /> </trans-unit> <trans-unit id="InvalidPointerDereference"> <source>Cannot dereference '{0}'. The pointer is not valid.</source> <target state="translated">Impossible de déréférencer '{0}'. Le pointeur n'est pas valide.</target> <note>Invalid pointer dereference</note> </trans-unit> <trans-unit id="NativeView"> <source>Native View</source> <target state="translated">Vue native</target> <note>Native COM object expansion</note> </trans-unit> <trans-unit id="NativeViewNotNativeDebugging"> <source>To inspect the native object, enable native code debugging.</source> <target state="translated">Pour inspecter l'objet natif, activez le débogage du code natif.</target> <note>Display value of Native View node when native debugging is not enabled</note> </trans-unit> <trans-unit id="NonPublicMembers"> <source>Non-Public members</source> <target state="translated">Membres non publics</target> <note>Non-public type members</note> </trans-unit> <trans-unit id="RawView"> <source>Raw View</source> <target state="translated">Affichage brut</target> <note>DebuggerTypeProxy "Raw View"</note> </trans-unit> <trans-unit id="ResultsView"> <source>Results View</source> <target state="translated">Affichage des résultats</target> <note>IEnumerable results expansion</note> </trans-unit> <trans-unit id="ResultsViewNoSystemCore"> <source>Results View requires System.Core.dll to be referenced</source> <target state="translated">L'affichage des résultats nécessite le référencement de System.Core.dll</target> <note>"results" format specifier requires System.Core.dll</note> </trans-unit> <trans-unit id="ResultsViewNotEnumerable"> <source>Only Enumerable types can have Results View</source> <target state="translated">Seuls les types énumérables peuvent avoir un affichage des résultats</target> <note>Cannot use "results" format specifier on non-enumerable type</note> </trans-unit> <trans-unit id="ResultsViewValueWarning"> <source>Expanding the Results View will enumerate the IEnumerable</source> <target state="translated">Le développement de l'affichage des résultats permet d'énumérer IEnumerable</target> <note>Warning reported in Results View value</note> </trans-unit> <trans-unit id="SharedMembers"> <source>Shared members</source> <target state="translated">Membres partagés</target> <note>Shared type members (VB only)</note> </trans-unit> <trans-unit id="StaticMembers"> <source>Static members</source> <target state="translated">Membres statiques</target> <note>Static type members (C# only)</note> </trans-unit> <trans-unit id="TypeVariablesName"> <source>Type variables</source> <target state="translated">Variables de type</target> <note>Type variables result name</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Portable/Syntax/SwitchStatementSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class SwitchStatementSyntax { public SwitchStatementSyntax Update(SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList<SwitchSectionSyntax> sections, SyntaxToken closeBraceToken) => Update(AttributeLists, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static SwitchStatementSyntax SwitchStatement(SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList<SwitchSectionSyntax> sections, SyntaxToken closeBraceToken) => SwitchStatement(attributeLists: default, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class SwitchStatementSyntax { public SwitchStatementSyntax Update(SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList<SwitchSectionSyntax> sections, SyntaxToken closeBraceToken) => Update(AttributeLists, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static SwitchStatementSyntax SwitchStatement(SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList<SwitchSectionSyntax> sections, SyntaxToken closeBraceToken) => SwitchStatement(attributeLists: default, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Portable/Binder/Binder_Deconstruct.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts deconstruction-assignment syntax (AssignmentExpressionSyntax nodes with the left /// being a tuple expression or declaration expression) into a BoundDeconstructionAssignmentOperator (or bad node). /// The BoundDeconstructionAssignmentOperator will have: /// - a BoundTupleLiteral as its Left, /// - a BoundConversion as its Right, holding: /// - a tree of Conversion objects with Kind=Deconstruction, information about a Deconstruct method (optional) and /// an array of nested Conversions (like a tuple conversion), /// - a BoundExpression as its Operand. /// </summary> internal partial class Binder { internal BoundExpression BindDeconstruction(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics, bool resultIsUsedOverride = false) { var left = node.Left; var right = node.Right; DeclarationExpressionSyntax? declaration = null; ExpressionSyntax? expression = null; var result = BindDeconstruction(node, left, right, diagnostics, ref declaration, ref expression, resultIsUsedOverride); if (declaration != null) { // only allowed at the top level, or in a for loop switch (node.Parent?.Kind()) { case null: case SyntaxKind.ExpressionStatement: if (expression != null) { MessageID.IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction .CheckFeatureAvailability(diagnostics, Compilation, node.Location); } break; case SyntaxKind.ForStatement: if (((ForStatementSyntax)node.Parent).Initializers.Contains(node)) { if (expression != null) { MessageID.IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction .CheckFeatureAvailability(diagnostics, Compilation, node.Location); } } else { Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, declaration); } break; default: Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, declaration); break; } } return result; } /// <summary> /// Bind a deconstruction assignment. /// </summary> /// <param name="deconstruction">The deconstruction operation</param> /// <param name="left">The left (tuple) operand</param> /// <param name="right">The right (deconstructable) operand</param> /// <param name="diagnostics">Where to report diagnostics</param> /// <param name="declaration">A variable set to the first variable declaration found in the left</param> /// <param name="expression">A variable set to the first expression in the left that isn't a declaration or discard</param> /// <param name="resultIsUsedOverride">The expression evaluator needs to bind deconstructions (both assignments and declarations) as expression-statements /// and still access the returned value</param> /// <param name="rightPlaceholder"></param> /// <returns></returns> internal BoundDeconstructionAssignmentOperator BindDeconstruction( CSharpSyntaxNode deconstruction, ExpressionSyntax left, ExpressionSyntax right, BindingDiagnosticBag diagnostics, ref DeclarationExpressionSyntax? declaration, ref ExpressionSyntax? expression, bool resultIsUsedOverride = false, BoundDeconstructValuePlaceholder? rightPlaceholder = null) { DeconstructionVariable locals = BindDeconstructionVariables(left, diagnostics, ref declaration, ref expression); Debug.Assert(locals.NestedVariables is object); var deconstructionDiagnostics = new BindingDiagnosticBag(new DiagnosticBag(), diagnostics.DependenciesBag); BoundExpression boundRight = rightPlaceholder ?? BindValue(right, deconstructionDiagnostics, BindValueKind.RValue); boundRight = FixTupleLiteral(locals.NestedVariables, boundRight, deconstruction, deconstructionDiagnostics); boundRight = BindToNaturalType(boundRight, diagnostics); bool resultIsUsed = resultIsUsedOverride || IsDeconstructionResultUsed(left); var assignment = BindDeconstructionAssignment(deconstruction, left, boundRight, locals.NestedVariables, resultIsUsed, deconstructionDiagnostics); DeconstructionVariable.FreeDeconstructionVariables(locals.NestedVariables); diagnostics.AddRange(deconstructionDiagnostics.DiagnosticBag); return assignment; } private BoundDeconstructionAssignmentOperator BindDeconstructionAssignment( CSharpSyntaxNode node, ExpressionSyntax left, BoundExpression boundRHS, ArrayBuilder<DeconstructionVariable> checkedVariables, bool resultIsUsed, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics.DiagnosticBag is object); uint rightEscape = GetValEscape(boundRHS, this.LocalScopeDepth); if ((object?)boundRHS.Type == null || boundRHS.Type.IsErrorType()) { // we could still not infer a type for the RHS FailRemainingInferencesAndSetValEscape(checkedVariables, diagnostics, rightEscape); var voidType = GetSpecialType(SpecialType.System_Void, diagnostics, node); var type = boundRHS.Type ?? voidType; return new BoundDeconstructionAssignmentOperator( node, DeconstructionVariablesAsTuple(left, checkedVariables, diagnostics, ignoreDiagnosticsFromTuple: true), new BoundConversion(boundRHS.Syntax, boundRHS, Conversion.Deconstruction, @checked: false, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, type: type, hasErrors: true), resultIsUsed, voidType, hasErrors: true); } Conversion conversion; bool hasErrors = !MakeDeconstructionConversion( boundRHS.Type, node, boundRHS.Syntax, diagnostics, checkedVariables, out conversion); if (conversion.Method != null) { CheckImplicitThisCopyInReadOnlyMember(boundRHS, conversion.Method, diagnostics); } FailRemainingInferencesAndSetValEscape(checkedVariables, diagnostics, rightEscape); var lhsTuple = DeconstructionVariablesAsTuple(left, checkedVariables, diagnostics, ignoreDiagnosticsFromTuple: diagnostics.HasAnyErrors() || !resultIsUsed); Debug.Assert(hasErrors || lhsTuple.Type is object); TypeSymbol returnType = hasErrors ? CreateErrorType() : lhsTuple.Type!; uint leftEscape = GetBroadestValEscape(lhsTuple, this.LocalScopeDepth); boundRHS = ValidateEscape(boundRHS, leftEscape, isByRef: false, diagnostics: diagnostics); var boundConversion = new BoundConversion( boundRHS.Syntax, boundRHS, conversion, @checked: false, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, type: returnType, hasErrors: hasErrors) { WasCompilerGenerated = true }; return new BoundDeconstructionAssignmentOperator(node, lhsTuple, boundConversion, resultIsUsed, returnType); } private static bool IsDeconstructionResultUsed(ExpressionSyntax left) { var parent = left.Parent; if (parent is null || parent.Kind() == SyntaxKind.ForEachVariableStatement) { return false; } Debug.Assert(parent.Kind() == SyntaxKind.SimpleAssignmentExpression); var grandParent = parent.Parent; if (grandParent is null) { return false; } switch (grandParent.Kind()) { case SyntaxKind.ExpressionStatement: return ((ExpressionStatementSyntax)grandParent).Expression != parent; case SyntaxKind.ForStatement: // Incrementors and Initializers don't have to produce a value var loop = (ForStatementSyntax)grandParent; return !loop.Incrementors.Contains(parent) && !loop.Initializers.Contains(parent); default: return true; } } /// <summary>When boundRHS is a tuple literal, fix it up by inferring its types.</summary> private BoundExpression FixTupleLiteral(ArrayBuilder<DeconstructionVariable> checkedVariables, BoundExpression boundRHS, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics.DiagnosticBag is object); if (boundRHS.Kind == BoundKind.TupleLiteral) { // Let's fix the literal up by figuring out its type // For declarations, that means merging type information from the LHS and RHS // For assignments, only the LHS side matters since it is necessarily typed // If we already have diagnostics at this point, it is not worth collecting likely duplicate diagnostics from making the merged type bool hadErrors = diagnostics.HasAnyErrors(); TypeSymbol? mergedTupleType = MakeMergedTupleType(checkedVariables, (BoundTupleLiteral)boundRHS, syntax, hadErrors ? null : diagnostics); if ((object?)mergedTupleType != null) { boundRHS = GenerateConversionForAssignment(mergedTupleType, boundRHS, diagnostics); } } else if ((object?)boundRHS.Type == null) { Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, boundRHS.Syntax); } return boundRHS; } /// <summary> /// Recursively builds a Conversion object with Kind=Deconstruction including information about any necessary /// Deconstruct method and any element-wise conversion. /// /// Note that the variables may either be plain or nested variables. /// The variables may be updated with inferred types if they didn't have types initially. /// Returns false if there was an error. /// </summary> private bool MakeDeconstructionConversion( TypeSymbol type, SyntaxNode syntax, SyntaxNode rightSyntax, BindingDiagnosticBag diagnostics, ArrayBuilder<DeconstructionVariable> variables, out Conversion conversion) { Debug.Assert((object)type != null); ImmutableArray<TypeSymbol> tupleOrDeconstructedTypes; conversion = Conversion.Deconstruction; // Figure out the deconstruct method (if one is required) and determine the types we get from the RHS at this level var deconstructMethod = default(DeconstructMethodInfo); if (type.IsTupleType) { // tuple literal such as `(1, 2)`, `(null, null)`, `(x.P, y.M())` tupleOrDeconstructedTypes = type.TupleElementTypesWithAnnotations.SelectAsArray(TypeMap.AsTypeSymbol); SetInferredTypes(variables, tupleOrDeconstructedTypes, diagnostics); if (variables.Count != tupleOrDeconstructedTypes.Length) { Error(diagnostics, ErrorCode.ERR_DeconstructWrongCardinality, syntax, tupleOrDeconstructedTypes.Length, variables.Count); return false; } } else { if (variables.Count < 2) { Error(diagnostics, ErrorCode.ERR_DeconstructTooFewElements, syntax); return false; } var inputPlaceholder = new BoundDeconstructValuePlaceholder(syntax, this.LocalScopeDepth, type); BoundExpression deconstructInvocation = MakeDeconstructInvocationExpression(variables.Count, inputPlaceholder, rightSyntax, diagnostics, outPlaceholders: out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, out _); if (deconstructInvocation.HasAnyErrors) { return false; } deconstructMethod = new DeconstructMethodInfo(deconstructInvocation, inputPlaceholder, outPlaceholders); tupleOrDeconstructedTypes = outPlaceholders.SelectAsArray(p => p.Type); SetInferredTypes(variables, tupleOrDeconstructedTypes, diagnostics); } // Figure out whether those types will need conversions, including further deconstructions bool hasErrors = false; int count = variables.Count; var nestedConversions = ArrayBuilder<Conversion>.GetInstance(count); for (int i = 0; i < count; i++) { var variable = variables[i]; Conversion nestedConversion; if (variable.NestedVariables is object) { var elementSyntax = syntax.Kind() == SyntaxKind.TupleExpression ? ((TupleExpressionSyntax)syntax).Arguments[i] : syntax; hasErrors |= !MakeDeconstructionConversion(tupleOrDeconstructedTypes[i], elementSyntax, rightSyntax, diagnostics, variable.NestedVariables, out nestedConversion); } else { var single = variable.Single; Debug.Assert(single is object); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); nestedConversion = this.Conversions.ClassifyConversionFromType(tupleOrDeconstructedTypes[i], single.Type, ref useSiteInfo); diagnostics.Add(single.Syntax, useSiteInfo); if (!nestedConversion.IsImplicit) { hasErrors = true; GenerateImplicitConversionError(diagnostics, Compilation, single.Syntax, nestedConversion, tupleOrDeconstructedTypes[i], single.Type); } } nestedConversions.Add(nestedConversion); } conversion = new Conversion(ConversionKind.Deconstruction, deconstructMethod, nestedConversions.ToImmutableAndFree()); return !hasErrors; } /// <summary> /// Inform the variables about found types. /// </summary> private void SetInferredTypes(ArrayBuilder<DeconstructionVariable> variables, ImmutableArray<TypeSymbol> foundTypes, BindingDiagnosticBag diagnostics) { var matchCount = Math.Min(variables.Count, foundTypes.Length); for (int i = 0; i < matchCount; i++) { var variable = variables[i]; if (variable.Single is { } pending) { if ((object?)pending.Type != null) { continue; } variables[i] = new DeconstructionVariable(SetInferredType(pending, foundTypes[i], diagnostics), variable.Syntax); } } } private BoundExpression SetInferredType(BoundExpression expression, TypeSymbol type, BindingDiagnosticBag diagnostics) { switch (expression.Kind) { case BoundKind.DeconstructionVariablePendingInference: { var pending = (DeconstructionVariablePendingInference)expression; return pending.SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(type), this, diagnostics); } case BoundKind.DiscardExpression: { var pending = (BoundDiscardExpression)expression; Debug.Assert((object?)pending.Type == null); return pending.SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(type)); } default: throw ExceptionUtilities.UnexpectedValue(expression.Kind); } } /// <summary> /// Find any deconstruction locals that are still pending inference and fail their inference. /// Set the safe-to-escape scope for all deconstruction locals. /// </summary> private void FailRemainingInferencesAndSetValEscape(ArrayBuilder<DeconstructionVariable> variables, BindingDiagnosticBag diagnostics, uint rhsValEscape) { int count = variables.Count; for (int i = 0; i < count; i++) { var variable = variables[i]; if (variable.NestedVariables is object) { FailRemainingInferencesAndSetValEscape(variable.NestedVariables, diagnostics, rhsValEscape); } else { Debug.Assert(variable.Single is object); switch (variable.Single.Kind) { case BoundKind.Local: var local = (BoundLocal)variable.Single; if (local.DeclarationKind != BoundLocalDeclarationKind.None) { ((SourceLocalSymbol)local.LocalSymbol).SetValEscape(rhsValEscape); } break; case BoundKind.DeconstructionVariablePendingInference: BoundExpression errorLocal = ((DeconstructionVariablePendingInference)variable.Single).FailInference(this, diagnostics); variables[i] = new DeconstructionVariable(errorLocal, errorLocal.Syntax); break; case BoundKind.DiscardExpression: var pending = (BoundDiscardExpression)variable.Single; if ((object?)pending.Type == null) { Error(diagnostics, ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, pending.Syntax, "_"); variables[i] = new DeconstructionVariable(pending.FailInference(this, diagnostics), pending.Syntax); } break; } // at this point we expect to have a type for every lvalue Debug.Assert((object?)variables[i].Single!.Type != null); } } } /// <summary> /// Holds the variables on the LHS of a deconstruction as a tree of bound expressions. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal sealed class DeconstructionVariable { internal readonly BoundExpression? Single; internal readonly ArrayBuilder<DeconstructionVariable>? NestedVariables; internal readonly CSharpSyntaxNode Syntax; internal DeconstructionVariable(BoundExpression variable, SyntaxNode syntax) { Single = variable; NestedVariables = null; Syntax = (CSharpSyntaxNode)syntax; } internal DeconstructionVariable(ArrayBuilder<DeconstructionVariable> variables, SyntaxNode syntax) { Single = null; NestedVariables = variables; Syntax = (CSharpSyntaxNode)syntax; } internal static void FreeDeconstructionVariables(ArrayBuilder<DeconstructionVariable> variables) { variables.FreeAll(v => v.NestedVariables); } private string GetDebuggerDisplay() { if (Single != null) { return Single.GetDebuggerDisplay(); } Debug.Assert(NestedVariables is object); return $"Nested variables ({NestedVariables.Count})"; } } /// <summary> /// For cases where the RHS of a deconstruction-declaration is a tuple literal, we merge type information from both the LHS and RHS. /// For cases where the RHS of a deconstruction-assignment is a tuple literal, the type information from the LHS determines the merged type, since all variables have a type. /// Returns null if a merged tuple type could not be fabricated. /// </summary> private TypeSymbol? MakeMergedTupleType(ArrayBuilder<DeconstructionVariable> lhsVariables, BoundTupleLiteral rhsLiteral, CSharpSyntaxNode syntax, BindingDiagnosticBag? diagnostics) { int leftLength = lhsVariables.Count; int rightLength = rhsLiteral.Arguments.Length; var typesWithAnnotationsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(leftLength); var locationsBuilder = ArrayBuilder<Location?>.GetInstance(leftLength); for (int i = 0; i < rightLength; i++) { BoundExpression element = rhsLiteral.Arguments[i]; TypeSymbol? mergedType = element.Type; if (i < leftLength) { var variable = lhsVariables[i]; if (variable.NestedVariables is object) { if (element.Kind == BoundKind.TupleLiteral) { // (variables) on the left and (elements) on the right mergedType = MakeMergedTupleType(variable.NestedVariables, (BoundTupleLiteral)element, syntax, diagnostics); } else if ((object?)mergedType == null && diagnostics is object) { // (variables) on the left and null on the right Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, element.Syntax); } } else { Debug.Assert(variable.Single is object); if ((object?)variable.Single.Type != null) { // typed-variable on the left mergedType = variable.Single.Type; } } } else { if ((object?)mergedType == null && diagnostics is object) { // a typeless element on the right, matching no variable on the left Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, element.Syntax); } } typesWithAnnotationsBuilder.Add(TypeWithAnnotations.Create(mergedType)); locationsBuilder.Add(element.Syntax.Location); } if (typesWithAnnotationsBuilder.Any(t => !t.HasType)) { typesWithAnnotationsBuilder.Free(); locationsBuilder.Free(); return null; } // The tuple created here is not identical to the one created by // DeconstructionVariablesAsTuple. It represents a smaller // tree of types used for figuring out natural types in tuple literal. return NamedTypeSymbol.CreateTuple( locationOpt: null, elementTypesWithAnnotations: typesWithAnnotationsBuilder.ToImmutableAndFree(), elementLocations: locationsBuilder.ToImmutableAndFree(), elementNames: default(ImmutableArray<string?>), compilation: Compilation, diagnostics: diagnostics, shouldCheckConstraints: true, includeNullability: false, errorPositions: default(ImmutableArray<bool>), syntax: syntax); } private BoundTupleExpression DeconstructionVariablesAsTuple(CSharpSyntaxNode syntax, ArrayBuilder<DeconstructionVariable> variables, BindingDiagnosticBag diagnostics, bool ignoreDiagnosticsFromTuple) { int count = variables.Count; var valuesBuilder = ArrayBuilder<BoundExpression>.GetInstance(count); var typesWithAnnotationsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(count); var locationsBuilder = ArrayBuilder<Location?>.GetInstance(count); var namesBuilder = ArrayBuilder<string?>.GetInstance(count); foreach (var variable in variables) { BoundExpression value; if (variable.NestedVariables is object) { value = DeconstructionVariablesAsTuple(variable.Syntax, variable.NestedVariables, diagnostics, ignoreDiagnosticsFromTuple); namesBuilder.Add(null); } else { Debug.Assert(variable.Single is object); value = variable.Single; namesBuilder.Add(ExtractDeconstructResultElementName(value)); } valuesBuilder.Add(value); typesWithAnnotationsBuilder.Add(TypeWithAnnotations.Create(value.Type)); locationsBuilder.Add(variable.Syntax.Location); } ImmutableArray<BoundExpression> arguments = valuesBuilder.ToImmutableAndFree(); var uniqueFieldNames = PooledHashSet<string>.GetInstance(); RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref namesBuilder, uniqueFieldNames); uniqueFieldNames.Free(); ImmutableArray<string?> tupleNames = namesBuilder is null ? default : namesBuilder.ToImmutableAndFree(); ImmutableArray<bool> inferredPositions = tupleNames.IsDefault ? default : tupleNames.SelectAsArray(n => n != null); bool disallowInferredNames = this.Compilation.LanguageVersion.DisallowInferredTupleElementNames(); var type = NamedTypeSymbol.CreateTuple( syntax.Location, typesWithAnnotationsBuilder.ToImmutableAndFree(), locationsBuilder.ToImmutableAndFree(), tupleNames, this.Compilation, shouldCheckConstraints: !ignoreDiagnosticsFromTuple, includeNullability: false, errorPositions: disallowInferredNames ? inferredPositions : default, syntax: syntax, diagnostics: ignoreDiagnosticsFromTuple ? null : diagnostics); return (BoundTupleExpression)BindToNaturalType(new BoundTupleLiteral(syntax, arguments, tupleNames, inferredPositions, type), diagnostics); } /// <summary>Extract inferred name from a single deconstruction variable.</summary> private static string? ExtractDeconstructResultElementName(BoundExpression expression) { if (expression.Kind == BoundKind.DiscardExpression) { return null; } return InferTupleElementName(expression.Syntax); } /// <summary> /// Find the Deconstruct method for the expression on the right, that will fit the number of assignable variables on the left. /// Returns an invocation expression if the Deconstruct method is found. /// If so, it outputs placeholders that were coerced to the output types of the resolved Deconstruct method. /// The overload resolution is similar to writing <c>receiver.Deconstruct(out var x1, out var x2, ...)</c>. /// </summary> private BoundExpression MakeDeconstructInvocationExpression( int numCheckedVariables, BoundExpression receiver, SyntaxNode rightSyntax, BindingDiagnosticBag diagnostics, out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, out bool anyApplicableCandidates) { anyApplicableCandidates = false; var receiverSyntax = (CSharpSyntaxNode)receiver.Syntax; if (receiver.Type?.IsDynamic() ?? false) { Error(diagnostics, ErrorCode.ERR_CannotDeconstructDynamic, rightSyntax); outPlaceholders = default(ImmutableArray<BoundDeconstructValuePlaceholder>); return BadExpression(receiverSyntax, receiver); } receiver = BindToNaturalType(receiver, diagnostics); var analyzedArguments = AnalyzedArguments.GetInstance(); var outVars = ArrayBuilder<OutDeconstructVarPendingInference>.GetInstance(numCheckedVariables); try { for (int i = 0; i < numCheckedVariables; i++) { var variable = new OutDeconstructVarPendingInference(receiverSyntax); analyzedArguments.Arguments.Add(variable); analyzedArguments.RefKinds.Add(RefKind.Out); outVars.Add(variable); } const string methodName = WellKnownMemberNames.DeconstructMethodName; var memberAccess = BindInstanceMemberAccess( rightSyntax, receiverSyntax, receiver, methodName, rightArity: 0, typeArgumentsSyntax: default(SeparatedSyntaxList<TypeSyntax>), typeArgumentsWithAnnotations: default(ImmutableArray<TypeWithAnnotations>), invoked: true, indexed: false, diagnostics: diagnostics); memberAccess = CheckValue(memberAccess, BindValueKind.RValueOrMethodGroup, diagnostics); memberAccess.WasCompilerGenerated = true; if (memberAccess.Kind != BoundKind.MethodGroup) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, receiver); } // After the overload resolution completes, the last step is to coerce the arguments with inferred types. // That step returns placeholder (of correct type) instead of the outVar nodes that were passed in as arguments. // So the generated invocation expression will contain placeholders instead of those outVar nodes. // Those placeholders are also recorded in the outVar for easy access below, by the `SetInferredType` call on the outVar nodes. BoundExpression result = BindMethodGroupInvocation( rightSyntax, rightSyntax, methodName, (BoundMethodGroup)memberAccess, analyzedArguments, diagnostics, queryClause: null, allowUnexpandedForm: true, anyApplicableCandidates: out anyApplicableCandidates); result.WasCompilerGenerated = true; if (!anyApplicableCandidates) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } // Verify all the parameters (except "this" for extension methods) are out parameters. // This prevents, for example, an unused params parameter after the out parameters. var deconstructMethod = ((BoundCall)result).Method; var parameters = deconstructMethod.Parameters; for (int i = (deconstructMethod.IsExtensionMethod ? 1 : 0); i < parameters.Length; i++) { if (parameters[i].RefKind != RefKind.Out) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } } if (deconstructMethod.ReturnType.GetSpecialTypeSafe() != SpecialType.System_Void) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } if (outVars.Any(v => v.Placeholder is null)) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } outPlaceholders = outVars.SelectAsArray(v => v.Placeholder!); return result; } finally { analyzedArguments.Free(); outVars.Free(); } } private BoundBadExpression MissingDeconstruct(BoundExpression receiver, SyntaxNode rightSyntax, int numParameters, BindingDiagnosticBag diagnostics, out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, BoundExpression childNode) { if (receiver.Type?.IsErrorType() == false) { Error(diagnostics, ErrorCode.ERR_MissingDeconstruct, rightSyntax, receiver.Type!, numParameters); } outPlaceholders = default; return BadExpression(rightSyntax, childNode); } /// <summary> /// Prepares locals (or fields in global statement) and lvalue expressions corresponding to the variables of the declaration. /// The locals/fields/lvalues are kept in a tree which captures the nesting of variables. /// Each local or field is either a simple local or field access (when its type is known) or a deconstruction variable pending inference. /// The caller is responsible for releasing the nested ArrayBuilders. /// </summary> private DeconstructionVariable BindDeconstructionVariables( ExpressionSyntax node, BindingDiagnosticBag diagnostics, ref DeclarationExpressionSyntax? declaration, ref ExpressionSyntax? expression) { switch (node.Kind()) { case SyntaxKind.DeclarationExpression: { var component = (DeclarationExpressionSyntax)node; if (declaration == null) { declaration = component; } bool isVar; bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(component.Designation, diagnostics, component.Type, ref isConst, out isVar, out alias); Debug.Assert(isVar == !declType.HasType); if (component.Designation.Kind() == SyntaxKind.ParenthesizedVariableDesignation && !isVar) { // An explicit is not allowed with a parenthesized designation Error(diagnostics, ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, component.Designation); } return BindDeconstructionVariables(declType, component.Designation, component, diagnostics); } case SyntaxKind.TupleExpression: { var component = (TupleExpressionSyntax)node; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(component.Arguments.Count); foreach (var arg in component.Arguments) { if (arg.NameColon != null) { Error(diagnostics, ErrorCode.ERR_TupleElementNamesInDeconstruction, arg.NameColon); } builder.Add(BindDeconstructionVariables(arg.Expression, diagnostics, ref declaration, ref expression)); } return new DeconstructionVariable(builder, node); } default: var boundVariable = BindExpression(node, diagnostics, invoked: false, indexed: false); var checkedVariable = CheckValue(boundVariable, BindValueKind.Assignable, diagnostics); if (expression == null && checkedVariable.Kind != BoundKind.DiscardExpression) { expression = node; } return new DeconstructionVariable(checkedVariable, node); } } private DeconstructionVariable BindDeconstructionVariables( TypeWithAnnotations declTypeWithAnnotations, VariableDesignationSyntax node, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.SingleVariableDesignation: { var single = (SingleVariableDesignationSyntax)node; return new DeconstructionVariable(BindDeconstructionVariable(declTypeWithAnnotations, single, syntax, diagnostics), syntax); } case SyntaxKind.DiscardDesignation: { var discarded = (DiscardDesignationSyntax)node; return new DeconstructionVariable(BindDiscardExpression(syntax, declTypeWithAnnotations), syntax); } case SyntaxKind.ParenthesizedVariableDesignation: { var tuple = (ParenthesizedVariableDesignationSyntax)node; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(); foreach (var n in tuple.Variables) { builder.Add(BindDeconstructionVariables(declTypeWithAnnotations, n, n, diagnostics)); } return new DeconstructionVariable(builder, syntax); } default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } private static BoundDiscardExpression BindDiscardExpression( SyntaxNode syntax, TypeWithAnnotations declTypeWithAnnotations) { return new BoundDiscardExpression(syntax, declTypeWithAnnotations.Type); } /// <summary> /// In embedded statements, returns a BoundLocal when the type was explicit. /// In global statements, returns a BoundFieldAccess when the type was explicit. /// Otherwise returns a DeconstructionVariablePendingInference when the type is implicit. /// </summary> private BoundExpression BindDeconstructionVariable( TypeWithAnnotations declTypeWithAnnotations, SingleVariableDesignationSyntax designation, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { SourceLocalSymbol localSymbol = LookupLocal(designation.Identifier); // is this a local? if ((object)localSymbol != null) { // Check for variable declaration errors. // Use the binder that owns the scope for the local because this (the current) binder // might own nested scope. var hasErrors = localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); if (declTypeWithAnnotations.HasType) { return new BoundLocal(syntax, localSymbol, BoundLocalDeclarationKind.WithExplicitType, constantValueOpt: null, isNullableUnknown: false, type: declTypeWithAnnotations.Type, hasErrors: hasErrors); } return new DeconstructionVariablePendingInference(syntax, localSymbol, receiverOpt: null); } // Is this a field? GlobalExpressionVariable field = LookupDeclaredField(designation); if ((object)field == null) { // We should have the right binder in the chain, cannot continue otherwise. throw ExceptionUtilities.Unreachable; } BoundThisReference receiver = ThisReference(designation, this.ContainingType, hasErrors: false, wasCompilerGenerated: true); if (declTypeWithAnnotations.HasType) { var fieldType = field.GetFieldType(this.FieldsBeingBound); Debug.Assert(TypeSymbol.Equals(declTypeWithAnnotations.Type, fieldType.Type, TypeCompareKind.ConsiderEverything2)); return new BoundFieldAccess(syntax, receiver, field, constantValueOpt: null, resultKind: LookupResultKind.Viable, isDeclaration: true, type: fieldType.Type); } return new DeconstructionVariablePendingInference(syntax, field, receiver); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts deconstruction-assignment syntax (AssignmentExpressionSyntax nodes with the left /// being a tuple expression or declaration expression) into a BoundDeconstructionAssignmentOperator (or bad node). /// The BoundDeconstructionAssignmentOperator will have: /// - a BoundTupleLiteral as its Left, /// - a BoundConversion as its Right, holding: /// - a tree of Conversion objects with Kind=Deconstruction, information about a Deconstruct method (optional) and /// an array of nested Conversions (like a tuple conversion), /// - a BoundExpression as its Operand. /// </summary> internal partial class Binder { internal BoundExpression BindDeconstruction(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics, bool resultIsUsedOverride = false) { var left = node.Left; var right = node.Right; DeclarationExpressionSyntax? declaration = null; ExpressionSyntax? expression = null; var result = BindDeconstruction(node, left, right, diagnostics, ref declaration, ref expression, resultIsUsedOverride); if (declaration != null) { // only allowed at the top level, or in a for loop switch (node.Parent?.Kind()) { case null: case SyntaxKind.ExpressionStatement: if (expression != null) { MessageID.IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction .CheckFeatureAvailability(diagnostics, Compilation, node.Location); } break; case SyntaxKind.ForStatement: if (((ForStatementSyntax)node.Parent).Initializers.Contains(node)) { if (expression != null) { MessageID.IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction .CheckFeatureAvailability(diagnostics, Compilation, node.Location); } } else { Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, declaration); } break; default: Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, declaration); break; } } return result; } /// <summary> /// Bind a deconstruction assignment. /// </summary> /// <param name="deconstruction">The deconstruction operation</param> /// <param name="left">The left (tuple) operand</param> /// <param name="right">The right (deconstructable) operand</param> /// <param name="diagnostics">Where to report diagnostics</param> /// <param name="declaration">A variable set to the first variable declaration found in the left</param> /// <param name="expression">A variable set to the first expression in the left that isn't a declaration or discard</param> /// <param name="resultIsUsedOverride">The expression evaluator needs to bind deconstructions (both assignments and declarations) as expression-statements /// and still access the returned value</param> /// <param name="rightPlaceholder"></param> /// <returns></returns> internal BoundDeconstructionAssignmentOperator BindDeconstruction( CSharpSyntaxNode deconstruction, ExpressionSyntax left, ExpressionSyntax right, BindingDiagnosticBag diagnostics, ref DeclarationExpressionSyntax? declaration, ref ExpressionSyntax? expression, bool resultIsUsedOverride = false, BoundDeconstructValuePlaceholder? rightPlaceholder = null) { DeconstructionVariable locals = BindDeconstructionVariables(left, diagnostics, ref declaration, ref expression); Debug.Assert(locals.NestedVariables is object); var deconstructionDiagnostics = new BindingDiagnosticBag(new DiagnosticBag(), diagnostics.DependenciesBag); BoundExpression boundRight = rightPlaceholder ?? BindValue(right, deconstructionDiagnostics, BindValueKind.RValue); boundRight = FixTupleLiteral(locals.NestedVariables, boundRight, deconstruction, deconstructionDiagnostics); boundRight = BindToNaturalType(boundRight, diagnostics); bool resultIsUsed = resultIsUsedOverride || IsDeconstructionResultUsed(left); var assignment = BindDeconstructionAssignment(deconstruction, left, boundRight, locals.NestedVariables, resultIsUsed, deconstructionDiagnostics); DeconstructionVariable.FreeDeconstructionVariables(locals.NestedVariables); diagnostics.AddRange(deconstructionDiagnostics.DiagnosticBag); return assignment; } private BoundDeconstructionAssignmentOperator BindDeconstructionAssignment( CSharpSyntaxNode node, ExpressionSyntax left, BoundExpression boundRHS, ArrayBuilder<DeconstructionVariable> checkedVariables, bool resultIsUsed, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics.DiagnosticBag is object); uint rightEscape = GetValEscape(boundRHS, this.LocalScopeDepth); if ((object?)boundRHS.Type == null || boundRHS.Type.IsErrorType()) { // we could still not infer a type for the RHS FailRemainingInferencesAndSetValEscape(checkedVariables, diagnostics, rightEscape); var voidType = GetSpecialType(SpecialType.System_Void, diagnostics, node); var type = boundRHS.Type ?? voidType; return new BoundDeconstructionAssignmentOperator( node, DeconstructionVariablesAsTuple(left, checkedVariables, diagnostics, ignoreDiagnosticsFromTuple: true), new BoundConversion(boundRHS.Syntax, boundRHS, Conversion.Deconstruction, @checked: false, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, type: type, hasErrors: true), resultIsUsed, voidType, hasErrors: true); } Conversion conversion; bool hasErrors = !MakeDeconstructionConversion( boundRHS.Type, node, boundRHS.Syntax, diagnostics, checkedVariables, out conversion); if (conversion.Method != null) { CheckImplicitThisCopyInReadOnlyMember(boundRHS, conversion.Method, diagnostics); } FailRemainingInferencesAndSetValEscape(checkedVariables, diagnostics, rightEscape); var lhsTuple = DeconstructionVariablesAsTuple(left, checkedVariables, diagnostics, ignoreDiagnosticsFromTuple: diagnostics.HasAnyErrors() || !resultIsUsed); Debug.Assert(hasErrors || lhsTuple.Type is object); TypeSymbol returnType = hasErrors ? CreateErrorType() : lhsTuple.Type!; uint leftEscape = GetBroadestValEscape(lhsTuple, this.LocalScopeDepth); boundRHS = ValidateEscape(boundRHS, leftEscape, isByRef: false, diagnostics: diagnostics); var boundConversion = new BoundConversion( boundRHS.Syntax, boundRHS, conversion, @checked: false, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, type: returnType, hasErrors: hasErrors) { WasCompilerGenerated = true }; return new BoundDeconstructionAssignmentOperator(node, lhsTuple, boundConversion, resultIsUsed, returnType); } private static bool IsDeconstructionResultUsed(ExpressionSyntax left) { var parent = left.Parent; if (parent is null || parent.Kind() == SyntaxKind.ForEachVariableStatement) { return false; } Debug.Assert(parent.Kind() == SyntaxKind.SimpleAssignmentExpression); var grandParent = parent.Parent; if (grandParent is null) { return false; } switch (grandParent.Kind()) { case SyntaxKind.ExpressionStatement: return ((ExpressionStatementSyntax)grandParent).Expression != parent; case SyntaxKind.ForStatement: // Incrementors and Initializers don't have to produce a value var loop = (ForStatementSyntax)grandParent; return !loop.Incrementors.Contains(parent) && !loop.Initializers.Contains(parent); default: return true; } } /// <summary>When boundRHS is a tuple literal, fix it up by inferring its types.</summary> private BoundExpression FixTupleLiteral(ArrayBuilder<DeconstructionVariable> checkedVariables, BoundExpression boundRHS, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics.DiagnosticBag is object); if (boundRHS.Kind == BoundKind.TupleLiteral) { // Let's fix the literal up by figuring out its type // For declarations, that means merging type information from the LHS and RHS // For assignments, only the LHS side matters since it is necessarily typed // If we already have diagnostics at this point, it is not worth collecting likely duplicate diagnostics from making the merged type bool hadErrors = diagnostics.HasAnyErrors(); TypeSymbol? mergedTupleType = MakeMergedTupleType(checkedVariables, (BoundTupleLiteral)boundRHS, syntax, hadErrors ? null : diagnostics); if ((object?)mergedTupleType != null) { boundRHS = GenerateConversionForAssignment(mergedTupleType, boundRHS, diagnostics); } } else if ((object?)boundRHS.Type == null) { Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, boundRHS.Syntax); } return boundRHS; } /// <summary> /// Recursively builds a Conversion object with Kind=Deconstruction including information about any necessary /// Deconstruct method and any element-wise conversion. /// /// Note that the variables may either be plain or nested variables. /// The variables may be updated with inferred types if they didn't have types initially. /// Returns false if there was an error. /// </summary> private bool MakeDeconstructionConversion( TypeSymbol type, SyntaxNode syntax, SyntaxNode rightSyntax, BindingDiagnosticBag diagnostics, ArrayBuilder<DeconstructionVariable> variables, out Conversion conversion) { Debug.Assert((object)type != null); ImmutableArray<TypeSymbol> tupleOrDeconstructedTypes; conversion = Conversion.Deconstruction; // Figure out the deconstruct method (if one is required) and determine the types we get from the RHS at this level var deconstructMethod = default(DeconstructMethodInfo); if (type.IsTupleType) { // tuple literal such as `(1, 2)`, `(null, null)`, `(x.P, y.M())` tupleOrDeconstructedTypes = type.TupleElementTypesWithAnnotations.SelectAsArray(TypeMap.AsTypeSymbol); SetInferredTypes(variables, tupleOrDeconstructedTypes, diagnostics); if (variables.Count != tupleOrDeconstructedTypes.Length) { Error(diagnostics, ErrorCode.ERR_DeconstructWrongCardinality, syntax, tupleOrDeconstructedTypes.Length, variables.Count); return false; } } else { if (variables.Count < 2) { Error(diagnostics, ErrorCode.ERR_DeconstructTooFewElements, syntax); return false; } var inputPlaceholder = new BoundDeconstructValuePlaceholder(syntax, this.LocalScopeDepth, type); BoundExpression deconstructInvocation = MakeDeconstructInvocationExpression(variables.Count, inputPlaceholder, rightSyntax, diagnostics, outPlaceholders: out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, out _); if (deconstructInvocation.HasAnyErrors) { return false; } deconstructMethod = new DeconstructMethodInfo(deconstructInvocation, inputPlaceholder, outPlaceholders); tupleOrDeconstructedTypes = outPlaceholders.SelectAsArray(p => p.Type); SetInferredTypes(variables, tupleOrDeconstructedTypes, diagnostics); } // Figure out whether those types will need conversions, including further deconstructions bool hasErrors = false; int count = variables.Count; var nestedConversions = ArrayBuilder<Conversion>.GetInstance(count); for (int i = 0; i < count; i++) { var variable = variables[i]; Conversion nestedConversion; if (variable.NestedVariables is object) { var elementSyntax = syntax.Kind() == SyntaxKind.TupleExpression ? ((TupleExpressionSyntax)syntax).Arguments[i] : syntax; hasErrors |= !MakeDeconstructionConversion(tupleOrDeconstructedTypes[i], elementSyntax, rightSyntax, diagnostics, variable.NestedVariables, out nestedConversion); } else { var single = variable.Single; Debug.Assert(single is object); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); nestedConversion = this.Conversions.ClassifyConversionFromType(tupleOrDeconstructedTypes[i], single.Type, ref useSiteInfo); diagnostics.Add(single.Syntax, useSiteInfo); if (!nestedConversion.IsImplicit) { hasErrors = true; GenerateImplicitConversionError(diagnostics, Compilation, single.Syntax, nestedConversion, tupleOrDeconstructedTypes[i], single.Type); } } nestedConversions.Add(nestedConversion); } conversion = new Conversion(ConversionKind.Deconstruction, deconstructMethod, nestedConversions.ToImmutableAndFree()); return !hasErrors; } /// <summary> /// Inform the variables about found types. /// </summary> private void SetInferredTypes(ArrayBuilder<DeconstructionVariable> variables, ImmutableArray<TypeSymbol> foundTypes, BindingDiagnosticBag diagnostics) { var matchCount = Math.Min(variables.Count, foundTypes.Length); for (int i = 0; i < matchCount; i++) { var variable = variables[i]; if (variable.Single is { } pending) { if ((object?)pending.Type != null) { continue; } variables[i] = new DeconstructionVariable(SetInferredType(pending, foundTypes[i], diagnostics), variable.Syntax); } } } private BoundExpression SetInferredType(BoundExpression expression, TypeSymbol type, BindingDiagnosticBag diagnostics) { switch (expression.Kind) { case BoundKind.DeconstructionVariablePendingInference: { var pending = (DeconstructionVariablePendingInference)expression; return pending.SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(type), this, diagnostics); } case BoundKind.DiscardExpression: { var pending = (BoundDiscardExpression)expression; Debug.Assert((object?)pending.Type == null); return pending.SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(type)); } default: throw ExceptionUtilities.UnexpectedValue(expression.Kind); } } /// <summary> /// Find any deconstruction locals that are still pending inference and fail their inference. /// Set the safe-to-escape scope for all deconstruction locals. /// </summary> private void FailRemainingInferencesAndSetValEscape(ArrayBuilder<DeconstructionVariable> variables, BindingDiagnosticBag diagnostics, uint rhsValEscape) { int count = variables.Count; for (int i = 0; i < count; i++) { var variable = variables[i]; if (variable.NestedVariables is object) { FailRemainingInferencesAndSetValEscape(variable.NestedVariables, diagnostics, rhsValEscape); } else { Debug.Assert(variable.Single is object); switch (variable.Single.Kind) { case BoundKind.Local: var local = (BoundLocal)variable.Single; if (local.DeclarationKind != BoundLocalDeclarationKind.None) { ((SourceLocalSymbol)local.LocalSymbol).SetValEscape(rhsValEscape); } break; case BoundKind.DeconstructionVariablePendingInference: BoundExpression errorLocal = ((DeconstructionVariablePendingInference)variable.Single).FailInference(this, diagnostics); variables[i] = new DeconstructionVariable(errorLocal, errorLocal.Syntax); break; case BoundKind.DiscardExpression: var pending = (BoundDiscardExpression)variable.Single; if ((object?)pending.Type == null) { Error(diagnostics, ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, pending.Syntax, "_"); variables[i] = new DeconstructionVariable(pending.FailInference(this, diagnostics), pending.Syntax); } break; } // at this point we expect to have a type for every lvalue Debug.Assert((object?)variables[i].Single!.Type != null); } } } /// <summary> /// Holds the variables on the LHS of a deconstruction as a tree of bound expressions. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal sealed class DeconstructionVariable { internal readonly BoundExpression? Single; internal readonly ArrayBuilder<DeconstructionVariable>? NestedVariables; internal readonly CSharpSyntaxNode Syntax; internal DeconstructionVariable(BoundExpression variable, SyntaxNode syntax) { Single = variable; NestedVariables = null; Syntax = (CSharpSyntaxNode)syntax; } internal DeconstructionVariable(ArrayBuilder<DeconstructionVariable> variables, SyntaxNode syntax) { Single = null; NestedVariables = variables; Syntax = (CSharpSyntaxNode)syntax; } internal static void FreeDeconstructionVariables(ArrayBuilder<DeconstructionVariable> variables) { variables.FreeAll(v => v.NestedVariables); } private string GetDebuggerDisplay() { if (Single != null) { return Single.GetDebuggerDisplay(); } Debug.Assert(NestedVariables is object); return $"Nested variables ({NestedVariables.Count})"; } } /// <summary> /// For cases where the RHS of a deconstruction-declaration is a tuple literal, we merge type information from both the LHS and RHS. /// For cases where the RHS of a deconstruction-assignment is a tuple literal, the type information from the LHS determines the merged type, since all variables have a type. /// Returns null if a merged tuple type could not be fabricated. /// </summary> private TypeSymbol? MakeMergedTupleType(ArrayBuilder<DeconstructionVariable> lhsVariables, BoundTupleLiteral rhsLiteral, CSharpSyntaxNode syntax, BindingDiagnosticBag? diagnostics) { int leftLength = lhsVariables.Count; int rightLength = rhsLiteral.Arguments.Length; var typesWithAnnotationsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(leftLength); var locationsBuilder = ArrayBuilder<Location?>.GetInstance(leftLength); for (int i = 0; i < rightLength; i++) { BoundExpression element = rhsLiteral.Arguments[i]; TypeSymbol? mergedType = element.Type; if (i < leftLength) { var variable = lhsVariables[i]; if (variable.NestedVariables is object) { if (element.Kind == BoundKind.TupleLiteral) { // (variables) on the left and (elements) on the right mergedType = MakeMergedTupleType(variable.NestedVariables, (BoundTupleLiteral)element, syntax, diagnostics); } else if ((object?)mergedType == null && diagnostics is object) { // (variables) on the left and null on the right Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, element.Syntax); } } else { Debug.Assert(variable.Single is object); if ((object?)variable.Single.Type != null) { // typed-variable on the left mergedType = variable.Single.Type; } } } else { if ((object?)mergedType == null && diagnostics is object) { // a typeless element on the right, matching no variable on the left Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, element.Syntax); } } typesWithAnnotationsBuilder.Add(TypeWithAnnotations.Create(mergedType)); locationsBuilder.Add(element.Syntax.Location); } if (typesWithAnnotationsBuilder.Any(t => !t.HasType)) { typesWithAnnotationsBuilder.Free(); locationsBuilder.Free(); return null; } // The tuple created here is not identical to the one created by // DeconstructionVariablesAsTuple. It represents a smaller // tree of types used for figuring out natural types in tuple literal. return NamedTypeSymbol.CreateTuple( locationOpt: null, elementTypesWithAnnotations: typesWithAnnotationsBuilder.ToImmutableAndFree(), elementLocations: locationsBuilder.ToImmutableAndFree(), elementNames: default(ImmutableArray<string?>), compilation: Compilation, diagnostics: diagnostics, shouldCheckConstraints: true, includeNullability: false, errorPositions: default(ImmutableArray<bool>), syntax: syntax); } private BoundTupleExpression DeconstructionVariablesAsTuple(CSharpSyntaxNode syntax, ArrayBuilder<DeconstructionVariable> variables, BindingDiagnosticBag diagnostics, bool ignoreDiagnosticsFromTuple) { int count = variables.Count; var valuesBuilder = ArrayBuilder<BoundExpression>.GetInstance(count); var typesWithAnnotationsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(count); var locationsBuilder = ArrayBuilder<Location?>.GetInstance(count); var namesBuilder = ArrayBuilder<string?>.GetInstance(count); foreach (var variable in variables) { BoundExpression value; if (variable.NestedVariables is object) { value = DeconstructionVariablesAsTuple(variable.Syntax, variable.NestedVariables, diagnostics, ignoreDiagnosticsFromTuple); namesBuilder.Add(null); } else { Debug.Assert(variable.Single is object); value = variable.Single; namesBuilder.Add(ExtractDeconstructResultElementName(value)); } valuesBuilder.Add(value); typesWithAnnotationsBuilder.Add(TypeWithAnnotations.Create(value.Type)); locationsBuilder.Add(variable.Syntax.Location); } ImmutableArray<BoundExpression> arguments = valuesBuilder.ToImmutableAndFree(); var uniqueFieldNames = PooledHashSet<string>.GetInstance(); RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref namesBuilder, uniqueFieldNames); uniqueFieldNames.Free(); ImmutableArray<string?> tupleNames = namesBuilder is null ? default : namesBuilder.ToImmutableAndFree(); ImmutableArray<bool> inferredPositions = tupleNames.IsDefault ? default : tupleNames.SelectAsArray(n => n != null); bool disallowInferredNames = this.Compilation.LanguageVersion.DisallowInferredTupleElementNames(); var type = NamedTypeSymbol.CreateTuple( syntax.Location, typesWithAnnotationsBuilder.ToImmutableAndFree(), locationsBuilder.ToImmutableAndFree(), tupleNames, this.Compilation, shouldCheckConstraints: !ignoreDiagnosticsFromTuple, includeNullability: false, errorPositions: disallowInferredNames ? inferredPositions : default, syntax: syntax, diagnostics: ignoreDiagnosticsFromTuple ? null : diagnostics); return (BoundTupleExpression)BindToNaturalType(new BoundTupleLiteral(syntax, arguments, tupleNames, inferredPositions, type), diagnostics); } /// <summary>Extract inferred name from a single deconstruction variable.</summary> private static string? ExtractDeconstructResultElementName(BoundExpression expression) { if (expression.Kind == BoundKind.DiscardExpression) { return null; } return InferTupleElementName(expression.Syntax); } /// <summary> /// Find the Deconstruct method for the expression on the right, that will fit the number of assignable variables on the left. /// Returns an invocation expression if the Deconstruct method is found. /// If so, it outputs placeholders that were coerced to the output types of the resolved Deconstruct method. /// The overload resolution is similar to writing <c>receiver.Deconstruct(out var x1, out var x2, ...)</c>. /// </summary> private BoundExpression MakeDeconstructInvocationExpression( int numCheckedVariables, BoundExpression receiver, SyntaxNode rightSyntax, BindingDiagnosticBag diagnostics, out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, out bool anyApplicableCandidates) { anyApplicableCandidates = false; var receiverSyntax = (CSharpSyntaxNode)receiver.Syntax; if (receiver.Type?.IsDynamic() ?? false) { Error(diagnostics, ErrorCode.ERR_CannotDeconstructDynamic, rightSyntax); outPlaceholders = default(ImmutableArray<BoundDeconstructValuePlaceholder>); return BadExpression(receiverSyntax, receiver); } receiver = BindToNaturalType(receiver, diagnostics); var analyzedArguments = AnalyzedArguments.GetInstance(); var outVars = ArrayBuilder<OutDeconstructVarPendingInference>.GetInstance(numCheckedVariables); try { for (int i = 0; i < numCheckedVariables; i++) { var variable = new OutDeconstructVarPendingInference(receiverSyntax); analyzedArguments.Arguments.Add(variable); analyzedArguments.RefKinds.Add(RefKind.Out); outVars.Add(variable); } const string methodName = WellKnownMemberNames.DeconstructMethodName; var memberAccess = BindInstanceMemberAccess( rightSyntax, receiverSyntax, receiver, methodName, rightArity: 0, typeArgumentsSyntax: default(SeparatedSyntaxList<TypeSyntax>), typeArgumentsWithAnnotations: default(ImmutableArray<TypeWithAnnotations>), invoked: true, indexed: false, diagnostics: diagnostics); memberAccess = CheckValue(memberAccess, BindValueKind.RValueOrMethodGroup, diagnostics); memberAccess.WasCompilerGenerated = true; if (memberAccess.Kind != BoundKind.MethodGroup) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, receiver); } // After the overload resolution completes, the last step is to coerce the arguments with inferred types. // That step returns placeholder (of correct type) instead of the outVar nodes that were passed in as arguments. // So the generated invocation expression will contain placeholders instead of those outVar nodes. // Those placeholders are also recorded in the outVar for easy access below, by the `SetInferredType` call on the outVar nodes. BoundExpression result = BindMethodGroupInvocation( rightSyntax, rightSyntax, methodName, (BoundMethodGroup)memberAccess, analyzedArguments, diagnostics, queryClause: null, allowUnexpandedForm: true, anyApplicableCandidates: out anyApplicableCandidates); result.WasCompilerGenerated = true; if (!anyApplicableCandidates) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } // Verify all the parameters (except "this" for extension methods) are out parameters. // This prevents, for example, an unused params parameter after the out parameters. var deconstructMethod = ((BoundCall)result).Method; var parameters = deconstructMethod.Parameters; for (int i = (deconstructMethod.IsExtensionMethod ? 1 : 0); i < parameters.Length; i++) { if (parameters[i].RefKind != RefKind.Out) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } } if (deconstructMethod.ReturnType.GetSpecialTypeSafe() != SpecialType.System_Void) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } if (outVars.Any(v => v.Placeholder is null)) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } outPlaceholders = outVars.SelectAsArray(v => v.Placeholder!); return result; } finally { analyzedArguments.Free(); outVars.Free(); } } private BoundBadExpression MissingDeconstruct(BoundExpression receiver, SyntaxNode rightSyntax, int numParameters, BindingDiagnosticBag diagnostics, out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, BoundExpression childNode) { if (receiver.Type?.IsErrorType() == false) { Error(diagnostics, ErrorCode.ERR_MissingDeconstruct, rightSyntax, receiver.Type!, numParameters); } outPlaceholders = default; return BadExpression(rightSyntax, childNode); } /// <summary> /// Prepares locals (or fields in global statement) and lvalue expressions corresponding to the variables of the declaration. /// The locals/fields/lvalues are kept in a tree which captures the nesting of variables. /// Each local or field is either a simple local or field access (when its type is known) or a deconstruction variable pending inference. /// The caller is responsible for releasing the nested ArrayBuilders. /// </summary> private DeconstructionVariable BindDeconstructionVariables( ExpressionSyntax node, BindingDiagnosticBag diagnostics, ref DeclarationExpressionSyntax? declaration, ref ExpressionSyntax? expression) { switch (node.Kind()) { case SyntaxKind.DeclarationExpression: { var component = (DeclarationExpressionSyntax)node; if (declaration == null) { declaration = component; } bool isVar; bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(component.Designation, diagnostics, component.Type, ref isConst, out isVar, out alias); Debug.Assert(isVar == !declType.HasType); if (component.Designation.Kind() == SyntaxKind.ParenthesizedVariableDesignation && !isVar) { // An explicit is not allowed with a parenthesized designation Error(diagnostics, ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, component.Designation); } return BindDeconstructionVariables(declType, component.Designation, component, diagnostics); } case SyntaxKind.TupleExpression: { var component = (TupleExpressionSyntax)node; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(component.Arguments.Count); foreach (var arg in component.Arguments) { if (arg.NameColon != null) { Error(diagnostics, ErrorCode.ERR_TupleElementNamesInDeconstruction, arg.NameColon); } builder.Add(BindDeconstructionVariables(arg.Expression, diagnostics, ref declaration, ref expression)); } return new DeconstructionVariable(builder, node); } default: var boundVariable = BindExpression(node, diagnostics, invoked: false, indexed: false); var checkedVariable = CheckValue(boundVariable, BindValueKind.Assignable, diagnostics); if (expression == null && checkedVariable.Kind != BoundKind.DiscardExpression) { expression = node; } return new DeconstructionVariable(checkedVariable, node); } } private DeconstructionVariable BindDeconstructionVariables( TypeWithAnnotations declTypeWithAnnotations, VariableDesignationSyntax node, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.SingleVariableDesignation: { var single = (SingleVariableDesignationSyntax)node; return new DeconstructionVariable(BindDeconstructionVariable(declTypeWithAnnotations, single, syntax, diagnostics), syntax); } case SyntaxKind.DiscardDesignation: { var discarded = (DiscardDesignationSyntax)node; return new DeconstructionVariable(BindDiscardExpression(syntax, declTypeWithAnnotations), syntax); } case SyntaxKind.ParenthesizedVariableDesignation: { var tuple = (ParenthesizedVariableDesignationSyntax)node; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(); foreach (var n in tuple.Variables) { builder.Add(BindDeconstructionVariables(declTypeWithAnnotations, n, n, diagnostics)); } return new DeconstructionVariable(builder, syntax); } default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } private static BoundDiscardExpression BindDiscardExpression( SyntaxNode syntax, TypeWithAnnotations declTypeWithAnnotations) { return new BoundDiscardExpression(syntax, declTypeWithAnnotations.Type); } /// <summary> /// In embedded statements, returns a BoundLocal when the type was explicit. /// In global statements, returns a BoundFieldAccess when the type was explicit. /// Otherwise returns a DeconstructionVariablePendingInference when the type is implicit. /// </summary> private BoundExpression BindDeconstructionVariable( TypeWithAnnotations declTypeWithAnnotations, SingleVariableDesignationSyntax designation, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { SourceLocalSymbol localSymbol = LookupLocal(designation.Identifier); // is this a local? if ((object)localSymbol != null) { // Check for variable declaration errors. // Use the binder that owns the scope for the local because this (the current) binder // might own nested scope. var hasErrors = localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); if (declTypeWithAnnotations.HasType) { return new BoundLocal(syntax, localSymbol, BoundLocalDeclarationKind.WithExplicitType, constantValueOpt: null, isNullableUnknown: false, type: declTypeWithAnnotations.Type, hasErrors: hasErrors); } return new DeconstructionVariablePendingInference(syntax, localSymbol, receiverOpt: null); } // Is this a field? GlobalExpressionVariable field = LookupDeclaredField(designation); if ((object)field == null) { // We should have the right binder in the chain, cannot continue otherwise. throw ExceptionUtilities.Unreachable; } BoundThisReference receiver = ThisReference(designation, this.ContainingType, hasErrors: false, wasCompilerGenerated: true); if (declTypeWithAnnotations.HasType) { var fieldType = field.GetFieldType(this.FieldsBeingBound); Debug.Assert(TypeSymbol.Equals(declTypeWithAnnotations.Type, fieldType.Type, TypeCompareKind.ConsiderEverything2)); return new BoundFieldAccess(syntax, receiver, field, constantValueOpt: null, resultKind: LookupResultKind.Viable, isDeclaration: true, type: fieldType.Type); } return new DeconstructionVariablePendingInference(syntax, field, receiver); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Test/Syntax/IncrementalParsing/SyntaxDifferences.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp { public class SyntaxDifferences { /// <summary> /// Returns the nodes in the new tree that do not share the same underlying /// representation in the old tree. These may be entirely new nodes or rebuilt nodes. /// </summary> public static ImmutableArray<SyntaxNodeOrToken> GetRebuiltNodes(SyntaxTree oldTree, SyntaxTree newTree) { var hashSet = new HashSet<GreenNode>(); GatherNodes(oldTree.GetCompilationUnitRoot(), hashSet); var nodes = ArrayBuilder<SyntaxNodeOrToken>.GetInstance(); GetRebuiltNodes(newTree.GetCompilationUnitRoot(), hashSet, nodes); return nodes.ToImmutableAndFree(); } private static void GetRebuiltNodes(SyntaxNodeOrToken newNode, HashSet<GreenNode> hashSet, ArrayBuilder<SyntaxNodeOrToken> nodes) { if (hashSet.Contains(newNode.UnderlyingNode)) { return; } nodes.Add(newNode); foreach (var child in newNode.ChildNodesAndTokens()) { GetRebuiltNodes(child, hashSet, nodes); } } private static void GatherNodes(SyntaxNodeOrToken node, HashSet<GreenNode> hashSet) { hashSet.Add(node.UnderlyingNode); foreach (var child in node.ChildNodesAndTokens()) { GatherNodes(child, hashSet); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp { public class SyntaxDifferences { /// <summary> /// Returns the nodes in the new tree that do not share the same underlying /// representation in the old tree. These may be entirely new nodes or rebuilt nodes. /// </summary> public static ImmutableArray<SyntaxNodeOrToken> GetRebuiltNodes(SyntaxTree oldTree, SyntaxTree newTree) { var hashSet = new HashSet<GreenNode>(); GatherNodes(oldTree.GetCompilationUnitRoot(), hashSet); var nodes = ArrayBuilder<SyntaxNodeOrToken>.GetInstance(); GetRebuiltNodes(newTree.GetCompilationUnitRoot(), hashSet, nodes); return nodes.ToImmutableAndFree(); } private static void GetRebuiltNodes(SyntaxNodeOrToken newNode, HashSet<GreenNode> hashSet, ArrayBuilder<SyntaxNodeOrToken> nodes) { if (hashSet.Contains(newNode.UnderlyingNode)) { return; } nodes.Add(newNode); foreach (var child in newNode.ChildNodesAndTokens()) { GetRebuiltNodes(child, hashSet, nodes); } } private static void GatherNodes(SyntaxNodeOrToken node, HashSet<GreenNode> hashSet) { hashSet.Add(node.UnderlyingNode); foreach (var child in node.ChildNodesAndTokens()) { GatherNodes(child, hashSet); } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/Core/Portable/InternalUtilities/IncrementalHashExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection.Metadata; using System.Security.Cryptography; namespace Roslyn.Utilities { internal static class IncrementalHashExtensions { internal static void AppendData(this IncrementalHash hash, IEnumerable<Blob> blobs) { foreach (var blob in blobs) { hash.AppendData(blob.GetBytes()); } } internal static void AppendData(this IncrementalHash hash, IEnumerable<ArraySegment<byte>> blobs) { foreach (var blob in blobs) { hash.AppendData(blob); } } internal static void AppendData(this IncrementalHash hash, ArraySegment<byte> segment) { RoslynDebug.AssertNotNull(segment.Array); hash.AppendData(segment.Array, segment.Offset, segment.Count); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection.Metadata; using System.Security.Cryptography; namespace Roslyn.Utilities { internal static class IncrementalHashExtensions { internal static void AppendData(this IncrementalHash hash, IEnumerable<Blob> blobs) { foreach (var blob in blobs) { hash.AppendData(blob.GetBytes()); } } internal static void AppendData(this IncrementalHash hash, IEnumerable<ArraySegment<byte>> blobs) { foreach (var blob in blobs) { hash.AppendData(blob); } } internal static void AppendData(this IncrementalHash hash, ArraySegment<byte> segment) { RoslynDebug.AssertNotNull(segment.Array); hash.AppendData(segment.Array, segment.Offset, segment.Count); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Test/Symbol/Symbols/Metadata/PE/LoadingGenericTypeParameters.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE { public class LoadingGenericTypeParameters : CSharpTestBase { [Fact] public void Test1() { var assembly = MetadataTestHelpers.GetSymbolForReference(TestMetadata.Net40.mscorlib); var module0 = assembly.Modules[0]; var objectType = module0.GlobalNamespace.GetMembers("System"). OfType<NamespaceSymbol>().Single(). GetTypeMembers("Object").Single(); Assert.Equal(0, objectType.Arity); Assert.Equal(0, objectType.TypeParameters.Length); Assert.Equal(0, objectType.TypeArguments().Length); assembly = MetadataTestHelpers.GetSymbolForReference(TestReferences.SymbolsTests.MDTestLib1); module0 = assembly.Modules[0]; var varC1 = module0.GlobalNamespace.GetTypeMembers("C1").Single(); Assert.Equal(1, varC1.Arity); Assert.Equal(1, varC1.TypeParameters.Length); Assert.Equal(1, varC1.TypeArguments().Length); var varC1_T = varC1.TypeParameters[0]; Assert.Equal(varC1_T, varC1.TypeArguments()[0]); Assert.NotNull(varC1_T.EffectiveBaseClassNoUseSiteDiagnostics); Assert.Equal(assembly, varC1_T.ContainingAssembly); Assert.Equal(module0.GlobalNamespace, varC1_T.ContainingNamespace); // Null(C1_T.ContainingNamespace) Assert.Equal(varC1, varC1_T.ContainingSymbol); Assert.Equal(varC1, varC1_T.ContainingType); Assert.Equal(Accessibility.NotApplicable, varC1_T.DeclaredAccessibility); Assert.Equal("C1_T", varC1_T.Name); Assert.Equal("C1_T", varC1_T.ToTestDisplayString()); Assert.Equal(0, varC1_T.GetMembers().Length); Assert.Equal(0, varC1_T.GetMembers("goo").Length); Assert.Equal(0, varC1_T.GetTypeMembers().Length); Assert.Equal(0, varC1_T.GetTypeMembers("goo").Length); Assert.Equal(0, varC1_T.GetTypeMembers("goo", 1).Length); Assert.False(varC1_T.HasConstructorConstraint); Assert.False(varC1_T.HasReferenceTypeConstraint); Assert.False(varC1_T.HasValueTypeConstraint); Assert.Equal(0, varC1_T.EffectiveInterfacesNoUseSiteDiagnostics.Length); Assert.True(varC1_T.IsDefinition); Assert.False(varC1_T.IsAbstract); Assert.False(varC1_T.IsNamespace); Assert.False(varC1_T.IsSealed); Assert.False(varC1_T.IsVirtual); Assert.False(varC1_T.IsOverride); Assert.False(varC1_T.IsStatic); Assert.True(varC1_T.IsType); Assert.Equal(SymbolKind.TypeParameter, varC1_T.Kind); Assert.Equal(0, varC1_T.Ordinal); Assert.Equal(varC1_T, varC1_T.OriginalDefinition); Assert.Equal(TypeKind.TypeParameter, varC1_T.TypeKind); Assert.Equal(VarianceKind.None, varC1_T.Variance); Assert.Same(module0, varC1_T.Locations.Single().MetadataModuleInternal); Assert.Equal(0, varC1_T.ConstraintTypes().Length); var varC2 = varC1.GetTypeMembers("C2").Single(); Assert.Equal(1, varC2.Arity); Assert.Equal(1, varC2.TypeParameters.Length); Assert.Equal(1, varC2.TypeArguments().Length); var varC2_T = varC2.TypeParameters[0]; Assert.Equal("C2_T", varC2_T.Name); Assert.Equal(varC2, varC2_T.ContainingType); var varC3 = varC1.GetTypeMembers("C3").Single(); Assert.Equal(0, varC3.Arity); Assert.Equal(0, varC3.TypeParameters.Length); Assert.Equal(0, varC3.TypeArguments().Length); var varC4 = varC3.GetTypeMembers("C4").Single(); Assert.Equal(1, varC4.Arity); Assert.Equal(1, varC4.TypeParameters.Length); Assert.Equal(1, varC4.TypeArguments().Length); var varC4_T = varC4.TypeParameters[0]; Assert.Equal("C4_T", varC4_T.Name); Assert.Equal(varC4, varC4_T.ContainingType); var varTC2 = module0.GlobalNamespace.GetTypeMembers("TC2").Single(); Assert.Equal(2, varTC2.Arity); Assert.Equal(2, varTC2.TypeParameters.Length); Assert.Equal(2, varTC2.TypeArguments().Length); var varTC2_T1 = varTC2.TypeParameters[0]; var varTC2_T2 = varTC2.TypeParameters[1]; Assert.Equal(varTC2_T1, varTC2.TypeArguments()[0]); Assert.Equal(varTC2_T2, varTC2.TypeArguments()[1]); Assert.Equal("TC2_T1", varTC2_T1.Name); Assert.Equal(varTC2, varTC2_T1.ContainingType); Assert.Equal(0, varTC2_T1.Ordinal); Assert.Equal("TC2_T2", varTC2_T2.Name); Assert.Equal(varTC2, varTC2_T2.ContainingType); Assert.Equal(1, varTC2_T2.Ordinal); var varC100 = module0.GlobalNamespace.GetTypeMembers("C100").Single(); var varT = varC100.TypeParameters[0]; Assert.False(varT.HasConstructorConstraint); Assert.False(varT.HasReferenceTypeConstraint); Assert.False(varT.HasValueTypeConstraint); Assert.Equal(VarianceKind.Out, varT.Variance); var varC101 = module0.GlobalNamespace.GetTypeMembers("C101").Single(); varT = varC101.TypeParameters[0]; Assert.False(varT.HasConstructorConstraint); Assert.False(varT.HasReferenceTypeConstraint); Assert.False(varT.HasValueTypeConstraint); Assert.Equal(VarianceKind.In, varT.Variance); var varC102 = module0.GlobalNamespace.GetTypeMembers("C102").Single(); varT = varC102.TypeParameters[0]; Assert.True(varT.HasConstructorConstraint); Assert.False(varT.HasReferenceTypeConstraint); Assert.False(varT.HasValueTypeConstraint); Assert.Equal(VarianceKind.None, varT.Variance); Assert.Equal(0, varT.ConstraintTypes().Length); var varC103 = module0.GlobalNamespace.GetTypeMembers("C103").Single(); varT = varC103.TypeParameters[0]; Assert.False(varT.HasConstructorConstraint); Assert.True(varT.HasReferenceTypeConstraint); Assert.False(varT.HasValueTypeConstraint); Assert.Equal(VarianceKind.None, varT.Variance); Assert.Equal(0, varT.ConstraintTypes().Length); var varC104 = module0.GlobalNamespace.GetTypeMembers("C104").Single(); varT = varC104.TypeParameters[0]; Assert.False(varT.HasConstructorConstraint); Assert.False(varT.HasReferenceTypeConstraint); Assert.True(varT.HasValueTypeConstraint); Assert.Equal(VarianceKind.None, varT.Variance); Assert.Equal(0, varT.ConstraintTypes().Length); var varC105 = module0.GlobalNamespace.GetTypeMembers("C105").Single(); varT = varC105.TypeParameters[0]; Assert.True(varT.HasConstructorConstraint); Assert.True(varT.HasReferenceTypeConstraint); Assert.False(varT.HasValueTypeConstraint); Assert.Equal(VarianceKind.None, varT.Variance); var varC106 = module0.GlobalNamespace.GetTypeMembers("C106").Single(); varT = varC106.TypeParameters[0]; Assert.True(varT.HasConstructorConstraint); Assert.True(varT.HasReferenceTypeConstraint); Assert.False(varT.HasValueTypeConstraint); Assert.Equal(VarianceKind.Out, varT.Variance); var varI101 = module0.GlobalNamespace.GetTypeMembers("I101").Single(); var varI102 = module0.GlobalNamespace.GetTypeMembers("I102").Single(); var varC201 = module0.GlobalNamespace.GetTypeMembers("C201").Single(); varT = varC201.TypeParameters[0]; Assert.Equal(1, varT.ConstraintTypes().Length); Assert.Same(varI101, varT.ConstraintTypes().ElementAt(0)); var localC202 = module0.GlobalNamespace.GetTypeMembers("C202").Single(); varT = localC202.TypeParameters[0]; Assert.Equal(2, varT.ConstraintTypes().Length); Assert.Same(varI101, varT.ConstraintTypes().ElementAt(0)); Assert.Same(varI102, varT.ConstraintTypes().ElementAt(1)); } [Fact, WorkItem(619267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/619267")] public void InvalidNestedArity() { // .class public C`2<T1,T2> // .class nested public D<S1> var mdRef = MetadataReference.CreateFromImage(TestResources.MetadataTests.Invalid.InvalidGenericType.AsImmutableOrNull()); string source = "class X : C<int, int>.D { }"; CreateCompilation(source, new[] { mdRef }).VerifyDiagnostics( // (2,11): error CS0648: 'C<T1, T2>.D' is a type not supported by the language // class X : C<int, int>.D { } Diagnostic(ErrorCode.ERR_BogusType, "C<int, int>.D").WithArguments("C<T1, T2>.D") ); } [WorkItem(528859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528859")] [Fact] public void InvalidNestedArity_2() { var ilSource = @".class interface public abstract I0 { .class interface abstract nested public IT<T> { .class interface abstract nested public I0 { } } } .class interface public abstract IT<T> { .class interface abstract nested public I0 { .class interface abstract nested public I0 { } .class interface abstract nested public IT<T> { } } .class interface abstract nested public IT<T> { .class interface abstract nested public I0 { } } .class interface abstract nested public ITU<T, U> { .class interface abstract nested public IT<T> { } } }"; var csharpSource = @"class C0_T : I0.IT<object> { } class C0_T_0 : I0.IT<object>.I0 { } class CT_0 : IT<object>.I0 { } class CT_0_0 : IT<object>.I0.I0 { } class CT_0_T : IT<object>.I0.IT { } class CT_T_0 : IT<object>.IT.I0 { } class CT_TU_T : IT<object>.ITU<int>.IT { } "; var compilation1 = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource); compilation1.VerifyDiagnostics( // (2,7): error CS0648: 'I0.IT<T>.I0' is a type not supported by the language // class C0_T_0 : I0.IT<object>.I0 { } Diagnostic(ErrorCode.ERR_BogusType, "C0_T_0").WithArguments("I0.IT<T>.I0"), // (3,7): error CS0648: 'IT<T>.I0' is a type not supported by the language // class CT_0 : IT<object>.I0 { } Diagnostic(ErrorCode.ERR_BogusType, "CT_0").WithArguments("IT<T>.I0"), // (4,27): error CS0648: 'IT<T>.I0' is a type not supported by the language // class CT_0_0 : IT<object>.I0.I0 { } Diagnostic(ErrorCode.ERR_BogusType, "I0").WithArguments("IT<T>.I0"), // (4,7): error CS0648: 'IT<T>.I0.I0' is a type not supported by the language // class CT_0_0 : IT<object>.I0.I0 { } Diagnostic(ErrorCode.ERR_BogusType, "CT_0_0").WithArguments("IT<T>.I0.I0"), // (5,27): error CS0648: 'IT<T>.I0' is a type not supported by the language // class CT_0_T : IT<object>.I0.IT { } Diagnostic(ErrorCode.ERR_BogusType, "I0").WithArguments("IT<T>.I0"), // (6,7): error CS0648: 'IT<T>.IT.I0' is a type not supported by the language // class CT_T_0 : IT<object>.IT.I0 { } Diagnostic(ErrorCode.ERR_BogusType, "CT_T_0").WithArguments("IT<T>.IT.I0"), // (7,7): error CS0648: 'IT<T>.ITU<U>.IT' is a type not supported by the language // class CT_TU_T : IT<object>.ITU<int>.IT { } Diagnostic(ErrorCode.ERR_BogusType, "CT_TU_T").WithArguments("IT<T>.ITU<U>.IT")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE { public class LoadingGenericTypeParameters : CSharpTestBase { [Fact] public void Test1() { var assembly = MetadataTestHelpers.GetSymbolForReference(TestMetadata.Net40.mscorlib); var module0 = assembly.Modules[0]; var objectType = module0.GlobalNamespace.GetMembers("System"). OfType<NamespaceSymbol>().Single(). GetTypeMembers("Object").Single(); Assert.Equal(0, objectType.Arity); Assert.Equal(0, objectType.TypeParameters.Length); Assert.Equal(0, objectType.TypeArguments().Length); assembly = MetadataTestHelpers.GetSymbolForReference(TestReferences.SymbolsTests.MDTestLib1); module0 = assembly.Modules[0]; var varC1 = module0.GlobalNamespace.GetTypeMembers("C1").Single(); Assert.Equal(1, varC1.Arity); Assert.Equal(1, varC1.TypeParameters.Length); Assert.Equal(1, varC1.TypeArguments().Length); var varC1_T = varC1.TypeParameters[0]; Assert.Equal(varC1_T, varC1.TypeArguments()[0]); Assert.NotNull(varC1_T.EffectiveBaseClassNoUseSiteDiagnostics); Assert.Equal(assembly, varC1_T.ContainingAssembly); Assert.Equal(module0.GlobalNamespace, varC1_T.ContainingNamespace); // Null(C1_T.ContainingNamespace) Assert.Equal(varC1, varC1_T.ContainingSymbol); Assert.Equal(varC1, varC1_T.ContainingType); Assert.Equal(Accessibility.NotApplicable, varC1_T.DeclaredAccessibility); Assert.Equal("C1_T", varC1_T.Name); Assert.Equal("C1_T", varC1_T.ToTestDisplayString()); Assert.Equal(0, varC1_T.GetMembers().Length); Assert.Equal(0, varC1_T.GetMembers("goo").Length); Assert.Equal(0, varC1_T.GetTypeMembers().Length); Assert.Equal(0, varC1_T.GetTypeMembers("goo").Length); Assert.Equal(0, varC1_T.GetTypeMembers("goo", 1).Length); Assert.False(varC1_T.HasConstructorConstraint); Assert.False(varC1_T.HasReferenceTypeConstraint); Assert.False(varC1_T.HasValueTypeConstraint); Assert.Equal(0, varC1_T.EffectiveInterfacesNoUseSiteDiagnostics.Length); Assert.True(varC1_T.IsDefinition); Assert.False(varC1_T.IsAbstract); Assert.False(varC1_T.IsNamespace); Assert.False(varC1_T.IsSealed); Assert.False(varC1_T.IsVirtual); Assert.False(varC1_T.IsOverride); Assert.False(varC1_T.IsStatic); Assert.True(varC1_T.IsType); Assert.Equal(SymbolKind.TypeParameter, varC1_T.Kind); Assert.Equal(0, varC1_T.Ordinal); Assert.Equal(varC1_T, varC1_T.OriginalDefinition); Assert.Equal(TypeKind.TypeParameter, varC1_T.TypeKind); Assert.Equal(VarianceKind.None, varC1_T.Variance); Assert.Same(module0, varC1_T.Locations.Single().MetadataModuleInternal); Assert.Equal(0, varC1_T.ConstraintTypes().Length); var varC2 = varC1.GetTypeMembers("C2").Single(); Assert.Equal(1, varC2.Arity); Assert.Equal(1, varC2.TypeParameters.Length); Assert.Equal(1, varC2.TypeArguments().Length); var varC2_T = varC2.TypeParameters[0]; Assert.Equal("C2_T", varC2_T.Name); Assert.Equal(varC2, varC2_T.ContainingType); var varC3 = varC1.GetTypeMembers("C3").Single(); Assert.Equal(0, varC3.Arity); Assert.Equal(0, varC3.TypeParameters.Length); Assert.Equal(0, varC3.TypeArguments().Length); var varC4 = varC3.GetTypeMembers("C4").Single(); Assert.Equal(1, varC4.Arity); Assert.Equal(1, varC4.TypeParameters.Length); Assert.Equal(1, varC4.TypeArguments().Length); var varC4_T = varC4.TypeParameters[0]; Assert.Equal("C4_T", varC4_T.Name); Assert.Equal(varC4, varC4_T.ContainingType); var varTC2 = module0.GlobalNamespace.GetTypeMembers("TC2").Single(); Assert.Equal(2, varTC2.Arity); Assert.Equal(2, varTC2.TypeParameters.Length); Assert.Equal(2, varTC2.TypeArguments().Length); var varTC2_T1 = varTC2.TypeParameters[0]; var varTC2_T2 = varTC2.TypeParameters[1]; Assert.Equal(varTC2_T1, varTC2.TypeArguments()[0]); Assert.Equal(varTC2_T2, varTC2.TypeArguments()[1]); Assert.Equal("TC2_T1", varTC2_T1.Name); Assert.Equal(varTC2, varTC2_T1.ContainingType); Assert.Equal(0, varTC2_T1.Ordinal); Assert.Equal("TC2_T2", varTC2_T2.Name); Assert.Equal(varTC2, varTC2_T2.ContainingType); Assert.Equal(1, varTC2_T2.Ordinal); var varC100 = module0.GlobalNamespace.GetTypeMembers("C100").Single(); var varT = varC100.TypeParameters[0]; Assert.False(varT.HasConstructorConstraint); Assert.False(varT.HasReferenceTypeConstraint); Assert.False(varT.HasValueTypeConstraint); Assert.Equal(VarianceKind.Out, varT.Variance); var varC101 = module0.GlobalNamespace.GetTypeMembers("C101").Single(); varT = varC101.TypeParameters[0]; Assert.False(varT.HasConstructorConstraint); Assert.False(varT.HasReferenceTypeConstraint); Assert.False(varT.HasValueTypeConstraint); Assert.Equal(VarianceKind.In, varT.Variance); var varC102 = module0.GlobalNamespace.GetTypeMembers("C102").Single(); varT = varC102.TypeParameters[0]; Assert.True(varT.HasConstructorConstraint); Assert.False(varT.HasReferenceTypeConstraint); Assert.False(varT.HasValueTypeConstraint); Assert.Equal(VarianceKind.None, varT.Variance); Assert.Equal(0, varT.ConstraintTypes().Length); var varC103 = module0.GlobalNamespace.GetTypeMembers("C103").Single(); varT = varC103.TypeParameters[0]; Assert.False(varT.HasConstructorConstraint); Assert.True(varT.HasReferenceTypeConstraint); Assert.False(varT.HasValueTypeConstraint); Assert.Equal(VarianceKind.None, varT.Variance); Assert.Equal(0, varT.ConstraintTypes().Length); var varC104 = module0.GlobalNamespace.GetTypeMembers("C104").Single(); varT = varC104.TypeParameters[0]; Assert.False(varT.HasConstructorConstraint); Assert.False(varT.HasReferenceTypeConstraint); Assert.True(varT.HasValueTypeConstraint); Assert.Equal(VarianceKind.None, varT.Variance); Assert.Equal(0, varT.ConstraintTypes().Length); var varC105 = module0.GlobalNamespace.GetTypeMembers("C105").Single(); varT = varC105.TypeParameters[0]; Assert.True(varT.HasConstructorConstraint); Assert.True(varT.HasReferenceTypeConstraint); Assert.False(varT.HasValueTypeConstraint); Assert.Equal(VarianceKind.None, varT.Variance); var varC106 = module0.GlobalNamespace.GetTypeMembers("C106").Single(); varT = varC106.TypeParameters[0]; Assert.True(varT.HasConstructorConstraint); Assert.True(varT.HasReferenceTypeConstraint); Assert.False(varT.HasValueTypeConstraint); Assert.Equal(VarianceKind.Out, varT.Variance); var varI101 = module0.GlobalNamespace.GetTypeMembers("I101").Single(); var varI102 = module0.GlobalNamespace.GetTypeMembers("I102").Single(); var varC201 = module0.GlobalNamespace.GetTypeMembers("C201").Single(); varT = varC201.TypeParameters[0]; Assert.Equal(1, varT.ConstraintTypes().Length); Assert.Same(varI101, varT.ConstraintTypes().ElementAt(0)); var localC202 = module0.GlobalNamespace.GetTypeMembers("C202").Single(); varT = localC202.TypeParameters[0]; Assert.Equal(2, varT.ConstraintTypes().Length); Assert.Same(varI101, varT.ConstraintTypes().ElementAt(0)); Assert.Same(varI102, varT.ConstraintTypes().ElementAt(1)); } [Fact, WorkItem(619267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/619267")] public void InvalidNestedArity() { // .class public C`2<T1,T2> // .class nested public D<S1> var mdRef = MetadataReference.CreateFromImage(TestResources.MetadataTests.Invalid.InvalidGenericType.AsImmutableOrNull()); string source = "class X : C<int, int>.D { }"; CreateCompilation(source, new[] { mdRef }).VerifyDiagnostics( // (2,11): error CS0648: 'C<T1, T2>.D' is a type not supported by the language // class X : C<int, int>.D { } Diagnostic(ErrorCode.ERR_BogusType, "C<int, int>.D").WithArguments("C<T1, T2>.D") ); } [WorkItem(528859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528859")] [Fact] public void InvalidNestedArity_2() { var ilSource = @".class interface public abstract I0 { .class interface abstract nested public IT<T> { .class interface abstract nested public I0 { } } } .class interface public abstract IT<T> { .class interface abstract nested public I0 { .class interface abstract nested public I0 { } .class interface abstract nested public IT<T> { } } .class interface abstract nested public IT<T> { .class interface abstract nested public I0 { } } .class interface abstract nested public ITU<T, U> { .class interface abstract nested public IT<T> { } } }"; var csharpSource = @"class C0_T : I0.IT<object> { } class C0_T_0 : I0.IT<object>.I0 { } class CT_0 : IT<object>.I0 { } class CT_0_0 : IT<object>.I0.I0 { } class CT_0_T : IT<object>.I0.IT { } class CT_T_0 : IT<object>.IT.I0 { } class CT_TU_T : IT<object>.ITU<int>.IT { } "; var compilation1 = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource); compilation1.VerifyDiagnostics( // (2,7): error CS0648: 'I0.IT<T>.I0' is a type not supported by the language // class C0_T_0 : I0.IT<object>.I0 { } Diagnostic(ErrorCode.ERR_BogusType, "C0_T_0").WithArguments("I0.IT<T>.I0"), // (3,7): error CS0648: 'IT<T>.I0' is a type not supported by the language // class CT_0 : IT<object>.I0 { } Diagnostic(ErrorCode.ERR_BogusType, "CT_0").WithArguments("IT<T>.I0"), // (4,27): error CS0648: 'IT<T>.I0' is a type not supported by the language // class CT_0_0 : IT<object>.I0.I0 { } Diagnostic(ErrorCode.ERR_BogusType, "I0").WithArguments("IT<T>.I0"), // (4,7): error CS0648: 'IT<T>.I0.I0' is a type not supported by the language // class CT_0_0 : IT<object>.I0.I0 { } Diagnostic(ErrorCode.ERR_BogusType, "CT_0_0").WithArguments("IT<T>.I0.I0"), // (5,27): error CS0648: 'IT<T>.I0' is a type not supported by the language // class CT_0_T : IT<object>.I0.IT { } Diagnostic(ErrorCode.ERR_BogusType, "I0").WithArguments("IT<T>.I0"), // (6,7): error CS0648: 'IT<T>.IT.I0' is a type not supported by the language // class CT_T_0 : IT<object>.IT.I0 { } Diagnostic(ErrorCode.ERR_BogusType, "CT_T_0").WithArguments("IT<T>.IT.I0"), // (7,7): error CS0648: 'IT<T>.ITU<U>.IT' is a type not supported by the language // class CT_TU_T : IT<object>.ITU<int>.IT { } Diagnostic(ErrorCode.ERR_BogusType, "CT_TU_T").WithArguments("IT<T>.ITU<U>.IT")); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/Core/Portable/Text/StringText.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// Implementation of SourceText based on a <see cref="String"/> input /// </summary> internal sealed class StringText : SourceText { private readonly string _source; private readonly Encoding? _encodingOpt; internal StringText( string source, Encoding? encodingOpt, ImmutableArray<byte> checksum = default(ImmutableArray<byte>), SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, ImmutableArray<byte> embeddedTextBlob = default(ImmutableArray<byte>)) : base(checksum, checksumAlgorithm, embeddedTextBlob) { RoslynDebug.Assert(source != null); _source = source; _encodingOpt = encodingOpt; } public override Encoding? Encoding => _encodingOpt; /// <summary> /// Underlying string which is the source of this <see cref="StringText"/>instance /// </summary> public string Source => _source; /// <summary> /// The length of the text represented by <see cref="StringText"/>. /// </summary> public override int Length => _source.Length; /// <summary> /// Returns a character at given position. /// </summary> /// <param name="position">The position to get the character from.</param> /// <returns>The character.</returns> /// <exception cref="ArgumentOutOfRangeException">When position is negative or /// greater than <see cref="Length"/>.</exception> public override char this[int position] { get { // NOTE: we are not validating position here as that would not // add any value to the range check that string accessor performs anyways. return _source[position]; } } /// <summary> /// Provides a string representation of the StringText located within given span. /// </summary> /// <exception cref="ArgumentOutOfRangeException">When given span is outside of the text range.</exception> public override string ToString(TextSpan span) { if (span.End > this.Source.Length) { throw new ArgumentOutOfRangeException(nameof(span)); } if (span.Start == 0 && span.Length == this.Length) { return this.Source; } return this.Source.Substring(span.Start, span.Length); } public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { this.Source.CopyTo(sourceIndex, destination, destinationIndex, count); } public override void Write(TextWriter textWriter, TextSpan span, CancellationToken cancellationToken = default(CancellationToken)) { if (span.Start == 0 && span.End == this.Length) { textWriter.Write(this.Source); } else { base.Write(textWriter, span, cancellationToken); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// Implementation of SourceText based on a <see cref="String"/> input /// </summary> internal sealed class StringText : SourceText { private readonly string _source; private readonly Encoding? _encodingOpt; internal StringText( string source, Encoding? encodingOpt, ImmutableArray<byte> checksum = default(ImmutableArray<byte>), SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, ImmutableArray<byte> embeddedTextBlob = default(ImmutableArray<byte>)) : base(checksum, checksumAlgorithm, embeddedTextBlob) { RoslynDebug.Assert(source != null); _source = source; _encodingOpt = encodingOpt; } public override Encoding? Encoding => _encodingOpt; /// <summary> /// Underlying string which is the source of this <see cref="StringText"/>instance /// </summary> public string Source => _source; /// <summary> /// The length of the text represented by <see cref="StringText"/>. /// </summary> public override int Length => _source.Length; /// <summary> /// Returns a character at given position. /// </summary> /// <param name="position">The position to get the character from.</param> /// <returns>The character.</returns> /// <exception cref="ArgumentOutOfRangeException">When position is negative or /// greater than <see cref="Length"/>.</exception> public override char this[int position] { get { // NOTE: we are not validating position here as that would not // add any value to the range check that string accessor performs anyways. return _source[position]; } } /// <summary> /// Provides a string representation of the StringText located within given span. /// </summary> /// <exception cref="ArgumentOutOfRangeException">When given span is outside of the text range.</exception> public override string ToString(TextSpan span) { if (span.End > this.Source.Length) { throw new ArgumentOutOfRangeException(nameof(span)); } if (span.Start == 0 && span.Length == this.Length) { return this.Source; } return this.Source.Substring(span.Start, span.Length); } public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { this.Source.CopyTo(sourceIndex, destination, destinationIndex, count); } public override void Write(TextWriter textWriter, TextSpan span, CancellationToken cancellationToken = default(CancellationToken)) { if (span.Start == 0 && span.End == this.Length) { textWriter.Write(this.Source); } else { base.Write(textWriter, span, cancellationToken); } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Test/Semantic/Semantics/UsingStatementTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Tests related to binding (but not lowering) using statements (not directives). /// </summary> public class UsingStatementTests : CompilingTestBase { private const string _managedClass = @" class MyManagedType : System.IDisposable { public void Dispose() { } }"; private const string _managedStruct = @" struct MyManagedType : System.IDisposable { public void Dispose() { } }"; [Fact] public void SemanticModel() { var source = @" class C { static void Main() { using (System.IDisposable i = null) { i.Dispose(); //this makes no sense, but we're only testing binding } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var usingStatement = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingStatementSyntax>().Single(); var declaredSymbol = model.GetDeclaredSymbol(usingStatement.Declaration.Variables.Single()); Assert.NotNull(declaredSymbol); Assert.Equal(SymbolKind.Local, declaredSymbol.Kind); var declaredLocal = (ILocalSymbol)declaredSymbol; Assert.Equal("i", declaredLocal.Name); Assert.Equal(SpecialType.System_IDisposable, declaredLocal.Type.SpecialType); var memberAccessExpression = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var info = model.GetSymbolInfo(memberAccessExpression.Expression); Assert.NotEqual(default, info); Assert.Equal(declaredLocal, info.Symbol); var lookupSymbol = model.LookupSymbols(memberAccessExpression.SpanStart, name: declaredLocal.Name).Single(); Assert.Equal(declaredLocal, lookupSymbol); } [Fact] public void MethodGroup() { var source = @" class C { static void Main() { using (Main) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,16): error CS1674: 'method group': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "Main").WithArguments("method group")); } [Fact] public void UsingPatternRefStructTest() { var source = @" ref struct S1 { public void Dispose() { } } class C2 { static void Main() { using (S1 s = new S1()) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPatternReferenceTypeTest() { var source = @" class C1 { public void Dispose() { } } class C2 { static void Main() { using (C1 c1 = new C1()) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (11,16): error CS1674: 'C1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (C1 c1 = new C1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "C1 c1 = new C1()").WithArguments("C1").WithLocation(11, 16) ); } [Fact] public void UsingPatternSameSignatureAmbiguousTest() { var source = @" ref struct S1 { public void Dispose() { } public void Dispose() { } } class C2 { static void Main() { using (S1 s = new S1()) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (5,17): error CS0111: Type 'S1' already defines a member called 'Dispose' with the same parameter types // public void Dispose() { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Dispose").WithArguments("Dispose", "S1").WithLocation(5, 17), // (12,16): error CS0121: The call is ambiguous between the following methods or properties: 'S1.Dispose()' and 'S1.Dispose()' // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_AmbigCall, "S1 s = new S1()").WithArguments("S1.Dispose()", "S1.Dispose()").WithLocation(12, 16), // (12,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(12, 16) ); } [Fact] public void UsingPatternAmbiguousOverloadTest() { var source = @" ref struct S1 { public void Dispose() { } public bool Dispose() { return false; } } class C2 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (5,17): error CS0111: Type 'S1' already defines a member called 'Dispose' with the same parameter types // public bool Dispose() { return false; } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Dispose").WithArguments("Dispose", "S1").WithLocation(5, 17), // (12,16): error CS0121: The call is ambiguous between the following methods or properties: 'S1.Dispose()' and 'S1.Dispose()' // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_AmbigCall, "S1 s = new S1()").WithArguments("S1.Dispose()", "S1.Dispose()").WithLocation(12, 16), // (12,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(12, 16), // (16,16): error CS0121: The call is ambiguous between the following methods or properties: 'S1.Dispose()' and 'S1.Dispose()' // using (c1b) { } Diagnostic(ErrorCode.ERR_AmbigCall, "s1b").WithArguments("S1.Dispose()", "S1.Dispose()").WithLocation(16, 16), // (16,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (c1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s1b").WithArguments("S1").WithLocation(16, 16) ); } [Fact] public void UsingPatternDifferentParameterOverloadTest() { var source = @" ref struct S1 { public void Dispose() { } public void Dispose(int x) { } } class C2 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } } }"; // Shouldn't throw an error as the method signatures are different. CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPatternInaccessibleAmbiguousTest() { var source = @" ref struct S1 { public void Dispose() { } internal void Dispose() { } } class C2 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (5,19): error CS0111: Type 'S1' already defines a member called 'Dispose' with the same parameter types // internal void Dispose() { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Dispose").WithArguments("Dispose", "S1").WithLocation(5, 19), // (12,16): error CS0121: The call is ambiguous between the following methods or properties: 'S1.Dispose()' and 'S1.Dispose()' // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_AmbigCall, "S1 s = new S1()").WithArguments("S1.Dispose()", "S1.Dispose()").WithLocation(12, 16), // (12,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(12, 16), // (16,16): error CS0121: The call is ambiguous between the following methods or properties: 'S1.Dispose()' and 'S1.Dispose()' // using (c1b) { } Diagnostic(ErrorCode.ERR_AmbigCall, "s1b").WithArguments("S1.Dispose()", "S1.Dispose()").WithLocation(16, 16), // (16,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (c1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s1b").WithArguments("S1").WithLocation(16, 16) ); } [Fact] public void UsingPatternImplicitConversionToDisposable() { var source = @" ref struct S1 { public void Dispose() { } // User-defined implicit conversion from C2 to S1 public static implicit operator S1(C2 o) { return new S1(); } } class C2 { } class C3 { static void Main() { using (S1 s = new C2()) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPatternExtensionMethodTest() { var source = @" ref struct S1 { } static class C2 { public static void Dispose(this S1 c1) { } } class C3 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (15,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(15, 16), // (19,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (s1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s1b").WithArguments("S1").WithLocation(19, 16) ); } [Fact] public void UsingPatternExtensionMethodPropertyHidingTest() { var source = @" ref struct S1 { public int Dispose { get; } } static class C2 { public static void Dispose(this S1 s1) { } } class C3 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (16,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(16, 16), // (20,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (s1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s1b").WithArguments("S1").WithLocation(20, 16) ); } [Fact] public void UsingPatternStaticMethodTest() { var source = @" ref struct S1 { public static void Dispose() { } } class C2 { static void Main() { using (S1 s = new S1()) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (11,16): error CS0176: Member 'S1.Dispose()' cannot be accessed with an instance reference; qualify it with a type name instead // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_ObjectProhibited, "S1 s = new S1()").WithArguments("S1.Dispose()").WithLocation(11, 16), // (11,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(11, 16) ); } [Fact] public void UsingPatternAmbiguousExtensionMethodTest() { var source = @" ref struct S1 { } static class C2 { public static void Dispose(this S1 s1) { } } static class C3 { public static void Dispose(this S1 s1) { } } class C4 { static void Main() { using (S1 s = new S1()) { } } }"; // Extension methods should just be ignored, rather than rejected after-the-fact. So there should be no error about ambiguities // Tracked by https://github.com/dotnet/roslyn/issues/32767 CreateCompilation(source).VerifyDiagnostics( // (20,16): error CS0121: The call is ambiguous between the following methods or properties: 'C2.Dispose(S1)' and 'C3.Dispose(S1)' // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_AmbigCall, "S1 s = new S1()").WithArguments("C2.Dispose(S1)", "C3.Dispose(S1)").WithLocation(20, 16), // (20,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(20, 16) ); } [Fact] public void UsingPatternScopedExtensionMethodTest() { var source = @" ref struct S1 { } namespace N1 { static class C2 { public static void Dispose(this S1 s1) { } } } namespace N2 { static class C3 { public static void Dispose(this S1 s1) { } } } namespace N3 { static class C4 { public static int Dispose(this S1 s1) { return 0; } } } namespace N4 { partial class C5 { static void M() { using (S1 s = new S1()) // error 1 { } } } } namespace N4 { using N1; partial class C5 { static void M2() { using (S1 s = new S1()) // error 2 { } } } } namespace N4 { using N3; partial class C5 { static void M3() { using (S1 s = new S1()) // error 3 { } } } } namespace N4 { using N1; using N3; partial class C5 { static void M4() { using (S1 s = new S1()) // error 4 { } } } } namespace N4 { using N3; namespace N5 { partial class C5 { static void M5() { using (S1 s = new S1()) // error 5 { } } } namespace N6 { using N1; partial class C5 { static void M6() { using (S1 s = new S1()) // error 6 { } } } } } }"; // Extension methods should just be ignored, rather than rejected after-the-fact. So there should be no error about ambiguities // Tracked by https://github.com/dotnet/roslyn/issues/32767 CreateCompilation(source).VerifyDiagnostics( // (37,20): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) // error 1 Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(37, 20), // (50,20): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) // error 2 Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(50, 20), // (63,20): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) // error 3 Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(63, 20), // (77,20): error CS0121: The call is ambiguous between the following methods or properties: 'N1.C2.Dispose(S1)' and 'N3.C4.Dispose(S1)' // using (S1 s = new S1()) // error 4 Diagnostic(ErrorCode.ERR_AmbigCall, "S1 s = new S1()").WithArguments("N1.C2.Dispose(S1)", "N3.C4.Dispose(S1)").WithLocation(77, 20), // (77,20): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) // error 4 Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(77, 20), // (92,24): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) // error 5 Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(92, 24), // (105,28): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) // error 6 Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(105, 28) ); } [Fact] public void UsingPatternWithMultipleExtensionTargets() { var source = @" ref struct S1 { } ref struct S2 { } static class C3 { public static void Dispose(this S1 s1) { } public static void Dispose(this S2 s2) { } } class C4 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } using (S2 s = new S2()) { } S2 s2b = new S2(); using (s2b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (22,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(22, 16), // (26,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (s1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s1b").WithArguments("S1").WithLocation(26, 16), // (28,16): error CS1674: 'S2': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S2 s = new S2()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S2 s = new S2()").WithArguments("S2").WithLocation(28, 16), // (32,16): error CS1674: 'S2': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (s2b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s2b").WithArguments("S2").WithLocation(32, 16) ); } [Fact] public void UsingPatternExtensionMethodWithDefaultArgumentsAmbiguous() { var source = @" ref struct S1 { } static class C2 { internal static void Dispose(this S1 s1, int a = 1) { } } static class C3 { internal static void Dispose(this S1 s1, int b = 2) { } } class C4 { static void Main() { using (S1 s = new S1()) { } } }"; // Extension methods should just be ignored, rather than rejected after-the-fact. So there should be no error about ambiguities // Tracked by https://github.com/dotnet/roslyn/issues/32767 CreateCompilation(source).VerifyDiagnostics( // (21,15): error CS0121: The call is ambiguous between the following methods or properties: 'C2.Dispose(S1, int)' and 'C3.Dispose(S1, int)' // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_AmbigCall, "S1 s = new S1()").WithArguments("C2.Dispose(S1, int)", "C3.Dispose(S1, int)").WithLocation(21, 15), // (21,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(21, 15) ); } [Fact] public void UsingPatternExtensionMethodNonPublic() { var source = @" ref struct S1 { } static class C2 { internal static void Dispose(this S1 s1) { } } class C3 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (15,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(15, 15), // (19,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (s1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s1b").WithArguments("S1").WithLocation(19, 15) ); } [Fact] public void UsingPatternExtensionMethodWithInvalidInstanceMethod() { var source = @" ref struct S1 { public int Dispose() { return 0; } } static class C2 { internal static void Dispose(this S1 s1) { } } class C3 { static void Main() { using (S1 s = new S1()) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (19,15): warning CS0280: 'S1' does not implement the 'disposable' pattern. 'S1.Dispose()' has the wrong signature. // using (S1 s = new S1()) Diagnostic(ErrorCode.WRN_PatternBadSignature, "S1 s = new S1()").WithArguments("S1", "disposable", "S1.Dispose()").WithLocation(19, 15), // (19,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(19, 15) ); } [Fact] public void UsingPatternExtensionMethodWithInvalidInstanceProperty() { var source = @" ref struct S1 { public int Dispose => 0; } static class C2 { internal static void Dispose(this S1 s1) { } } class C3 { static void Main() { using (S1 s = new S1()) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (16,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(16, 15) ); } [Fact] public void UsingPatternExtensionMethodWithDefaultArguments() { var source = @" ref struct S1 { } static class C2 { internal static void Dispose(this S1 s1, int a = 1) { } } class C3 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (15,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(15, 15), // (19,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (s1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s1b").WithArguments("S1").WithLocation(19, 15) ); } [Fact] public void UsingPatternExtensionMethodOnInStruct() { var source = @" ref struct S1 { } static class C1 { public static void Dispose(in this S1 s1) { } } class C2 { static void Main() { using (S1 s = new S1()) { } } }"; var compilation = CreateCompilation(source).VerifyDiagnostics( // (15,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(15, 15) ); } [Fact] public void UsingPatternExtensionMethodRefParameterOnStruct() { var source = @" ref struct S1 { } static class C1 { public static void Dispose(ref this S1 s1) { } } class C2 { static void Main() { using (S1 s = new S1()) { } } }"; var compilation = CreateCompilation(source).VerifyDiagnostics( // (15,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(15, 15), // (15,18): error CS1657: Cannot use 's' as a ref or out value because it is a 'using variable' // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "S1 s = new S1()").WithArguments("s", "using variable").WithLocation(15, 15) ); } [Fact] public void UsingPatternWithParamsTest() { var source = @" ref struct S1 { public void Dispose(params int[] args){ } } class C2 { static void Main() { using (S1 c = new S1()) { } S1 c1b = new S1(); using (c1b) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPatternWithDefaultParametersTest() { var source = @" ref struct S1 { public void Dispose(int a = 4){ } } class C2 { static void Main() { using (S1 c = new S1()) { } S1 c1b = new S1(); using (c1b) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPatternWrongReturnTest() { var source = @" ref struct S1 { public bool Dispose() { return false; } } class C2 { static void Main() { using (S1 c = new S1()) { } S1 c1b = new S1(); using (c1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (11,16): warning CS0280: 'S1' does not implement the 'disposable' pattern. 'S1.Dispose()' has the wrong signature. // using (S1 c = new S1()) Diagnostic(ErrorCode.WRN_PatternBadSignature, "S1 c = new S1()").WithArguments("S1", "disposable", "S1.Dispose()").WithLocation(11, 16), // (11,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 c = new S1()").WithArguments("S1").WithLocation(11, 16), // (15,16): warning CS0280: 'S1' does not implement the 'disposable' pattern. 'S1.Dispose()' has the wrong signature. // using (c1b) { } Diagnostic(ErrorCode.WRN_PatternBadSignature, "c1b").WithArguments("S1", "disposable", "S1.Dispose()").WithLocation(15, 16), // (15,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (c1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "c1b").WithArguments("S1").WithLocation(15, 16) ); } [Fact] public void UsingPatternWrongAccessibilityTest() { var source = @" ref struct S1 { private void Dispose() { } } class C2 { static void Main() { using (S1 c = new S1()) { } S1 c1b = new S1(); using (c1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (11,16): error CS0122: 'S1.Dispose()' is inaccessible due to its protection level // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_BadAccess, "S1 c = new S1()").WithArguments("S1.Dispose()").WithLocation(11, 16), // (11,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 c = new S1()").WithArguments("S1").WithLocation(11, 16), // (15,16): error CS0122: 'S1.Dispose()' is inaccessible due to its protection level // using (c1b) { } Diagnostic(ErrorCode.ERR_BadAccess, "c1b").WithArguments("S1.Dispose()").WithLocation(15, 16), // (15,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (c1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "c1b").WithArguments("S1").WithLocation(15, 16) ); } [Fact] public void UsingPatternNonPublicAccessibilityTest() { var source = @" ref struct S1 { internal void Dispose() { } } class C2 { static void Main() { using (S1 c = new S1()) { } S1 c1b = new S1(); using (c1b) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPatternStaticMethod() { var source = @" ref struct S1 { public static void Dispose() { } } class C2 { static void Main() { using (S1 c1 = new S1()) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (11,16): error CS0176: Member 'S1.Dispose()' cannot be accessed with an instance reference; qualify it with a type name instead // using (S1 c1 = new S1()) Diagnostic(ErrorCode.ERR_ObjectProhibited, "S1 c1 = new S1()").WithArguments("S1.Dispose()").WithLocation(11, 16), // (11,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c1 = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 c1 = new S1()").WithArguments("S1").WithLocation(11, 16) ); } [Fact] public void UsingPatternGenericMethodTest() { var source = @" ref struct S1 { public void Dispose<T>() { } } class C2 { static void Main() { using (S1 c = new S1()) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (11,16): error CS0411: The type arguments for method 'S1.Dispose<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "S1 c = new S1()").WithArguments("S1.Dispose<T>()").WithLocation(11, 16), // (11,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 c = new S1()").WithArguments("S1").WithLocation(11, 16) ); } [Fact] public void UsingPatternDynamicArgument() { var source = @" class C1 { public void Dispose(dynamic x = null) { } } class C2 { static void Main() { using (C1 c1 = new C1()) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (11,16): error CS1674: 'C1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (C1 c1 = new C1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "C1 c1 = new C1()").WithArguments("C1").WithLocation(11, 16) ); } [Fact] public void UsingPatternAsyncTest() { var source = @" using System.Threading.Tasks; ref struct S1 { public ValueTask DisposeAsync() { System.Console.WriteLine(""Dispose async""); return new ValueTask(Task.CompletedTask); } } class C2 { static async Task Main() { await using (S1 c = new S1()) { } } }"; var compilation = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }).VerifyDiagnostics( // (16,22): error CS4012: Parameters or locals of type 'S1' cannot be declared in async methods or async lambda expressions. // await using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "S1").WithArguments("S1").WithLocation(16, 22) ); } [Fact] [WorkItem(32728, "https://github.com/dotnet/roslyn/issues/32728")] public void UsingPatternWithLangVer7_3() { var source = @" ref struct S1 { public void Dispose() { } } class C2 { static void Main() { using (S1 s = new S1()) { } } } "; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (11,16): error CS8370: The feature 'using declarations' is not available in C# 7.3. Please use language version 8.0 or greater. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "S1 s = new S1()").WithArguments("using declarations", "8.0").WithLocation(11, 16) ); CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics(); } [Fact] [WorkItem(32728, "https://github.com/dotnet/roslyn/issues/32728")] public void UsingInvalidPatternWithLangVer7_3() { var source = @" ref struct S1 { public int Dispose() { return 0; } } class C2 { static void Main() { using (S1 s = new S1()) { } } } "; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (11,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable' or implement a suitable 'Dispose' method. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(11, 16) ); CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (11,16): warning CS0280: 'S1' does not implement the 'disposable' pattern. 'S1.Dispose()' has the wrong signature. // using (S1 s = new S1()) Diagnostic(ErrorCode.WRN_PatternBadSignature, "S1 s = new S1()").WithArguments("S1", "disposable", "S1.Dispose()").WithLocation(11, 16), // (11,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable' or implement a suitable 'Dispose' method. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(11, 16) ); } [Fact] public void Lambda() { var source = @" class C { static void Main() { using (x => x) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,16): error CS1674: 'lambda expression': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "x => x").WithArguments("lambda expression")); } [Fact] public void Null() { var source = @" class C { static void Main() { using (null) { } } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UnusedVariable() { var source = @" class C { static void Main() { using (System.IDisposable d = null) { } } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void EmbeddedStatement() { var source = @" class C { static void Main() { using (System.IDisposable a = null) using (System.IDisposable b = null) using (System.IDisposable c = null) ; } } "; CreateCompilation(source).VerifyDiagnostics( // (8,53): warning CS0642: Possible mistaken empty statement Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";")); } [Fact] public void ModifyUsingLocal() { var source = @" using System; class C { static void Main() { using (IDisposable i = null) { i = null; Ref(ref i); Out(out i); } } static void Ref(ref IDisposable i) { } static void Out(out IDisposable i) { i = null; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,13): error CS1656: Cannot assign to 'i' because it is a 'using variable' // i = null; Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "i").WithArguments("i", "using variable").WithLocation(10, 13), // (11,21): error CS1657: Cannot use 'i' as a ref or out value because it is a 'using variable' // Ref(ref i); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "i").WithArguments("i", "using variable").WithLocation(11, 21), // (12,21): error CS1657: Cannot use 'i' as a ref or out value because it is a 'using variable' // Out(out i); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "i").WithArguments("i", "using variable").WithLocation(12, 21) ); } [Fact] public void ImplicitType1() { var source = @" using System.IO; class C { static void Main() { using (var a = new StreamWriter("""")) { } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var usingStatement = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingStatementSyntax>().Single(); var declaredSymbol = model.GetDeclaredSymbol(usingStatement.Declaration.Variables.Single()); Assert.Equal("System.IO.StreamWriter a", declaredSymbol.ToTestDisplayString()); var typeInfo = model.GetSymbolInfo(usingStatement.Declaration.Type); Assert.Equal(((ILocalSymbol)declaredSymbol).Type, typeInfo.Symbol); } [Fact] public void ImplicitType2() { var source = @" using System.IO; class C { static void Main() { using (var a = new StreamWriter(""""), b = new StreamReader("""")) { } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (8,16): error CS0819: Implicitly-typed variables cannot have multiple declarators Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, @"var a = new StreamWriter(""""), b = new StreamReader("""")")); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var usingStatement = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingStatementSyntax>().Single(); var firstDeclaredSymbol = model.GetDeclaredSymbol(usingStatement.Declaration.Variables.First()); Assert.Equal("System.IO.StreamWriter a", firstDeclaredSymbol.ToTestDisplayString()); var secondDeclaredSymbol = model.GetDeclaredSymbol(usingStatement.Declaration.Variables.Last()); Assert.Equal("System.IO.StreamReader b", secondDeclaredSymbol.ToTestDisplayString()); var typeInfo = model.GetSymbolInfo(usingStatement.Declaration.Type); // the type info uses the type inferred for the first declared local Assert.Equal(((ILocalSymbol)model.GetDeclaredSymbol(usingStatement.Declaration.Variables.First())).Type, typeInfo.Symbol); } [Fact] public void ModifyLocalInUsingExpression() { var source = @" using System; class C { void Main() { IDisposable i = null; using (i) { i = null; //CS0728 Ref(ref i); //CS0728 this[out i] = 1; //CS0728 } } void Ref(ref IDisposable i) { } int this[out IDisposable i] { set { i = null; } } //this is illegal, so if we break this test, we may need a metadata indexer } "; CreateCompilation(source).VerifyDiagnostics( // (18,14): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out"), // (11,13): warning CS0728: Possibly incorrect assignment to local 'i' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "i").WithArguments("i"), // (12,21): warning CS0728: Possibly incorrect assignment to local 'i' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "i").WithArguments("i"), // (13,22): warning CS0728: Possibly incorrect assignment to local 'i' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "i").WithArguments("i")); } [Fact] public void ModifyParameterInUsingExpression() { var source = @" using System; class C { void M(IDisposable i) { using (i) { i = null; //CS0728 Ref(ref i); //CS0728 this[out i] = 1; //CS0728 } } void Ref(ref IDisposable i) { } int this[out IDisposable i] { set { i = null; } } //this is illegal, so if we break this test, we may need a metadata indexer } "; CreateCompilation(source).VerifyDiagnostics( // (17,14): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out"), // (10,13): warning CS0728: Possibly incorrect assignment to local 'i' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "i").WithArguments("i"), // (11,21): warning CS0728: Possibly incorrect assignment to local 'i' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "i").WithArguments("i"), // (12,22): warning CS0728: Possibly incorrect assignment to local 'i' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "i").WithArguments("i")); } // The object could be created outside the "using" statement [Fact] public void ResourceCreatedOutsideUsing() { var source = @" using System; class Program { static void Main(string[] args) { MyManagedType mnObj1 = null; using (mnObj1) { } } } " + _managedClass; var compilation = CreateCompilation(source); VerifyDeclaredSymbolForUsingStatements(compilation); } // The object created inside the "using" statement but declared no variable [Fact] public void ResourceCreatedInsideUsingWithNoVarDeclared() { var source = @" using System; class Program { static void Main(string[] args) { using (new MyManagedType()) { } } } " + _managedStruct; var compilation = CreateCompilation(source); VerifyDeclaredSymbolForUsingStatements(compilation); } // Multiple resource created inside Using /// <bug id="10509" project="Roslyn"/> [Fact()] public void MultipleResourceCreatedInsideUsing() { var source = @" using System; class Program { static void Main(string[] args) { using (MyManagedType mnObj1 = null, mnObj2 = default(MyManagedType)) { } } } " + _managedStruct; var compilation = CreateCompilation(source); var symbols = VerifyDeclaredSymbolForUsingStatements(compilation, 1, "mnObj1", "mnObj2"); foreach (var x in symbols) { VerifySymbolInfoForUsingStatements(compilation, x.Type); } } [Fact] public void MultipleResourceCreatedInNestedUsing() { var source = @" using System; class Program { static void Main(string[] args) { using (MyManagedType mnObj1 = null, mnObj2 = default(MyManagedType)) { using (MyManagedType mnObj3 = null, mnObj4 = default(MyManagedType)) { mnObj3.Dispose(); } } } } " + _managedClass; var compilation = CreateCompilation(source); var symbols = VerifyDeclaredSymbolForUsingStatements(compilation, 2, "mnObj3", "mnObj4"); foreach (var x in symbols) { var localSymbol = x; VerifyLookUpSymbolForUsingStatements(compilation, localSymbol, 2); VerifySymbolInfoForUsingStatements(compilation, x.Type, 2); } } [Fact] public void ResourceTypeDerivedFromClassImplementIdisposable() { var source = @" using System; class Program { public static void Main(string[] args) { using (MyManagedTypeDerived mnObj = new MyManagedTypeDerived()) { } } } class MyManagedTypeDerived : MyManagedType { } " + _managedClass; var compilation = CreateCompilation(source); var symbols = VerifyDeclaredSymbolForUsingStatements(compilation, 1, "mnObj"); foreach (var x in symbols) { var localSymbol = x; VerifyLookUpSymbolForUsingStatements(compilation, localSymbol, 1); VerifySymbolInfoForUsingStatements(compilation, x.Type, 1); } } [Fact] public void LinqInUsing() { var source = @" using System; using System.Linq; class Program { public static void Main(string[] args) { using (var mnObj = (from x in ""1"" select new MyManagedType()).First () ) { } } } " + _managedClass; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var symbols = VerifyDeclaredSymbolForUsingStatements(compilation, 1, "mnObj"); foreach (var x in symbols) { var localSymbol = x; VerifyLookUpSymbolForUsingStatements(compilation, localSymbol, 1); VerifySymbolInfoForUsingStatements(compilation, x.Type, 1); } } [Fact] public void LambdaInUsing() { var source = @" using System; using System.Linq; class Program { public static void Main(string[] args) { MyManagedType[] mnObjs = { }; using (var mnObj = mnObjs.Where(x => x.ToString() == "").First()) { } } } " + _managedStruct; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var symbols = VerifyDeclaredSymbolForUsingStatements(compilation, 1, "mnObj"); foreach (var x in symbols) { var localSymbol = x; VerifyLookUpSymbolForUsingStatements(compilation, localSymbol, 1); VerifySymbolInfoForUsingStatements(compilation, x.Type, 1); } } [Fact] public void UsingForGenericType() { var source = @" using System; using System.Collections.Generic; class Test<T> { public static IEnumerator<T> M<U>(IEnumerable<T> items) where U : IDisposable, new() { using (U u = new U()) { } return null; } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var symbols = VerifyDeclaredSymbolForUsingStatements(compilation, 1, "u"); foreach (var x in symbols) { var localSymbol = x; VerifyLookUpSymbolForUsingStatements(compilation, localSymbol, 1); VerifySymbolInfoForUsingStatements(compilation, x.Type, 1); } } [Fact] public void UsingForGenericTypeWithClassConstraint() { var source = @"using System; class A { } class B : A, IDisposable { void IDisposable.Dispose() { } } class C { static void M<T0, T1, T2, T3, T4>(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4) where T0 : A where T1 : A, IDisposable where T2 : B where T3 : T1 where T4 : T2 { using (t0) { } using (t1) { } using (t2) { } using (t3) { } using (t4) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (16,16): error CS1674: 'T0': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "t0").WithArguments("T0").WithLocation(16, 16)); } [WorkItem(543168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543168")] [Fact] public void EmbeddedDeclaration() { var source = @" class C { static void Main() { using(null) object o = new object(); } } "; CreateCompilation(source).VerifyDiagnostics( // (6,20): error CS1023: Embedded statement cannot be a declaration or labeled statement Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "object o = new object();")); } [WorkItem(529547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529547")] [Fact] public void UnusedLocal() { var source = @" using System; class C : IDisposable { public void Dispose() { } } struct S : IDisposable { public void Dispose() { } } public class Test { public static void Main() { using (S s = new S()) { } //fine using (C c = new C()) { } //fine } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(545331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545331")] [Fact] public void MissingIDisposable() { var source = @" namespace System { public class Object { } public class Void { } } class C { void M() { using (var v = null) ; } }"; CreateEmptyCompilation(source).VerifyDiagnostics( // (11,9): error CS0518: Predefined type 'System.IDisposable' is not defined or imported // using (var v = null) ; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "using").WithArguments("System.IDisposable").WithLocation(11, 9), // (11,20): error CS0815: Cannot assign <null> to an implicitly-typed variable // using (var v = null) ; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "v = null").WithArguments("<null>").WithLocation(11, 20), // (11,30): warning CS0642: Possible mistaken empty statement // using (var v = null) ; Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(11, 30)); } [WorkItem(9581, "https://github.com/dotnet/roslyn/issues/9581")] [Fact] public void TestCyclicInference() { var source = @" class C { void M() { using (var v = v) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (6,24): error CS0841: Cannot use local variable 'v' before it is declared // using (var v = v) { } Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "v").WithArguments("v").WithLocation(6, 24) ); } [Fact] public void SemanticModel_02() { var source = @" class C { static void Main() { System.IDisposable i = null; using (i) { int x; x = 1; } } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "never")); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Single(); Assert.Equal(SpecialType.System_Int32, model.GetTypeInfo(node).Type.SpecialType); } #region help method private UsingStatementSyntax GetUsingStatements(CSharpCompilation compilation, int index = 1) { var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var usingStatements = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingStatementSyntax>().ToList(); return usingStatements[index - 1]; } private IEnumerable<ILocalSymbol> VerifyDeclaredSymbolForUsingStatements(CSharpCompilation compilation, int index = 1, params string[] variables) { var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var usingStatements = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingStatementSyntax>().ToList(); var i = 0; foreach (var x in usingStatements[index - 1].Declaration.Variables) { var symbol = model.GetDeclaredSymbol(x); Assert.Equal(SymbolKind.Local, symbol.Kind); Assert.Equal(variables[i++].ToString(), symbol.ToDisplayString()); yield return (ILocalSymbol)symbol; } } private SymbolInfo VerifySymbolInfoForUsingStatements(CSharpCompilation compilation, ISymbol symbol, int index = 1) { var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var usingStatements = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingStatementSyntax>().ToList(); var type = model.GetSymbolInfo(usingStatements[index - 1].Declaration.Type); Assert.Equal(symbol, type.Symbol); return type; } private ISymbol VerifyLookUpSymbolForUsingStatements(CSharpCompilation compilation, ISymbol symbol, int index = 1) { var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var usingStatements = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingStatementSyntax>().ToList(); var actualSymbol = model.LookupSymbols(usingStatements[index - 1].SpanStart, name: symbol.Name).Single(); Assert.Equal(SymbolKind.Local, actualSymbol.Kind); Assert.Equal(symbol, actualSymbol); return actualSymbol; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Tests related to binding (but not lowering) using statements (not directives). /// </summary> public class UsingStatementTests : CompilingTestBase { private const string _managedClass = @" class MyManagedType : System.IDisposable { public void Dispose() { } }"; private const string _managedStruct = @" struct MyManagedType : System.IDisposable { public void Dispose() { } }"; [Fact] public void SemanticModel() { var source = @" class C { static void Main() { using (System.IDisposable i = null) { i.Dispose(); //this makes no sense, but we're only testing binding } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var usingStatement = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingStatementSyntax>().Single(); var declaredSymbol = model.GetDeclaredSymbol(usingStatement.Declaration.Variables.Single()); Assert.NotNull(declaredSymbol); Assert.Equal(SymbolKind.Local, declaredSymbol.Kind); var declaredLocal = (ILocalSymbol)declaredSymbol; Assert.Equal("i", declaredLocal.Name); Assert.Equal(SpecialType.System_IDisposable, declaredLocal.Type.SpecialType); var memberAccessExpression = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var info = model.GetSymbolInfo(memberAccessExpression.Expression); Assert.NotEqual(default, info); Assert.Equal(declaredLocal, info.Symbol); var lookupSymbol = model.LookupSymbols(memberAccessExpression.SpanStart, name: declaredLocal.Name).Single(); Assert.Equal(declaredLocal, lookupSymbol); } [Fact] public void MethodGroup() { var source = @" class C { static void Main() { using (Main) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,16): error CS1674: 'method group': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "Main").WithArguments("method group")); } [Fact] public void UsingPatternRefStructTest() { var source = @" ref struct S1 { public void Dispose() { } } class C2 { static void Main() { using (S1 s = new S1()) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPatternReferenceTypeTest() { var source = @" class C1 { public void Dispose() { } } class C2 { static void Main() { using (C1 c1 = new C1()) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (11,16): error CS1674: 'C1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (C1 c1 = new C1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "C1 c1 = new C1()").WithArguments("C1").WithLocation(11, 16) ); } [Fact] public void UsingPatternSameSignatureAmbiguousTest() { var source = @" ref struct S1 { public void Dispose() { } public void Dispose() { } } class C2 { static void Main() { using (S1 s = new S1()) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (5,17): error CS0111: Type 'S1' already defines a member called 'Dispose' with the same parameter types // public void Dispose() { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Dispose").WithArguments("Dispose", "S1").WithLocation(5, 17), // (12,16): error CS0121: The call is ambiguous between the following methods or properties: 'S1.Dispose()' and 'S1.Dispose()' // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_AmbigCall, "S1 s = new S1()").WithArguments("S1.Dispose()", "S1.Dispose()").WithLocation(12, 16), // (12,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(12, 16) ); } [Fact] public void UsingPatternAmbiguousOverloadTest() { var source = @" ref struct S1 { public void Dispose() { } public bool Dispose() { return false; } } class C2 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (5,17): error CS0111: Type 'S1' already defines a member called 'Dispose' with the same parameter types // public bool Dispose() { return false; } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Dispose").WithArguments("Dispose", "S1").WithLocation(5, 17), // (12,16): error CS0121: The call is ambiguous between the following methods or properties: 'S1.Dispose()' and 'S1.Dispose()' // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_AmbigCall, "S1 s = new S1()").WithArguments("S1.Dispose()", "S1.Dispose()").WithLocation(12, 16), // (12,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(12, 16), // (16,16): error CS0121: The call is ambiguous between the following methods or properties: 'S1.Dispose()' and 'S1.Dispose()' // using (c1b) { } Diagnostic(ErrorCode.ERR_AmbigCall, "s1b").WithArguments("S1.Dispose()", "S1.Dispose()").WithLocation(16, 16), // (16,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (c1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s1b").WithArguments("S1").WithLocation(16, 16) ); } [Fact] public void UsingPatternDifferentParameterOverloadTest() { var source = @" ref struct S1 { public void Dispose() { } public void Dispose(int x) { } } class C2 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } } }"; // Shouldn't throw an error as the method signatures are different. CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPatternInaccessibleAmbiguousTest() { var source = @" ref struct S1 { public void Dispose() { } internal void Dispose() { } } class C2 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (5,19): error CS0111: Type 'S1' already defines a member called 'Dispose' with the same parameter types // internal void Dispose() { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Dispose").WithArguments("Dispose", "S1").WithLocation(5, 19), // (12,16): error CS0121: The call is ambiguous between the following methods or properties: 'S1.Dispose()' and 'S1.Dispose()' // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_AmbigCall, "S1 s = new S1()").WithArguments("S1.Dispose()", "S1.Dispose()").WithLocation(12, 16), // (12,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(12, 16), // (16,16): error CS0121: The call is ambiguous between the following methods or properties: 'S1.Dispose()' and 'S1.Dispose()' // using (c1b) { } Diagnostic(ErrorCode.ERR_AmbigCall, "s1b").WithArguments("S1.Dispose()", "S1.Dispose()").WithLocation(16, 16), // (16,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (c1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s1b").WithArguments("S1").WithLocation(16, 16) ); } [Fact] public void UsingPatternImplicitConversionToDisposable() { var source = @" ref struct S1 { public void Dispose() { } // User-defined implicit conversion from C2 to S1 public static implicit operator S1(C2 o) { return new S1(); } } class C2 { } class C3 { static void Main() { using (S1 s = new C2()) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPatternExtensionMethodTest() { var source = @" ref struct S1 { } static class C2 { public static void Dispose(this S1 c1) { } } class C3 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (15,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(15, 16), // (19,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (s1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s1b").WithArguments("S1").WithLocation(19, 16) ); } [Fact] public void UsingPatternExtensionMethodPropertyHidingTest() { var source = @" ref struct S1 { public int Dispose { get; } } static class C2 { public static void Dispose(this S1 s1) { } } class C3 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (16,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(16, 16), // (20,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (s1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s1b").WithArguments("S1").WithLocation(20, 16) ); } [Fact] public void UsingPatternStaticMethodTest() { var source = @" ref struct S1 { public static void Dispose() { } } class C2 { static void Main() { using (S1 s = new S1()) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (11,16): error CS0176: Member 'S1.Dispose()' cannot be accessed with an instance reference; qualify it with a type name instead // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_ObjectProhibited, "S1 s = new S1()").WithArguments("S1.Dispose()").WithLocation(11, 16), // (11,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(11, 16) ); } [Fact] public void UsingPatternAmbiguousExtensionMethodTest() { var source = @" ref struct S1 { } static class C2 { public static void Dispose(this S1 s1) { } } static class C3 { public static void Dispose(this S1 s1) { } } class C4 { static void Main() { using (S1 s = new S1()) { } } }"; // Extension methods should just be ignored, rather than rejected after-the-fact. So there should be no error about ambiguities // Tracked by https://github.com/dotnet/roslyn/issues/32767 CreateCompilation(source).VerifyDiagnostics( // (20,16): error CS0121: The call is ambiguous between the following methods or properties: 'C2.Dispose(S1)' and 'C3.Dispose(S1)' // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_AmbigCall, "S1 s = new S1()").WithArguments("C2.Dispose(S1)", "C3.Dispose(S1)").WithLocation(20, 16), // (20,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(20, 16) ); } [Fact] public void UsingPatternScopedExtensionMethodTest() { var source = @" ref struct S1 { } namespace N1 { static class C2 { public static void Dispose(this S1 s1) { } } } namespace N2 { static class C3 { public static void Dispose(this S1 s1) { } } } namespace N3 { static class C4 { public static int Dispose(this S1 s1) { return 0; } } } namespace N4 { partial class C5 { static void M() { using (S1 s = new S1()) // error 1 { } } } } namespace N4 { using N1; partial class C5 { static void M2() { using (S1 s = new S1()) // error 2 { } } } } namespace N4 { using N3; partial class C5 { static void M3() { using (S1 s = new S1()) // error 3 { } } } } namespace N4 { using N1; using N3; partial class C5 { static void M4() { using (S1 s = new S1()) // error 4 { } } } } namespace N4 { using N3; namespace N5 { partial class C5 { static void M5() { using (S1 s = new S1()) // error 5 { } } } namespace N6 { using N1; partial class C5 { static void M6() { using (S1 s = new S1()) // error 6 { } } } } } }"; // Extension methods should just be ignored, rather than rejected after-the-fact. So there should be no error about ambiguities // Tracked by https://github.com/dotnet/roslyn/issues/32767 CreateCompilation(source).VerifyDiagnostics( // (37,20): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) // error 1 Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(37, 20), // (50,20): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) // error 2 Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(50, 20), // (63,20): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) // error 3 Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(63, 20), // (77,20): error CS0121: The call is ambiguous between the following methods or properties: 'N1.C2.Dispose(S1)' and 'N3.C4.Dispose(S1)' // using (S1 s = new S1()) // error 4 Diagnostic(ErrorCode.ERR_AmbigCall, "S1 s = new S1()").WithArguments("N1.C2.Dispose(S1)", "N3.C4.Dispose(S1)").WithLocation(77, 20), // (77,20): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) // error 4 Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(77, 20), // (92,24): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) // error 5 Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(92, 24), // (105,28): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) // error 6 Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(105, 28) ); } [Fact] public void UsingPatternWithMultipleExtensionTargets() { var source = @" ref struct S1 { } ref struct S2 { } static class C3 { public static void Dispose(this S1 s1) { } public static void Dispose(this S2 s2) { } } class C4 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } using (S2 s = new S2()) { } S2 s2b = new S2(); using (s2b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (22,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(22, 16), // (26,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (s1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s1b").WithArguments("S1").WithLocation(26, 16), // (28,16): error CS1674: 'S2': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S2 s = new S2()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S2 s = new S2()").WithArguments("S2").WithLocation(28, 16), // (32,16): error CS1674: 'S2': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (s2b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s2b").WithArguments("S2").WithLocation(32, 16) ); } [Fact] public void UsingPatternExtensionMethodWithDefaultArgumentsAmbiguous() { var source = @" ref struct S1 { } static class C2 { internal static void Dispose(this S1 s1, int a = 1) { } } static class C3 { internal static void Dispose(this S1 s1, int b = 2) { } } class C4 { static void Main() { using (S1 s = new S1()) { } } }"; // Extension methods should just be ignored, rather than rejected after-the-fact. So there should be no error about ambiguities // Tracked by https://github.com/dotnet/roslyn/issues/32767 CreateCompilation(source).VerifyDiagnostics( // (21,15): error CS0121: The call is ambiguous between the following methods or properties: 'C2.Dispose(S1, int)' and 'C3.Dispose(S1, int)' // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_AmbigCall, "S1 s = new S1()").WithArguments("C2.Dispose(S1, int)", "C3.Dispose(S1, int)").WithLocation(21, 15), // (21,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(21, 15) ); } [Fact] public void UsingPatternExtensionMethodNonPublic() { var source = @" ref struct S1 { } static class C2 { internal static void Dispose(this S1 s1) { } } class C3 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (15,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(15, 15), // (19,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (s1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s1b").WithArguments("S1").WithLocation(19, 15) ); } [Fact] public void UsingPatternExtensionMethodWithInvalidInstanceMethod() { var source = @" ref struct S1 { public int Dispose() { return 0; } } static class C2 { internal static void Dispose(this S1 s1) { } } class C3 { static void Main() { using (S1 s = new S1()) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (19,15): warning CS0280: 'S1' does not implement the 'disposable' pattern. 'S1.Dispose()' has the wrong signature. // using (S1 s = new S1()) Diagnostic(ErrorCode.WRN_PatternBadSignature, "S1 s = new S1()").WithArguments("S1", "disposable", "S1.Dispose()").WithLocation(19, 15), // (19,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(19, 15) ); } [Fact] public void UsingPatternExtensionMethodWithInvalidInstanceProperty() { var source = @" ref struct S1 { public int Dispose => 0; } static class C2 { internal static void Dispose(this S1 s1) { } } class C3 { static void Main() { using (S1 s = new S1()) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (16,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(16, 15) ); } [Fact] public void UsingPatternExtensionMethodWithDefaultArguments() { var source = @" ref struct S1 { } static class C2 { internal static void Dispose(this S1 s1, int a = 1) { } } class C3 { static void Main() { using (S1 s = new S1()) { } S1 s1b = new S1(); using (s1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (15,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(15, 15), // (19,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (s1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "s1b").WithArguments("S1").WithLocation(19, 15) ); } [Fact] public void UsingPatternExtensionMethodOnInStruct() { var source = @" ref struct S1 { } static class C1 { public static void Dispose(in this S1 s1) { } } class C2 { static void Main() { using (S1 s = new S1()) { } } }"; var compilation = CreateCompilation(source).VerifyDiagnostics( // (15,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(15, 15) ); } [Fact] public void UsingPatternExtensionMethodRefParameterOnStruct() { var source = @" ref struct S1 { } static class C1 { public static void Dispose(ref this S1 s1) { } } class C2 { static void Main() { using (S1 s = new S1()) { } } }"; var compilation = CreateCompilation(source).VerifyDiagnostics( // (15,15): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(15, 15), // (15,18): error CS1657: Cannot use 's' as a ref or out value because it is a 'using variable' // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "S1 s = new S1()").WithArguments("s", "using variable").WithLocation(15, 15) ); } [Fact] public void UsingPatternWithParamsTest() { var source = @" ref struct S1 { public void Dispose(params int[] args){ } } class C2 { static void Main() { using (S1 c = new S1()) { } S1 c1b = new S1(); using (c1b) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPatternWithDefaultParametersTest() { var source = @" ref struct S1 { public void Dispose(int a = 4){ } } class C2 { static void Main() { using (S1 c = new S1()) { } S1 c1b = new S1(); using (c1b) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPatternWrongReturnTest() { var source = @" ref struct S1 { public bool Dispose() { return false; } } class C2 { static void Main() { using (S1 c = new S1()) { } S1 c1b = new S1(); using (c1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (11,16): warning CS0280: 'S1' does not implement the 'disposable' pattern. 'S1.Dispose()' has the wrong signature. // using (S1 c = new S1()) Diagnostic(ErrorCode.WRN_PatternBadSignature, "S1 c = new S1()").WithArguments("S1", "disposable", "S1.Dispose()").WithLocation(11, 16), // (11,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 c = new S1()").WithArguments("S1").WithLocation(11, 16), // (15,16): warning CS0280: 'S1' does not implement the 'disposable' pattern. 'S1.Dispose()' has the wrong signature. // using (c1b) { } Diagnostic(ErrorCode.WRN_PatternBadSignature, "c1b").WithArguments("S1", "disposable", "S1.Dispose()").WithLocation(15, 16), // (15,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (c1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "c1b").WithArguments("S1").WithLocation(15, 16) ); } [Fact] public void UsingPatternWrongAccessibilityTest() { var source = @" ref struct S1 { private void Dispose() { } } class C2 { static void Main() { using (S1 c = new S1()) { } S1 c1b = new S1(); using (c1b) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (11,16): error CS0122: 'S1.Dispose()' is inaccessible due to its protection level // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_BadAccess, "S1 c = new S1()").WithArguments("S1.Dispose()").WithLocation(11, 16), // (11,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 c = new S1()").WithArguments("S1").WithLocation(11, 16), // (15,16): error CS0122: 'S1.Dispose()' is inaccessible due to its protection level // using (c1b) { } Diagnostic(ErrorCode.ERR_BadAccess, "c1b").WithArguments("S1.Dispose()").WithLocation(15, 16), // (15,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (c1b) { } Diagnostic(ErrorCode.ERR_NoConvToIDisp, "c1b").WithArguments("S1").WithLocation(15, 16) ); } [Fact] public void UsingPatternNonPublicAccessibilityTest() { var source = @" ref struct S1 { internal void Dispose() { } } class C2 { static void Main() { using (S1 c = new S1()) { } S1 c1b = new S1(); using (c1b) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPatternStaticMethod() { var source = @" ref struct S1 { public static void Dispose() { } } class C2 { static void Main() { using (S1 c1 = new S1()) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (11,16): error CS0176: Member 'S1.Dispose()' cannot be accessed with an instance reference; qualify it with a type name instead // using (S1 c1 = new S1()) Diagnostic(ErrorCode.ERR_ObjectProhibited, "S1 c1 = new S1()").WithArguments("S1.Dispose()").WithLocation(11, 16), // (11,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c1 = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 c1 = new S1()").WithArguments("S1").WithLocation(11, 16) ); } [Fact] public void UsingPatternGenericMethodTest() { var source = @" ref struct S1 { public void Dispose<T>() { } } class C2 { static void Main() { using (S1 c = new S1()) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (11,16): error CS0411: The type arguments for method 'S1.Dispose<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "S1 c = new S1()").WithArguments("S1.Dispose<T>()").WithLocation(11, 16), // (11,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 c = new S1()").WithArguments("S1").WithLocation(11, 16) ); } [Fact] public void UsingPatternDynamicArgument() { var source = @" class C1 { public void Dispose(dynamic x = null) { } } class C2 { static void Main() { using (C1 c1 = new C1()) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (11,16): error CS1674: 'C1': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (C1 c1 = new C1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "C1 c1 = new C1()").WithArguments("C1").WithLocation(11, 16) ); } [Fact] public void UsingPatternAsyncTest() { var source = @" using System.Threading.Tasks; ref struct S1 { public ValueTask DisposeAsync() { System.Console.WriteLine(""Dispose async""); return new ValueTask(Task.CompletedTask); } } class C2 { static async Task Main() { await using (S1 c = new S1()) { } } }"; var compilation = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }).VerifyDiagnostics( // (16,22): error CS4012: Parameters or locals of type 'S1' cannot be declared in async methods or async lambda expressions. // await using (S1 c = new S1()) Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "S1").WithArguments("S1").WithLocation(16, 22) ); } [Fact] [WorkItem(32728, "https://github.com/dotnet/roslyn/issues/32728")] public void UsingPatternWithLangVer7_3() { var source = @" ref struct S1 { public void Dispose() { } } class C2 { static void Main() { using (S1 s = new S1()) { } } } "; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (11,16): error CS8370: The feature 'using declarations' is not available in C# 7.3. Please use language version 8.0 or greater. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "S1 s = new S1()").WithArguments("using declarations", "8.0").WithLocation(11, 16) ); CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics(); } [Fact] [WorkItem(32728, "https://github.com/dotnet/roslyn/issues/32728")] public void UsingInvalidPatternWithLangVer7_3() { var source = @" ref struct S1 { public int Dispose() { return 0; } } class C2 { static void Main() { using (S1 s = new S1()) { } } } "; CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (11,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable' or implement a suitable 'Dispose' method. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(11, 16) ); CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (11,16): warning CS0280: 'S1' does not implement the 'disposable' pattern. 'S1.Dispose()' has the wrong signature. // using (S1 s = new S1()) Diagnostic(ErrorCode.WRN_PatternBadSignature, "S1 s = new S1()").WithArguments("S1", "disposable", "S1.Dispose()").WithLocation(11, 16), // (11,16): error CS1674: 'S1': type used in a using statement must be implicitly convertible to 'System.IDisposable' or implement a suitable 'Dispose' method. // using (S1 s = new S1()) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "S1 s = new S1()").WithArguments("S1").WithLocation(11, 16) ); } [Fact] public void Lambda() { var source = @" class C { static void Main() { using (x => x) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,16): error CS1674: 'lambda expression': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "x => x").WithArguments("lambda expression")); } [Fact] public void Null() { var source = @" class C { static void Main() { using (null) { } } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UnusedVariable() { var source = @" class C { static void Main() { using (System.IDisposable d = null) { } } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void EmbeddedStatement() { var source = @" class C { static void Main() { using (System.IDisposable a = null) using (System.IDisposable b = null) using (System.IDisposable c = null) ; } } "; CreateCompilation(source).VerifyDiagnostics( // (8,53): warning CS0642: Possible mistaken empty statement Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";")); } [Fact] public void ModifyUsingLocal() { var source = @" using System; class C { static void Main() { using (IDisposable i = null) { i = null; Ref(ref i); Out(out i); } } static void Ref(ref IDisposable i) { } static void Out(out IDisposable i) { i = null; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,13): error CS1656: Cannot assign to 'i' because it is a 'using variable' // i = null; Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "i").WithArguments("i", "using variable").WithLocation(10, 13), // (11,21): error CS1657: Cannot use 'i' as a ref or out value because it is a 'using variable' // Ref(ref i); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "i").WithArguments("i", "using variable").WithLocation(11, 21), // (12,21): error CS1657: Cannot use 'i' as a ref or out value because it is a 'using variable' // Out(out i); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "i").WithArguments("i", "using variable").WithLocation(12, 21) ); } [Fact] public void ImplicitType1() { var source = @" using System.IO; class C { static void Main() { using (var a = new StreamWriter("""")) { } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var usingStatement = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingStatementSyntax>().Single(); var declaredSymbol = model.GetDeclaredSymbol(usingStatement.Declaration.Variables.Single()); Assert.Equal("System.IO.StreamWriter a", declaredSymbol.ToTestDisplayString()); var typeInfo = model.GetSymbolInfo(usingStatement.Declaration.Type); Assert.Equal(((ILocalSymbol)declaredSymbol).Type, typeInfo.Symbol); } [Fact] public void ImplicitType2() { var source = @" using System.IO; class C { static void Main() { using (var a = new StreamWriter(""""), b = new StreamReader("""")) { } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (8,16): error CS0819: Implicitly-typed variables cannot have multiple declarators Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, @"var a = new StreamWriter(""""), b = new StreamReader("""")")); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var usingStatement = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingStatementSyntax>().Single(); var firstDeclaredSymbol = model.GetDeclaredSymbol(usingStatement.Declaration.Variables.First()); Assert.Equal("System.IO.StreamWriter a", firstDeclaredSymbol.ToTestDisplayString()); var secondDeclaredSymbol = model.GetDeclaredSymbol(usingStatement.Declaration.Variables.Last()); Assert.Equal("System.IO.StreamReader b", secondDeclaredSymbol.ToTestDisplayString()); var typeInfo = model.GetSymbolInfo(usingStatement.Declaration.Type); // the type info uses the type inferred for the first declared local Assert.Equal(((ILocalSymbol)model.GetDeclaredSymbol(usingStatement.Declaration.Variables.First())).Type, typeInfo.Symbol); } [Fact] public void ModifyLocalInUsingExpression() { var source = @" using System; class C { void Main() { IDisposable i = null; using (i) { i = null; //CS0728 Ref(ref i); //CS0728 this[out i] = 1; //CS0728 } } void Ref(ref IDisposable i) { } int this[out IDisposable i] { set { i = null; } } //this is illegal, so if we break this test, we may need a metadata indexer } "; CreateCompilation(source).VerifyDiagnostics( // (18,14): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out"), // (11,13): warning CS0728: Possibly incorrect assignment to local 'i' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "i").WithArguments("i"), // (12,21): warning CS0728: Possibly incorrect assignment to local 'i' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "i").WithArguments("i"), // (13,22): warning CS0728: Possibly incorrect assignment to local 'i' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "i").WithArguments("i")); } [Fact] public void ModifyParameterInUsingExpression() { var source = @" using System; class C { void M(IDisposable i) { using (i) { i = null; //CS0728 Ref(ref i); //CS0728 this[out i] = 1; //CS0728 } } void Ref(ref IDisposable i) { } int this[out IDisposable i] { set { i = null; } } //this is illegal, so if we break this test, we may need a metadata indexer } "; CreateCompilation(source).VerifyDiagnostics( // (17,14): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out"), // (10,13): warning CS0728: Possibly incorrect assignment to local 'i' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "i").WithArguments("i"), // (11,21): warning CS0728: Possibly incorrect assignment to local 'i' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "i").WithArguments("i"), // (12,22): warning CS0728: Possibly incorrect assignment to local 'i' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "i").WithArguments("i")); } // The object could be created outside the "using" statement [Fact] public void ResourceCreatedOutsideUsing() { var source = @" using System; class Program { static void Main(string[] args) { MyManagedType mnObj1 = null; using (mnObj1) { } } } " + _managedClass; var compilation = CreateCompilation(source); VerifyDeclaredSymbolForUsingStatements(compilation); } // The object created inside the "using" statement but declared no variable [Fact] public void ResourceCreatedInsideUsingWithNoVarDeclared() { var source = @" using System; class Program { static void Main(string[] args) { using (new MyManagedType()) { } } } " + _managedStruct; var compilation = CreateCompilation(source); VerifyDeclaredSymbolForUsingStatements(compilation); } // Multiple resource created inside Using /// <bug id="10509" project="Roslyn"/> [Fact()] public void MultipleResourceCreatedInsideUsing() { var source = @" using System; class Program { static void Main(string[] args) { using (MyManagedType mnObj1 = null, mnObj2 = default(MyManagedType)) { } } } " + _managedStruct; var compilation = CreateCompilation(source); var symbols = VerifyDeclaredSymbolForUsingStatements(compilation, 1, "mnObj1", "mnObj2"); foreach (var x in symbols) { VerifySymbolInfoForUsingStatements(compilation, x.Type); } } [Fact] public void MultipleResourceCreatedInNestedUsing() { var source = @" using System; class Program { static void Main(string[] args) { using (MyManagedType mnObj1 = null, mnObj2 = default(MyManagedType)) { using (MyManagedType mnObj3 = null, mnObj4 = default(MyManagedType)) { mnObj3.Dispose(); } } } } " + _managedClass; var compilation = CreateCompilation(source); var symbols = VerifyDeclaredSymbolForUsingStatements(compilation, 2, "mnObj3", "mnObj4"); foreach (var x in symbols) { var localSymbol = x; VerifyLookUpSymbolForUsingStatements(compilation, localSymbol, 2); VerifySymbolInfoForUsingStatements(compilation, x.Type, 2); } } [Fact] public void ResourceTypeDerivedFromClassImplementIdisposable() { var source = @" using System; class Program { public static void Main(string[] args) { using (MyManagedTypeDerived mnObj = new MyManagedTypeDerived()) { } } } class MyManagedTypeDerived : MyManagedType { } " + _managedClass; var compilation = CreateCompilation(source); var symbols = VerifyDeclaredSymbolForUsingStatements(compilation, 1, "mnObj"); foreach (var x in symbols) { var localSymbol = x; VerifyLookUpSymbolForUsingStatements(compilation, localSymbol, 1); VerifySymbolInfoForUsingStatements(compilation, x.Type, 1); } } [Fact] public void LinqInUsing() { var source = @" using System; using System.Linq; class Program { public static void Main(string[] args) { using (var mnObj = (from x in ""1"" select new MyManagedType()).First () ) { } } } " + _managedClass; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var symbols = VerifyDeclaredSymbolForUsingStatements(compilation, 1, "mnObj"); foreach (var x in symbols) { var localSymbol = x; VerifyLookUpSymbolForUsingStatements(compilation, localSymbol, 1); VerifySymbolInfoForUsingStatements(compilation, x.Type, 1); } } [Fact] public void LambdaInUsing() { var source = @" using System; using System.Linq; class Program { public static void Main(string[] args) { MyManagedType[] mnObjs = { }; using (var mnObj = mnObjs.Where(x => x.ToString() == "").First()) { } } } " + _managedStruct; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var symbols = VerifyDeclaredSymbolForUsingStatements(compilation, 1, "mnObj"); foreach (var x in symbols) { var localSymbol = x; VerifyLookUpSymbolForUsingStatements(compilation, localSymbol, 1); VerifySymbolInfoForUsingStatements(compilation, x.Type, 1); } } [Fact] public void UsingForGenericType() { var source = @" using System; using System.Collections.Generic; class Test<T> { public static IEnumerator<T> M<U>(IEnumerable<T> items) where U : IDisposable, new() { using (U u = new U()) { } return null; } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var symbols = VerifyDeclaredSymbolForUsingStatements(compilation, 1, "u"); foreach (var x in symbols) { var localSymbol = x; VerifyLookUpSymbolForUsingStatements(compilation, localSymbol, 1); VerifySymbolInfoForUsingStatements(compilation, x.Type, 1); } } [Fact] public void UsingForGenericTypeWithClassConstraint() { var source = @"using System; class A { } class B : A, IDisposable { void IDisposable.Dispose() { } } class C { static void M<T0, T1, T2, T3, T4>(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4) where T0 : A where T1 : A, IDisposable where T2 : B where T3 : T1 where T4 : T2 { using (t0) { } using (t1) { } using (t2) { } using (t3) { } using (t4) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (16,16): error CS1674: 'T0': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "t0").WithArguments("T0").WithLocation(16, 16)); } [WorkItem(543168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543168")] [Fact] public void EmbeddedDeclaration() { var source = @" class C { static void Main() { using(null) object o = new object(); } } "; CreateCompilation(source).VerifyDiagnostics( // (6,20): error CS1023: Embedded statement cannot be a declaration or labeled statement Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "object o = new object();")); } [WorkItem(529547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529547")] [Fact] public void UnusedLocal() { var source = @" using System; class C : IDisposable { public void Dispose() { } } struct S : IDisposable { public void Dispose() { } } public class Test { public static void Main() { using (S s = new S()) { } //fine using (C c = new C()) { } //fine } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(545331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545331")] [Fact] public void MissingIDisposable() { var source = @" namespace System { public class Object { } public class Void { } } class C { void M() { using (var v = null) ; } }"; CreateEmptyCompilation(source).VerifyDiagnostics( // (11,9): error CS0518: Predefined type 'System.IDisposable' is not defined or imported // using (var v = null) ; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "using").WithArguments("System.IDisposable").WithLocation(11, 9), // (11,20): error CS0815: Cannot assign <null> to an implicitly-typed variable // using (var v = null) ; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "v = null").WithArguments("<null>").WithLocation(11, 20), // (11,30): warning CS0642: Possible mistaken empty statement // using (var v = null) ; Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(11, 30)); } [WorkItem(9581, "https://github.com/dotnet/roslyn/issues/9581")] [Fact] public void TestCyclicInference() { var source = @" class C { void M() { using (var v = v) { } } }"; CreateCompilation(source).VerifyDiagnostics( // (6,24): error CS0841: Cannot use local variable 'v' before it is declared // using (var v = v) { } Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "v").WithArguments("v").WithLocation(6, 24) ); } [Fact] public void SemanticModel_02() { var source = @" class C { static void Main() { System.IDisposable i = null; using (i) { int x; x = 1; } } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "never")); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Single(); Assert.Equal(SpecialType.System_Int32, model.GetTypeInfo(node).Type.SpecialType); } #region help method private UsingStatementSyntax GetUsingStatements(CSharpCompilation compilation, int index = 1) { var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var usingStatements = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingStatementSyntax>().ToList(); return usingStatements[index - 1]; } private IEnumerable<ILocalSymbol> VerifyDeclaredSymbolForUsingStatements(CSharpCompilation compilation, int index = 1, params string[] variables) { var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var usingStatements = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingStatementSyntax>().ToList(); var i = 0; foreach (var x in usingStatements[index - 1].Declaration.Variables) { var symbol = model.GetDeclaredSymbol(x); Assert.Equal(SymbolKind.Local, symbol.Kind); Assert.Equal(variables[i++].ToString(), symbol.ToDisplayString()); yield return (ILocalSymbol)symbol; } } private SymbolInfo VerifySymbolInfoForUsingStatements(CSharpCompilation compilation, ISymbol symbol, int index = 1) { var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var usingStatements = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingStatementSyntax>().ToList(); var type = model.GetSymbolInfo(usingStatements[index - 1].Declaration.Type); Assert.Equal(symbol, type.Symbol); return type; } private ISymbol VerifyLookUpSymbolForUsingStatements(CSharpCompilation compilation, ISymbol symbol, int index = 1) { var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var usingStatements = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingStatementSyntax>().ToList(); var actualSymbol = model.LookupSymbols(usingStatements[index - 1].SpanStart, name: symbol.Name).Single(); Assert.Equal(SymbolKind.Local, actualSymbol.Kind); Assert.Equal(symbol, actualSymbol); return actualSymbol; } #endregion } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/Core/ReferenceHighlighting/NagivateToHighlightReferenceCommandHandler.StartComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.ReferenceHighlighting { internal partial class NavigateToHighlightReferenceCommandHandler { private class StartComparer : IComparer<SnapshotSpan> { public int Compare(SnapshotSpan x, SnapshotSpan y) => x.Start.CompareTo(y.Start); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.ReferenceHighlighting { internal partial class NavigateToHighlightReferenceCommandHandler { private class StartComparer : IComparer<SnapshotSpan> { public int Compare(SnapshotSpan x, SnapshotSpan y) => x.Start.CompareTo(y.Start); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/Core/Portable/CodeAnalysisResources.resx
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="OutputKindNotSupported" xml:space="preserve"> <value>Output kind not supported.</value> </data> <data name="PathReturnedByResolveMetadataFileMustBeAbsolute" xml:space="preserve"> <value>Path returned by {0}.ResolveMetadataFile must be absolute: '{1}'</value> </data> <data name="AssemblyMustHaveAtLeastOneModule" xml:space="preserve"> <value>Assembly must have at least one module.</value> </data> <data name="ModuleCopyCannotBeUsedToCreateAssemblyMetadata" xml:space="preserve"> <value>Module copy can't be used to create an assembly metadata.</value> </data> <data name="Unresolved" xml:space="preserve"> <value>Unresolved: </value> </data> <data name="Assembly" xml:space="preserve"> <value>assembly</value> </data> <data name="Class1" xml:space="preserve"> <value>class</value> </data> <data name="Constructor" xml:space="preserve"> <value>constructor</value> </data> <data name="Delegate1" xml:space="preserve"> <value>delegate</value> </data> <data name="Enum1" xml:space="preserve"> <value>enum</value> </data> <data name="Event1" xml:space="preserve"> <value>event</value> </data> <data name="Field" xml:space="preserve"> <value>field</value> </data> <data name="TypeParameter" xml:space="preserve"> <value>type parameter</value> </data> <data name="Interface1" xml:space="preserve"> <value>interface</value> </data> <data name="Method" xml:space="preserve"> <value>method</value> </data> <data name="Module" xml:space="preserve"> <value>module</value> </data> <data name="Parameter" xml:space="preserve"> <value>parameter</value> </data> <data name="Property" xml:space="preserve"> <value>property, indexer</value> </data> <data name="Return1" xml:space="preserve"> <value>return</value> </data> <data name="Struct1" xml:space="preserve"> <value>struct</value> </data> <data name="CannotCreateReferenceToSubmission" xml:space="preserve"> <value>Can't create a reference to a submission.</value> </data> <data name="CannotCreateReferenceToModule" xml:space="preserve"> <value>Can't create a reference to a module.</value> </data> <data name="InMemoryAssembly" xml:space="preserve"> <value>&lt;in-memory assembly&gt;</value> </data> <data name="InMemoryModule" xml:space="preserve"> <value>&lt;in-memory module&gt;</value> </data> <data name="SizeHasToBePositive" xml:space="preserve"> <value>Size has to be positive.</value> </data> <data name="AssemblyFileNotFound" xml:space="preserve"> <value>Assembly file not found</value> </data> <data name="CannotEmbedInteropTypesFromModule" xml:space="preserve"> <value>Can't embed interop types from module.</value> </data> <data name="CannotAliasModule" xml:space="preserve"> <value>Can't alias a module.</value> </data> <data name="InvalidAlias" xml:space="preserve"> <value>Invalid alias.</value> </data> <data name="GetMetadataMustReturnInstance" xml:space="preserve"> <value>{0}.GetMetadata() must return an instance of {1}.</value> </data> <data name="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer" xml:space="preserve"> <value>Value too large to be represented as a 30 bit unsigned integer.</value> </data> <data name="Arrays_with_more_than_one_dimension_cannot_be_serialized" xml:space="preserve"> <value>Arrays with more than one dimension cannot be serialized.</value> </data> <data name="InvalidAssemblyName" xml:space="preserve"> <value>Invalid assembly name: '{0}'</value> </data> <data name="AbsolutePathExpected" xml:space="preserve"> <value>Absolute path expected.</value> </data> <data name="EmptyKeyInPathMap" xml:space="preserve"> <value>A key in the pathMap is empty.</value> </data> <data name="NullValueInPathMap" xml:space="preserve"> <value>A value in the pathMap is null.</value> </data> <data name="CompilationOptionsMustNotHaveErrors" xml:space="preserve"> <value>Compilation options must not have errors.</value> </data> <data name="ReturnTypeCannotBeValuePointerbyRefOrOpen" xml:space="preserve"> <value>Return type can't be a value type, pointer, by-ref or open generic type</value> </data> <data name="ReturnTypeCannotBeVoidByRefOrOpen" xml:space="preserve"> <value>Return type can't be void, by-ref or open generic type</value> </data> <data name="TypeMustBeSameAsHostObjectTypeOfPreviousSubmission" xml:space="preserve"> <value>Type must be same as host object type of previous submission.</value> </data> <data name="PreviousSubmissionHasErrors" xml:space="preserve"> <value>Previous submission has errors.</value> </data> <data name="InvalidOutputKindForSubmission" xml:space="preserve"> <value>Invalid output kind for submission. DynamicallyLinkedLibrary expected.</value> </data> <data name="InvalidCompilationOptions" xml:space="preserve"> <value>Invalid compilation options -- submission can't be signed.</value> </data> <data name="ResourceStreamProviderShouldReturnNonNullStream" xml:space="preserve"> <value>Resource stream provider should return non-null stream.</value> </data> <data name="ReferenceResolverShouldReturnReadableNonNullStream" xml:space="preserve"> <value>Reference resolver should return readable non-null stream.</value> </data> <data name="EmptyOrInvalidResourceName" xml:space="preserve"> <value>Empty or invalid resource name</value> </data> <data name="EmptyOrInvalidFileName" xml:space="preserve"> <value>Empty or invalid file name</value> </data> <data name="ResourceDataProviderShouldReturnNonNullStream" xml:space="preserve"> <value>Resource data provider should return non-null stream</value> </data> <data name="FileNotFound" xml:space="preserve"> <value>File not found.</value> </data> <data name="PathReturnedByResolveStrongNameKeyFileMustBeAbsolute" xml:space="preserve"> <value>Path returned by {0}.ResolveStrongNameKeyFile must be absolute: '{1}'</value> </data> <data name="TypeMustBeASubclassOfSyntaxAnnotation" xml:space="preserve"> <value>type must be a subclass of SyntaxAnnotation.</value> </data> <data name="InvalidModuleName" xml:space="preserve"> <value>Invalid module name specified in metadata module '{0}': '{1}'</value> </data> <data name="FileSizeExceedsMaximumAllowed" xml:space="preserve"> <value>File size exceeds maximum allowed size of a valid metadata file.</value> </data> <data name="NameCannotBeNull" xml:space="preserve"> <value>Name cannot be null.</value> </data> <data name="NameCannotBeEmpty" xml:space="preserve"> <value>Name cannot be empty.</value> </data> <data name="NameCannotStartWithWhitespace" xml:space="preserve"> <value>Name cannot start with whitespace.</value> </data> <data name="NameContainsInvalidCharacter" xml:space="preserve"> <value>Name contains invalid characters.</value> </data> <data name="SpanDoesNotIncludeStartOfLine" xml:space="preserve"> <value>The span does not include the start of a line.</value> </data> <data name="SpanDoesNotIncludeEndOfLine" xml:space="preserve"> <value>The span does not include the end of a line.</value> </data> <data name="StartMustNotBeNegative" xml:space="preserve"> <value>'start' must not be negative</value> </data> <data name="EndMustNotBeLessThanStart" xml:space="preserve"> <value>'end' must not be less than 'start'</value> </data> <data name="InvalidContentType" xml:space="preserve"> <value>Invalid content type</value> </data> <data name="ExpectedNonEmptyPublicKey" xml:space="preserve"> <value>Expected non-empty public key</value> </data> <data name="InvalidSizeOfPublicKeyToken" xml:space="preserve"> <value>Invalid size of public key token.</value> </data> <data name="InvalidCharactersInAssemblyName" xml:space="preserve"> <value>Invalid characters in assembly name</value> </data> <data name="InvalidCharactersInAssemblyCultureName" xml:space="preserve"> <value>Invalid characters in assembly culture name</value> </data> <data name="StreamMustSupportReadAndSeek" xml:space="preserve"> <value>Stream must support read and seek operations.</value> </data> <data name="StreamMustSupportRead" xml:space="preserve"> <value>Stream must be readable.</value> </data> <data name="StreamMustSupportWrite" xml:space="preserve"> <value>Stream must be writable.</value> </data> <data name="PdbStreamUnexpectedWhenEmbedding" xml:space="preserve"> <value>PDB stream should not be given when embedding PDB into the PE stream.</value> </data> <data name="PdbStreamUnexpectedWhenEmittingMetadataOnly" xml:space="preserve"> <value>PDB stream should not be given when emitting metadata only.</value> </data> <data name="MetadataPeStreamUnexpectedWhenEmittingMetadataOnly" xml:space="preserve"> <value>Metadata PE stream should not be given when emitting metadata only.</value> </data> <data name="IncludingPrivateMembersUnexpectedWhenEmittingToMetadataPeStream" xml:space="preserve"> <value>Including private members should not be used when emitting to the secondary assembly output.</value> </data> <data name="MustIncludePrivateMembersUnlessRefAssembly" xml:space="preserve"> <value>Must include private members unless emitting a ref assembly.</value> </data> <data name="EmbeddingPdbUnexpectedWhenEmittingMetadata" xml:space="preserve"> <value>Embedding PDB is not allowed when emitting metadata.</value> </data> <data name="CannotTargetNetModuleWhenEmittingRefAssembly" xml:space="preserve"> <value>Cannot target net module when emitting ref assembly.</value> </data> <data name="InvalidHash" xml:space="preserve"> <value>Invalid hash.</value> </data> <data name="UnsupportedHashAlgorithm" xml:space="preserve"> <value>Unsupported hash algorithm.</value> </data> <data name="InconsistentLanguageVersions" xml:space="preserve"> <value>Inconsistent language versions</value> </data> <data name="CoffResourceInvalidRelocation" xml:space="preserve"> <value>Win32 resources, assumed to be in COFF object format, have one or more invalid relocation header values.</value> </data> <data name="CoffResourceInvalidSectionSize" xml:space="preserve"> <value>Win32 resources, assumed to be in COFF object format, have an invalid section size.</value> </data> <data name="CoffResourceInvalidSymbol" xml:space="preserve"> <value>Win32 resources, assumed to be in COFF object format, have one or more invalid symbol values.</value> </data> <data name="CoffResourceMissingSection" xml:space="preserve"> <value>Win32 resources, assumed to be in COFF object format, are missing one or both of sections '.rsrc$01' and '.rsrc$02'</value> </data> <data name="IconStreamUnexpectedFormat" xml:space="preserve"> <value>Icon stream is not in the expected format.</value> </data> <data name="InvalidCultureName" xml:space="preserve"> <value>Invalid culture name: '{0}'</value> </data> <data name="WinRTIdentityCantBeRetargetable" xml:space="preserve"> <value>WindowsRuntime identity can't be retargetable</value> </data> <data name="PEImageNotAvailable" xml:space="preserve"> <value>PE image not available.</value> </data> <data name="AssemblySigningNotSupported" xml:space="preserve"> <value>Assembly signing not supported.</value> </data> <data name="XmlReferencesNotSupported" xml:space="preserve"> <value>References to XML documents are not supported.</value> </data> <data name="FailedToResolveRuleSetName" xml:space="preserve"> <value>Could not locate the rule set file '{0}'.</value> </data> <data name="InvalidRuleSetInclude" xml:space="preserve"> <value>An error occurred while loading the included rule set file {0} - {1}</value> </data> <data name="CompilerAnalyzerFailure" xml:space="preserve"> <value>Analyzer Failure</value> <comment>{0}: Analyzer name {1}: Type name {2}: Localized exception message {3}: Localized detail message</comment> </data> <data name="CompilerAnalyzerThrows" xml:space="preserve"> <value>Analyzer '{0}' threw an exception of type '{1}' with message '{2}'. {3}</value> </data> <data name="CompilerAnalyzerThrowsDescription" xml:space="preserve"> <value>Analyzer '{0}' threw the following exception: '{1}'.</value> </data> <data name="AnalyzerDriverFailure" xml:space="preserve"> <value>Analyzer Driver Failure</value> </data> <data name="AnalyzerDriverThrows" xml:space="preserve"> <value>Analyzer driver threw an exception of type '{0}' with message '{1}'.</value> </data> <data name="AnalyzerDriverThrowsDescription" xml:space="preserve"> <value>Analyzer driver threw the following exception: '{0}'.</value> </data> <data name="PEImageDoesntContainManagedMetadata" xml:space="preserve"> <value>PE image doesn't contain managed metadata.</value> </data> <data name="ChangesMustNotOverlap" xml:space="preserve"> <value>The changes must not overlap.</value> </data> <data name="DiagnosticIdCantBeNullOrWhitespace" xml:space="preserve"> <value>A DiagnosticDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space.</value> </data> <data name="SuppressionIdCantBeNullOrWhitespace" xml:space="preserve"> <value>A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space.</value> </data> <data name="RuleSetHasDuplicateRules" xml:space="preserve"> <value>The rule set file has duplicate rules for '{0}' with differing actions '{1}' and '{2}'.</value> </data> <data name="CantCreateModuleReferenceToAssembly" xml:space="preserve"> <value>Can't create a module reference to an assembly.</value> </data> <data name="CantCreateReferenceToDynamicAssembly" xml:space="preserve"> <value>Can't create a metadata reference to a dynamic assembly.</value> </data> <data name="CantCreateReferenceToAssemblyWithoutLocation" xml:space="preserve"> <value>Can't create a metadata reference to an assembly without location.</value> </data> <data name="ArgumentCannotBeEmpty" xml:space="preserve"> <value>Argument cannot be empty.</value> </data> <data name="ArgumentElementCannotBeNull" xml:space="preserve"> <value>Argument cannot have a null element.</value> </data> <data name="UnsupportedDiagnosticReported" xml:space="preserve"> <value>Reported diagnostic with ID '{0}' is not supported by the analyzer.</value> </data> <data name="UnsupportedSuppressionReported" xml:space="preserve"> <value>Reported suppression with ID '{0}' is not supported by the suppressor.</value> </data> <data name="InvalidDiagnosticSuppressionReported" xml:space="preserve"> <value>Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor.</value> </data> <data name="NonReportedDiagnosticCannotBeSuppressed" xml:space="preserve"> <value>Non-reported diagnostic with ID '{0}' cannot be suppressed.</value> </data> <data name="InvalidDiagnosticIdReported" xml:space="preserve"> <value>Reported diagnostic has an ID '{0}', which is not a valid identifier.</value> </data> <data name="InvalidDiagnosticLocationReported" xml:space="preserve"> <value>Reported diagnostic '{0}' has a source location in file '{1}', which is not part of the compilation being analyzed.</value> </data> <data name="SupportedDiagnosticsHasNullDescriptor" xml:space="preserve"> <value>Analyzer '{0}' contains a null descriptor in its 'SupportedDiagnostics'.</value> </data> <data name="SupportedSuppressionsHasNullDescriptor" xml:space="preserve"> <value>Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'.</value> </data> <data name="The_type_0_is_not_understood_by_the_serialization_binder" xml:space="preserve"> <value>The type '{0}' is not understood by the serialization binder.</value> </data> <data name="Cannot_deserialize_type_0" xml:space="preserve"> <value>Cannot deserialize type '{0}'.</value> </data> <data name="Cannot_serialize_type_0" xml:space="preserve"> <value>Cannot serialize type '{0}'.</value> </data> <data name="InvalidNodeToTrack" xml:space="preserve"> <value>Node to track is not a descendant of the root.</value> </data> <data name="NodeOrTokenOutOfSequence" xml:space="preserve"> <value>A node or token is out of sequence.</value> </data> <data name="UnexpectedTypeOfNodeInList" xml:space="preserve"> <value>A node in the list is not of the expected type.</value> </data> <data name="MissingListItem" xml:space="preserve"> <value>The item specified is not the element of a list.</value> </data> <data name="InvalidPublicKey" xml:space="preserve"> <value>Invalid public key.</value> </data> <data name="InvalidPublicKeyToken" xml:space="preserve"> <value>Invalid public key token.</value> </data> <data name="InvalidDataAtOffset" xml:space="preserve"> <value>Invalid data at offset {0}: {1}{2}*{3}{4}</value> </data> <data name="SymWriterNotDeterministic" xml:space="preserve"> <value>Windows PDB writer doesn't support deterministic compilation: '{0}'</value> </data> <data name="SymWriterOlderVersionThanRequired" xml:space="preserve"> <value>The version of Windows PDB writer is older than required: '{0}'</value> </data> <data name="SymWriterDoesNotSupportSourceLink" xml:space="preserve"> <value>Windows PDB writer doesn't support SourceLink feature: '{0}'</value> </data> <data name="RuleSetBadAttributeValue" xml:space="preserve"> <value>The attribute {0} has an invalid value of {1}.</value> </data> <data name="RuleSetMissingAttribute" xml:space="preserve"> <value>The element {0} is missing an attribute named {1}.</value> </data> <data name="KeepAliveIsNotAnInteger" xml:space="preserve"> <value>Argument to '/keepalive' option is not a 32-bit integer.</value> </data> <data name="KeepAliveIsTooSmall" xml:space="preserve"> <value>Arguments to '/keepalive' option below -1 are invalid.</value> </data> <data name="KeepAliveWithoutShared" xml:space="preserve"> <value>'/keepalive' option is only valid with '/shared' option.</value> </data> <data name="MismatchedVersion" xml:space="preserve"> <value>Roslyn compiler server reports different protocol version than build task.</value> </data> <data name="MissingKeepAlive" xml:space="preserve"> <value>Missing argument for '/keepalive' option.</value> </data> <data name="AnalyzerTotalExecutionTime" xml:space="preserve"> <value>Total analyzer execution time: {0} seconds.</value> </data> <data name="MultithreadedAnalyzerExecutionNote" xml:space="preserve"> <value>NOTE: Elapsed time may be less than analyzer execution time because analyzers can run concurrently.</value> </data> <data name="AnalyzerExecutionTimeColumnHeader" xml:space="preserve"> <value>Time (s)</value> </data> <data name="AnalyzerNameColumnHeader" xml:space="preserve"> <value>Analyzer</value> </data> <data name="NoAnalyzersFound" xml:space="preserve"> <value>No analyzers found</value> </data> <data name="DuplicateAnalyzerInstances" xml:space="preserve"> <value>Argument contains duplicate analyzer instances.</value> </data> <data name="UnsupportedAnalyzerInstance" xml:space="preserve"> <value>Argument contains an analyzer instance that does not belong to the 'Analyzers' for this CompilationWithAnalyzers instance.</value> </data> <data name="InvalidTree" xml:space="preserve"> <value>Syntax tree doesn't belong to the underlying 'Compilation'.</value> </data> <data name="InvalidAdditionalFile" xml:space="preserve"> <value>Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'.</value> </data> <data name="ResourceStreamEndedUnexpectedly" xml:space="preserve"> <value>Resource stream ended at {0} bytes, expected {1} bytes.</value> </data> <data name="SharedArgumentMissing" xml:space="preserve"> <value>Value for argument '/shared:' must not be empty</value> </data> <data name="ExceptionContext" xml:space="preserve"> <value>Exception occurred with following context: {0}</value> </data> <data name="AnonymousTypeMemberAndNamesCountMismatch2" xml:space="preserve"> <value>{0} and {1} must have the same length.</value> </data> <data name="AnonymousTypeArgumentCountMismatch2" xml:space="preserve"> <value>{0} must either be 'default' or have the same length as {1}.</value> </data> <data name="InconsistentSyntaxTreeFeature" xml:space="preserve"> <value>Inconsistent syntax tree features</value> </data> <data name="ReferenceOfTypeIsInvalid1" xml:space="preserve"> <value>Reference of type '{0}' is not valid for this compilation.</value> </data> <data name="MetadataRefNotFoundToRemove1" xml:space="preserve"> <value>MetadataReference '{0}' not found to remove.</value> </data> <data name="TupleElementNameCountMismatch" xml:space="preserve"> <value>If tuple element names are specified, the number of element names must match the cardinality of the tuple.</value> </data> <data name="TupleElementNameEmpty" xml:space="preserve"> <value>Tuple element name cannot be an empty string.</value> </data> <data name="TupleElementLocationCountMismatch" xml:space="preserve"> <value>If tuple element locations are specified, the number of locations must match the cardinality of the tuple.</value> </data> <data name="TupleElementNullableAnnotationCountMismatch" xml:space="preserve"> <value>If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple.</value> </data> <data name="TuplesNeedAtLeastTwoElements" xml:space="preserve"> <value>Tuples must have at least two elements.</value> </data> <data name="CompilationReferencesAssembliesWithDifferentAutoGeneratedVersion" xml:space="preserve"> <value>The compilation references multiple assemblies whose versions only differ in auto-generated build and/or revision numbers.</value> </data> <data name="TupleUnderlyingTypeMustBeTupleCompatible" xml:space="preserve"> <value>The underlying type for a tuple must be tuple-compatible.</value> </data> <data name="UnrecognizedResourceFileFormat" xml:space="preserve"> <value>Unrecognized resource file format.</value> </data> <data name="SourceTextCannotBeEmbedded" xml:space="preserve"> <value>SourceText cannot be embedded. Provide encoding or canBeEmbedded=true at construction.</value> </data> <data name="StreamIsTooLong" xml:space="preserve"> <value>Stream is too long.</value> </data> <data name="EmbeddedTextsRequirePdb" xml:space="preserve"> <value>Embedded texts are only supported when emitting a PDB.</value> </data> <data name="TheStreamCannotBeWrittenTo" xml:space="preserve"> <value>The stream cannot be written to.</value> </data> <data name="ElementIsExpected" xml:space="preserve"> <value>element is expected</value> </data> <data name="SeparatorIsExpected" xml:space="preserve"> <value>separator is expected</value> </data> <data name="TheStreamCannotBeReadFrom" xml:space="preserve"> <value>The stream cannot be read from.</value> </data> <data name="Deserialization_reader_for_0_read_incorrect_number_of_values" xml:space="preserve"> <value>Deserialization reader for '{0}' read incorrect number of values.</value> </data> <data name="Stream_contains_invalid_data" xml:space="preserve"> <value>Stream contains invalid data</value> </data> <data name="InvalidDiagnosticSpanReported" xml:space="preserve"> <value>Reported diagnostic '{0}' has a source location '{1}' in file '{2}', which is outside of the given file.</value> </data> <data name="ExceptionEnablingMulticoreJit" xml:space="preserve"> <value>Warning: Could not enable multicore JIT due to exception: {0}.</value> </data> <data name="NotARootOperation" xml:space="preserve"> <value>Given operation has a non-null parent.</value> </data> <data name="OperationHasNullSemanticModel" xml:space="preserve"> <value>Given operation has a null semantic model.</value> </data> <data name="InvalidOperationBlockForAnalysisContext" xml:space="preserve"> <value>Given operation block does not belong to the current analysis context.</value> </data> <data name="IsSymbolAccessibleBadWithin" xml:space="preserve"> <value>Parameter '{0}' must be an 'INamedTypeSymbol' or an 'IAssemblySymbol'.</value> </data> <data name="IsSymbolAccessibleWrongAssembly" xml:space="preserve"> <value>Parameter '{0}' must be a symbol from this compilation or some referenced assembly.</value> </data> <data name="OperationMustNotBeControlFlowGraphPart" xml:space="preserve"> <value>The provided operation must not be part of a Control Flow Graph.</value> </data> <data name="A_language_name_cannot_be_specified_for_this_option" xml:space="preserve"> <value>A language name cannot be specified for this option.</value> </data> <data name="A_language_name_must_be_specified_for_this_option" xml:space="preserve"> <value>A language name must be specified for this option.</value> </data> <data name="WRN_InvalidSeverityInAnalyzerConfig" xml:space="preserve"> <value>The diagnostic '{0}' was given an invalid severity '{1}' in the analyzer config file at '{2}'.</value> </data> <data name="WRN_InvalidSeverityInAnalyzerConfig_Title" xml:space="preserve"> <value>Invalid severity in analyzer config file.</value> </data> <data name="SuppressionDiagnosticDescriptorTitle" xml:space="preserve"> <value>Programmatic suppression of an analyzer diagnostic</value> </data> <data name="SuppressionDiagnosticDescriptorMessage" xml:space="preserve"> <value>Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}'</value> </data> <data name="ModuleHasInvalidAttributes" xml:space="preserve"> <value>Module has invalid attributes.</value> </data> <data name="UnableToDetermineSpecificCauseOfFailure" xml:space="preserve"> <value>Unable to determine specific cause of the failure.</value> </data> <data name="ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging" xml:space="preserve"> <value>Changing the version of an assembly reference is not allowed during debugging: '{0}' changed version to '{1}'.</value> </data> <data name="DisableAnalyzerDiagnosticsMessage" xml:space="preserve"> <value>Suppress the following diagnostics to disable this analyzer: {0}</value> <comment>{0}: Comma-separated list of diagnostic IDs</comment> </data> <data name="Single_type_per_generator_0" xml:space="preserve"> <value>Only a single {0} can be registered per generator.</value> <comment>{0}: type name</comment> </data> <data name="WRN_MultipleGlobalAnalyzerKeys" xml:space="preserve"> <value>Multiple global analyzer config files set the same key '{0}' in section '{1}'. It has been unset. Key was set by the following files: '{2}'</value> </data> <data name="WRN_MultipleGlobalAnalyzerKeys_Title" xml:space="preserve"> <value>Multiple global analyzer config files set the same key. It has been unset.</value> </data> <data name="HintNameUniquePerGenerator" xml:space="preserve"> <value>The hintName '{0}' of the added source file must be unique within a generator.</value> <comment>{0}: the provided hintname</comment> </data> <data name="HintNameInvalidChar" xml:space="preserve"> <value>The hintName '{0}' contains an invalid character '{1}' at position {2}.</value> <comment>{0}: the provided hintname. {1}: the invalid character, {2} the position it occurred at</comment> </data> <data name="SourceTextRequiresEncoding" xml:space="preserve"> <value>The SourceText with hintName '{0}' must have an explicit encoding set.</value> <comment>'SourceText' is not localizable. {0}: the provided hintname</comment> </data> <data name="AssemblyReferencesNetFramework" xml:space="preserve"> <value>The assembly containing type '{0}' references .NET Framework, which is not supported.</value> </data> <data name="WRN_InvalidGlobalSectionName" xml:space="preserve"> <value>Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}'</value> <comment>{0}: invalid section name, {1} path to global config</comment> </data> <data name="WRN_InvalidGlobalSectionName_Title" xml:space="preserve"> <value>Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored.</value> </data> <data name="ChangesMustBeWithinBoundsOfSourceText" xml:space="preserve"> <value>Changes must be within bounds of SourceText</value> </data> </root>
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="OutputKindNotSupported" xml:space="preserve"> <value>Output kind not supported.</value> </data> <data name="PathReturnedByResolveMetadataFileMustBeAbsolute" xml:space="preserve"> <value>Path returned by {0}.ResolveMetadataFile must be absolute: '{1}'</value> </data> <data name="AssemblyMustHaveAtLeastOneModule" xml:space="preserve"> <value>Assembly must have at least one module.</value> </data> <data name="ModuleCopyCannotBeUsedToCreateAssemblyMetadata" xml:space="preserve"> <value>Module copy can't be used to create an assembly metadata.</value> </data> <data name="Unresolved" xml:space="preserve"> <value>Unresolved: </value> </data> <data name="Assembly" xml:space="preserve"> <value>assembly</value> </data> <data name="Class1" xml:space="preserve"> <value>class</value> </data> <data name="Constructor" xml:space="preserve"> <value>constructor</value> </data> <data name="Delegate1" xml:space="preserve"> <value>delegate</value> </data> <data name="Enum1" xml:space="preserve"> <value>enum</value> </data> <data name="Event1" xml:space="preserve"> <value>event</value> </data> <data name="Field" xml:space="preserve"> <value>field</value> </data> <data name="TypeParameter" xml:space="preserve"> <value>type parameter</value> </data> <data name="Interface1" xml:space="preserve"> <value>interface</value> </data> <data name="Method" xml:space="preserve"> <value>method</value> </data> <data name="Module" xml:space="preserve"> <value>module</value> </data> <data name="Parameter" xml:space="preserve"> <value>parameter</value> </data> <data name="Property" xml:space="preserve"> <value>property, indexer</value> </data> <data name="Return1" xml:space="preserve"> <value>return</value> </data> <data name="Struct1" xml:space="preserve"> <value>struct</value> </data> <data name="CannotCreateReferenceToSubmission" xml:space="preserve"> <value>Can't create a reference to a submission.</value> </data> <data name="CannotCreateReferenceToModule" xml:space="preserve"> <value>Can't create a reference to a module.</value> </data> <data name="InMemoryAssembly" xml:space="preserve"> <value>&lt;in-memory assembly&gt;</value> </data> <data name="InMemoryModule" xml:space="preserve"> <value>&lt;in-memory module&gt;</value> </data> <data name="SizeHasToBePositive" xml:space="preserve"> <value>Size has to be positive.</value> </data> <data name="AssemblyFileNotFound" xml:space="preserve"> <value>Assembly file not found</value> </data> <data name="CannotEmbedInteropTypesFromModule" xml:space="preserve"> <value>Can't embed interop types from module.</value> </data> <data name="CannotAliasModule" xml:space="preserve"> <value>Can't alias a module.</value> </data> <data name="InvalidAlias" xml:space="preserve"> <value>Invalid alias.</value> </data> <data name="GetMetadataMustReturnInstance" xml:space="preserve"> <value>{0}.GetMetadata() must return an instance of {1}.</value> </data> <data name="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer" xml:space="preserve"> <value>Value too large to be represented as a 30 bit unsigned integer.</value> </data> <data name="Arrays_with_more_than_one_dimension_cannot_be_serialized" xml:space="preserve"> <value>Arrays with more than one dimension cannot be serialized.</value> </data> <data name="InvalidAssemblyName" xml:space="preserve"> <value>Invalid assembly name: '{0}'</value> </data> <data name="AbsolutePathExpected" xml:space="preserve"> <value>Absolute path expected.</value> </data> <data name="EmptyKeyInPathMap" xml:space="preserve"> <value>A key in the pathMap is empty.</value> </data> <data name="NullValueInPathMap" xml:space="preserve"> <value>A value in the pathMap is null.</value> </data> <data name="CompilationOptionsMustNotHaveErrors" xml:space="preserve"> <value>Compilation options must not have errors.</value> </data> <data name="ReturnTypeCannotBeValuePointerbyRefOrOpen" xml:space="preserve"> <value>Return type can't be a value type, pointer, by-ref or open generic type</value> </data> <data name="ReturnTypeCannotBeVoidByRefOrOpen" xml:space="preserve"> <value>Return type can't be void, by-ref or open generic type</value> </data> <data name="TypeMustBeSameAsHostObjectTypeOfPreviousSubmission" xml:space="preserve"> <value>Type must be same as host object type of previous submission.</value> </data> <data name="PreviousSubmissionHasErrors" xml:space="preserve"> <value>Previous submission has errors.</value> </data> <data name="InvalidOutputKindForSubmission" xml:space="preserve"> <value>Invalid output kind for submission. DynamicallyLinkedLibrary expected.</value> </data> <data name="InvalidCompilationOptions" xml:space="preserve"> <value>Invalid compilation options -- submission can't be signed.</value> </data> <data name="ResourceStreamProviderShouldReturnNonNullStream" xml:space="preserve"> <value>Resource stream provider should return non-null stream.</value> </data> <data name="ReferenceResolverShouldReturnReadableNonNullStream" xml:space="preserve"> <value>Reference resolver should return readable non-null stream.</value> </data> <data name="EmptyOrInvalidResourceName" xml:space="preserve"> <value>Empty or invalid resource name</value> </data> <data name="EmptyOrInvalidFileName" xml:space="preserve"> <value>Empty or invalid file name</value> </data> <data name="ResourceDataProviderShouldReturnNonNullStream" xml:space="preserve"> <value>Resource data provider should return non-null stream</value> </data> <data name="FileNotFound" xml:space="preserve"> <value>File not found.</value> </data> <data name="PathReturnedByResolveStrongNameKeyFileMustBeAbsolute" xml:space="preserve"> <value>Path returned by {0}.ResolveStrongNameKeyFile must be absolute: '{1}'</value> </data> <data name="TypeMustBeASubclassOfSyntaxAnnotation" xml:space="preserve"> <value>type must be a subclass of SyntaxAnnotation.</value> </data> <data name="InvalidModuleName" xml:space="preserve"> <value>Invalid module name specified in metadata module '{0}': '{1}'</value> </data> <data name="FileSizeExceedsMaximumAllowed" xml:space="preserve"> <value>File size exceeds maximum allowed size of a valid metadata file.</value> </data> <data name="NameCannotBeNull" xml:space="preserve"> <value>Name cannot be null.</value> </data> <data name="NameCannotBeEmpty" xml:space="preserve"> <value>Name cannot be empty.</value> </data> <data name="NameCannotStartWithWhitespace" xml:space="preserve"> <value>Name cannot start with whitespace.</value> </data> <data name="NameContainsInvalidCharacter" xml:space="preserve"> <value>Name contains invalid characters.</value> </data> <data name="SpanDoesNotIncludeStartOfLine" xml:space="preserve"> <value>The span does not include the start of a line.</value> </data> <data name="SpanDoesNotIncludeEndOfLine" xml:space="preserve"> <value>The span does not include the end of a line.</value> </data> <data name="StartMustNotBeNegative" xml:space="preserve"> <value>'start' must not be negative</value> </data> <data name="EndMustNotBeLessThanStart" xml:space="preserve"> <value>'end' must not be less than 'start'</value> </data> <data name="InvalidContentType" xml:space="preserve"> <value>Invalid content type</value> </data> <data name="ExpectedNonEmptyPublicKey" xml:space="preserve"> <value>Expected non-empty public key</value> </data> <data name="InvalidSizeOfPublicKeyToken" xml:space="preserve"> <value>Invalid size of public key token.</value> </data> <data name="InvalidCharactersInAssemblyName" xml:space="preserve"> <value>Invalid characters in assembly name</value> </data> <data name="InvalidCharactersInAssemblyCultureName" xml:space="preserve"> <value>Invalid characters in assembly culture name</value> </data> <data name="StreamMustSupportReadAndSeek" xml:space="preserve"> <value>Stream must support read and seek operations.</value> </data> <data name="StreamMustSupportRead" xml:space="preserve"> <value>Stream must be readable.</value> </data> <data name="StreamMustSupportWrite" xml:space="preserve"> <value>Stream must be writable.</value> </data> <data name="PdbStreamUnexpectedWhenEmbedding" xml:space="preserve"> <value>PDB stream should not be given when embedding PDB into the PE stream.</value> </data> <data name="PdbStreamUnexpectedWhenEmittingMetadataOnly" xml:space="preserve"> <value>PDB stream should not be given when emitting metadata only.</value> </data> <data name="MetadataPeStreamUnexpectedWhenEmittingMetadataOnly" xml:space="preserve"> <value>Metadata PE stream should not be given when emitting metadata only.</value> </data> <data name="IncludingPrivateMembersUnexpectedWhenEmittingToMetadataPeStream" xml:space="preserve"> <value>Including private members should not be used when emitting to the secondary assembly output.</value> </data> <data name="MustIncludePrivateMembersUnlessRefAssembly" xml:space="preserve"> <value>Must include private members unless emitting a ref assembly.</value> </data> <data name="EmbeddingPdbUnexpectedWhenEmittingMetadata" xml:space="preserve"> <value>Embedding PDB is not allowed when emitting metadata.</value> </data> <data name="CannotTargetNetModuleWhenEmittingRefAssembly" xml:space="preserve"> <value>Cannot target net module when emitting ref assembly.</value> </data> <data name="InvalidHash" xml:space="preserve"> <value>Invalid hash.</value> </data> <data name="UnsupportedHashAlgorithm" xml:space="preserve"> <value>Unsupported hash algorithm.</value> </data> <data name="InconsistentLanguageVersions" xml:space="preserve"> <value>Inconsistent language versions</value> </data> <data name="CoffResourceInvalidRelocation" xml:space="preserve"> <value>Win32 resources, assumed to be in COFF object format, have one or more invalid relocation header values.</value> </data> <data name="CoffResourceInvalidSectionSize" xml:space="preserve"> <value>Win32 resources, assumed to be in COFF object format, have an invalid section size.</value> </data> <data name="CoffResourceInvalidSymbol" xml:space="preserve"> <value>Win32 resources, assumed to be in COFF object format, have one or more invalid symbol values.</value> </data> <data name="CoffResourceMissingSection" xml:space="preserve"> <value>Win32 resources, assumed to be in COFF object format, are missing one or both of sections '.rsrc$01' and '.rsrc$02'</value> </data> <data name="IconStreamUnexpectedFormat" xml:space="preserve"> <value>Icon stream is not in the expected format.</value> </data> <data name="InvalidCultureName" xml:space="preserve"> <value>Invalid culture name: '{0}'</value> </data> <data name="WinRTIdentityCantBeRetargetable" xml:space="preserve"> <value>WindowsRuntime identity can't be retargetable</value> </data> <data name="PEImageNotAvailable" xml:space="preserve"> <value>PE image not available.</value> </data> <data name="AssemblySigningNotSupported" xml:space="preserve"> <value>Assembly signing not supported.</value> </data> <data name="XmlReferencesNotSupported" xml:space="preserve"> <value>References to XML documents are not supported.</value> </data> <data name="FailedToResolveRuleSetName" xml:space="preserve"> <value>Could not locate the rule set file '{0}'.</value> </data> <data name="InvalidRuleSetInclude" xml:space="preserve"> <value>An error occurred while loading the included rule set file {0} - {1}</value> </data> <data name="CompilerAnalyzerFailure" xml:space="preserve"> <value>Analyzer Failure</value> <comment>{0}: Analyzer name {1}: Type name {2}: Localized exception message {3}: Localized detail message</comment> </data> <data name="CompilerAnalyzerThrows" xml:space="preserve"> <value>Analyzer '{0}' threw an exception of type '{1}' with message '{2}'. {3}</value> </data> <data name="CompilerAnalyzerThrowsDescription" xml:space="preserve"> <value>Analyzer '{0}' threw the following exception: '{1}'.</value> </data> <data name="AnalyzerDriverFailure" xml:space="preserve"> <value>Analyzer Driver Failure</value> </data> <data name="AnalyzerDriverThrows" xml:space="preserve"> <value>Analyzer driver threw an exception of type '{0}' with message '{1}'.</value> </data> <data name="AnalyzerDriverThrowsDescription" xml:space="preserve"> <value>Analyzer driver threw the following exception: '{0}'.</value> </data> <data name="PEImageDoesntContainManagedMetadata" xml:space="preserve"> <value>PE image doesn't contain managed metadata.</value> </data> <data name="ChangesMustNotOverlap" xml:space="preserve"> <value>The changes must not overlap.</value> </data> <data name="DiagnosticIdCantBeNullOrWhitespace" xml:space="preserve"> <value>A DiagnosticDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space.</value> </data> <data name="SuppressionIdCantBeNullOrWhitespace" xml:space="preserve"> <value>A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space.</value> </data> <data name="RuleSetHasDuplicateRules" xml:space="preserve"> <value>The rule set file has duplicate rules for '{0}' with differing actions '{1}' and '{2}'.</value> </data> <data name="CantCreateModuleReferenceToAssembly" xml:space="preserve"> <value>Can't create a module reference to an assembly.</value> </data> <data name="CantCreateReferenceToDynamicAssembly" xml:space="preserve"> <value>Can't create a metadata reference to a dynamic assembly.</value> </data> <data name="CantCreateReferenceToAssemblyWithoutLocation" xml:space="preserve"> <value>Can't create a metadata reference to an assembly without location.</value> </data> <data name="ArgumentCannotBeEmpty" xml:space="preserve"> <value>Argument cannot be empty.</value> </data> <data name="ArgumentElementCannotBeNull" xml:space="preserve"> <value>Argument cannot have a null element.</value> </data> <data name="UnsupportedDiagnosticReported" xml:space="preserve"> <value>Reported diagnostic with ID '{0}' is not supported by the analyzer.</value> </data> <data name="UnsupportedSuppressionReported" xml:space="preserve"> <value>Reported suppression with ID '{0}' is not supported by the suppressor.</value> </data> <data name="InvalidDiagnosticSuppressionReported" xml:space="preserve"> <value>Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor.</value> </data> <data name="NonReportedDiagnosticCannotBeSuppressed" xml:space="preserve"> <value>Non-reported diagnostic with ID '{0}' cannot be suppressed.</value> </data> <data name="InvalidDiagnosticIdReported" xml:space="preserve"> <value>Reported diagnostic has an ID '{0}', which is not a valid identifier.</value> </data> <data name="InvalidDiagnosticLocationReported" xml:space="preserve"> <value>Reported diagnostic '{0}' has a source location in file '{1}', which is not part of the compilation being analyzed.</value> </data> <data name="SupportedDiagnosticsHasNullDescriptor" xml:space="preserve"> <value>Analyzer '{0}' contains a null descriptor in its 'SupportedDiagnostics'.</value> </data> <data name="SupportedSuppressionsHasNullDescriptor" xml:space="preserve"> <value>Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'.</value> </data> <data name="The_type_0_is_not_understood_by_the_serialization_binder" xml:space="preserve"> <value>The type '{0}' is not understood by the serialization binder.</value> </data> <data name="Cannot_deserialize_type_0" xml:space="preserve"> <value>Cannot deserialize type '{0}'.</value> </data> <data name="Cannot_serialize_type_0" xml:space="preserve"> <value>Cannot serialize type '{0}'.</value> </data> <data name="InvalidNodeToTrack" xml:space="preserve"> <value>Node to track is not a descendant of the root.</value> </data> <data name="NodeOrTokenOutOfSequence" xml:space="preserve"> <value>A node or token is out of sequence.</value> </data> <data name="UnexpectedTypeOfNodeInList" xml:space="preserve"> <value>A node in the list is not of the expected type.</value> </data> <data name="MissingListItem" xml:space="preserve"> <value>The item specified is not the element of a list.</value> </data> <data name="InvalidPublicKey" xml:space="preserve"> <value>Invalid public key.</value> </data> <data name="InvalidPublicKeyToken" xml:space="preserve"> <value>Invalid public key token.</value> </data> <data name="InvalidDataAtOffset" xml:space="preserve"> <value>Invalid data at offset {0}: {1}{2}*{3}{4}</value> </data> <data name="SymWriterNotDeterministic" xml:space="preserve"> <value>Windows PDB writer doesn't support deterministic compilation: '{0}'</value> </data> <data name="SymWriterOlderVersionThanRequired" xml:space="preserve"> <value>The version of Windows PDB writer is older than required: '{0}'</value> </data> <data name="SymWriterDoesNotSupportSourceLink" xml:space="preserve"> <value>Windows PDB writer doesn't support SourceLink feature: '{0}'</value> </data> <data name="RuleSetBadAttributeValue" xml:space="preserve"> <value>The attribute {0} has an invalid value of {1}.</value> </data> <data name="RuleSetMissingAttribute" xml:space="preserve"> <value>The element {0} is missing an attribute named {1}.</value> </data> <data name="KeepAliveIsNotAnInteger" xml:space="preserve"> <value>Argument to '/keepalive' option is not a 32-bit integer.</value> </data> <data name="KeepAliveIsTooSmall" xml:space="preserve"> <value>Arguments to '/keepalive' option below -1 are invalid.</value> </data> <data name="KeepAliveWithoutShared" xml:space="preserve"> <value>'/keepalive' option is only valid with '/shared' option.</value> </data> <data name="MismatchedVersion" xml:space="preserve"> <value>Roslyn compiler server reports different protocol version than build task.</value> </data> <data name="MissingKeepAlive" xml:space="preserve"> <value>Missing argument for '/keepalive' option.</value> </data> <data name="AnalyzerTotalExecutionTime" xml:space="preserve"> <value>Total analyzer execution time: {0} seconds.</value> </data> <data name="MultithreadedAnalyzerExecutionNote" xml:space="preserve"> <value>NOTE: Elapsed time may be less than analyzer execution time because analyzers can run concurrently.</value> </data> <data name="AnalyzerExecutionTimeColumnHeader" xml:space="preserve"> <value>Time (s)</value> </data> <data name="AnalyzerNameColumnHeader" xml:space="preserve"> <value>Analyzer</value> </data> <data name="NoAnalyzersFound" xml:space="preserve"> <value>No analyzers found</value> </data> <data name="DuplicateAnalyzerInstances" xml:space="preserve"> <value>Argument contains duplicate analyzer instances.</value> </data> <data name="UnsupportedAnalyzerInstance" xml:space="preserve"> <value>Argument contains an analyzer instance that does not belong to the 'Analyzers' for this CompilationWithAnalyzers instance.</value> </data> <data name="InvalidTree" xml:space="preserve"> <value>Syntax tree doesn't belong to the underlying 'Compilation'.</value> </data> <data name="InvalidAdditionalFile" xml:space="preserve"> <value>Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'.</value> </data> <data name="ResourceStreamEndedUnexpectedly" xml:space="preserve"> <value>Resource stream ended at {0} bytes, expected {1} bytes.</value> </data> <data name="SharedArgumentMissing" xml:space="preserve"> <value>Value for argument '/shared:' must not be empty</value> </data> <data name="ExceptionContext" xml:space="preserve"> <value>Exception occurred with following context: {0}</value> </data> <data name="AnonymousTypeMemberAndNamesCountMismatch2" xml:space="preserve"> <value>{0} and {1} must have the same length.</value> </data> <data name="AnonymousTypeArgumentCountMismatch2" xml:space="preserve"> <value>{0} must either be 'default' or have the same length as {1}.</value> </data> <data name="InconsistentSyntaxTreeFeature" xml:space="preserve"> <value>Inconsistent syntax tree features</value> </data> <data name="ReferenceOfTypeIsInvalid1" xml:space="preserve"> <value>Reference of type '{0}' is not valid for this compilation.</value> </data> <data name="MetadataRefNotFoundToRemove1" xml:space="preserve"> <value>MetadataReference '{0}' not found to remove.</value> </data> <data name="TupleElementNameCountMismatch" xml:space="preserve"> <value>If tuple element names are specified, the number of element names must match the cardinality of the tuple.</value> </data> <data name="TupleElementNameEmpty" xml:space="preserve"> <value>Tuple element name cannot be an empty string.</value> </data> <data name="TupleElementLocationCountMismatch" xml:space="preserve"> <value>If tuple element locations are specified, the number of locations must match the cardinality of the tuple.</value> </data> <data name="TupleElementNullableAnnotationCountMismatch" xml:space="preserve"> <value>If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple.</value> </data> <data name="TuplesNeedAtLeastTwoElements" xml:space="preserve"> <value>Tuples must have at least two elements.</value> </data> <data name="CompilationReferencesAssembliesWithDifferentAutoGeneratedVersion" xml:space="preserve"> <value>The compilation references multiple assemblies whose versions only differ in auto-generated build and/or revision numbers.</value> </data> <data name="TupleUnderlyingTypeMustBeTupleCompatible" xml:space="preserve"> <value>The underlying type for a tuple must be tuple-compatible.</value> </data> <data name="UnrecognizedResourceFileFormat" xml:space="preserve"> <value>Unrecognized resource file format.</value> </data> <data name="SourceTextCannotBeEmbedded" xml:space="preserve"> <value>SourceText cannot be embedded. Provide encoding or canBeEmbedded=true at construction.</value> </data> <data name="StreamIsTooLong" xml:space="preserve"> <value>Stream is too long.</value> </data> <data name="EmbeddedTextsRequirePdb" xml:space="preserve"> <value>Embedded texts are only supported when emitting a PDB.</value> </data> <data name="TheStreamCannotBeWrittenTo" xml:space="preserve"> <value>The stream cannot be written to.</value> </data> <data name="ElementIsExpected" xml:space="preserve"> <value>element is expected</value> </data> <data name="SeparatorIsExpected" xml:space="preserve"> <value>separator is expected</value> </data> <data name="TheStreamCannotBeReadFrom" xml:space="preserve"> <value>The stream cannot be read from.</value> </data> <data name="Deserialization_reader_for_0_read_incorrect_number_of_values" xml:space="preserve"> <value>Deserialization reader for '{0}' read incorrect number of values.</value> </data> <data name="Stream_contains_invalid_data" xml:space="preserve"> <value>Stream contains invalid data</value> </data> <data name="InvalidDiagnosticSpanReported" xml:space="preserve"> <value>Reported diagnostic '{0}' has a source location '{1}' in file '{2}', which is outside of the given file.</value> </data> <data name="ExceptionEnablingMulticoreJit" xml:space="preserve"> <value>Warning: Could not enable multicore JIT due to exception: {0}.</value> </data> <data name="NotARootOperation" xml:space="preserve"> <value>Given operation has a non-null parent.</value> </data> <data name="OperationHasNullSemanticModel" xml:space="preserve"> <value>Given operation has a null semantic model.</value> </data> <data name="InvalidOperationBlockForAnalysisContext" xml:space="preserve"> <value>Given operation block does not belong to the current analysis context.</value> </data> <data name="IsSymbolAccessibleBadWithin" xml:space="preserve"> <value>Parameter '{0}' must be an 'INamedTypeSymbol' or an 'IAssemblySymbol'.</value> </data> <data name="IsSymbolAccessibleWrongAssembly" xml:space="preserve"> <value>Parameter '{0}' must be a symbol from this compilation or some referenced assembly.</value> </data> <data name="OperationMustNotBeControlFlowGraphPart" xml:space="preserve"> <value>The provided operation must not be part of a Control Flow Graph.</value> </data> <data name="A_language_name_cannot_be_specified_for_this_option" xml:space="preserve"> <value>A language name cannot be specified for this option.</value> </data> <data name="A_language_name_must_be_specified_for_this_option" xml:space="preserve"> <value>A language name must be specified for this option.</value> </data> <data name="WRN_InvalidSeverityInAnalyzerConfig" xml:space="preserve"> <value>The diagnostic '{0}' was given an invalid severity '{1}' in the analyzer config file at '{2}'.</value> </data> <data name="WRN_InvalidSeverityInAnalyzerConfig_Title" xml:space="preserve"> <value>Invalid severity in analyzer config file.</value> </data> <data name="SuppressionDiagnosticDescriptorTitle" xml:space="preserve"> <value>Programmatic suppression of an analyzer diagnostic</value> </data> <data name="SuppressionDiagnosticDescriptorMessage" xml:space="preserve"> <value>Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}'</value> </data> <data name="ModuleHasInvalidAttributes" xml:space="preserve"> <value>Module has invalid attributes.</value> </data> <data name="UnableToDetermineSpecificCauseOfFailure" xml:space="preserve"> <value>Unable to determine specific cause of the failure.</value> </data> <data name="ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging" xml:space="preserve"> <value>Changing the version of an assembly reference is not allowed during debugging: '{0}' changed version to '{1}'.</value> </data> <data name="DisableAnalyzerDiagnosticsMessage" xml:space="preserve"> <value>Suppress the following diagnostics to disable this analyzer: {0}</value> <comment>{0}: Comma-separated list of diagnostic IDs</comment> </data> <data name="Single_type_per_generator_0" xml:space="preserve"> <value>Only a single {0} can be registered per generator.</value> <comment>{0}: type name</comment> </data> <data name="WRN_MultipleGlobalAnalyzerKeys" xml:space="preserve"> <value>Multiple global analyzer config files set the same key '{0}' in section '{1}'. It has been unset. Key was set by the following files: '{2}'</value> </data> <data name="WRN_MultipleGlobalAnalyzerKeys_Title" xml:space="preserve"> <value>Multiple global analyzer config files set the same key. It has been unset.</value> </data> <data name="HintNameUniquePerGenerator" xml:space="preserve"> <value>The hintName '{0}' of the added source file must be unique within a generator.</value> <comment>{0}: the provided hintname</comment> </data> <data name="HintNameInvalidChar" xml:space="preserve"> <value>The hintName '{0}' contains an invalid character '{1}' at position {2}.</value> <comment>{0}: the provided hintname. {1}: the invalid character, {2} the position it occurred at</comment> </data> <data name="SourceTextRequiresEncoding" xml:space="preserve"> <value>The SourceText with hintName '{0}' must have an explicit encoding set.</value> <comment>'SourceText' is not localizable. {0}: the provided hintname</comment> </data> <data name="AssemblyReferencesNetFramework" xml:space="preserve"> <value>The assembly containing type '{0}' references .NET Framework, which is not supported.</value> </data> <data name="WRN_InvalidGlobalSectionName" xml:space="preserve"> <value>Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}'</value> <comment>{0}: invalid section name, {1} path to global config</comment> </data> <data name="WRN_InvalidGlobalSectionName_Title" xml:space="preserve"> <value>Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored.</value> </data> <data name="ChangesMustBeWithinBoundsOfSourceText" xml:space="preserve"> <value>Changes must be within bounds of SourceText</value> </data> </root>
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/CodeActions/Operations/PreviewOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CodeActions { /// <summary> /// Represents a preview operation for generating a custom user preview for the operation. /// </summary> public abstract class PreviewOperation : CodeActionOperation { /// <summary> /// Gets a custom preview control for the operation. /// If preview is null and <see cref="CodeActionOperation.Title"/> is non-null, then <see cref="CodeActionOperation.Title"/> is used to generate the preview. /// </summary> public abstract Task<object> GetPreviewAsync(CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CodeActions { /// <summary> /// Represents a preview operation for generating a custom user preview for the operation. /// </summary> public abstract class PreviewOperation : CodeActionOperation { /// <summary> /// Gets a custom preview control for the operation. /// If preview is null and <see cref="CodeActionOperation.Title"/> is non-null, then <see cref="CodeActionOperation.Title"/> is used to generate the preview. /// </summary> public abstract Task<object> GetPreviewAsync(CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/Navigation/NavigationOptionsProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Navigation { [ExportOptionProvider, Shared] internal class NavigationOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NavigationOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( NavigationOptions.PreferProvisionalTab); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Navigation { [ExportOptionProvider, Shared] internal class NavigationOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NavigationOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( NavigationOptions.PreferProvisionalTab); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/GetKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class GetKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public GetKeywordRecommender() : base(SyntaxKind.GetKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.TargetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(position, SyntaxKind.GetKeyword) || context.TargetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(position, SyntaxKind.GetKeyword); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class GetKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public GetKeywordRecommender() : base(SyntaxKind.GetKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.TargetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(position, SyntaxKind.GetKeyword) || context.TargetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(position, SyntaxKind.GetKeyword); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/ExpressionSyntaxExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class ExpressionSyntaxExtensions { public static ExpressionSyntax WalkUpParentheses(this ExpressionSyntax expression) { while (expression.IsParentKind(SyntaxKind.ParenthesizedExpression, out ExpressionSyntax? parentExpr)) expression = parentExpr; return expression; } public static ExpressionSyntax WalkDownParentheses(this ExpressionSyntax expression) { while (expression.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpression)) expression = parenExpression.Expression; return expression; } public static bool IsQualifiedCrefName(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.NameMemberCref) && expression.Parent.IsParentKind(SyntaxKind.QualifiedCref); public static bool IsSimpleMemberAccessExpressionName([NotNullWhen(true)] this ExpressionSyntax? expression) => expression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess) && memberAccess.Name == expression; public static bool IsAnyMemberAccessExpressionName(this ExpressionSyntax expression) { if (expression == null) { return false; } return expression == (expression.Parent as MemberAccessExpressionSyntax)?.Name || expression.IsMemberBindingExpressionName(); } public static bool IsMemberBindingExpressionName([NotNullWhen(true)] this ExpressionSyntax? expression) => expression.IsParentKind(SyntaxKind.MemberBindingExpression, out MemberBindingExpressionSyntax? memberBinding) && memberBinding.Name == expression; public static bool IsRightSideOfQualifiedName([NotNullWhen(true)] this ExpressionSyntax? expression) => expression.IsParentKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName) && qualifiedName.Right == expression; public static bool IsRightSideOfColonColon(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.AliasQualifiedName, out AliasQualifiedNameSyntax? aliasName) && aliasName.Name == expression; public static bool IsRightSideOfDot(this ExpressionSyntax name) => IsSimpleMemberAccessExpressionName(name) || IsMemberBindingExpressionName(name) || IsRightSideOfQualifiedName(name) || IsQualifiedCrefName(name); public static bool IsRightSideOfDotOrArrow(this ExpressionSyntax name) => IsAnyMemberAccessExpressionName(name) || IsRightSideOfQualifiedName(name); public static bool IsRightSideOfDotOrColonColon(this ExpressionSyntax name) => IsRightSideOfDot(name) || IsRightSideOfColonColon(name); public static bool IsRightSideOfDotOrArrowOrColonColon([NotNullWhen(true)] this ExpressionSyntax name) => IsRightSideOfDotOrArrow(name) || IsRightSideOfColonColon(name); public static bool IsRightOfCloseParen(this ExpressionSyntax expression) { var firstToken = expression.GetFirstToken(); return firstToken.Kind() != SyntaxKind.None && firstToken.GetPreviousToken().Kind() == SyntaxKind.CloseParenToken; } public static bool IsLeftSideOfDot([NotNullWhen(true)] this ExpressionSyntax? expression) { if (expression == null) return false; return IsLeftSideOfQualifiedName(expression) || IsLeftSideOfSimpleMemberAccessExpression(expression); } public static bool IsLeftSideOfSimpleMemberAccessExpression(this ExpressionSyntax expression) => (expression?.Parent).IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess) && memberAccess.Expression == expression; public static bool IsLeftSideOfDotOrArrow(this ExpressionSyntax expression) => IsLeftSideOfQualifiedName(expression) || (expression.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Expression == expression); public static bool IsLeftSideOfQualifiedName(this ExpressionSyntax expression) => (expression?.Parent).IsKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName) && qualifiedName.Left == expression; public static bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] this NameSyntax? name) => name.IsParentKind(SyntaxKind.ExplicitInterfaceSpecifier); public static bool IsExpressionOfInvocation(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax? invocation) && invocation.Expression == expression; public static bool TryGetNameParts(this ExpressionSyntax expression, [NotNullWhen(true)] out IList<string>? parts) { var partsList = new List<string>(); if (!TryGetNameParts(expression, partsList)) { parts = null; return false; } parts = partsList; return true; } public static bool TryGetNameParts(this ExpressionSyntax expression, List<string> parts) { if (expression.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess)) { if (!TryGetNameParts(memberAccess.Expression, parts)) { return false; } return AddSimpleName(memberAccess.Name, parts); } else if (expression.IsKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName)) { if (!TryGetNameParts(qualifiedName.Left, parts)) { return false; } return AddSimpleName(qualifiedName.Right, parts); } else if (expression is SimpleNameSyntax simpleName) { return AddSimpleName(simpleName, parts); } else { return false; } } private static bool AddSimpleName(SimpleNameSyntax simpleName, List<string> parts) { if (!simpleName.IsKind(SyntaxKind.IdentifierName)) { return false; } parts.Add(simpleName.Identifier.ValueText); return true; } public static bool IsAnyLiteralExpression(this ExpressionSyntax expression) => expression is LiteralExpressionSyntax; public static bool IsInConstantContext([NotNullWhen(true)] this ExpressionSyntax? expression) { if (expression == null) return false; if (expression.GetAncestor<ParameterSyntax>() != null) return true; var attributeArgument = expression.GetAncestor<AttributeArgumentSyntax>(); if (attributeArgument != null) { if (attributeArgument.NameEquals == null || expression != attributeArgument.NameEquals.Name) { return true; } } if (expression.IsParentKind(SyntaxKind.ConstantPattern)) return true; // note: the above list is not intended to be exhaustive. If more cases // are discovered that should be considered 'constant' contexts in the // language, then this should be updated accordingly. return false; } public static bool IsInOutContext(this ExpressionSyntax expression) { return expression?.Parent is ArgumentSyntax argument && argument.Expression == expression && argument.RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword; } public static bool IsInRefContext(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.RefExpression) || (expression?.Parent as ArgumentSyntax)?.RefOrOutKeyword.Kind() == SyntaxKind.RefKeyword; public static bool IsInInContext(this ExpressionSyntax expression) => (expression?.Parent as ArgumentSyntax)?.RefKindKeyword.Kind() == SyntaxKind.InKeyword; private static ExpressionSyntax GetExpressionToAnalyzeForWrites(ExpressionSyntax expression) { if (expression.IsRightSideOfDotOrArrow()) { expression = (ExpressionSyntax)expression.GetRequiredParent(); } expression = expression.WalkUpParentheses(); return expression; } public static bool IsOnlyWrittenTo(this ExpressionSyntax expression) { expression = GetExpressionToAnalyzeForWrites(expression); if (expression != null) { if (expression.IsInOutContext()) { return true; } if (expression.Parent != null) { if (expression.IsLeftSideOfAssignExpression()) { return true; } if (expression.IsAttributeNamedArgumentIdentifier()) { return true; } } if (IsExpressionOfArgumentInDeconstruction(expression)) { return true; } } return false; } /// <summary> /// If this declaration or identifier is part of a deconstruction, find the deconstruction. /// If found, returns either an assignment expression or a foreach variable statement. /// Returns null otherwise. /// /// copied from SyntaxExtensions.GetContainingDeconstruction /// </summary> private static bool IsExpressionOfArgumentInDeconstruction(ExpressionSyntax expr) { if (!expr.IsParentKind(SyntaxKind.Argument)) { return false; } while (true) { var parent = expr.Parent; if (parent == null) { return false; } switch (parent.Kind()) { case SyntaxKind.Argument: if (parent.Parent?.Kind() == SyntaxKind.TupleExpression) { expr = (TupleExpressionSyntax)parent.Parent; continue; } return false; case SyntaxKind.SimpleAssignmentExpression: if (((AssignmentExpressionSyntax)parent).Left == expr) { return true; } return false; case SyntaxKind.ForEachVariableStatement: if (((ForEachVariableStatementSyntax)parent).Variable == expr) { return true; } return false; default: return false; } } } public static bool IsWrittenTo(this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { if (expression == null) return false; expression = GetExpressionToAnalyzeForWrites(expression); if (expression.IsOnlyWrittenTo()) return true; if (expression.IsInRefContext()) { // most cases of `ref x` will count as a potential write of `x`. An important exception is: // `ref readonly y = ref x`. In that case, because 'y' can't be written to, this would not // be a write of 'x'. if (expression is { Parent: { RawKind: (int)SyntaxKind.RefExpression, Parent: EqualsValueClauseSyntax { Parent: VariableDeclaratorSyntax { Parent: VariableDeclarationSyntax { Type: RefTypeSyntax refType } } } } } && refType.ReadOnlyKeyword != default) { return false; } return true; } // Similar to `ref x`, `&x` allows reads and write of the value, meaning `x` may be (but is not definitely) // written to. if (expression.Parent.IsKind(SyntaxKind.AddressOfExpression)) return true; // We're written if we're used in a ++, or -- expression. if (expression.IsOperandOfIncrementOrDecrementExpression()) return true; if (expression.IsLeftSideOfAnyAssignExpression()) return true; // An extension method invocation with a ref-this parameter can write to an expression. if (expression.Parent is MemberAccessExpressionSyntax memberAccess && expression == memberAccess.Expression) { var symbol = semanticModel.GetSymbolInfo(memberAccess, cancellationToken).Symbol; if (symbol is IMethodSymbol { MethodKind: MethodKind.ReducedExtension, ReducedFrom: IMethodSymbol reducedFrom } && reducedFrom.Parameters.Length > 0 && reducedFrom.Parameters.First().RefKind == RefKind.Ref) { return true; } } return false; } public static bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] this ExpressionSyntax? expression) { var nameEquals = expression?.Parent as NameEqualsSyntax; return nameEquals.IsParentKind(SyntaxKind.AttributeArgument); } public static bool IsOperandOfIncrementOrDecrementExpression(this ExpressionSyntax expression) { if (expression?.Parent is SyntaxNode parent) { switch (parent.Kind()) { case SyntaxKind.PostIncrementExpression: case SyntaxKind.PreIncrementExpression: case SyntaxKind.PostDecrementExpression: case SyntaxKind.PreDecrementExpression: return true; } } return false; } public static bool IsNamedArgumentIdentifier(this ExpressionSyntax expression) => expression is IdentifierNameSyntax && expression.Parent is NameColonSyntax; public static bool IsInsideNameOfExpression( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { var invocation = expression?.GetAncestor<InvocationExpressionSyntax>(); if (invocation?.Expression is IdentifierNameSyntax name && name.Identifier.Text == SyntaxFacts.GetText(SyntaxKind.NameOfKeyword)) { return semanticModel.GetMemberGroup(name, cancellationToken).IsDefaultOrEmpty; } return false; } private static bool CanReplace(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Field: case SymbolKind.Local: case SymbolKind.Method: case SymbolKind.Parameter: case SymbolKind.Property: case SymbolKind.RangeVariable: case SymbolKind.FunctionPointerType: return true; } return false; } public static bool CanReplaceWithRValue( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { // An RValue can't be written into. // i.e. you can't replace "a" in "a = b" with "Goo() = b". return expression != null && !expression.IsWrittenTo(semanticModel, cancellationToken) && CanReplaceWithLValue(expression, semanticModel, cancellationToken); } public static bool CanReplaceWithLValue( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { if (expression.IsKind(SyntaxKind.StackAllocArrayCreationExpression)) { // Stack alloc is very interesting. While it appears to be an expression, it is only // such so it can appear in a variable decl. It is not a normal expression that can // go anywhere. return false; } if (expression.IsKind(SyntaxKind.BaseExpression) || expression.IsKind(SyntaxKind.CollectionInitializerExpression) || expression.IsKind(SyntaxKind.ObjectInitializerExpression) || expression.IsKind(SyntaxKind.ComplexElementInitializerExpression)) { return false; } // literal can be always replaced. if (expression is LiteralExpressionSyntax && !expression.IsParentKind(SyntaxKind.UnaryMinusExpression)) { return true; } if (expression is TupleExpressionSyntax) { return true; } if (!(expression is ObjectCreationExpressionSyntax) && !(expression is AnonymousObjectCreationExpressionSyntax) && !expression.IsLeftSideOfAssignExpression()) { var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken); if (!symbolInfo.GetBestOrAllSymbols().All(CanReplace)) { // If the expression is actually a reference to a type, then it can't be replaced // with an arbitrary expression. return false; } } // If we are a conditional access expression: // case (1) : obj?.Method(), obj1.obj2?.Property // case (2) : obj?.GetAnotherObj()?.Length, obj?.AnotherObj?.Length // in case (1), the entire expression forms the conditional access expression, which can be replaced with an LValue. // in case (2), the nested conditional access expression is ".GetAnotherObj()?.Length" or ".AnotherObj()?.Length" // essentially, the first expression (before the operator) in a nested conditional access expression // is some form of member binding expression and they cannot be replaced with an LValue. if (expression.IsKind(SyntaxKind.ConditionalAccessExpression)) { return expression is { Parent: { RawKind: not (int)SyntaxKind.ConditionalAccessExpression } }; } if (expression.Parent == null) return false; switch (expression.Parent.Kind()) { case SyntaxKind.InvocationExpression: // Technically, you could introduce an LValue for "Goo" in "Goo()" even if "Goo" binds // to a method. (i.e. by assigning to a Func<...> type). However, this is so contrived // and none of the features that use this extension consider this replaceable. if (expression.IsKind(SyntaxKind.IdentifierName) || expression is MemberAccessExpressionSyntax) { // If it looks like a method then we don't allow it to be replaced if it is a // method (or if it doesn't bind). var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken); return symbolInfo.GetBestOrAllSymbols().Any() && !symbolInfo.GetBestOrAllSymbols().Any(s => s is IMethodSymbol); } else { // It doesn't look like a method, we allow this to be replaced. return true; } // If the parent is a conditional access expression, we could introduce an LValue // for the given expression, unless it is itself a MemberBindingExpression or starts with one. // Case (1) : The WhenNotNull clause always starts with a MemberBindingExpression. // expression '.Method()' in a?.Method() // Case (2) : The Expression clause always starts with a MemberBindingExpression if // the grandparent is a conditional access expression. // expression '.Method' in a?.Method()?.Length // Case (3) : The child Conditional access expression always starts with a MemberBindingExpression if // the parent is a conditional access expression. This case is already covered before the parent kind switch case SyntaxKind.ConditionalAccessExpression: var parentConditionalAccessExpression = (ConditionalAccessExpressionSyntax)expression.Parent; return expression != parentConditionalAccessExpression.WhenNotNull && !parentConditionalAccessExpression.Parent.IsKind(SyntaxKind.ConditionalAccessExpression); case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: // Can't introduce a variable for the type portion of an is/as check. var isOrAsExpression = (BinaryExpressionSyntax)expression.Parent; return expression == isOrAsExpression.Left; case SyntaxKind.EqualsValueClause: case SyntaxKind.ExpressionStatement: case SyntaxKind.ArrayInitializerExpression: case SyntaxKind.CollectionInitializerExpression: case SyntaxKind.Argument: case SyntaxKind.AttributeArgument: case SyntaxKind.AnonymousObjectMemberDeclarator: case SyntaxKind.ArrowExpressionClause: case SyntaxKind.AwaitExpression: case SyntaxKind.ReturnStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedExpression: case SyntaxKind.ArrayRankSpecifier: case SyntaxKind.ConditionalExpression: case SyntaxKind.IfStatement: case SyntaxKind.CatchFilterClause: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.InterpolatedStringExpression: case SyntaxKind.ComplexElementInitializerExpression: case SyntaxKind.Interpolation: case SyntaxKind.RefExpression: case SyntaxKind.LockStatement: case SyntaxKind.ElementAccessExpression: case SyntaxKind.SwitchExpressionArm: // Direct parent kind checks. return true; } if (expression.Parent is PrefixUnaryExpressionSyntax) { if (!(expression is LiteralExpressionSyntax && expression.IsParentKind(SyntaxKind.UnaryMinusExpression))) { return true; } } var parentNonExpression = expression.GetAncestors().SkipWhile(n => n is ExpressionSyntax).FirstOrDefault(); var topExpression = expression; while (topExpression.Parent is TypeSyntax typeSyntax) { topExpression = typeSyntax; } if (parentNonExpression != null && parentNonExpression.IsKind(SyntaxKind.FromClause, out FromClauseSyntax? fromClause) && topExpression != null && fromClause.Type == topExpression) { return false; } // Parent type checks. if (expression.Parent is PostfixUnaryExpressionSyntax || expression.Parent is BinaryExpressionSyntax || expression.Parent is AssignmentExpressionSyntax || expression.Parent is QueryClauseSyntax || expression.Parent is SelectOrGroupClauseSyntax || expression.Parent is CheckedExpressionSyntax) { return true; } // Specific child checks. if (expression.CheckParent<CommonForEachStatementSyntax>(f => f.Expression == expression) || expression.CheckParent<MemberAccessExpressionSyntax>(m => m.Expression == expression) || expression.CheckParent<CastExpressionSyntax>(c => c.Expression == expression)) { return true; } // Misc checks. if ((expression.IsParentKind(SyntaxKind.NameEquals) && expression.Parent.IsParentKind(SyntaxKind.AttributeArgument)) || expression.IsLeftSideOfAnyAssignExpression()) { return true; } return false; } public static bool CanAccessInstanceAndStaticMembersOffOf( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { // Check for the Color Color case. // // color color: if you bind "A" and you get a symbol and the type of that symbol is // Q; and if you bind "A" *again* as a type and you get type Q, then both A.static // and A.instance are permitted if (expression is IdentifierNameSyntax) { var instanceSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).GetAnySymbol(); if (!(instanceSymbol is INamespaceOrTypeSymbol)) { var instanceType = instanceSymbol.GetSymbolType(); if (instanceType != null) { var speculativeSymbolInfo = semanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace); if (speculativeSymbolInfo.CandidateReason != CandidateReason.NotATypeOrNamespace) { var staticType = speculativeSymbolInfo.GetAnySymbol().GetSymbolType(); return SymbolEquivalenceComparer.Instance.Equals(instanceType, staticType); } } } } return false; } public static bool IsNameOfArgumentExpression(this ExpressionSyntax expression) { return expression is { Parent: { RawKind: (int)SyntaxKind.Argument, Parent: { RawKind: (int)SyntaxKind.ArgumentList, Parent: InvocationExpressionSyntax invocation } } } && invocation.IsNameOfInvocation(); } public static bool IsNameOfInvocation(this InvocationExpressionSyntax invocation) { return invocation.Expression is IdentifierNameSyntax identifierName && identifierName.Identifier.IsKindOrHasMatchingText(SyntaxKind.NameOfKeyword); } public static SimpleNameSyntax? GetRightmostName(this ExpressionSyntax node) { if (node is MemberAccessExpressionSyntax memberAccess && memberAccess.Name != null) { return memberAccess.Name; } if (node is QualifiedNameSyntax qualified && qualified.Right != null) { return qualified.Right; } if (node is SimpleNameSyntax simple) { return simple; } if (node is ConditionalAccessExpressionSyntax conditional) { return conditional.WhenNotNull.GetRightmostName(); } if (node is MemberBindingExpressionSyntax memberBinding) { return memberBinding.Name; } if (node is AliasQualifiedNameSyntax aliasQualifiedName && aliasQualifiedName.Name != null) { return aliasQualifiedName.Name; } return null; } public static OperatorPrecedence GetOperatorPrecedence(this ExpressionSyntax expression) { switch (expression.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.ConditionalAccessExpression: case SyntaxKind.InvocationExpression: case SyntaxKind.ElementAccessExpression: case SyntaxKind.PostIncrementExpression: case SyntaxKind.PostDecrementExpression: case SyntaxKind.ObjectCreationExpression: case SyntaxKind.TypeOfExpression: case SyntaxKind.DefaultExpression: case SyntaxKind.CheckedExpression: case SyntaxKind.UncheckedExpression: case SyntaxKind.AnonymousMethodExpression: // unsafe code case SyntaxKind.SizeOfExpression: case SyntaxKind.PointerMemberAccessExpression: // From C# spec, 7.3.1: // Primary: x.y x?.y x?[y] f(x) a[x] x++ x-- new typeof default checked unchecked delegate return OperatorPrecedence.Primary; case SyntaxKind.UnaryPlusExpression: case SyntaxKind.UnaryMinusExpression: case SyntaxKind.LogicalNotExpression: case SyntaxKind.BitwiseNotExpression: case SyntaxKind.PreIncrementExpression: case SyntaxKind.PreDecrementExpression: case SyntaxKind.CastExpression: case SyntaxKind.AwaitExpression: // unsafe code. case SyntaxKind.PointerIndirectionExpression: case SyntaxKind.AddressOfExpression: // From C# spec, 7.3.1: // Unary: + - ! ~ ++x --x (T)x await Task return OperatorPrecedence.Unary; case SyntaxKind.RangeExpression: // From C# spec, https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#systemrange // Range: .. return OperatorPrecedence.Range; case SyntaxKind.MultiplyExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: // From C# spec, 7.3.1: // Multiplicative: * / % return OperatorPrecedence.Multiplicative; case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: // From C# spec, 7.3.1: // Additive: + - return OperatorPrecedence.Additive; case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: // From C# spec, 7.3.1: // Shift: << >> return OperatorPrecedence.Shift; case SyntaxKind.LessThanExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: case SyntaxKind.IsPatternExpression: // From C# spec, 7.3.1: // Relational and type testing: < > <= >= is as return OperatorPrecedence.RelationalAndTypeTesting; case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: // From C# spec, 7.3.1: // Equality: == != return OperatorPrecedence.Equality; case SyntaxKind.BitwiseAndExpression: // From C# spec, 7.3.1: // Logical AND: & return OperatorPrecedence.LogicalAnd; case SyntaxKind.ExclusiveOrExpression: // From C# spec, 7.3.1: // Logical XOR: ^ return OperatorPrecedence.LogicalXor; case SyntaxKind.BitwiseOrExpression: // From C# spec, 7.3.1: // Logical OR: | return OperatorPrecedence.LogicalOr; case SyntaxKind.LogicalAndExpression: // From C# spec, 7.3.1: // Conditional AND: && return OperatorPrecedence.ConditionalAnd; case SyntaxKind.LogicalOrExpression: // From C# spec, 7.3.1: // Conditional AND: || return OperatorPrecedence.ConditionalOr; case SyntaxKind.CoalesceExpression: // From C# spec, 7.3.1: // Null coalescing: ?? return OperatorPrecedence.NullCoalescing; case SyntaxKind.ConditionalExpression: // From C# spec, 7.3.1: // Conditional: ?: return OperatorPrecedence.Conditional; case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: // From C# spec, 7.3.1: // Conditional: ?: return OperatorPrecedence.AssignmentAndLambdaExpression; case SyntaxKind.SwitchExpression: return OperatorPrecedence.Switch; default: return OperatorPrecedence.None; } } public static bool TryConvertToStatement( this ExpressionSyntax expression, SyntaxToken? semicolonTokenOpt, bool createReturnStatementForExpression, [NotNullWhen(true)] out StatementSyntax? statement) { // It's tricky to convert an arrow expression with directives over to a block. // We'd need to find and remove the directives *after* the arrow expression and // move them accordingly. So, for now, we just disallow this. if (expression.GetLeadingTrivia().Any(t => t.IsDirective)) { statement = null; return false; } var semicolonToken = semicolonTokenOpt ?? SyntaxFactory.Token(SyntaxKind.SemicolonToken); statement = ConvertToStatement(expression, semicolonToken, createReturnStatementForExpression); return true; } private static StatementSyntax ConvertToStatement(ExpressionSyntax expression, SyntaxToken semicolonToken, bool createReturnStatementForExpression) { if (expression.IsKind(SyntaxKind.ThrowExpression, out ThrowExpressionSyntax? throwExpression)) { return SyntaxFactory.ThrowStatement(throwExpression.ThrowKeyword, throwExpression.Expression, semicolonToken); } else if (createReturnStatementForExpression) { if (expression.GetLeadingTrivia().Any(t => t.IsSingleOrMultiLineComment())) { return SyntaxFactory.ReturnStatement(expression.WithLeadingTrivia(SyntaxFactory.ElasticSpace)) .WithSemicolonToken(semicolonToken) .WithLeadingTrivia(expression.GetLeadingTrivia()) .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker); } else { return SyntaxFactory.ReturnStatement(expression) .WithSemicolonToken(semicolonToken); } } else { return SyntaxFactory.ExpressionStatement(expression) .WithSemicolonToken(semicolonToken); } } public static bool IsDirectChildOfMemberAccessExpression(this ExpressionSyntax expression) => expression?.Parent is MemberAccessExpressionSyntax; public static bool InsideCrefReference(this ExpressionSyntax expression) => expression.FirstAncestorOrSelf<XmlCrefAttributeSyntax>() != null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class ExpressionSyntaxExtensions { public static ExpressionSyntax WalkUpParentheses(this ExpressionSyntax expression) { while (expression.IsParentKind(SyntaxKind.ParenthesizedExpression, out ExpressionSyntax? parentExpr)) expression = parentExpr; return expression; } public static ExpressionSyntax WalkDownParentheses(this ExpressionSyntax expression) { while (expression.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpression)) expression = parenExpression.Expression; return expression; } public static bool IsQualifiedCrefName(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.NameMemberCref) && expression.Parent.IsParentKind(SyntaxKind.QualifiedCref); public static bool IsSimpleMemberAccessExpressionName([NotNullWhen(true)] this ExpressionSyntax? expression) => expression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess) && memberAccess.Name == expression; public static bool IsAnyMemberAccessExpressionName(this ExpressionSyntax expression) { if (expression == null) { return false; } return expression == (expression.Parent as MemberAccessExpressionSyntax)?.Name || expression.IsMemberBindingExpressionName(); } public static bool IsMemberBindingExpressionName([NotNullWhen(true)] this ExpressionSyntax? expression) => expression.IsParentKind(SyntaxKind.MemberBindingExpression, out MemberBindingExpressionSyntax? memberBinding) && memberBinding.Name == expression; public static bool IsRightSideOfQualifiedName([NotNullWhen(true)] this ExpressionSyntax? expression) => expression.IsParentKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName) && qualifiedName.Right == expression; public static bool IsRightSideOfColonColon(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.AliasQualifiedName, out AliasQualifiedNameSyntax? aliasName) && aliasName.Name == expression; public static bool IsRightSideOfDot(this ExpressionSyntax name) => IsSimpleMemberAccessExpressionName(name) || IsMemberBindingExpressionName(name) || IsRightSideOfQualifiedName(name) || IsQualifiedCrefName(name); public static bool IsRightSideOfDotOrArrow(this ExpressionSyntax name) => IsAnyMemberAccessExpressionName(name) || IsRightSideOfQualifiedName(name); public static bool IsRightSideOfDotOrColonColon(this ExpressionSyntax name) => IsRightSideOfDot(name) || IsRightSideOfColonColon(name); public static bool IsRightSideOfDotOrArrowOrColonColon([NotNullWhen(true)] this ExpressionSyntax name) => IsRightSideOfDotOrArrow(name) || IsRightSideOfColonColon(name); public static bool IsRightOfCloseParen(this ExpressionSyntax expression) { var firstToken = expression.GetFirstToken(); return firstToken.Kind() != SyntaxKind.None && firstToken.GetPreviousToken().Kind() == SyntaxKind.CloseParenToken; } public static bool IsLeftSideOfDot([NotNullWhen(true)] this ExpressionSyntax? expression) { if (expression == null) return false; return IsLeftSideOfQualifiedName(expression) || IsLeftSideOfSimpleMemberAccessExpression(expression); } public static bool IsLeftSideOfSimpleMemberAccessExpression(this ExpressionSyntax expression) => (expression?.Parent).IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess) && memberAccess.Expression == expression; public static bool IsLeftSideOfDotOrArrow(this ExpressionSyntax expression) => IsLeftSideOfQualifiedName(expression) || (expression.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Expression == expression); public static bool IsLeftSideOfQualifiedName(this ExpressionSyntax expression) => (expression?.Parent).IsKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName) && qualifiedName.Left == expression; public static bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] this NameSyntax? name) => name.IsParentKind(SyntaxKind.ExplicitInterfaceSpecifier); public static bool IsExpressionOfInvocation(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax? invocation) && invocation.Expression == expression; public static bool TryGetNameParts(this ExpressionSyntax expression, [NotNullWhen(true)] out IList<string>? parts) { var partsList = new List<string>(); if (!TryGetNameParts(expression, partsList)) { parts = null; return false; } parts = partsList; return true; } public static bool TryGetNameParts(this ExpressionSyntax expression, List<string> parts) { if (expression.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess)) { if (!TryGetNameParts(memberAccess.Expression, parts)) { return false; } return AddSimpleName(memberAccess.Name, parts); } else if (expression.IsKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName)) { if (!TryGetNameParts(qualifiedName.Left, parts)) { return false; } return AddSimpleName(qualifiedName.Right, parts); } else if (expression is SimpleNameSyntax simpleName) { return AddSimpleName(simpleName, parts); } else { return false; } } private static bool AddSimpleName(SimpleNameSyntax simpleName, List<string> parts) { if (!simpleName.IsKind(SyntaxKind.IdentifierName)) { return false; } parts.Add(simpleName.Identifier.ValueText); return true; } public static bool IsAnyLiteralExpression(this ExpressionSyntax expression) => expression is LiteralExpressionSyntax; public static bool IsInConstantContext([NotNullWhen(true)] this ExpressionSyntax? expression) { if (expression == null) return false; if (expression.GetAncestor<ParameterSyntax>() != null) return true; var attributeArgument = expression.GetAncestor<AttributeArgumentSyntax>(); if (attributeArgument != null) { if (attributeArgument.NameEquals == null || expression != attributeArgument.NameEquals.Name) { return true; } } if (expression.IsParentKind(SyntaxKind.ConstantPattern)) return true; // note: the above list is not intended to be exhaustive. If more cases // are discovered that should be considered 'constant' contexts in the // language, then this should be updated accordingly. return false; } public static bool IsInOutContext(this ExpressionSyntax expression) { return expression?.Parent is ArgumentSyntax argument && argument.Expression == expression && argument.RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword; } public static bool IsInRefContext(this ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.RefExpression) || (expression?.Parent as ArgumentSyntax)?.RefOrOutKeyword.Kind() == SyntaxKind.RefKeyword; public static bool IsInInContext(this ExpressionSyntax expression) => (expression?.Parent as ArgumentSyntax)?.RefKindKeyword.Kind() == SyntaxKind.InKeyword; private static ExpressionSyntax GetExpressionToAnalyzeForWrites(ExpressionSyntax expression) { if (expression.IsRightSideOfDotOrArrow()) { expression = (ExpressionSyntax)expression.GetRequiredParent(); } expression = expression.WalkUpParentheses(); return expression; } public static bool IsOnlyWrittenTo(this ExpressionSyntax expression) { expression = GetExpressionToAnalyzeForWrites(expression); if (expression != null) { if (expression.IsInOutContext()) { return true; } if (expression.Parent != null) { if (expression.IsLeftSideOfAssignExpression()) { return true; } if (expression.IsAttributeNamedArgumentIdentifier()) { return true; } } if (IsExpressionOfArgumentInDeconstruction(expression)) { return true; } } return false; } /// <summary> /// If this declaration or identifier is part of a deconstruction, find the deconstruction. /// If found, returns either an assignment expression or a foreach variable statement. /// Returns null otherwise. /// /// copied from SyntaxExtensions.GetContainingDeconstruction /// </summary> private static bool IsExpressionOfArgumentInDeconstruction(ExpressionSyntax expr) { if (!expr.IsParentKind(SyntaxKind.Argument)) { return false; } while (true) { var parent = expr.Parent; if (parent == null) { return false; } switch (parent.Kind()) { case SyntaxKind.Argument: if (parent.Parent?.Kind() == SyntaxKind.TupleExpression) { expr = (TupleExpressionSyntax)parent.Parent; continue; } return false; case SyntaxKind.SimpleAssignmentExpression: if (((AssignmentExpressionSyntax)parent).Left == expr) { return true; } return false; case SyntaxKind.ForEachVariableStatement: if (((ForEachVariableStatementSyntax)parent).Variable == expr) { return true; } return false; default: return false; } } } public static bool IsWrittenTo(this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { if (expression == null) return false; expression = GetExpressionToAnalyzeForWrites(expression); if (expression.IsOnlyWrittenTo()) return true; if (expression.IsInRefContext()) { // most cases of `ref x` will count as a potential write of `x`. An important exception is: // `ref readonly y = ref x`. In that case, because 'y' can't be written to, this would not // be a write of 'x'. if (expression is { Parent: { RawKind: (int)SyntaxKind.RefExpression, Parent: EqualsValueClauseSyntax { Parent: VariableDeclaratorSyntax { Parent: VariableDeclarationSyntax { Type: RefTypeSyntax refType } } } } } && refType.ReadOnlyKeyword != default) { return false; } return true; } // Similar to `ref x`, `&x` allows reads and write of the value, meaning `x` may be (but is not definitely) // written to. if (expression.Parent.IsKind(SyntaxKind.AddressOfExpression)) return true; // We're written if we're used in a ++, or -- expression. if (expression.IsOperandOfIncrementOrDecrementExpression()) return true; if (expression.IsLeftSideOfAnyAssignExpression()) return true; // An extension method invocation with a ref-this parameter can write to an expression. if (expression.Parent is MemberAccessExpressionSyntax memberAccess && expression == memberAccess.Expression) { var symbol = semanticModel.GetSymbolInfo(memberAccess, cancellationToken).Symbol; if (symbol is IMethodSymbol { MethodKind: MethodKind.ReducedExtension, ReducedFrom: IMethodSymbol reducedFrom } && reducedFrom.Parameters.Length > 0 && reducedFrom.Parameters.First().RefKind == RefKind.Ref) { return true; } } return false; } public static bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] this ExpressionSyntax? expression) { var nameEquals = expression?.Parent as NameEqualsSyntax; return nameEquals.IsParentKind(SyntaxKind.AttributeArgument); } public static bool IsOperandOfIncrementOrDecrementExpression(this ExpressionSyntax expression) { if (expression?.Parent is SyntaxNode parent) { switch (parent.Kind()) { case SyntaxKind.PostIncrementExpression: case SyntaxKind.PreIncrementExpression: case SyntaxKind.PostDecrementExpression: case SyntaxKind.PreDecrementExpression: return true; } } return false; } public static bool IsNamedArgumentIdentifier(this ExpressionSyntax expression) => expression is IdentifierNameSyntax && expression.Parent is NameColonSyntax; public static bool IsInsideNameOfExpression( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { var invocation = expression?.GetAncestor<InvocationExpressionSyntax>(); if (invocation?.Expression is IdentifierNameSyntax name && name.Identifier.Text == SyntaxFacts.GetText(SyntaxKind.NameOfKeyword)) { return semanticModel.GetMemberGroup(name, cancellationToken).IsDefaultOrEmpty; } return false; } private static bool CanReplace(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Field: case SymbolKind.Local: case SymbolKind.Method: case SymbolKind.Parameter: case SymbolKind.Property: case SymbolKind.RangeVariable: case SymbolKind.FunctionPointerType: return true; } return false; } public static bool CanReplaceWithRValue( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { // An RValue can't be written into. // i.e. you can't replace "a" in "a = b" with "Goo() = b". return expression != null && !expression.IsWrittenTo(semanticModel, cancellationToken) && CanReplaceWithLValue(expression, semanticModel, cancellationToken); } public static bool CanReplaceWithLValue( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { if (expression.IsKind(SyntaxKind.StackAllocArrayCreationExpression)) { // Stack alloc is very interesting. While it appears to be an expression, it is only // such so it can appear in a variable decl. It is not a normal expression that can // go anywhere. return false; } if (expression.IsKind(SyntaxKind.BaseExpression) || expression.IsKind(SyntaxKind.CollectionInitializerExpression) || expression.IsKind(SyntaxKind.ObjectInitializerExpression) || expression.IsKind(SyntaxKind.ComplexElementInitializerExpression)) { return false; } // literal can be always replaced. if (expression is LiteralExpressionSyntax && !expression.IsParentKind(SyntaxKind.UnaryMinusExpression)) { return true; } if (expression is TupleExpressionSyntax) { return true; } if (!(expression is ObjectCreationExpressionSyntax) && !(expression is AnonymousObjectCreationExpressionSyntax) && !expression.IsLeftSideOfAssignExpression()) { var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken); if (!symbolInfo.GetBestOrAllSymbols().All(CanReplace)) { // If the expression is actually a reference to a type, then it can't be replaced // with an arbitrary expression. return false; } } // If we are a conditional access expression: // case (1) : obj?.Method(), obj1.obj2?.Property // case (2) : obj?.GetAnotherObj()?.Length, obj?.AnotherObj?.Length // in case (1), the entire expression forms the conditional access expression, which can be replaced with an LValue. // in case (2), the nested conditional access expression is ".GetAnotherObj()?.Length" or ".AnotherObj()?.Length" // essentially, the first expression (before the operator) in a nested conditional access expression // is some form of member binding expression and they cannot be replaced with an LValue. if (expression.IsKind(SyntaxKind.ConditionalAccessExpression)) { return expression is { Parent: { RawKind: not (int)SyntaxKind.ConditionalAccessExpression } }; } if (expression.Parent == null) return false; switch (expression.Parent.Kind()) { case SyntaxKind.InvocationExpression: // Technically, you could introduce an LValue for "Goo" in "Goo()" even if "Goo" binds // to a method. (i.e. by assigning to a Func<...> type). However, this is so contrived // and none of the features that use this extension consider this replaceable. if (expression.IsKind(SyntaxKind.IdentifierName) || expression is MemberAccessExpressionSyntax) { // If it looks like a method then we don't allow it to be replaced if it is a // method (or if it doesn't bind). var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken); return symbolInfo.GetBestOrAllSymbols().Any() && !symbolInfo.GetBestOrAllSymbols().Any(s => s is IMethodSymbol); } else { // It doesn't look like a method, we allow this to be replaced. return true; } // If the parent is a conditional access expression, we could introduce an LValue // for the given expression, unless it is itself a MemberBindingExpression or starts with one. // Case (1) : The WhenNotNull clause always starts with a MemberBindingExpression. // expression '.Method()' in a?.Method() // Case (2) : The Expression clause always starts with a MemberBindingExpression if // the grandparent is a conditional access expression. // expression '.Method' in a?.Method()?.Length // Case (3) : The child Conditional access expression always starts with a MemberBindingExpression if // the parent is a conditional access expression. This case is already covered before the parent kind switch case SyntaxKind.ConditionalAccessExpression: var parentConditionalAccessExpression = (ConditionalAccessExpressionSyntax)expression.Parent; return expression != parentConditionalAccessExpression.WhenNotNull && !parentConditionalAccessExpression.Parent.IsKind(SyntaxKind.ConditionalAccessExpression); case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: // Can't introduce a variable for the type portion of an is/as check. var isOrAsExpression = (BinaryExpressionSyntax)expression.Parent; return expression == isOrAsExpression.Left; case SyntaxKind.EqualsValueClause: case SyntaxKind.ExpressionStatement: case SyntaxKind.ArrayInitializerExpression: case SyntaxKind.CollectionInitializerExpression: case SyntaxKind.Argument: case SyntaxKind.AttributeArgument: case SyntaxKind.AnonymousObjectMemberDeclarator: case SyntaxKind.ArrowExpressionClause: case SyntaxKind.AwaitExpression: case SyntaxKind.ReturnStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedExpression: case SyntaxKind.ArrayRankSpecifier: case SyntaxKind.ConditionalExpression: case SyntaxKind.IfStatement: case SyntaxKind.CatchFilterClause: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.InterpolatedStringExpression: case SyntaxKind.ComplexElementInitializerExpression: case SyntaxKind.Interpolation: case SyntaxKind.RefExpression: case SyntaxKind.LockStatement: case SyntaxKind.ElementAccessExpression: case SyntaxKind.SwitchExpressionArm: // Direct parent kind checks. return true; } if (expression.Parent is PrefixUnaryExpressionSyntax) { if (!(expression is LiteralExpressionSyntax && expression.IsParentKind(SyntaxKind.UnaryMinusExpression))) { return true; } } var parentNonExpression = expression.GetAncestors().SkipWhile(n => n is ExpressionSyntax).FirstOrDefault(); var topExpression = expression; while (topExpression.Parent is TypeSyntax typeSyntax) { topExpression = typeSyntax; } if (parentNonExpression != null && parentNonExpression.IsKind(SyntaxKind.FromClause, out FromClauseSyntax? fromClause) && topExpression != null && fromClause.Type == topExpression) { return false; } // Parent type checks. if (expression.Parent is PostfixUnaryExpressionSyntax || expression.Parent is BinaryExpressionSyntax || expression.Parent is AssignmentExpressionSyntax || expression.Parent is QueryClauseSyntax || expression.Parent is SelectOrGroupClauseSyntax || expression.Parent is CheckedExpressionSyntax) { return true; } // Specific child checks. if (expression.CheckParent<CommonForEachStatementSyntax>(f => f.Expression == expression) || expression.CheckParent<MemberAccessExpressionSyntax>(m => m.Expression == expression) || expression.CheckParent<CastExpressionSyntax>(c => c.Expression == expression)) { return true; } // Misc checks. if ((expression.IsParentKind(SyntaxKind.NameEquals) && expression.Parent.IsParentKind(SyntaxKind.AttributeArgument)) || expression.IsLeftSideOfAnyAssignExpression()) { return true; } return false; } public static bool CanAccessInstanceAndStaticMembersOffOf( this ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { // Check for the Color Color case. // // color color: if you bind "A" and you get a symbol and the type of that symbol is // Q; and if you bind "A" *again* as a type and you get type Q, then both A.static // and A.instance are permitted if (expression is IdentifierNameSyntax) { var instanceSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).GetAnySymbol(); if (!(instanceSymbol is INamespaceOrTypeSymbol)) { var instanceType = instanceSymbol.GetSymbolType(); if (instanceType != null) { var speculativeSymbolInfo = semanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace); if (speculativeSymbolInfo.CandidateReason != CandidateReason.NotATypeOrNamespace) { var staticType = speculativeSymbolInfo.GetAnySymbol().GetSymbolType(); return SymbolEquivalenceComparer.Instance.Equals(instanceType, staticType); } } } } return false; } public static bool IsNameOfArgumentExpression(this ExpressionSyntax expression) { return expression is { Parent: { RawKind: (int)SyntaxKind.Argument, Parent: { RawKind: (int)SyntaxKind.ArgumentList, Parent: InvocationExpressionSyntax invocation } } } && invocation.IsNameOfInvocation(); } public static bool IsNameOfInvocation(this InvocationExpressionSyntax invocation) { return invocation.Expression is IdentifierNameSyntax identifierName && identifierName.Identifier.IsKindOrHasMatchingText(SyntaxKind.NameOfKeyword); } public static SimpleNameSyntax? GetRightmostName(this ExpressionSyntax node) { if (node is MemberAccessExpressionSyntax memberAccess && memberAccess.Name != null) { return memberAccess.Name; } if (node is QualifiedNameSyntax qualified && qualified.Right != null) { return qualified.Right; } if (node is SimpleNameSyntax simple) { return simple; } if (node is ConditionalAccessExpressionSyntax conditional) { return conditional.WhenNotNull.GetRightmostName(); } if (node is MemberBindingExpressionSyntax memberBinding) { return memberBinding.Name; } if (node is AliasQualifiedNameSyntax aliasQualifiedName && aliasQualifiedName.Name != null) { return aliasQualifiedName.Name; } return null; } public static OperatorPrecedence GetOperatorPrecedence(this ExpressionSyntax expression) { switch (expression.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.ConditionalAccessExpression: case SyntaxKind.InvocationExpression: case SyntaxKind.ElementAccessExpression: case SyntaxKind.PostIncrementExpression: case SyntaxKind.PostDecrementExpression: case SyntaxKind.ObjectCreationExpression: case SyntaxKind.TypeOfExpression: case SyntaxKind.DefaultExpression: case SyntaxKind.CheckedExpression: case SyntaxKind.UncheckedExpression: case SyntaxKind.AnonymousMethodExpression: // unsafe code case SyntaxKind.SizeOfExpression: case SyntaxKind.PointerMemberAccessExpression: // From C# spec, 7.3.1: // Primary: x.y x?.y x?[y] f(x) a[x] x++ x-- new typeof default checked unchecked delegate return OperatorPrecedence.Primary; case SyntaxKind.UnaryPlusExpression: case SyntaxKind.UnaryMinusExpression: case SyntaxKind.LogicalNotExpression: case SyntaxKind.BitwiseNotExpression: case SyntaxKind.PreIncrementExpression: case SyntaxKind.PreDecrementExpression: case SyntaxKind.CastExpression: case SyntaxKind.AwaitExpression: // unsafe code. case SyntaxKind.PointerIndirectionExpression: case SyntaxKind.AddressOfExpression: // From C# spec, 7.3.1: // Unary: + - ! ~ ++x --x (T)x await Task return OperatorPrecedence.Unary; case SyntaxKind.RangeExpression: // From C# spec, https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#systemrange // Range: .. return OperatorPrecedence.Range; case SyntaxKind.MultiplyExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: // From C# spec, 7.3.1: // Multiplicative: * / % return OperatorPrecedence.Multiplicative; case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: // From C# spec, 7.3.1: // Additive: + - return OperatorPrecedence.Additive; case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: // From C# spec, 7.3.1: // Shift: << >> return OperatorPrecedence.Shift; case SyntaxKind.LessThanExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: case SyntaxKind.IsPatternExpression: // From C# spec, 7.3.1: // Relational and type testing: < > <= >= is as return OperatorPrecedence.RelationalAndTypeTesting; case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: // From C# spec, 7.3.1: // Equality: == != return OperatorPrecedence.Equality; case SyntaxKind.BitwiseAndExpression: // From C# spec, 7.3.1: // Logical AND: & return OperatorPrecedence.LogicalAnd; case SyntaxKind.ExclusiveOrExpression: // From C# spec, 7.3.1: // Logical XOR: ^ return OperatorPrecedence.LogicalXor; case SyntaxKind.BitwiseOrExpression: // From C# spec, 7.3.1: // Logical OR: | return OperatorPrecedence.LogicalOr; case SyntaxKind.LogicalAndExpression: // From C# spec, 7.3.1: // Conditional AND: && return OperatorPrecedence.ConditionalAnd; case SyntaxKind.LogicalOrExpression: // From C# spec, 7.3.1: // Conditional AND: || return OperatorPrecedence.ConditionalOr; case SyntaxKind.CoalesceExpression: // From C# spec, 7.3.1: // Null coalescing: ?? return OperatorPrecedence.NullCoalescing; case SyntaxKind.ConditionalExpression: // From C# spec, 7.3.1: // Conditional: ?: return OperatorPrecedence.Conditional; case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: // From C# spec, 7.3.1: // Conditional: ?: return OperatorPrecedence.AssignmentAndLambdaExpression; case SyntaxKind.SwitchExpression: return OperatorPrecedence.Switch; default: return OperatorPrecedence.None; } } public static bool TryConvertToStatement( this ExpressionSyntax expression, SyntaxToken? semicolonTokenOpt, bool createReturnStatementForExpression, [NotNullWhen(true)] out StatementSyntax? statement) { // It's tricky to convert an arrow expression with directives over to a block. // We'd need to find and remove the directives *after* the arrow expression and // move them accordingly. So, for now, we just disallow this. if (expression.GetLeadingTrivia().Any(t => t.IsDirective)) { statement = null; return false; } var semicolonToken = semicolonTokenOpt ?? SyntaxFactory.Token(SyntaxKind.SemicolonToken); statement = ConvertToStatement(expression, semicolonToken, createReturnStatementForExpression); return true; } private static StatementSyntax ConvertToStatement(ExpressionSyntax expression, SyntaxToken semicolonToken, bool createReturnStatementForExpression) { if (expression.IsKind(SyntaxKind.ThrowExpression, out ThrowExpressionSyntax? throwExpression)) { return SyntaxFactory.ThrowStatement(throwExpression.ThrowKeyword, throwExpression.Expression, semicolonToken); } else if (createReturnStatementForExpression) { if (expression.GetLeadingTrivia().Any(t => t.IsSingleOrMultiLineComment())) { return SyntaxFactory.ReturnStatement(expression.WithLeadingTrivia(SyntaxFactory.ElasticSpace)) .WithSemicolonToken(semicolonToken) .WithLeadingTrivia(expression.GetLeadingTrivia()) .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker); } else { return SyntaxFactory.ReturnStatement(expression) .WithSemicolonToken(semicolonToken); } } else { return SyntaxFactory.ExpressionStatement(expression) .WithSemicolonToken(semicolonToken); } } public static bool IsDirectChildOfMemberAccessExpression(this ExpressionSyntax expression) => expression?.Parent is MemberAccessExpressionSyntax; public static bool InsideCrefReference(this ExpressionSyntax expression) => expression.FirstAncestorOrSelf<XmlCrefAttributeSyntax>() != null; } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpGenerateTypeDialog.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpGenerateTypeDialog : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; private GenerateTypeDialog_OutOfProc GenerateTypeDialog => VisualStudio.GenerateTypeDialog; public CSharpGenerateTypeDialog(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpGenerateTypeDialog)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public void OpenAndCloseDialog() { SetUpEditor(@"class C { void Method() { $$A a; } } "); VisualStudio.Editor.Verify.CodeAction("Generate new type...", applyFix: true, blockUntilComplete: false); GenerateTypeDialog.VerifyOpen(); GenerateTypeDialog.ClickCancel(); GenerateTypeDialog.VerifyClosed(); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public void CSharpToBasic() { var vbProj = new ProjectUtils.Project("VBProj"); VisualStudio.SolutionExplorer.AddProject(vbProj, WellKnownProjectTemplates.ClassLibrary, LanguageNames.VisualBasic); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); SetUpEditor(@"class C { void Method() { $$A a; } } "); VisualStudio.Editor.Verify.CodeAction("Generate new type...", applyFix: true, blockUntilComplete: false); GenerateTypeDialog.VerifyOpen(); GenerateTypeDialog.SetAccessibility("public"); GenerateTypeDialog.SetKind("interface"); GenerateTypeDialog.SetTargetProject("VBProj"); GenerateTypeDialog.SetTargetFileToNewName("GenerateTypeTest"); GenerateTypeDialog.ClickOK(); GenerateTypeDialog.VerifyClosed(); VisualStudio.SolutionExplorer.OpenFile(vbProj, "GenerateTypeTest.vb"); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"Public Interface A End Interface ", actualText); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"using VBProj; class C { void Method() { A a; } } ", actualText); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpGenerateTypeDialog : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; private GenerateTypeDialog_OutOfProc GenerateTypeDialog => VisualStudio.GenerateTypeDialog; public CSharpGenerateTypeDialog(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpGenerateTypeDialog)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public void OpenAndCloseDialog() { SetUpEditor(@"class C { void Method() { $$A a; } } "); VisualStudio.Editor.Verify.CodeAction("Generate new type...", applyFix: true, blockUntilComplete: false); GenerateTypeDialog.VerifyOpen(); GenerateTypeDialog.ClickCancel(); GenerateTypeDialog.VerifyClosed(); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public void CSharpToBasic() { var vbProj = new ProjectUtils.Project("VBProj"); VisualStudio.SolutionExplorer.AddProject(vbProj, WellKnownProjectTemplates.ClassLibrary, LanguageNames.VisualBasic); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); SetUpEditor(@"class C { void Method() { $$A a; } } "); VisualStudio.Editor.Verify.CodeAction("Generate new type...", applyFix: true, blockUntilComplete: false); GenerateTypeDialog.VerifyOpen(); GenerateTypeDialog.SetAccessibility("public"); GenerateTypeDialog.SetKind("interface"); GenerateTypeDialog.SetTargetProject("VBProj"); GenerateTypeDialog.SetTargetFileToNewName("GenerateTypeTest"); GenerateTypeDialog.ClickOK(); GenerateTypeDialog.VerifyClosed(); VisualStudio.SolutionExplorer.OpenFile(vbProj, "GenerateTypeTest.vb"); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"Public Interface A End Interface ", actualText); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"using VBProj; class C { void Method() { A a; } } ", actualText); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/Core/Test.Next/Remote/SerializationValidator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Remote.UnitTests { internal sealed class SerializationValidator { private sealed class AssetProvider : AbstractAssetProvider { private readonly SerializationValidator _validator; public AssetProvider(SerializationValidator validator) => _validator = validator; public override Task<T> GetAssetAsync<T>(Checksum checksum, CancellationToken cancellationToken) => _validator.GetValueAsync<T>(checksum); } internal sealed class ChecksumObjectCollection<T> : IEnumerable<T> where T : ChecksumWithChildren { public ImmutableArray<T> Children { get; } /// <summary> /// Indicates what kind of object it is /// <see cref="WellKnownSynchronizationKind"/> for examples. /// /// this will be used in tranportation framework and deserialization service /// to hand shake how to send over data and deserialize serialized data /// </summary> public readonly WellKnownSynchronizationKind Kind; /// <summary> /// Checksum of this object /// </summary> public readonly Checksum Checksum; public ChecksumObjectCollection(SerializationValidator validator, ChecksumCollection collection) { Checksum = collection.Checksum; Kind = collection.GetWellKnownSynchronizationKind(); // using .Result here since we don't want to convert all calls to this to async. // and none of ChecksumWithChildren actually use async Children = ImmutableArray.CreateRange(collection.Select(c => validator.GetValueAsync<T>(c).Result)); } public int Count => Children.Length; public T this[int index] => Children[index]; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IEnumerator<T> GetEnumerator() => Children.Select(t => t).GetEnumerator(); } public SolutionAssetStorage AssetStorage { get; } public ISerializerService Serializer { get; } public HostWorkspaceServices Services { get; } public SerializationValidator(HostWorkspaceServices services) { AssetStorage = services.GetRequiredService<ISolutionAssetStorageProvider>().AssetStorage; Serializer = services.GetRequiredService<ISerializerService>(); Services = services; } public async Task<T> GetValueAsync<T>(Checksum checksum) { var data = (await AssetStorage.GetTestAccessor().GetAssetAsync(checksum, CancellationToken.None).ConfigureAwait(false))!; Contract.ThrowIfNull(data.Value); using var context = SolutionReplicationContext.Create(); using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { Serializer.Serialize(data.Value, writer, context, CancellationToken.None); } stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); // deserialize bits to object var result = Serializer.Deserialize<T>(data.Kind, reader, CancellationToken.None); Contract.ThrowIfNull(result); return result; } public async Task<Solution> GetSolutionAsync(SolutionAssetStorage.Scope scope) { var (solutionInfo, _) = await new AssetProvider(this).CreateSolutionInfoAndOptionsAsync(scope.SolutionInfo.SolutionChecksum, CancellationToken.None).ConfigureAwait(false); var workspace = new AdhocWorkspace(Services.HostServices); return workspace.AddSolution(solutionInfo); } public ChecksumObjectCollection<ProjectStateChecksums> ToProjectObjects(ChecksumCollection collection) => new ChecksumObjectCollection<ProjectStateChecksums>(this, collection); public ChecksumObjectCollection<DocumentStateChecksums> ToDocumentObjects(ChecksumCollection collection) => new ChecksumObjectCollection<DocumentStateChecksums>(this, collection); internal async Task VerifyAssetAsync(SolutionStateChecksums solutionObject) { await VerifyAssetSerializationAsync<SolutionInfo.SolutionAttributes>( solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)).ConfigureAwait(false); foreach (var projectChecksum in solutionObject.Projects) { var projectObject = await GetValueAsync<ProjectStateChecksums>(projectChecksum).ConfigureAwait(false); await VerifyAssetAsync(projectObject).ConfigureAwait(false); } } internal async Task VerifyAssetAsync(ProjectStateChecksums projectObject) { var info = await VerifyAssetSerializationAsync<ProjectInfo.ProjectAttributes>( projectObject.Info, WellKnownSynchronizationKind.ProjectAttributes, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)).ConfigureAwait(false); await VerifyAssetSerializationAsync<CompilationOptions>( projectObject.CompilationOptions, WellKnownSynchronizationKind.CompilationOptions, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); await VerifyAssetSerializationAsync<ParseOptions>( projectObject.ParseOptions, WellKnownSynchronizationKind.ParseOptions, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); foreach (var checksum in projectObject.Documents) { var documentObject = await GetValueAsync<DocumentStateChecksums>(checksum).ConfigureAwait(false); await VerifyAssetAsync(documentObject).ConfigureAwait(false); } foreach (var checksum in projectObject.ProjectReferences) { await VerifyAssetSerializationAsync<ProjectReference>( checksum, WellKnownSynchronizationKind.ProjectReference, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } foreach (var checksum in projectObject.MetadataReferences) { await VerifyAssetSerializationAsync<MetadataReference>( checksum, WellKnownSynchronizationKind.MetadataReference, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } foreach (var checksum in projectObject.AnalyzerReferences) { await VerifyAssetSerializationAsync<AnalyzerReference>( checksum, WellKnownSynchronizationKind.AnalyzerReference, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } foreach (var checksum in projectObject.AdditionalDocuments) { var documentObject = await GetValueAsync<DocumentStateChecksums>(checksum).ConfigureAwait(false); await VerifyAssetAsync(documentObject).ConfigureAwait(false); } foreach (var checksum in projectObject.AnalyzerConfigDocuments) { var documentObject = await GetValueAsync<DocumentStateChecksums>(checksum).ConfigureAwait(false); await VerifyAssetAsync(documentObject).ConfigureAwait(false); } } internal async Task VerifyAssetAsync(DocumentStateChecksums documentObject) { var info = await VerifyAssetSerializationAsync<DocumentInfo.DocumentAttributes>( documentObject.Info, WellKnownSynchronizationKind.DocumentAttributes, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)).ConfigureAwait(false); await VerifyAssetSerializationAsync<SerializableSourceText>( documentObject.Text, WellKnownSynchronizationKind.SerializableSourceText, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } internal async Task<T> VerifyAssetSerializationAsync<T>( Checksum checksum, WellKnownSynchronizationKind kind, Func<T, WellKnownSynchronizationKind, ISerializerService, SolutionAsset> assetGetter) { // re-create asset from object var syncObject = (await AssetStorage.GetTestAccessor().GetAssetAsync(checksum, CancellationToken.None).ConfigureAwait(false))!; var recoveredValue = await GetValueAsync<T>(checksum).ConfigureAwait(false); var recreatedSyncObject = assetGetter(recoveredValue, kind, Serializer); // make sure original object and re-created object are same. SynchronizationObjectEqual(syncObject, recreatedSyncObject); return recoveredValue; } internal async Task VerifySolutionStateSerializationAsync(Solution solution, Checksum solutionChecksum) { var solutionObjectFromSyncObject = await GetValueAsync<SolutionStateChecksums>(solutionChecksum); Contract.ThrowIfFalse(solution.State.TryGetStateChecksums(out var solutionObjectFromSolution)); SolutionStateEqual(solutionObjectFromSolution, solutionObjectFromSyncObject); } internal void SolutionStateEqual(SolutionStateChecksums solutionObject1, SolutionStateChecksums solutionObject2) { ChecksumWithChildrenEqual(solutionObject1, solutionObject2); ProjectStatesEqual(ToProjectObjects(solutionObject1.Projects), ToProjectObjects(solutionObject2.Projects)); } internal void ProjectStateEqual(ProjectStateChecksums projectObjects1, ProjectStateChecksums projectObjects2) { ChecksumWithChildrenEqual(projectObjects1, projectObjects2); ChecksumWithChildrenEqual(ToDocumentObjects(projectObjects1.Documents), ToDocumentObjects(projectObjects2.Documents)); ChecksumWithChildrenEqual(ToDocumentObjects(projectObjects1.AdditionalDocuments), ToDocumentObjects(projectObjects2.AdditionalDocuments)); ChecksumWithChildrenEqual(ToDocumentObjects(projectObjects1.AnalyzerConfigDocuments), ToDocumentObjects(projectObjects2.AnalyzerConfigDocuments)); } internal void ProjectStatesEqual(ChecksumObjectCollection<ProjectStateChecksums> projectObjects1, ChecksumObjectCollection<ProjectStateChecksums> projectObjects2) { SynchronizationObjectEqual(projectObjects1, projectObjects2); Assert.Equal(projectObjects1.Count, projectObjects2.Count); for (var i = 0; i < projectObjects1.Count; i++) { ProjectStateEqual(projectObjects1[i], projectObjects2[i]); } } internal static void ChecksumWithChildrenEqual<T>(ChecksumObjectCollection<T> checksums1, ChecksumObjectCollection<T> checksums2) where T : ChecksumWithChildren { SynchronizationObjectEqual(checksums1, checksums2); Assert.Equal(checksums1.Count, checksums2.Count); for (var i = 0; i < checksums1.Count; i++) { ChecksumWithChildrenEqual(checksums1[i], checksums2[i]); } } internal static void ChecksumWithChildrenEqual(ChecksumWithChildren checksums1, ChecksumWithChildren checksums2) { Assert.Equal(checksums1.Checksum, checksums2.Checksum); Assert.Equal(checksums1.Children.Count, checksums2.Children.Count); for (var i = 0; i < checksums1.Children.Count; i++) { var child1 = checksums1.Children[i]; var child2 = checksums2.Children[i]; Assert.Equal(child1.GetType(), child2.GetType()); if (child1 is Checksum) { Assert.Equal((Checksum)child1, (Checksum)child2); continue; } ChecksumWithChildrenEqual((ChecksumCollection)child1, (ChecksumCollection)child2); } } internal async Task VerifySnapshotInServiceAsync( ProjectStateChecksums projectObject, int expectedDocumentCount, int expectedProjectReferenceCount, int expectedMetadataReferenceCount, int expectedAnalyzerReferenceCount, int expectedAdditionalDocumentCount) { await VerifyChecksumInServiceAsync(projectObject.Checksum, projectObject.GetWellKnownSynchronizationKind()).ConfigureAwait(false); await VerifyChecksumInServiceAsync(projectObject.Info, WellKnownSynchronizationKind.ProjectAttributes).ConfigureAwait(false); await VerifyChecksumInServiceAsync(projectObject.CompilationOptions, WellKnownSynchronizationKind.CompilationOptions).ConfigureAwait(false); await VerifyChecksumInServiceAsync(projectObject.ParseOptions, WellKnownSynchronizationKind.ParseOptions).ConfigureAwait(false); await VerifyCollectionInService(ToDocumentObjects(projectObject.Documents), expectedDocumentCount).ConfigureAwait(false); await VerifyCollectionInService(projectObject.ProjectReferences, expectedProjectReferenceCount, WellKnownSynchronizationKind.ProjectReference).ConfigureAwait(false); await VerifyCollectionInService(projectObject.MetadataReferences, expectedMetadataReferenceCount, WellKnownSynchronizationKind.MetadataReference).ConfigureAwait(false); await VerifyCollectionInService(projectObject.AnalyzerReferences, expectedAnalyzerReferenceCount, WellKnownSynchronizationKind.AnalyzerReference).ConfigureAwait(false); await VerifyCollectionInService(ToDocumentObjects(projectObject.AdditionalDocuments), expectedAdditionalDocumentCount).ConfigureAwait(false); } internal async Task VerifyCollectionInService(ChecksumCollection checksums, int expectedCount, WellKnownSynchronizationKind expectedItemKind) { await VerifyChecksumInServiceAsync(checksums.Checksum, checksums.GetWellKnownSynchronizationKind()).ConfigureAwait(false); Assert.Equal(checksums.Count, expectedCount); foreach (var checksum in checksums) { await VerifyChecksumInServiceAsync(checksum, expectedItemKind).ConfigureAwait(false); } } internal async Task VerifyCollectionInService(ChecksumObjectCollection<DocumentStateChecksums> documents, int expectedCount) { await VerifySynchronizationObjectInServiceAsync(documents).ConfigureAwait(false); Assert.Equal(documents.Count, expectedCount); foreach (var documentId in documents) { await VerifySnapshotInServiceAsync(documentId).ConfigureAwait(false); } } internal async Task VerifySnapshotInServiceAsync(DocumentStateChecksums documentObject) { await VerifyChecksumInServiceAsync(documentObject.Checksum, documentObject.GetWellKnownSynchronizationKind()).ConfigureAwait(false); await VerifyChecksumInServiceAsync(documentObject.Info, WellKnownSynchronizationKind.DocumentAttributes).ConfigureAwait(false); await VerifyChecksumInServiceAsync(documentObject.Text, WellKnownSynchronizationKind.SerializableSourceText).ConfigureAwait(false); } internal async Task VerifySynchronizationObjectInServiceAsync(SolutionAsset syncObject) => await VerifyChecksumInServiceAsync(syncObject.Checksum, syncObject.Kind).ConfigureAwait(false); internal async Task VerifySynchronizationObjectInServiceAsync<T>(ChecksumObjectCollection<T> syncObject) where T : ChecksumWithChildren => await VerifyChecksumInServiceAsync(syncObject.Checksum, syncObject.Kind).ConfigureAwait(false); internal async Task VerifyChecksumInServiceAsync(Checksum checksum, WellKnownSynchronizationKind kind) { Assert.NotNull(checksum); var otherObject = (await AssetStorage.GetTestAccessor().GetAssetAsync(checksum, CancellationToken.None).ConfigureAwait(false))!; ChecksumEqual(checksum, kind, otherObject.Checksum, otherObject.Kind); } internal static void SynchronizationObjectEqual<T>(ChecksumObjectCollection<T> checksumObject1, ChecksumObjectCollection<T> checksumObject2) where T : ChecksumWithChildren => ChecksumEqual(checksumObject1.Checksum, checksumObject1.Kind, checksumObject2.Checksum, checksumObject2.Kind); internal static void SynchronizationObjectEqual<T>(ChecksumObjectCollection<T> checksumObject1, SolutionAsset checksumObject2) where T : ChecksumWithChildren => ChecksumEqual(checksumObject1.Checksum, checksumObject1.Kind, checksumObject2.Checksum, checksumObject2.Kind); internal static void SynchronizationObjectEqual(SolutionAsset checksumObject1, SolutionAsset checksumObject2) => ChecksumEqual(checksumObject1.Checksum, checksumObject1.Kind, checksumObject2.Checksum, checksumObject2.Kind); internal static void ChecksumEqual(Checksum checksum1, WellKnownSynchronizationKind kind1, Checksum checksum2, WellKnownSynchronizationKind kind2) { Assert.Equal(checksum1, checksum2); Assert.Equal(kind1, kind2); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Remote.UnitTests { internal sealed class SerializationValidator { private sealed class AssetProvider : AbstractAssetProvider { private readonly SerializationValidator _validator; public AssetProvider(SerializationValidator validator) => _validator = validator; public override Task<T> GetAssetAsync<T>(Checksum checksum, CancellationToken cancellationToken) => _validator.GetValueAsync<T>(checksum); } internal sealed class ChecksumObjectCollection<T> : IEnumerable<T> where T : ChecksumWithChildren { public ImmutableArray<T> Children { get; } /// <summary> /// Indicates what kind of object it is /// <see cref="WellKnownSynchronizationKind"/> for examples. /// /// this will be used in tranportation framework and deserialization service /// to hand shake how to send over data and deserialize serialized data /// </summary> public readonly WellKnownSynchronizationKind Kind; /// <summary> /// Checksum of this object /// </summary> public readonly Checksum Checksum; public ChecksumObjectCollection(SerializationValidator validator, ChecksumCollection collection) { Checksum = collection.Checksum; Kind = collection.GetWellKnownSynchronizationKind(); // using .Result here since we don't want to convert all calls to this to async. // and none of ChecksumWithChildren actually use async Children = ImmutableArray.CreateRange(collection.Select(c => validator.GetValueAsync<T>(c).Result)); } public int Count => Children.Length; public T this[int index] => Children[index]; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IEnumerator<T> GetEnumerator() => Children.Select(t => t).GetEnumerator(); } public SolutionAssetStorage AssetStorage { get; } public ISerializerService Serializer { get; } public HostWorkspaceServices Services { get; } public SerializationValidator(HostWorkspaceServices services) { AssetStorage = services.GetRequiredService<ISolutionAssetStorageProvider>().AssetStorage; Serializer = services.GetRequiredService<ISerializerService>(); Services = services; } public async Task<T> GetValueAsync<T>(Checksum checksum) { var data = (await AssetStorage.GetTestAccessor().GetAssetAsync(checksum, CancellationToken.None).ConfigureAwait(false))!; Contract.ThrowIfNull(data.Value); using var context = SolutionReplicationContext.Create(); using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { Serializer.Serialize(data.Value, writer, context, CancellationToken.None); } stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); // deserialize bits to object var result = Serializer.Deserialize<T>(data.Kind, reader, CancellationToken.None); Contract.ThrowIfNull(result); return result; } public async Task<Solution> GetSolutionAsync(SolutionAssetStorage.Scope scope) { var (solutionInfo, _) = await new AssetProvider(this).CreateSolutionInfoAndOptionsAsync(scope.SolutionInfo.SolutionChecksum, CancellationToken.None).ConfigureAwait(false); var workspace = new AdhocWorkspace(Services.HostServices); return workspace.AddSolution(solutionInfo); } public ChecksumObjectCollection<ProjectStateChecksums> ToProjectObjects(ChecksumCollection collection) => new ChecksumObjectCollection<ProjectStateChecksums>(this, collection); public ChecksumObjectCollection<DocumentStateChecksums> ToDocumentObjects(ChecksumCollection collection) => new ChecksumObjectCollection<DocumentStateChecksums>(this, collection); internal async Task VerifyAssetAsync(SolutionStateChecksums solutionObject) { await VerifyAssetSerializationAsync<SolutionInfo.SolutionAttributes>( solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)).ConfigureAwait(false); foreach (var projectChecksum in solutionObject.Projects) { var projectObject = await GetValueAsync<ProjectStateChecksums>(projectChecksum).ConfigureAwait(false); await VerifyAssetAsync(projectObject).ConfigureAwait(false); } } internal async Task VerifyAssetAsync(ProjectStateChecksums projectObject) { var info = await VerifyAssetSerializationAsync<ProjectInfo.ProjectAttributes>( projectObject.Info, WellKnownSynchronizationKind.ProjectAttributes, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)).ConfigureAwait(false); await VerifyAssetSerializationAsync<CompilationOptions>( projectObject.CompilationOptions, WellKnownSynchronizationKind.CompilationOptions, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); await VerifyAssetSerializationAsync<ParseOptions>( projectObject.ParseOptions, WellKnownSynchronizationKind.ParseOptions, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); foreach (var checksum in projectObject.Documents) { var documentObject = await GetValueAsync<DocumentStateChecksums>(checksum).ConfigureAwait(false); await VerifyAssetAsync(documentObject).ConfigureAwait(false); } foreach (var checksum in projectObject.ProjectReferences) { await VerifyAssetSerializationAsync<ProjectReference>( checksum, WellKnownSynchronizationKind.ProjectReference, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } foreach (var checksum in projectObject.MetadataReferences) { await VerifyAssetSerializationAsync<MetadataReference>( checksum, WellKnownSynchronizationKind.MetadataReference, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } foreach (var checksum in projectObject.AnalyzerReferences) { await VerifyAssetSerializationAsync<AnalyzerReference>( checksum, WellKnownSynchronizationKind.AnalyzerReference, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } foreach (var checksum in projectObject.AdditionalDocuments) { var documentObject = await GetValueAsync<DocumentStateChecksums>(checksum).ConfigureAwait(false); await VerifyAssetAsync(documentObject).ConfigureAwait(false); } foreach (var checksum in projectObject.AnalyzerConfigDocuments) { var documentObject = await GetValueAsync<DocumentStateChecksums>(checksum).ConfigureAwait(false); await VerifyAssetAsync(documentObject).ConfigureAwait(false); } } internal async Task VerifyAssetAsync(DocumentStateChecksums documentObject) { var info = await VerifyAssetSerializationAsync<DocumentInfo.DocumentAttributes>( documentObject.Info, WellKnownSynchronizationKind.DocumentAttributes, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)).ConfigureAwait(false); await VerifyAssetSerializationAsync<SerializableSourceText>( documentObject.Text, WellKnownSynchronizationKind.SerializableSourceText, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } internal async Task<T> VerifyAssetSerializationAsync<T>( Checksum checksum, WellKnownSynchronizationKind kind, Func<T, WellKnownSynchronizationKind, ISerializerService, SolutionAsset> assetGetter) { // re-create asset from object var syncObject = (await AssetStorage.GetTestAccessor().GetAssetAsync(checksum, CancellationToken.None).ConfigureAwait(false))!; var recoveredValue = await GetValueAsync<T>(checksum).ConfigureAwait(false); var recreatedSyncObject = assetGetter(recoveredValue, kind, Serializer); // make sure original object and re-created object are same. SynchronizationObjectEqual(syncObject, recreatedSyncObject); return recoveredValue; } internal async Task VerifySolutionStateSerializationAsync(Solution solution, Checksum solutionChecksum) { var solutionObjectFromSyncObject = await GetValueAsync<SolutionStateChecksums>(solutionChecksum); Contract.ThrowIfFalse(solution.State.TryGetStateChecksums(out var solutionObjectFromSolution)); SolutionStateEqual(solutionObjectFromSolution, solutionObjectFromSyncObject); } internal void SolutionStateEqual(SolutionStateChecksums solutionObject1, SolutionStateChecksums solutionObject2) { ChecksumWithChildrenEqual(solutionObject1, solutionObject2); ProjectStatesEqual(ToProjectObjects(solutionObject1.Projects), ToProjectObjects(solutionObject2.Projects)); } internal void ProjectStateEqual(ProjectStateChecksums projectObjects1, ProjectStateChecksums projectObjects2) { ChecksumWithChildrenEqual(projectObjects1, projectObjects2); ChecksumWithChildrenEqual(ToDocumentObjects(projectObjects1.Documents), ToDocumentObjects(projectObjects2.Documents)); ChecksumWithChildrenEqual(ToDocumentObjects(projectObjects1.AdditionalDocuments), ToDocumentObjects(projectObjects2.AdditionalDocuments)); ChecksumWithChildrenEqual(ToDocumentObjects(projectObjects1.AnalyzerConfigDocuments), ToDocumentObjects(projectObjects2.AnalyzerConfigDocuments)); } internal void ProjectStatesEqual(ChecksumObjectCollection<ProjectStateChecksums> projectObjects1, ChecksumObjectCollection<ProjectStateChecksums> projectObjects2) { SynchronizationObjectEqual(projectObjects1, projectObjects2); Assert.Equal(projectObjects1.Count, projectObjects2.Count); for (var i = 0; i < projectObjects1.Count; i++) { ProjectStateEqual(projectObjects1[i], projectObjects2[i]); } } internal static void ChecksumWithChildrenEqual<T>(ChecksumObjectCollection<T> checksums1, ChecksumObjectCollection<T> checksums2) where T : ChecksumWithChildren { SynchronizationObjectEqual(checksums1, checksums2); Assert.Equal(checksums1.Count, checksums2.Count); for (var i = 0; i < checksums1.Count; i++) { ChecksumWithChildrenEqual(checksums1[i], checksums2[i]); } } internal static void ChecksumWithChildrenEqual(ChecksumWithChildren checksums1, ChecksumWithChildren checksums2) { Assert.Equal(checksums1.Checksum, checksums2.Checksum); Assert.Equal(checksums1.Children.Count, checksums2.Children.Count); for (var i = 0; i < checksums1.Children.Count; i++) { var child1 = checksums1.Children[i]; var child2 = checksums2.Children[i]; Assert.Equal(child1.GetType(), child2.GetType()); if (child1 is Checksum) { Assert.Equal((Checksum)child1, (Checksum)child2); continue; } ChecksumWithChildrenEqual((ChecksumCollection)child1, (ChecksumCollection)child2); } } internal async Task VerifySnapshotInServiceAsync( ProjectStateChecksums projectObject, int expectedDocumentCount, int expectedProjectReferenceCount, int expectedMetadataReferenceCount, int expectedAnalyzerReferenceCount, int expectedAdditionalDocumentCount) { await VerifyChecksumInServiceAsync(projectObject.Checksum, projectObject.GetWellKnownSynchronizationKind()).ConfigureAwait(false); await VerifyChecksumInServiceAsync(projectObject.Info, WellKnownSynchronizationKind.ProjectAttributes).ConfigureAwait(false); await VerifyChecksumInServiceAsync(projectObject.CompilationOptions, WellKnownSynchronizationKind.CompilationOptions).ConfigureAwait(false); await VerifyChecksumInServiceAsync(projectObject.ParseOptions, WellKnownSynchronizationKind.ParseOptions).ConfigureAwait(false); await VerifyCollectionInService(ToDocumentObjects(projectObject.Documents), expectedDocumentCount).ConfigureAwait(false); await VerifyCollectionInService(projectObject.ProjectReferences, expectedProjectReferenceCount, WellKnownSynchronizationKind.ProjectReference).ConfigureAwait(false); await VerifyCollectionInService(projectObject.MetadataReferences, expectedMetadataReferenceCount, WellKnownSynchronizationKind.MetadataReference).ConfigureAwait(false); await VerifyCollectionInService(projectObject.AnalyzerReferences, expectedAnalyzerReferenceCount, WellKnownSynchronizationKind.AnalyzerReference).ConfigureAwait(false); await VerifyCollectionInService(ToDocumentObjects(projectObject.AdditionalDocuments), expectedAdditionalDocumentCount).ConfigureAwait(false); } internal async Task VerifyCollectionInService(ChecksumCollection checksums, int expectedCount, WellKnownSynchronizationKind expectedItemKind) { await VerifyChecksumInServiceAsync(checksums.Checksum, checksums.GetWellKnownSynchronizationKind()).ConfigureAwait(false); Assert.Equal(checksums.Count, expectedCount); foreach (var checksum in checksums) { await VerifyChecksumInServiceAsync(checksum, expectedItemKind).ConfigureAwait(false); } } internal async Task VerifyCollectionInService(ChecksumObjectCollection<DocumentStateChecksums> documents, int expectedCount) { await VerifySynchronizationObjectInServiceAsync(documents).ConfigureAwait(false); Assert.Equal(documents.Count, expectedCount); foreach (var documentId in documents) { await VerifySnapshotInServiceAsync(documentId).ConfigureAwait(false); } } internal async Task VerifySnapshotInServiceAsync(DocumentStateChecksums documentObject) { await VerifyChecksumInServiceAsync(documentObject.Checksum, documentObject.GetWellKnownSynchronizationKind()).ConfigureAwait(false); await VerifyChecksumInServiceAsync(documentObject.Info, WellKnownSynchronizationKind.DocumentAttributes).ConfigureAwait(false); await VerifyChecksumInServiceAsync(documentObject.Text, WellKnownSynchronizationKind.SerializableSourceText).ConfigureAwait(false); } internal async Task VerifySynchronizationObjectInServiceAsync(SolutionAsset syncObject) => await VerifyChecksumInServiceAsync(syncObject.Checksum, syncObject.Kind).ConfigureAwait(false); internal async Task VerifySynchronizationObjectInServiceAsync<T>(ChecksumObjectCollection<T> syncObject) where T : ChecksumWithChildren => await VerifyChecksumInServiceAsync(syncObject.Checksum, syncObject.Kind).ConfigureAwait(false); internal async Task VerifyChecksumInServiceAsync(Checksum checksum, WellKnownSynchronizationKind kind) { Assert.NotNull(checksum); var otherObject = (await AssetStorage.GetTestAccessor().GetAssetAsync(checksum, CancellationToken.None).ConfigureAwait(false))!; ChecksumEqual(checksum, kind, otherObject.Checksum, otherObject.Kind); } internal static void SynchronizationObjectEqual<T>(ChecksumObjectCollection<T> checksumObject1, ChecksumObjectCollection<T> checksumObject2) where T : ChecksumWithChildren => ChecksumEqual(checksumObject1.Checksum, checksumObject1.Kind, checksumObject2.Checksum, checksumObject2.Kind); internal static void SynchronizationObjectEqual<T>(ChecksumObjectCollection<T> checksumObject1, SolutionAsset checksumObject2) where T : ChecksumWithChildren => ChecksumEqual(checksumObject1.Checksum, checksumObject1.Kind, checksumObject2.Checksum, checksumObject2.Kind); internal static void SynchronizationObjectEqual(SolutionAsset checksumObject1, SolutionAsset checksumObject2) => ChecksumEqual(checksumObject1.Checksum, checksumObject1.Kind, checksumObject2.Checksum, checksumObject2.Kind); internal static void ChecksumEqual(Checksum checksum1, WellKnownSynchronizationKind kind1, Checksum checksum2, WellKnownSynchronizationKind kind2) { Assert.Equal(checksum1, checksum2); Assert.Equal(kind1, kind2); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/Core/Portable/Symbols/INamedTypeSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a type other than an array, a pointer, a type parameter. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface INamedTypeSymbol : ITypeSymbol { /// <summary> /// Returns the arity of this type, or the number of type parameters it takes. /// A non-generic type has zero arity. /// </summary> int Arity { get; } /// <summary> /// True if this type or some containing type has type parameters. /// </summary> bool IsGenericType { get; } /// <summary> /// True if this is a reference to an <em>unbound</em> generic type. A generic type is /// considered <em>unbound</em> if all of the type argument lists in its fully qualified /// name are empty. Note that the type arguments of an unbound generic type will be /// returned as error types because they do not really have type arguments. An unbound /// generic type yields null for its BaseType and an empty result for its Interfaces. /// </summary> bool IsUnboundGenericType { get; } /// <summary> /// Returns true if the type is a Script class. /// It might be an interactive submission class or a Script class in a csx file. /// </summary> bool IsScriptClass { get; } /// <summary> /// Returns true if the type is the implicit class that holds onto invalid global members (like methods or /// statements in a non script file). /// </summary> bool IsImplicitClass { get; } /// <summary> /// Specifies that the class or interface is imported from another module. See /// <see cref="TypeAttributes.Import"/> and <see cref="ComImportAttribute"/> /// </summary> bool IsComImport { get; } /// <summary> /// Returns collection of names of members declared within this type. /// </summary> IEnumerable<string> MemberNames { get; } /// <summary> /// Returns the type parameters that this type has. If this is a non-generic type, /// returns an empty ImmutableArray. /// </summary> ImmutableArray<ITypeParameterSymbol> TypeParameters { get; } /// <summary> /// Returns the type arguments that have been substituted for the type parameters. /// If nothing has been substituted for a given type parameter, /// then the type parameter itself is considered the type argument. /// </summary> ImmutableArray<ITypeSymbol> TypeArguments { get; } /// <summary> /// Returns the top-level nullability of the type arguments that have been substituted /// for the type parameters. If nothing has been substituted for a given type parameter, /// then <see cref="NullableAnnotation.None"/> is returned for that type argument. /// </summary> ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations { get; } /// <summary> /// Returns custom modifiers for the type argument that has been substituted for the type parameter. /// The modifiers correspond to the type argument at the same ordinal within the <see cref="TypeArguments"/> /// array. Returns an empty array if there are no modifiers. /// </summary> ImmutableArray<CustomModifier> GetTypeArgumentCustomModifiers(int ordinal); /// <summary> /// Get the original definition of this type symbol. If this symbol is derived from another /// symbol by (say) type substitution, this gets the original symbol, as it was defined in /// source or metadata. /// </summary> new INamedTypeSymbol OriginalDefinition { get; } /// <summary> /// For delegate types, gets the delegate's invoke method. Returns null on /// all other kinds of types. Note that it is possible to have an ill-formed /// delegate type imported from metadata which does not have an Invoke method. /// Such a type will be classified as a delegate but its DelegateInvokeMethod /// would be null. /// </summary> IMethodSymbol? DelegateInvokeMethod { get; } /// <summary> /// For enum types, gets the underlying type. Returns null on all other /// kinds of types. /// </summary> INamedTypeSymbol? EnumUnderlyingType { get; } /// <summary> /// Returns the type symbol that this type was constructed from. This type symbol /// has the same containing type (if any), but has type arguments that are the same /// as the type parameters (although its containing type might not). /// </summary> INamedTypeSymbol ConstructedFrom { get; } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments">The immediate type arguments to be replaced for type /// parameters in the type.</param> INamedTypeSymbol Construct(params ITypeSymbol[] typeArguments); /// <summary> /// Returns a constructed type given its type arguments and type argument nullable annotations. /// </summary> INamedTypeSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<NullableAnnotation> typeArgumentNullableAnnotations); /// <summary> /// Returns an unbound generic type of this named type. /// </summary> INamedTypeSymbol ConstructUnboundGenericType(); /// <summary> /// Get the instance constructors for this type. /// </summary> ImmutableArray<IMethodSymbol> InstanceConstructors { get; } /// <summary> /// Get the static constructors for this type. /// </summary> ImmutableArray<IMethodSymbol> StaticConstructors { get; } /// <summary> /// Get the both instance and static constructors for this type. /// </summary> ImmutableArray<IMethodSymbol> Constructors { get; } /// <summary> /// For implicitly declared delegate types returns the EventSymbol that caused this /// delegate type to be generated. /// For all other types returns null. /// Note, the set of possible associated symbols might be expanded in the future to /// reflect changes in the languages. /// </summary> ISymbol? AssociatedSymbol { get; } /// <summary> /// Determines if the symbol might contain extension methods. /// If false, the symbol does not contain extension methods. /// </summary> bool MightContainExtensionMethods { get; } /// <summary> /// If this is a tuple type with element names, returns the symbol for the tuple type without names. /// Otherwise, returns null. /// The type argument corresponding to the type of the extension field (VT[8].Rest), /// which is at the 8th (one based) position is always a symbol for another tuple, /// rather than its underlying type. /// </summary> INamedTypeSymbol? TupleUnderlyingType { get; } /// <summary> /// Returns fields that represent tuple elements for types that are tuples. /// /// If this type is not a tuple, then returns default. /// </summary> ImmutableArray<IFieldSymbol> TupleElements { get; } /// <summary> /// True if the type is serializable (has Serializable metadata flag). /// </summary> bool IsSerializable { get; } /// <summary> /// If this is a native integer, returns the symbol for the underlying type, /// either <see cref="System.IntPtr"/> or <see cref="System.UIntPtr"/>. /// Otherwise, returns null. /// </summary> INamedTypeSymbol? NativeIntegerUnderlyingType { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a type other than an array, a pointer, a type parameter. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface INamedTypeSymbol : ITypeSymbol { /// <summary> /// Returns the arity of this type, or the number of type parameters it takes. /// A non-generic type has zero arity. /// </summary> int Arity { get; } /// <summary> /// True if this type or some containing type has type parameters. /// </summary> bool IsGenericType { get; } /// <summary> /// True if this is a reference to an <em>unbound</em> generic type. A generic type is /// considered <em>unbound</em> if all of the type argument lists in its fully qualified /// name are empty. Note that the type arguments of an unbound generic type will be /// returned as error types because they do not really have type arguments. An unbound /// generic type yields null for its BaseType and an empty result for its Interfaces. /// </summary> bool IsUnboundGenericType { get; } /// <summary> /// Returns true if the type is a Script class. /// It might be an interactive submission class or a Script class in a csx file. /// </summary> bool IsScriptClass { get; } /// <summary> /// Returns true if the type is the implicit class that holds onto invalid global members (like methods or /// statements in a non script file). /// </summary> bool IsImplicitClass { get; } /// <summary> /// Specifies that the class or interface is imported from another module. See /// <see cref="TypeAttributes.Import"/> and <see cref="ComImportAttribute"/> /// </summary> bool IsComImport { get; } /// <summary> /// Returns collection of names of members declared within this type. /// </summary> IEnumerable<string> MemberNames { get; } /// <summary> /// Returns the type parameters that this type has. If this is a non-generic type, /// returns an empty ImmutableArray. /// </summary> ImmutableArray<ITypeParameterSymbol> TypeParameters { get; } /// <summary> /// Returns the type arguments that have been substituted for the type parameters. /// If nothing has been substituted for a given type parameter, /// then the type parameter itself is considered the type argument. /// </summary> ImmutableArray<ITypeSymbol> TypeArguments { get; } /// <summary> /// Returns the top-level nullability of the type arguments that have been substituted /// for the type parameters. If nothing has been substituted for a given type parameter, /// then <see cref="NullableAnnotation.None"/> is returned for that type argument. /// </summary> ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations { get; } /// <summary> /// Returns custom modifiers for the type argument that has been substituted for the type parameter. /// The modifiers correspond to the type argument at the same ordinal within the <see cref="TypeArguments"/> /// array. Returns an empty array if there are no modifiers. /// </summary> ImmutableArray<CustomModifier> GetTypeArgumentCustomModifiers(int ordinal); /// <summary> /// Get the original definition of this type symbol. If this symbol is derived from another /// symbol by (say) type substitution, this gets the original symbol, as it was defined in /// source or metadata. /// </summary> new INamedTypeSymbol OriginalDefinition { get; } /// <summary> /// For delegate types, gets the delegate's invoke method. Returns null on /// all other kinds of types. Note that it is possible to have an ill-formed /// delegate type imported from metadata which does not have an Invoke method. /// Such a type will be classified as a delegate but its DelegateInvokeMethod /// would be null. /// </summary> IMethodSymbol? DelegateInvokeMethod { get; } /// <summary> /// For enum types, gets the underlying type. Returns null on all other /// kinds of types. /// </summary> INamedTypeSymbol? EnumUnderlyingType { get; } /// <summary> /// Returns the type symbol that this type was constructed from. This type symbol /// has the same containing type (if any), but has type arguments that are the same /// as the type parameters (although its containing type might not). /// </summary> INamedTypeSymbol ConstructedFrom { get; } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments">The immediate type arguments to be replaced for type /// parameters in the type.</param> INamedTypeSymbol Construct(params ITypeSymbol[] typeArguments); /// <summary> /// Returns a constructed type given its type arguments and type argument nullable annotations. /// </summary> INamedTypeSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<NullableAnnotation> typeArgumentNullableAnnotations); /// <summary> /// Returns an unbound generic type of this named type. /// </summary> INamedTypeSymbol ConstructUnboundGenericType(); /// <summary> /// Get the instance constructors for this type. /// </summary> ImmutableArray<IMethodSymbol> InstanceConstructors { get; } /// <summary> /// Get the static constructors for this type. /// </summary> ImmutableArray<IMethodSymbol> StaticConstructors { get; } /// <summary> /// Get the both instance and static constructors for this type. /// </summary> ImmutableArray<IMethodSymbol> Constructors { get; } /// <summary> /// For implicitly declared delegate types returns the EventSymbol that caused this /// delegate type to be generated. /// For all other types returns null. /// Note, the set of possible associated symbols might be expanded in the future to /// reflect changes in the languages. /// </summary> ISymbol? AssociatedSymbol { get; } /// <summary> /// Determines if the symbol might contain extension methods. /// If false, the symbol does not contain extension methods. /// </summary> bool MightContainExtensionMethods { get; } /// <summary> /// If this is a tuple type with element names, returns the symbol for the tuple type without names. /// Otherwise, returns null. /// The type argument corresponding to the type of the extension field (VT[8].Rest), /// which is at the 8th (one based) position is always a symbol for another tuple, /// rather than its underlying type. /// </summary> INamedTypeSymbol? TupleUnderlyingType { get; } /// <summary> /// Returns fields that represent tuple elements for types that are tuples. /// /// If this type is not a tuple, then returns default. /// </summary> ImmutableArray<IFieldSymbol> TupleElements { get; } /// <summary> /// True if the type is serializable (has Serializable metadata flag). /// </summary> bool IsSerializable { get; } /// <summary> /// If this is a native integer, returns the symbol for the underlying type, /// either <see cref="System.IntPtr"/> or <see cref="System.UIntPtr"/>. /// Otherwise, returns null. /// </summary> INamedTypeSymbol? NativeIntegerUnderlyingType { get; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/IntegrationTest/IntegrationTests/AbstractIntegrationTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Harness; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests { [CaptureTestName] public abstract class AbstractIntegrationTest : IAsyncLifetime, IDisposable { protected const string ProjectName = "TestProj"; protected const string SolutionName = "TestSolution"; private readonly MessageFilter _messageFilter; private readonly VisualStudioInstanceFactory _instanceFactory; private VisualStudioInstanceContext _visualStudioContext; protected AbstractIntegrationTest(VisualStudioInstanceFactory instanceFactory) { Assert.Equal(ApartmentState.STA, Thread.CurrentThread.GetApartmentState()); // Install a COM message filter to handle retry operations when the first attempt fails _messageFilter = RegisterMessageFilter(); _instanceFactory = instanceFactory; try { Helper.Automation.TransactionTimeout = 20000; } catch { _messageFilter.Dispose(); _messageFilter = null; throw; } } public VisualStudioInstance VisualStudio => _visualStudioContext?.Instance; public virtual async Task InitializeAsync() { try { _visualStudioContext = await _instanceFactory.GetNewOrUsedInstanceAsync(SharedIntegrationHostFixture.RequiredPackageIds).ConfigureAwait(false); _visualStudioContext.Instance.ActivateMainWindow(); } catch { _messageFilter.Dispose(); throw; } } /// <summary> /// This method implements <see cref="IAsyncLifetime.DisposeAsync"/>, and is used for releasing resources /// created by <see cref="IAsyncLifetime.InitializeAsync"/>. This method is only called if /// <see cref="InitializeAsync"/> completes successfully. /// </summary> public virtual Task DisposeAsync() { if (VisualStudio?.Editor.IsCompletionActive() ?? false) { // Make sure completion isn't visible. // 🐛 Only needed as a workaround for https://devdiv.visualstudio.com/DevDiv/_workitems/edit/801435 VisualStudio.SendKeys.Send(VirtualKey.Escape); } _visualStudioContext.Dispose(); return Task.CompletedTask; } protected virtual MessageFilter RegisterMessageFilter() => new MessageFilter(); protected void Wait(double seconds) { var timeout = TimeSpan.FromMilliseconds(seconds * 1000); Thread.Sleep(timeout); } /// <summary> /// This method provides the implementation for <see cref="IDisposable.Dispose"/>. /// This method is called via the <see cref="IDisposable"/> interface if the constructor completes successfully. /// The <see cref="InitializeAsync"/> may or may not have completed successfully. /// </summary> public virtual void Dispose() { _messageFilter.Dispose(); } protected KeyPress Ctrl(VirtualKey virtualKey) => new KeyPress(virtualKey, ShiftState.Ctrl); protected KeyPress Shift(VirtualKey virtualKey) => new KeyPress(virtualKey, ShiftState.Shift); protected KeyPress Alt(VirtualKey virtualKey) => new KeyPress(virtualKey, ShiftState.Alt); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Harness; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests { [CaptureTestName] public abstract class AbstractIntegrationTest : IAsyncLifetime, IDisposable { protected const string ProjectName = "TestProj"; protected const string SolutionName = "TestSolution"; private readonly MessageFilter _messageFilter; private readonly VisualStudioInstanceFactory _instanceFactory; private VisualStudioInstanceContext _visualStudioContext; protected AbstractIntegrationTest(VisualStudioInstanceFactory instanceFactory) { Assert.Equal(ApartmentState.STA, Thread.CurrentThread.GetApartmentState()); // Install a COM message filter to handle retry operations when the first attempt fails _messageFilter = RegisterMessageFilter(); _instanceFactory = instanceFactory; try { Helper.Automation.TransactionTimeout = 20000; } catch { _messageFilter.Dispose(); _messageFilter = null; throw; } } public VisualStudioInstance VisualStudio => _visualStudioContext?.Instance; public virtual async Task InitializeAsync() { try { _visualStudioContext = await _instanceFactory.GetNewOrUsedInstanceAsync(SharedIntegrationHostFixture.RequiredPackageIds).ConfigureAwait(false); _visualStudioContext.Instance.ActivateMainWindow(); } catch { _messageFilter.Dispose(); throw; } } /// <summary> /// This method implements <see cref="IAsyncLifetime.DisposeAsync"/>, and is used for releasing resources /// created by <see cref="IAsyncLifetime.InitializeAsync"/>. This method is only called if /// <see cref="InitializeAsync"/> completes successfully. /// </summary> public virtual Task DisposeAsync() { if (VisualStudio?.Editor.IsCompletionActive() ?? false) { // Make sure completion isn't visible. // 🐛 Only needed as a workaround for https://devdiv.visualstudio.com/DevDiv/_workitems/edit/801435 VisualStudio.SendKeys.Send(VirtualKey.Escape); } _visualStudioContext.Dispose(); return Task.CompletedTask; } protected virtual MessageFilter RegisterMessageFilter() => new MessageFilter(); protected void Wait(double seconds) { var timeout = TimeSpan.FromMilliseconds(seconds * 1000); Thread.Sleep(timeout); } /// <summary> /// This method provides the implementation for <see cref="IDisposable.Dispose"/>. /// This method is called via the <see cref="IDisposable"/> interface if the constructor completes successfully. /// The <see cref="InitializeAsync"/> may or may not have completed successfully. /// </summary> public virtual void Dispose() { _messageFilter.Dispose(); } protected KeyPress Ctrl(VirtualKey virtualKey) => new KeyPress(virtualKey, ShiftState.Ctrl); protected KeyPress Shift(VirtualKey virtualKey) => new KeyPress(virtualKey, ShiftState.Shift); protected KeyPress Alt(VirtualKey virtualKey) => new KeyPress(virtualKey, ShiftState.Alt); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxTokenListTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp { public class SyntaxTokenListTests : CSharpTestBase { [Fact] public void TestEquality() { var node1 = SyntaxFactory.ReturnStatement(); EqualityTesting.AssertEqual(default(SyntaxTokenList), default(SyntaxTokenList)); EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0)); // index is considered EqualityTesting.AssertNotEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 1), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0)); // position not considered: EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 1, 0), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0)); } [Fact] public void TestReverse_Equality() { var node1 = SyntaxFactory.ReturnStatement(); EqualityTesting.AssertEqual(default(SyntaxTokenList).Reverse(), default(SyntaxTokenList).Reverse()); EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse(), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse()); // index is considered EqualityTesting.AssertNotEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 1).Reverse(), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse()); // position not considered: EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 1, 0).Reverse(), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse()); } [Fact] public void TestEnumeratorEquality() { Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Enumerator).GetHashCode()); Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Enumerator).Equals(default(SyntaxTokenList.Enumerator))); Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Reversed.Enumerator).GetHashCode()); Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Reversed.Enumerator).Equals(default(SyntaxTokenList.Reversed.Enumerator))); } [Fact] public void TestAddInsertRemoveReplace() { var list = SyntaxFactory.TokenList(SyntaxFactory.ParseToken("A "), SyntaxFactory.ParseToken("B "), SyntaxFactory.ParseToken("C ")); Assert.Equal(3, list.Count); Assert.Equal("A", list[0].ToString()); Assert.Equal("B", list[1].ToString()); Assert.Equal("C", list[2].ToString()); Assert.Equal("A B C ", list.ToFullString()); var elementA = list[0]; var elementB = list[1]; var elementC = list[2]; Assert.Equal(0, list.IndexOf(elementA)); Assert.Equal(1, list.IndexOf(elementB)); Assert.Equal(2, list.IndexOf(elementC)); var tokenD = SyntaxFactory.ParseToken("D "); var tokenE = SyntaxFactory.ParseToken("E "); var newList = list.Add(tokenD); Assert.Equal(4, newList.Count); Assert.Equal("A B C D ", newList.ToFullString()); newList = list.AddRange(new[] { tokenD, tokenE }); Assert.Equal(5, newList.Count); Assert.Equal("A B C D E ", newList.ToFullString()); newList = list.Insert(0, tokenD); Assert.Equal(4, newList.Count); Assert.Equal("D A B C ", newList.ToFullString()); newList = list.Insert(1, tokenD); Assert.Equal(4, newList.Count); Assert.Equal("A D B C ", newList.ToFullString()); newList = list.Insert(2, tokenD); Assert.Equal(4, newList.Count); Assert.Equal("A B D C ", newList.ToFullString()); newList = list.Insert(3, tokenD); Assert.Equal(4, newList.Count); Assert.Equal("A B C D ", newList.ToFullString()); newList = list.InsertRange(0, new[] { tokenD, tokenE }); Assert.Equal(5, newList.Count); Assert.Equal("D E A B C ", newList.ToFullString()); newList = list.InsertRange(1, new[] { tokenD, tokenE }); Assert.Equal(5, newList.Count); Assert.Equal("A D E B C ", newList.ToFullString()); newList = list.InsertRange(2, new[] { tokenD, tokenE }); Assert.Equal(5, newList.Count); Assert.Equal("A B D E C ", newList.ToFullString()); newList = list.InsertRange(3, new[] { tokenD, tokenE }); Assert.Equal(5, newList.Count); Assert.Equal("A B C D E ", newList.ToFullString()); newList = list.RemoveAt(0); Assert.Equal(2, newList.Count); Assert.Equal("B C ", newList.ToFullString()); newList = list.RemoveAt(list.Count - 1); Assert.Equal(2, newList.Count); Assert.Equal("A B ", newList.ToFullString()); newList = list.Remove(elementA); Assert.Equal(2, newList.Count); Assert.Equal("B C ", newList.ToFullString()); newList = list.Remove(elementB); Assert.Equal(2, newList.Count); Assert.Equal("A C ", newList.ToFullString()); newList = list.Remove(elementC); Assert.Equal(2, newList.Count); Assert.Equal("A B ", newList.ToFullString()); newList = list.Replace(elementA, tokenD); Assert.Equal(3, newList.Count); Assert.Equal("D B C ", newList.ToFullString()); newList = list.Replace(elementB, tokenD); Assert.Equal(3, newList.Count); Assert.Equal("A D C ", newList.ToFullString()); newList = list.Replace(elementC, tokenD); Assert.Equal(3, newList.Count); Assert.Equal("A B D ", newList.ToFullString()); newList = list.ReplaceRange(elementA, new[] { tokenD, tokenE }); Assert.Equal(4, newList.Count); Assert.Equal("D E B C ", newList.ToFullString()); newList = list.ReplaceRange(elementB, new[] { tokenD, tokenE }); Assert.Equal(4, newList.Count); Assert.Equal("A D E C ", newList.ToFullString()); newList = list.ReplaceRange(elementC, new[] { tokenD, tokenE }); Assert.Equal(4, newList.Count); Assert.Equal("A B D E ", newList.ToFullString()); newList = list.ReplaceRange(elementA, new SyntaxToken[] { }); Assert.Equal(2, newList.Count); Assert.Equal("B C ", newList.ToFullString()); newList = list.ReplaceRange(elementB, new SyntaxToken[] { }); Assert.Equal(2, newList.Count); Assert.Equal("A C ", newList.ToFullString()); newList = list.ReplaceRange(elementC, new SyntaxToken[] { }); Assert.Equal(2, newList.Count); Assert.Equal("A B ", newList.ToFullString()); Assert.Equal(-1, list.IndexOf(tokenD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, tokenD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(list.Count + 1, tokenD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { tokenD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(list.Count + 1, new[] { tokenD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(list.Count)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxToken))); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxToken))); Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxToken>)null)); Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxToken>)null)); Assert.Throws<ArgumentNullException>(() => list.ReplaceRange(elementA, (IEnumerable<SyntaxToken>)null)); } [Fact] public void TestAddInsertRemoveReplaceOnEmptyList() { DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxFactory.TokenList()); DoTestAddInsertRemoveReplaceOnEmptyList(default(SyntaxTokenList)); } private void DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxTokenList list) { Assert.Equal(0, list.Count); var tokenD = SyntaxFactory.ParseToken("D "); var tokenE = SyntaxFactory.ParseToken("E "); var newList = list.Add(tokenD); Assert.Equal(1, newList.Count); Assert.Equal("D ", newList.ToFullString()); newList = list.AddRange(new[] { tokenD, tokenE }); Assert.Equal(2, newList.Count); Assert.Equal("D E ", newList.ToFullString()); newList = list.Insert(0, tokenD); Assert.Equal(1, newList.Count); Assert.Equal("D ", newList.ToFullString()); newList = list.InsertRange(0, new[] { tokenD, tokenE }); Assert.Equal(2, newList.Count); Assert.Equal("D E ", newList.ToFullString()); newList = list.Remove(tokenD); Assert.Equal(0, newList.Count); Assert.Equal(-1, list.IndexOf(tokenD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(0)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(1, tokenD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, tokenD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { tokenD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(list.Count + 1, new[] { tokenD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.Replace(tokenD, tokenE)); Assert.Throws<ArgumentOutOfRangeException>(() => list.ReplaceRange(tokenD, new[] { tokenE })); Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxToken))); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxToken))); Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxToken>)null)); Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxToken>)null)); } [Fact] public void Extensions() { var list = SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.SizeOfKeyword), SyntaxFactory.Literal("x"), SyntaxFactory.Token(SyntaxKind.DotToken)); Assert.Equal(0, list.IndexOf(SyntaxKind.SizeOfKeyword)); Assert.True(list.Any(SyntaxKind.SizeOfKeyword)); Assert.Equal(1, list.IndexOf(SyntaxKind.StringLiteralToken)); Assert.True(list.Any(SyntaxKind.StringLiteralToken)); Assert.Equal(2, list.IndexOf(SyntaxKind.DotToken)); Assert.True(list.Any(SyntaxKind.DotToken)); Assert.Equal(-1, list.IndexOf(SyntaxKind.NullKeyword)); Assert.False(list.Any(SyntaxKind.NullKeyword)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp { public class SyntaxTokenListTests : CSharpTestBase { [Fact] public void TestEquality() { var node1 = SyntaxFactory.ReturnStatement(); EqualityTesting.AssertEqual(default(SyntaxTokenList), default(SyntaxTokenList)); EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0)); // index is considered EqualityTesting.AssertNotEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 1), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0)); // position not considered: EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 1, 0), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0)); } [Fact] public void TestReverse_Equality() { var node1 = SyntaxFactory.ReturnStatement(); EqualityTesting.AssertEqual(default(SyntaxTokenList).Reverse(), default(SyntaxTokenList).Reverse()); EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse(), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse()); // index is considered EqualityTesting.AssertNotEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 1).Reverse(), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse()); // position not considered: EqualityTesting.AssertEqual(new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 1, 0).Reverse(), new SyntaxTokenList(node1, node1.ReturnKeyword.Node, 0, 0).Reverse()); } [Fact] public void TestEnumeratorEquality() { Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Enumerator).GetHashCode()); Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Enumerator).Equals(default(SyntaxTokenList.Enumerator))); Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Reversed.Enumerator).GetHashCode()); Assert.Throws<NotSupportedException>(() => default(SyntaxTokenList.Reversed.Enumerator).Equals(default(SyntaxTokenList.Reversed.Enumerator))); } [Fact] public void TestAddInsertRemoveReplace() { var list = SyntaxFactory.TokenList(SyntaxFactory.ParseToken("A "), SyntaxFactory.ParseToken("B "), SyntaxFactory.ParseToken("C ")); Assert.Equal(3, list.Count); Assert.Equal("A", list[0].ToString()); Assert.Equal("B", list[1].ToString()); Assert.Equal("C", list[2].ToString()); Assert.Equal("A B C ", list.ToFullString()); var elementA = list[0]; var elementB = list[1]; var elementC = list[2]; Assert.Equal(0, list.IndexOf(elementA)); Assert.Equal(1, list.IndexOf(elementB)); Assert.Equal(2, list.IndexOf(elementC)); var tokenD = SyntaxFactory.ParseToken("D "); var tokenE = SyntaxFactory.ParseToken("E "); var newList = list.Add(tokenD); Assert.Equal(4, newList.Count); Assert.Equal("A B C D ", newList.ToFullString()); newList = list.AddRange(new[] { tokenD, tokenE }); Assert.Equal(5, newList.Count); Assert.Equal("A B C D E ", newList.ToFullString()); newList = list.Insert(0, tokenD); Assert.Equal(4, newList.Count); Assert.Equal("D A B C ", newList.ToFullString()); newList = list.Insert(1, tokenD); Assert.Equal(4, newList.Count); Assert.Equal("A D B C ", newList.ToFullString()); newList = list.Insert(2, tokenD); Assert.Equal(4, newList.Count); Assert.Equal("A B D C ", newList.ToFullString()); newList = list.Insert(3, tokenD); Assert.Equal(4, newList.Count); Assert.Equal("A B C D ", newList.ToFullString()); newList = list.InsertRange(0, new[] { tokenD, tokenE }); Assert.Equal(5, newList.Count); Assert.Equal("D E A B C ", newList.ToFullString()); newList = list.InsertRange(1, new[] { tokenD, tokenE }); Assert.Equal(5, newList.Count); Assert.Equal("A D E B C ", newList.ToFullString()); newList = list.InsertRange(2, new[] { tokenD, tokenE }); Assert.Equal(5, newList.Count); Assert.Equal("A B D E C ", newList.ToFullString()); newList = list.InsertRange(3, new[] { tokenD, tokenE }); Assert.Equal(5, newList.Count); Assert.Equal("A B C D E ", newList.ToFullString()); newList = list.RemoveAt(0); Assert.Equal(2, newList.Count); Assert.Equal("B C ", newList.ToFullString()); newList = list.RemoveAt(list.Count - 1); Assert.Equal(2, newList.Count); Assert.Equal("A B ", newList.ToFullString()); newList = list.Remove(elementA); Assert.Equal(2, newList.Count); Assert.Equal("B C ", newList.ToFullString()); newList = list.Remove(elementB); Assert.Equal(2, newList.Count); Assert.Equal("A C ", newList.ToFullString()); newList = list.Remove(elementC); Assert.Equal(2, newList.Count); Assert.Equal("A B ", newList.ToFullString()); newList = list.Replace(elementA, tokenD); Assert.Equal(3, newList.Count); Assert.Equal("D B C ", newList.ToFullString()); newList = list.Replace(elementB, tokenD); Assert.Equal(3, newList.Count); Assert.Equal("A D C ", newList.ToFullString()); newList = list.Replace(elementC, tokenD); Assert.Equal(3, newList.Count); Assert.Equal("A B D ", newList.ToFullString()); newList = list.ReplaceRange(elementA, new[] { tokenD, tokenE }); Assert.Equal(4, newList.Count); Assert.Equal("D E B C ", newList.ToFullString()); newList = list.ReplaceRange(elementB, new[] { tokenD, tokenE }); Assert.Equal(4, newList.Count); Assert.Equal("A D E C ", newList.ToFullString()); newList = list.ReplaceRange(elementC, new[] { tokenD, tokenE }); Assert.Equal(4, newList.Count); Assert.Equal("A B D E ", newList.ToFullString()); newList = list.ReplaceRange(elementA, new SyntaxToken[] { }); Assert.Equal(2, newList.Count); Assert.Equal("B C ", newList.ToFullString()); newList = list.ReplaceRange(elementB, new SyntaxToken[] { }); Assert.Equal(2, newList.Count); Assert.Equal("A C ", newList.ToFullString()); newList = list.ReplaceRange(elementC, new SyntaxToken[] { }); Assert.Equal(2, newList.Count); Assert.Equal("A B ", newList.ToFullString()); Assert.Equal(-1, list.IndexOf(tokenD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, tokenD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(list.Count + 1, tokenD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { tokenD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(list.Count + 1, new[] { tokenD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(list.Count)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxToken))); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxToken))); Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxToken>)null)); Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxToken>)null)); Assert.Throws<ArgumentNullException>(() => list.ReplaceRange(elementA, (IEnumerable<SyntaxToken>)null)); } [Fact] public void TestAddInsertRemoveReplaceOnEmptyList() { DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxFactory.TokenList()); DoTestAddInsertRemoveReplaceOnEmptyList(default(SyntaxTokenList)); } private void DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxTokenList list) { Assert.Equal(0, list.Count); var tokenD = SyntaxFactory.ParseToken("D "); var tokenE = SyntaxFactory.ParseToken("E "); var newList = list.Add(tokenD); Assert.Equal(1, newList.Count); Assert.Equal("D ", newList.ToFullString()); newList = list.AddRange(new[] { tokenD, tokenE }); Assert.Equal(2, newList.Count); Assert.Equal("D E ", newList.ToFullString()); newList = list.Insert(0, tokenD); Assert.Equal(1, newList.Count); Assert.Equal("D ", newList.ToFullString()); newList = list.InsertRange(0, new[] { tokenD, tokenE }); Assert.Equal(2, newList.Count); Assert.Equal("D E ", newList.ToFullString()); newList = list.Remove(tokenD); Assert.Equal(0, newList.Count); Assert.Equal(-1, list.IndexOf(tokenD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(0)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(1, tokenD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, tokenD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { tokenD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(list.Count + 1, new[] { tokenD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.Replace(tokenD, tokenE)); Assert.Throws<ArgumentOutOfRangeException>(() => list.ReplaceRange(tokenD, new[] { tokenE })); Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxToken))); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxToken))); Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxToken>)null)); Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxToken>)null)); } [Fact] public void Extensions() { var list = SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.SizeOfKeyword), SyntaxFactory.Literal("x"), SyntaxFactory.Token(SyntaxKind.DotToken)); Assert.Equal(0, list.IndexOf(SyntaxKind.SizeOfKeyword)); Assert.True(list.Any(SyntaxKind.SizeOfKeyword)); Assert.Equal(1, list.IndexOf(SyntaxKind.StringLiteralToken)); Assert.True(list.Any(SyntaxKind.StringLiteralToken)); Assert.Equal(2, list.IndexOf(SyntaxKind.DotToken)); Assert.True(list.Any(SyntaxKind.DotToken)); Assert.Equal(-1, list.IndexOf(SyntaxKind.NullKeyword)); Assert.False(list.Any(SyntaxKind.NullKeyword)); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_NullCoalescingOperator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { BoundExpression rewrittenLeft = VisitExpression(node.LeftOperand); BoundExpression rewrittenRight = VisitExpression(node.RightOperand); TypeSymbol? rewrittenResultType = VisitType(node.Type); return MakeNullCoalescingOperator(node.Syntax, rewrittenLeft, rewrittenRight, node.LeftConversion, node.OperatorResultKind, rewrittenResultType); } private BoundExpression MakeNullCoalescingOperator( SyntaxNode syntax, BoundExpression rewrittenLeft, BoundExpression rewrittenRight, Conversion leftConversion, BoundNullCoalescingOperatorResultKind resultKind, TypeSymbol? rewrittenResultType) { Debug.Assert(rewrittenLeft != null); Debug.Assert(rewrittenRight != null); Debug.Assert(leftConversion.IsValid); Debug.Assert(rewrittenResultType is { }); Debug.Assert(rewrittenRight.Type is { }); Debug.Assert(rewrittenRight.Type.Equals(rewrittenResultType, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); if (_inExpressionLambda) { // Because of Error CS0845 (An expression tree lambda may not contain a coalescing operator with a null or default literal left-hand side) // we know that the left-hand-side has a type. Debug.Assert(rewrittenLeft.Type is { }); TypeSymbol strippedLeftType = rewrittenLeft.Type.StrippedType(); Conversion rewrittenConversion = TryMakeConversion(syntax, leftConversion, strippedLeftType, rewrittenResultType); if (!rewrittenConversion.Exists) { return BadExpression(syntax, rewrittenResultType, rewrittenLeft, rewrittenRight); } return new BoundNullCoalescingOperator(syntax, rewrittenLeft, rewrittenRight, rewrittenConversion, resultKind, rewrittenResultType); } var isUnconstrainedTypeParameter = rewrittenLeft.Type is { IsReferenceType: false, IsValueType: false }; // first we can make a small optimization: // If left is a constant then we already know whether it is null or not. If it is null then we // can simply generate "right". If it is not null then we can simply generate // MakeConversion(left). This does not hold when the left is an unconstrained type parameter: at runtime, // it can be either left or right depending on the runtime type of T if (!isUnconstrainedTypeParameter) { if (rewrittenLeft.IsDefaultValue()) { return rewrittenRight; } if (rewrittenLeft.ConstantValue != null) { Debug.Assert(!rewrittenLeft.ConstantValue.IsNull); return GetConvertedLeftForNullCoalescingOperator(rewrittenLeft, leftConversion, rewrittenResultType); } } // string concatenation is never null. // interpolated string lowering may introduce redundant null coalescing, which we have to remove. if (IsStringConcat(rewrittenLeft)) { return GetConvertedLeftForNullCoalescingOperator(rewrittenLeft, leftConversion, rewrittenResultType); } // if left conversion is intrinsic implicit (always succeeds) and results in a reference type // we can apply conversion before doing the null check that allows for a more efficient IL emit. Debug.Assert(rewrittenLeft.Type is { }); if (rewrittenLeft.Type.IsReferenceType && leftConversion.IsImplicit && !leftConversion.IsUserDefined) { if (!leftConversion.IsIdentity) { rewrittenLeft = MakeConversionNode(rewrittenLeft.Syntax, rewrittenLeft, leftConversion, rewrittenResultType, @checked: false); } return new BoundNullCoalescingOperator(syntax, rewrittenLeft, rewrittenRight, Conversion.Identity, resultKind, rewrittenResultType); } if (leftConversion.IsIdentity || leftConversion.Kind == ConversionKind.ExplicitNullable) { var conditionalAccess = rewrittenLeft as BoundLoweredConditionalAccess; if (conditionalAccess != null && (conditionalAccess.WhenNullOpt == null || NullableNeverHasValue(conditionalAccess.WhenNullOpt))) { var notNullAccess = NullableAlwaysHasValue(conditionalAccess.WhenNotNull); if (notNullAccess != null) { BoundExpression? whenNullOpt = rewrittenRight; if (whenNullOpt.Type.IsNullableType()) { notNullAccess = conditionalAccess.WhenNotNull; } if (whenNullOpt.IsDefaultValue() && whenNullOpt.Type.SpecialType != SpecialType.System_Decimal) { whenNullOpt = null; } return conditionalAccess.Update( conditionalAccess.Receiver, conditionalAccess.HasValueMethodOpt, whenNotNull: notNullAccess, whenNullOpt: whenNullOpt, id: conditionalAccess.Id, type: rewrittenResultType ); } } } // Optimize left ?? right to left.GetValueOrDefault() when left is T? and right is the default value of T if (rewrittenLeft.Type.IsNullableType() && RemoveIdentityConversions(rewrittenRight).IsDefaultValue() && rewrittenRight.Type.Equals(rewrittenLeft.Type.GetNullableUnderlyingType(), TypeCompareKind.AllIgnoreOptions) && TryGetNullableMethod(rewrittenLeft.Syntax, rewrittenLeft.Type, SpecialMember.System_Nullable_T_GetValueOrDefault, out MethodSymbol getValueOrDefault)) { return BoundCall.Synthesized(rewrittenLeft.Syntax, rewrittenLeft, getValueOrDefault); } // We lower left ?? right to // // var temp = left; // (temp != null) ? MakeConversion(temp) : right // BoundAssignmentOperator tempAssignment; BoundLocal boundTemp = _factory.StoreToTemp(rewrittenLeft, out tempAssignment); // temp != null BoundExpression nullCheck = MakeNullCheck(syntax, boundTemp, BinaryOperatorKind.NotEqual); // MakeConversion(temp, rewrittenResultType) BoundExpression convertedLeft = GetConvertedLeftForNullCoalescingOperator(boundTemp, leftConversion, rewrittenResultType); Debug.Assert(convertedLeft.HasErrors || convertedLeft.Type!.Equals(rewrittenResultType, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // (temp != null) ? MakeConversion(temp, LeftConversion) : RightOperand BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: nullCheck, rewrittenConsequence: convertedLeft, rewrittenAlternative: rewrittenRight, constantValueOpt: null, rewrittenType: rewrittenResultType, isRef: false); Debug.Assert(conditionalExpression.ConstantValue == null); // we shouldn't have hit this else case otherwise Debug.Assert(conditionalExpression.Type!.Equals(rewrittenResultType, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); return new BoundSequence( syntax: syntax, locals: ImmutableArray.Create(boundTemp.LocalSymbol), sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignment), value: conditionalExpression, type: rewrittenResultType); } private bool IsStringConcat(BoundExpression expression) { if (expression.Kind != BoundKind.Call) { return false; } var boundCall = (BoundCall)expression; var method = boundCall.Method; if (method.IsStatic && method.ContainingType.SpecialType == SpecialType.System_String) { if ((object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString) || (object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringStringString) || (object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringStringStringString) || (object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatObject) || (object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatObjectObject) || (object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatObjectObjectObject) || (object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringArray) || (object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatObjectArray)) { return true; } } return false; } private static BoundExpression RemoveIdentityConversions(BoundExpression expression) { while (expression.Kind == BoundKind.Conversion) { var boundConversion = (BoundConversion)expression; if (boundConversion.ConversionKind != ConversionKind.Identity) { return expression; } expression = boundConversion.Operand; } return expression; } private BoundExpression GetConvertedLeftForNullCoalescingOperator(BoundExpression rewrittenLeft, Conversion leftConversion, TypeSymbol rewrittenResultType) { Debug.Assert(rewrittenLeft != null); Debug.Assert(rewrittenLeft.Type is { }); Debug.Assert(rewrittenResultType is { }); Debug.Assert(leftConversion.IsValid); TypeSymbol rewrittenLeftType = rewrittenLeft.Type; Debug.Assert(rewrittenLeftType.IsNullableType() || !rewrittenLeftType.IsValueType); // Native compiler violates the specification for the case where result type is right operand type and left operand is nullable. // For this case, we need to insert an extra explicit nullable conversion from the left operand to its underlying nullable type // before performing the leftConversion. // See comments in Binder.BindNullCoalescingOperator referring to GetConvertedLeftForNullCoalescingOperator for more details. if (!TypeSymbol.Equals(rewrittenLeftType, rewrittenResultType, TypeCompareKind.ConsiderEverything2) && rewrittenLeftType.IsNullableType()) { TypeSymbol strippedLeftType = rewrittenLeftType.GetNullableUnderlyingType(); MethodSymbol getValueOrDefault = UnsafeGetNullableMethod(rewrittenLeft.Syntax, rewrittenLeftType, SpecialMember.System_Nullable_T_GetValueOrDefault); rewrittenLeft = BoundCall.Synthesized(rewrittenLeft.Syntax, rewrittenLeft, getValueOrDefault); if (TypeSymbol.Equals(strippedLeftType, rewrittenResultType, TypeCompareKind.ConsiderEverything2)) { return rewrittenLeft; } } return MakeConversionNode(rewrittenLeft.Syntax, rewrittenLeft, leftConversion, rewrittenResultType, @checked: false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { BoundExpression rewrittenLeft = VisitExpression(node.LeftOperand); BoundExpression rewrittenRight = VisitExpression(node.RightOperand); TypeSymbol? rewrittenResultType = VisitType(node.Type); return MakeNullCoalescingOperator(node.Syntax, rewrittenLeft, rewrittenRight, node.LeftConversion, node.OperatorResultKind, rewrittenResultType); } private BoundExpression MakeNullCoalescingOperator( SyntaxNode syntax, BoundExpression rewrittenLeft, BoundExpression rewrittenRight, Conversion leftConversion, BoundNullCoalescingOperatorResultKind resultKind, TypeSymbol? rewrittenResultType) { Debug.Assert(rewrittenLeft != null); Debug.Assert(rewrittenRight != null); Debug.Assert(leftConversion.IsValid); Debug.Assert(rewrittenResultType is { }); Debug.Assert(rewrittenRight.Type is { }); Debug.Assert(rewrittenRight.Type.Equals(rewrittenResultType, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); if (_inExpressionLambda) { // Because of Error CS0845 (An expression tree lambda may not contain a coalescing operator with a null or default literal left-hand side) // we know that the left-hand-side has a type. Debug.Assert(rewrittenLeft.Type is { }); TypeSymbol strippedLeftType = rewrittenLeft.Type.StrippedType(); Conversion rewrittenConversion = TryMakeConversion(syntax, leftConversion, strippedLeftType, rewrittenResultType); if (!rewrittenConversion.Exists) { return BadExpression(syntax, rewrittenResultType, rewrittenLeft, rewrittenRight); } return new BoundNullCoalescingOperator(syntax, rewrittenLeft, rewrittenRight, rewrittenConversion, resultKind, rewrittenResultType); } var isUnconstrainedTypeParameter = rewrittenLeft.Type is { IsReferenceType: false, IsValueType: false }; // first we can make a small optimization: // If left is a constant then we already know whether it is null or not. If it is null then we // can simply generate "right". If it is not null then we can simply generate // MakeConversion(left). This does not hold when the left is an unconstrained type parameter: at runtime, // it can be either left or right depending on the runtime type of T if (!isUnconstrainedTypeParameter) { if (rewrittenLeft.IsDefaultValue()) { return rewrittenRight; } if (rewrittenLeft.ConstantValue != null) { Debug.Assert(!rewrittenLeft.ConstantValue.IsNull); return GetConvertedLeftForNullCoalescingOperator(rewrittenLeft, leftConversion, rewrittenResultType); } } // string concatenation is never null. // interpolated string lowering may introduce redundant null coalescing, which we have to remove. if (IsStringConcat(rewrittenLeft)) { return GetConvertedLeftForNullCoalescingOperator(rewrittenLeft, leftConversion, rewrittenResultType); } // if left conversion is intrinsic implicit (always succeeds) and results in a reference type // we can apply conversion before doing the null check that allows for a more efficient IL emit. Debug.Assert(rewrittenLeft.Type is { }); if (rewrittenLeft.Type.IsReferenceType && leftConversion.IsImplicit && !leftConversion.IsUserDefined) { if (!leftConversion.IsIdentity) { rewrittenLeft = MakeConversionNode(rewrittenLeft.Syntax, rewrittenLeft, leftConversion, rewrittenResultType, @checked: false); } return new BoundNullCoalescingOperator(syntax, rewrittenLeft, rewrittenRight, Conversion.Identity, resultKind, rewrittenResultType); } if (leftConversion.IsIdentity || leftConversion.Kind == ConversionKind.ExplicitNullable) { var conditionalAccess = rewrittenLeft as BoundLoweredConditionalAccess; if (conditionalAccess != null && (conditionalAccess.WhenNullOpt == null || NullableNeverHasValue(conditionalAccess.WhenNullOpt))) { var notNullAccess = NullableAlwaysHasValue(conditionalAccess.WhenNotNull); if (notNullAccess != null) { BoundExpression? whenNullOpt = rewrittenRight; if (whenNullOpt.Type.IsNullableType()) { notNullAccess = conditionalAccess.WhenNotNull; } if (whenNullOpt.IsDefaultValue() && whenNullOpt.Type.SpecialType != SpecialType.System_Decimal) { whenNullOpt = null; } return conditionalAccess.Update( conditionalAccess.Receiver, conditionalAccess.HasValueMethodOpt, whenNotNull: notNullAccess, whenNullOpt: whenNullOpt, id: conditionalAccess.Id, type: rewrittenResultType ); } } } // Optimize left ?? right to left.GetValueOrDefault() when left is T? and right is the default value of T if (rewrittenLeft.Type.IsNullableType() && RemoveIdentityConversions(rewrittenRight).IsDefaultValue() && rewrittenRight.Type.Equals(rewrittenLeft.Type.GetNullableUnderlyingType(), TypeCompareKind.AllIgnoreOptions) && TryGetNullableMethod(rewrittenLeft.Syntax, rewrittenLeft.Type, SpecialMember.System_Nullable_T_GetValueOrDefault, out MethodSymbol getValueOrDefault)) { return BoundCall.Synthesized(rewrittenLeft.Syntax, rewrittenLeft, getValueOrDefault); } // We lower left ?? right to // // var temp = left; // (temp != null) ? MakeConversion(temp) : right // BoundAssignmentOperator tempAssignment; BoundLocal boundTemp = _factory.StoreToTemp(rewrittenLeft, out tempAssignment); // temp != null BoundExpression nullCheck = MakeNullCheck(syntax, boundTemp, BinaryOperatorKind.NotEqual); // MakeConversion(temp, rewrittenResultType) BoundExpression convertedLeft = GetConvertedLeftForNullCoalescingOperator(boundTemp, leftConversion, rewrittenResultType); Debug.Assert(convertedLeft.HasErrors || convertedLeft.Type!.Equals(rewrittenResultType, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // (temp != null) ? MakeConversion(temp, LeftConversion) : RightOperand BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: syntax, rewrittenCondition: nullCheck, rewrittenConsequence: convertedLeft, rewrittenAlternative: rewrittenRight, constantValueOpt: null, rewrittenType: rewrittenResultType, isRef: false); Debug.Assert(conditionalExpression.ConstantValue == null); // we shouldn't have hit this else case otherwise Debug.Assert(conditionalExpression.Type!.Equals(rewrittenResultType, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); return new BoundSequence( syntax: syntax, locals: ImmutableArray.Create(boundTemp.LocalSymbol), sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignment), value: conditionalExpression, type: rewrittenResultType); } private bool IsStringConcat(BoundExpression expression) { if (expression.Kind != BoundKind.Call) { return false; } var boundCall = (BoundCall)expression; var method = boundCall.Method; if (method.IsStatic && method.ContainingType.SpecialType == SpecialType.System_String) { if ((object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString) || (object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringStringString) || (object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringStringStringString) || (object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatObject) || (object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatObjectObject) || (object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatObjectObjectObject) || (object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringArray) || (object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatObjectArray)) { return true; } } return false; } private static BoundExpression RemoveIdentityConversions(BoundExpression expression) { while (expression.Kind == BoundKind.Conversion) { var boundConversion = (BoundConversion)expression; if (boundConversion.ConversionKind != ConversionKind.Identity) { return expression; } expression = boundConversion.Operand; } return expression; } private BoundExpression GetConvertedLeftForNullCoalescingOperator(BoundExpression rewrittenLeft, Conversion leftConversion, TypeSymbol rewrittenResultType) { Debug.Assert(rewrittenLeft != null); Debug.Assert(rewrittenLeft.Type is { }); Debug.Assert(rewrittenResultType is { }); Debug.Assert(leftConversion.IsValid); TypeSymbol rewrittenLeftType = rewrittenLeft.Type; Debug.Assert(rewrittenLeftType.IsNullableType() || !rewrittenLeftType.IsValueType); // Native compiler violates the specification for the case where result type is right operand type and left operand is nullable. // For this case, we need to insert an extra explicit nullable conversion from the left operand to its underlying nullable type // before performing the leftConversion. // See comments in Binder.BindNullCoalescingOperator referring to GetConvertedLeftForNullCoalescingOperator for more details. if (!TypeSymbol.Equals(rewrittenLeftType, rewrittenResultType, TypeCompareKind.ConsiderEverything2) && rewrittenLeftType.IsNullableType()) { TypeSymbol strippedLeftType = rewrittenLeftType.GetNullableUnderlyingType(); MethodSymbol getValueOrDefault = UnsafeGetNullableMethod(rewrittenLeft.Syntax, rewrittenLeftType, SpecialMember.System_Nullable_T_GetValueOrDefault); rewrittenLeft = BoundCall.Synthesized(rewrittenLeft.Syntax, rewrittenLeft, getValueOrDefault); if (TypeSymbol.Equals(strippedLeftType, rewrittenResultType, TypeCompareKind.ConsiderEverything2)) { return rewrittenLeft; } } return MakeConversionNode(rewrittenLeft.Syntax, rewrittenLeft, leftConversion, rewrittenResultType, @checked: false); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/Serialization/SerializerService_Reference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Serialization { internal partial class SerializerService { private const int MetadataFailed = int.MaxValue; private static readonly ConditionalWeakTable<Metadata, object> s_lifetimeMap = new(); public static Checksum CreateChecksum(MetadataReference reference, CancellationToken cancellationToken) { if (reference is PortableExecutableReference portable) { return CreatePortableExecutableReferenceChecksum(portable, cancellationToken); } throw ExceptionUtilities.UnexpectedValue(reference.GetType()); } private static bool IsAnalyzerReferenceWithShadowCopyLoader(AnalyzerFileReference reference) => reference.AssemblyLoader is ShadowCopyAnalyzerAssemblyLoader; public static Checksum CreateChecksum(AnalyzerReference reference, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { switch (reference) { case AnalyzerFileReference file: writer.WriteString(file.FullPath); writer.WriteBoolean(IsAnalyzerReferenceWithShadowCopyLoader(file)); break; default: throw ExceptionUtilities.UnexpectedValue(reference); } } stream.Position = 0; return Checksum.Create(stream); } public virtual void WriteMetadataReferenceTo(MetadataReference reference, ObjectWriter writer, SolutionReplicationContext context, CancellationToken cancellationToken) { if (reference is PortableExecutableReference portable) { if (portable is ISupportTemporaryStorage supportTemporaryStorage) { if (TryWritePortableExecutableReferenceBackedByTemporaryStorageTo(supportTemporaryStorage, writer, context, cancellationToken)) { return; } } WritePortableExecutableReferenceTo(portable, writer, cancellationToken); return; } throw ExceptionUtilities.UnexpectedValue(reference.GetType()); } public virtual MetadataReference ReadMetadataReferenceFrom(ObjectReader reader, CancellationToken cancellationToken) { var type = reader.ReadString(); if (type == nameof(PortableExecutableReference)) { return ReadPortableExecutableReferenceFrom(reader, cancellationToken); } throw ExceptionUtilities.UnexpectedValue(type); } public virtual void WriteAnalyzerReferenceTo(AnalyzerReference reference, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); switch (reference) { case AnalyzerFileReference file: writer.WriteString(nameof(AnalyzerFileReference)); writer.WriteString(file.FullPath); writer.WriteBoolean(IsAnalyzerReferenceWithShadowCopyLoader(file)); break; default: throw ExceptionUtilities.UnexpectedValue(reference); } } public virtual AnalyzerReference ReadAnalyzerReferenceFrom(ObjectReader reader, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var type = reader.ReadString(); if (type == nameof(AnalyzerFileReference)) { var fullPath = reader.ReadString(); var shadowCopy = reader.ReadBoolean(); return new AnalyzerFileReference(fullPath, _analyzerLoaderProvider.GetLoader(new AnalyzerAssemblyLoaderOptions(shadowCopy))); } throw ExceptionUtilities.UnexpectedValue(type); } protected static void WritePortableExecutableReferenceHeaderTo( PortableExecutableReference reference, SerializationKinds kind, ObjectWriter writer, CancellationToken cancellationToken) { writer.WriteString(nameof(PortableExecutableReference)); writer.WriteInt32((int)kind); WritePortableExecutableReferencePropertiesTo(reference, writer, cancellationToken); } private static void WritePortableExecutableReferencePropertiesTo(PortableExecutableReference reference, ObjectWriter writer, CancellationToken cancellationToken) { WriteTo(reference.Properties, writer, cancellationToken); writer.WriteString(reference.FilePath); } private static Checksum CreatePortableExecutableReferenceChecksum(PortableExecutableReference reference, CancellationToken cancellationToken) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { WritePortableExecutableReferencePropertiesTo(reference, writer, cancellationToken); WriteMvidsTo(TryGetMetadata(reference), writer, cancellationToken); } stream.Position = 0; return Checksum.Create(stream); } private static void WriteMvidsTo(Metadata? metadata, ObjectWriter writer, CancellationToken cancellationToken) { if (metadata == null) { // handle error case where we couldn't load metadata of the reference. // this basically won't write anything to writer return; } if (metadata is AssemblyMetadata assemblyMetadata) { if (!TryGetModules(assemblyMetadata, out var modules)) { // Gracefully bail out without writing anything to the writer. return; } writer.WriteInt32((int)assemblyMetadata.Kind); writer.WriteInt32(modules.Length); foreach (var module in modules) { WriteMvidTo(module, writer, cancellationToken); } return; } WriteMvidTo((ModuleMetadata)metadata, writer, cancellationToken); } private static bool TryGetModules(AssemblyMetadata assemblyMetadata, out ImmutableArray<ModuleMetadata> modules) { // Gracefully handle documented exceptions from 'GetModules' invocation. try { modules = assemblyMetadata.GetModules(); return true; } catch (Exception ex) when (ex is BadImageFormatException || ex is IOException || ex is ObjectDisposedException) { modules = default; return false; } } private static void WriteMvidTo(ModuleMetadata metadata, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); writer.WriteInt32((int)metadata.Kind); var metadataReader = metadata.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; var guid = metadataReader.GetGuid(mvidHandle); writer.WriteGuid(guid); } private static void WritePortableExecutableReferenceTo( PortableExecutableReference reference, ObjectWriter writer, CancellationToken cancellationToken) { WritePortableExecutableReferenceHeaderTo(reference, SerializationKinds.Bits, writer, cancellationToken); WriteTo(TryGetMetadata(reference), writer, cancellationToken); // TODO: what I should do with documentation provider? it is not exposed outside } private PortableExecutableReference ReadPortableExecutableReferenceFrom(ObjectReader reader, CancellationToken cancellationToken) { var kind = (SerializationKinds)reader.ReadInt32(); if (kind == SerializationKinds.Bits || kind == SerializationKinds.MemoryMapFile) { var properties = ReadMetadataReferencePropertiesFrom(reader, cancellationToken); var filePath = reader.ReadString(); var tuple = TryReadMetadataFrom(reader, kind, cancellationToken); if (tuple == null) { // TODO: deal with xml document provider properly // should we shadow copy xml doc comment? // image doesn't exist return new MissingMetadataReference(properties, filePath, XmlDocumentationProvider.Default); } // for now, we will use IDocumentationProviderService to get DocumentationProvider for metadata // references. if the service is not available, then use Default (NoOp) provider. // since xml doc comment is not part of solution snapshot, (like xml reference resolver or strong name // provider) this provider can also potentially provide content that is different than one in the host. // an alternative approach of this is synching content of xml doc comment to remote host as well // so that we can put xml doc comment as part of snapshot. but until we believe that is necessary, // it will go with simpler approach var documentProvider = filePath != null && _documentationService != null ? _documentationService.GetDocumentationProvider(filePath) : XmlDocumentationProvider.Default; return new SerializedMetadataReference( properties, filePath, tuple.Value.metadata, tuple.Value.storages, documentProvider); } throw ExceptionUtilities.UnexpectedValue(kind); } private static void WriteTo(MetadataReferenceProperties properties, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); writer.WriteInt32((int)properties.Kind); writer.WriteValue(properties.Aliases.ToArray()); writer.WriteBoolean(properties.EmbedInteropTypes); } private static MetadataReferenceProperties ReadMetadataReferencePropertiesFrom(ObjectReader reader, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var kind = (MetadataImageKind)reader.ReadInt32(); var aliases = reader.ReadArray<string>().ToImmutableArrayOrEmpty(); var embedInteropTypes = reader.ReadBoolean(); return new MetadataReferenceProperties(kind, aliases, embedInteropTypes); } private static void WriteTo(Metadata? metadata, ObjectWriter writer, CancellationToken cancellationToken) { if (metadata == null) { // handle error case where metadata failed to load writer.WriteInt32(MetadataFailed); return; } if (metadata is AssemblyMetadata assemblyMetadata) { if (!TryGetModules(assemblyMetadata, out var modules)) { // Gracefully handle error case where unable to get modules. writer.WriteInt32(MetadataFailed); return; } writer.WriteInt32((int)assemblyMetadata.Kind); writer.WriteInt32(modules.Length); foreach (var module in modules) { WriteTo(module, writer, cancellationToken); } return; } WriteTo((ModuleMetadata)metadata, writer, cancellationToken); } private static bool TryWritePortableExecutableReferenceBackedByTemporaryStorageTo( ISupportTemporaryStorage reference, ObjectWriter writer, SolutionReplicationContext context, CancellationToken cancellationToken) { var storages = reference.GetStorages(); if (storages == null) { return false; } // Not clear if name should be allowed to be null here (https://github.com/dotnet/roslyn/issues/43037) using var pooled = Creator.CreateList<(string? name, long offset, long size)>(); foreach (var storage in storages) { if (storage is not ITemporaryStorageWithName storage2) { return false; } context.AddResource(storage); pooled.Object.Add((storage2.Name, storage2.Offset, storage2.Size)); } WritePortableExecutableReferenceHeaderTo((PortableExecutableReference)reference, SerializationKinds.MemoryMapFile, writer, cancellationToken); writer.WriteInt32((int)MetadataImageKind.Assembly); writer.WriteInt32(pooled.Object.Count); foreach (var (name, offset, size) in pooled.Object) { writer.WriteInt32((int)MetadataImageKind.Module); writer.WriteString(name); writer.WriteInt64(offset); writer.WriteInt64(size); } return true; } private (Metadata metadata, ImmutableArray<ITemporaryStreamStorage> storages)? TryReadMetadataFrom( ObjectReader reader, SerializationKinds kind, CancellationToken cancellationToken) { var imageKind = reader.ReadInt32(); if (imageKind == MetadataFailed) { // error case return null; } var metadataKind = (MetadataImageKind)imageKind; if (_storageService == null) { if (metadataKind == MetadataImageKind.Assembly) { using var pooledMetadata = Creator.CreateList<ModuleMetadata>(); var count = reader.ReadInt32(); for (var i = 0; i < count; i++) { metadataKind = (MetadataImageKind)reader.ReadInt32(); Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); #pragma warning disable CA2016 // https://github.com/dotnet/roslyn-analyzers/issues/4985 pooledMetadata.Object.Add(ReadModuleMetadataFrom(reader, kind)); #pragma warning restore CA2016 } return (AssemblyMetadata.Create(pooledMetadata.Object), storages: default); } Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); #pragma warning disable CA2016 // https://github.com/dotnet/roslyn-analyzers/issues/4985 return (ReadModuleMetadataFrom(reader, kind), storages: default); #pragma warning restore CA2016 } if (metadataKind == MetadataImageKind.Assembly) { using var pooledMetadata = Creator.CreateList<ModuleMetadata>(); using var pooledStorage = Creator.CreateList<ITemporaryStreamStorage>(); var count = reader.ReadInt32(); for (var i = 0; i < count; i++) { metadataKind = (MetadataImageKind)reader.ReadInt32(); Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); var (metadata, storage) = ReadModuleMetadataFrom(reader, kind, cancellationToken); pooledMetadata.Object.Add(metadata); pooledStorage.Object.Add(storage); } return (AssemblyMetadata.Create(pooledMetadata.Object), pooledStorage.Object.ToImmutableArrayOrEmpty()); } Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); var moduleInfo = ReadModuleMetadataFrom(reader, kind, cancellationToken); return (moduleInfo.metadata, ImmutableArray.Create(moduleInfo.storage)); } private (ModuleMetadata metadata, ITemporaryStreamStorage storage) ReadModuleMetadataFrom( ObjectReader reader, SerializationKinds kind, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); GetTemporaryStorage(reader, kind, out var storage, out var length, cancellationToken); var storageStream = storage.ReadStream(cancellationToken); Contract.ThrowIfFalse(length == storageStream.Length); GetMetadata(storageStream, length, out var metadata, out var lifeTimeObject); // make sure we keep storageStream alive while Metadata is alive // we use conditional weak table since we can't control metadata liftetime s_lifetimeMap.Add(metadata, lifeTimeObject); return (metadata, storage); } private static ModuleMetadata ReadModuleMetadataFrom(ObjectReader reader, SerializationKinds kind) { Contract.ThrowIfFalse(SerializationKinds.Bits == kind); var array = reader.ReadArray<byte>(); var pinnedObject = new PinnedObject(array); var metadata = ModuleMetadata.CreateFromMetadata(pinnedObject.GetPointer(), array.Length); // make sure we keep storageStream alive while Metadata is alive // we use conditional weak table since we can't control metadata liftetime s_lifetimeMap.Add(metadata, pinnedObject); return metadata; } private void GetTemporaryStorage( ObjectReader reader, SerializationKinds kind, out ITemporaryStreamStorage storage, out long length, CancellationToken cancellationToken) { if (kind == SerializationKinds.Bits) { storage = _storageService.CreateTemporaryStreamStorage(cancellationToken); using var stream = SerializableBytes.CreateWritableStream(); CopyByteArrayToStream(reader, stream, cancellationToken); length = stream.Length; stream.Position = 0; storage.WriteStream(stream, cancellationToken); return; } if (kind == SerializationKinds.MemoryMapFile) { var service2 = (ITemporaryStorageService2)_storageService; var name = reader.ReadString(); var offset = reader.ReadInt64(); var size = reader.ReadInt64(); storage = service2.AttachTemporaryStreamStorage(name, offset, size, cancellationToken); length = size; return; } throw ExceptionUtilities.UnexpectedValue(kind); } private static void GetMetadata(Stream stream, long length, out ModuleMetadata metadata, out object lifeTimeObject) { if (stream is ISupportDirectMemoryAccess directAccess) { metadata = ModuleMetadata.CreateFromMetadata(directAccess.GetPointer(), (int)length); lifeTimeObject = stream; return; } PinnedObject pinnedObject; if (stream is MemoryStream memory && memory.TryGetBuffer(out var buffer) && buffer.Offset == 0) { pinnedObject = new PinnedObject(buffer.Array!); } else { var array = new byte[length]; stream.Read(array, 0, (int)length); pinnedObject = new PinnedObject(array); } metadata = ModuleMetadata.CreateFromMetadata(pinnedObject.GetPointer(), (int)length); lifeTimeObject = pinnedObject; } private static void CopyByteArrayToStream(ObjectReader reader, Stream stream, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // TODO: make reader be able to read byte[] chunk var content = reader.ReadArray<byte>(); stream.Write(content, 0, content.Length); } private static void WriteTo(ModuleMetadata metadata, ObjectWriter writer, CancellationToken cancellationToken) { writer.WriteInt32((int)metadata.Kind); WriteTo(metadata.GetMetadataReader(), writer, cancellationToken); } private static unsafe void WriteTo(MetadataReader reader, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); writer.WriteValue(new ReadOnlySpan<byte>(reader.MetadataPointer, reader.MetadataLength)); } private static void WriteUnresolvedAnalyzerReferenceTo(AnalyzerReference reference, ObjectWriter writer) { writer.WriteString(nameof(UnresolvedAnalyzerReference)); writer.WriteString(reference.FullPath); } private static Metadata? TryGetMetadata(PortableExecutableReference reference) { try { return reference.GetMetadata(); } catch { // we have a reference but the file the reference is pointing to // might not actually exist on disk. // in that case, rather than crashing, we will handle it gracefully. return null; } } private sealed class PinnedObject : IDisposable { // shouldn't be read-only since GCHandle is a mutable struct private GCHandle _gcHandle; public PinnedObject(byte[] array) => _gcHandle = GCHandle.Alloc(array, GCHandleType.Pinned); internal IntPtr GetPointer() => _gcHandle.AddrOfPinnedObject(); private void OnDispose() { if (_gcHandle.IsAllocated) { _gcHandle.Free(); } } ~PinnedObject() => OnDispose(); public void Dispose() { GC.SuppressFinalize(this); OnDispose(); } } private sealed class MissingMetadataReference : PortableExecutableReference { private readonly DocumentationProvider _provider; public MissingMetadataReference( MetadataReferenceProperties properties, string? fullPath, DocumentationProvider initialDocumentation) : base(properties, fullPath, initialDocumentation) { // TODO: doc comment provider is a bit weird. _provider = initialDocumentation; } protected override DocumentationProvider CreateDocumentationProvider() { // TODO: properly implement this throw new NotImplementedException(); } protected override Metadata GetMetadataImpl() { // we just throw "FileNotFoundException" even if it might not be actual reason // why metadata has failed to load. in this context, we don't care much on actual // reason. we just need to maintain failure when re-constructing solution to maintain // snapshot integrity. // // if anyone care actual reason, he should get that info from original Solution. throw new FileNotFoundException(FilePath); } protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) => new MissingMetadataReference(properties, FilePath, _provider); } [DebuggerDisplay("{" + nameof(Display) + ",nq}")] private sealed class SerializedMetadataReference : PortableExecutableReference, ISupportTemporaryStorage { private readonly Metadata _metadata; private readonly ImmutableArray<ITemporaryStreamStorage> _storagesOpt; private readonly DocumentationProvider _provider; public SerializedMetadataReference( MetadataReferenceProperties properties, string? fullPath, Metadata metadata, ImmutableArray<ITemporaryStreamStorage> storagesOpt, DocumentationProvider initialDocumentation) : base(properties, fullPath, initialDocumentation) { _metadata = metadata; _storagesOpt = storagesOpt; _provider = initialDocumentation; } protected override DocumentationProvider CreateDocumentationProvider() { // this uses documentation provider given at the constructor throw ExceptionUtilities.Unreachable; } protected override Metadata GetMetadataImpl() => _metadata; protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) => new SerializedMetadataReference(properties, FilePath, _metadata, _storagesOpt, _provider); public IEnumerable<ITemporaryStreamStorage>? GetStorages() => _storagesOpt.IsDefault ? (IEnumerable<ITemporaryStreamStorage>?)null : _storagesOpt; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Serialization { internal partial class SerializerService { private const int MetadataFailed = int.MaxValue; private static readonly ConditionalWeakTable<Metadata, object> s_lifetimeMap = new(); public static Checksum CreateChecksum(MetadataReference reference, CancellationToken cancellationToken) { if (reference is PortableExecutableReference portable) { return CreatePortableExecutableReferenceChecksum(portable, cancellationToken); } throw ExceptionUtilities.UnexpectedValue(reference.GetType()); } private static bool IsAnalyzerReferenceWithShadowCopyLoader(AnalyzerFileReference reference) => reference.AssemblyLoader is ShadowCopyAnalyzerAssemblyLoader; public static Checksum CreateChecksum(AnalyzerReference reference, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { switch (reference) { case AnalyzerFileReference file: writer.WriteString(file.FullPath); writer.WriteBoolean(IsAnalyzerReferenceWithShadowCopyLoader(file)); break; default: throw ExceptionUtilities.UnexpectedValue(reference); } } stream.Position = 0; return Checksum.Create(stream); } public virtual void WriteMetadataReferenceTo(MetadataReference reference, ObjectWriter writer, SolutionReplicationContext context, CancellationToken cancellationToken) { if (reference is PortableExecutableReference portable) { if (portable is ISupportTemporaryStorage supportTemporaryStorage) { if (TryWritePortableExecutableReferenceBackedByTemporaryStorageTo(supportTemporaryStorage, writer, context, cancellationToken)) { return; } } WritePortableExecutableReferenceTo(portable, writer, cancellationToken); return; } throw ExceptionUtilities.UnexpectedValue(reference.GetType()); } public virtual MetadataReference ReadMetadataReferenceFrom(ObjectReader reader, CancellationToken cancellationToken) { var type = reader.ReadString(); if (type == nameof(PortableExecutableReference)) { return ReadPortableExecutableReferenceFrom(reader, cancellationToken); } throw ExceptionUtilities.UnexpectedValue(type); } public virtual void WriteAnalyzerReferenceTo(AnalyzerReference reference, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); switch (reference) { case AnalyzerFileReference file: writer.WriteString(nameof(AnalyzerFileReference)); writer.WriteString(file.FullPath); writer.WriteBoolean(IsAnalyzerReferenceWithShadowCopyLoader(file)); break; default: throw ExceptionUtilities.UnexpectedValue(reference); } } public virtual AnalyzerReference ReadAnalyzerReferenceFrom(ObjectReader reader, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var type = reader.ReadString(); if (type == nameof(AnalyzerFileReference)) { var fullPath = reader.ReadString(); var shadowCopy = reader.ReadBoolean(); return new AnalyzerFileReference(fullPath, _analyzerLoaderProvider.GetLoader(new AnalyzerAssemblyLoaderOptions(shadowCopy))); } throw ExceptionUtilities.UnexpectedValue(type); } protected static void WritePortableExecutableReferenceHeaderTo( PortableExecutableReference reference, SerializationKinds kind, ObjectWriter writer, CancellationToken cancellationToken) { writer.WriteString(nameof(PortableExecutableReference)); writer.WriteInt32((int)kind); WritePortableExecutableReferencePropertiesTo(reference, writer, cancellationToken); } private static void WritePortableExecutableReferencePropertiesTo(PortableExecutableReference reference, ObjectWriter writer, CancellationToken cancellationToken) { WriteTo(reference.Properties, writer, cancellationToken); writer.WriteString(reference.FilePath); } private static Checksum CreatePortableExecutableReferenceChecksum(PortableExecutableReference reference, CancellationToken cancellationToken) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { WritePortableExecutableReferencePropertiesTo(reference, writer, cancellationToken); WriteMvidsTo(TryGetMetadata(reference), writer, cancellationToken); } stream.Position = 0; return Checksum.Create(stream); } private static void WriteMvidsTo(Metadata? metadata, ObjectWriter writer, CancellationToken cancellationToken) { if (metadata == null) { // handle error case where we couldn't load metadata of the reference. // this basically won't write anything to writer return; } if (metadata is AssemblyMetadata assemblyMetadata) { if (!TryGetModules(assemblyMetadata, out var modules)) { // Gracefully bail out without writing anything to the writer. return; } writer.WriteInt32((int)assemblyMetadata.Kind); writer.WriteInt32(modules.Length); foreach (var module in modules) { WriteMvidTo(module, writer, cancellationToken); } return; } WriteMvidTo((ModuleMetadata)metadata, writer, cancellationToken); } private static bool TryGetModules(AssemblyMetadata assemblyMetadata, out ImmutableArray<ModuleMetadata> modules) { // Gracefully handle documented exceptions from 'GetModules' invocation. try { modules = assemblyMetadata.GetModules(); return true; } catch (Exception ex) when (ex is BadImageFormatException || ex is IOException || ex is ObjectDisposedException) { modules = default; return false; } } private static void WriteMvidTo(ModuleMetadata metadata, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); writer.WriteInt32((int)metadata.Kind); var metadataReader = metadata.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; var guid = metadataReader.GetGuid(mvidHandle); writer.WriteGuid(guid); } private static void WritePortableExecutableReferenceTo( PortableExecutableReference reference, ObjectWriter writer, CancellationToken cancellationToken) { WritePortableExecutableReferenceHeaderTo(reference, SerializationKinds.Bits, writer, cancellationToken); WriteTo(TryGetMetadata(reference), writer, cancellationToken); // TODO: what I should do with documentation provider? it is not exposed outside } private PortableExecutableReference ReadPortableExecutableReferenceFrom(ObjectReader reader, CancellationToken cancellationToken) { var kind = (SerializationKinds)reader.ReadInt32(); if (kind == SerializationKinds.Bits || kind == SerializationKinds.MemoryMapFile) { var properties = ReadMetadataReferencePropertiesFrom(reader, cancellationToken); var filePath = reader.ReadString(); var tuple = TryReadMetadataFrom(reader, kind, cancellationToken); if (tuple == null) { // TODO: deal with xml document provider properly // should we shadow copy xml doc comment? // image doesn't exist return new MissingMetadataReference(properties, filePath, XmlDocumentationProvider.Default); } // for now, we will use IDocumentationProviderService to get DocumentationProvider for metadata // references. if the service is not available, then use Default (NoOp) provider. // since xml doc comment is not part of solution snapshot, (like xml reference resolver or strong name // provider) this provider can also potentially provide content that is different than one in the host. // an alternative approach of this is synching content of xml doc comment to remote host as well // so that we can put xml doc comment as part of snapshot. but until we believe that is necessary, // it will go with simpler approach var documentProvider = filePath != null && _documentationService != null ? _documentationService.GetDocumentationProvider(filePath) : XmlDocumentationProvider.Default; return new SerializedMetadataReference( properties, filePath, tuple.Value.metadata, tuple.Value.storages, documentProvider); } throw ExceptionUtilities.UnexpectedValue(kind); } private static void WriteTo(MetadataReferenceProperties properties, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); writer.WriteInt32((int)properties.Kind); writer.WriteValue(properties.Aliases.ToArray()); writer.WriteBoolean(properties.EmbedInteropTypes); } private static MetadataReferenceProperties ReadMetadataReferencePropertiesFrom(ObjectReader reader, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var kind = (MetadataImageKind)reader.ReadInt32(); var aliases = reader.ReadArray<string>().ToImmutableArrayOrEmpty(); var embedInteropTypes = reader.ReadBoolean(); return new MetadataReferenceProperties(kind, aliases, embedInteropTypes); } private static void WriteTo(Metadata? metadata, ObjectWriter writer, CancellationToken cancellationToken) { if (metadata == null) { // handle error case where metadata failed to load writer.WriteInt32(MetadataFailed); return; } if (metadata is AssemblyMetadata assemblyMetadata) { if (!TryGetModules(assemblyMetadata, out var modules)) { // Gracefully handle error case where unable to get modules. writer.WriteInt32(MetadataFailed); return; } writer.WriteInt32((int)assemblyMetadata.Kind); writer.WriteInt32(modules.Length); foreach (var module in modules) { WriteTo(module, writer, cancellationToken); } return; } WriteTo((ModuleMetadata)metadata, writer, cancellationToken); } private static bool TryWritePortableExecutableReferenceBackedByTemporaryStorageTo( ISupportTemporaryStorage reference, ObjectWriter writer, SolutionReplicationContext context, CancellationToken cancellationToken) { var storages = reference.GetStorages(); if (storages == null) { return false; } // Not clear if name should be allowed to be null here (https://github.com/dotnet/roslyn/issues/43037) using var pooled = Creator.CreateList<(string? name, long offset, long size)>(); foreach (var storage in storages) { if (storage is not ITemporaryStorageWithName storage2) { return false; } context.AddResource(storage); pooled.Object.Add((storage2.Name, storage2.Offset, storage2.Size)); } WritePortableExecutableReferenceHeaderTo((PortableExecutableReference)reference, SerializationKinds.MemoryMapFile, writer, cancellationToken); writer.WriteInt32((int)MetadataImageKind.Assembly); writer.WriteInt32(pooled.Object.Count); foreach (var (name, offset, size) in pooled.Object) { writer.WriteInt32((int)MetadataImageKind.Module); writer.WriteString(name); writer.WriteInt64(offset); writer.WriteInt64(size); } return true; } private (Metadata metadata, ImmutableArray<ITemporaryStreamStorage> storages)? TryReadMetadataFrom( ObjectReader reader, SerializationKinds kind, CancellationToken cancellationToken) { var imageKind = reader.ReadInt32(); if (imageKind == MetadataFailed) { // error case return null; } var metadataKind = (MetadataImageKind)imageKind; if (_storageService == null) { if (metadataKind == MetadataImageKind.Assembly) { using var pooledMetadata = Creator.CreateList<ModuleMetadata>(); var count = reader.ReadInt32(); for (var i = 0; i < count; i++) { metadataKind = (MetadataImageKind)reader.ReadInt32(); Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); #pragma warning disable CA2016 // https://github.com/dotnet/roslyn-analyzers/issues/4985 pooledMetadata.Object.Add(ReadModuleMetadataFrom(reader, kind)); #pragma warning restore CA2016 } return (AssemblyMetadata.Create(pooledMetadata.Object), storages: default); } Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); #pragma warning disable CA2016 // https://github.com/dotnet/roslyn-analyzers/issues/4985 return (ReadModuleMetadataFrom(reader, kind), storages: default); #pragma warning restore CA2016 } if (metadataKind == MetadataImageKind.Assembly) { using var pooledMetadata = Creator.CreateList<ModuleMetadata>(); using var pooledStorage = Creator.CreateList<ITemporaryStreamStorage>(); var count = reader.ReadInt32(); for (var i = 0; i < count; i++) { metadataKind = (MetadataImageKind)reader.ReadInt32(); Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); var (metadata, storage) = ReadModuleMetadataFrom(reader, kind, cancellationToken); pooledMetadata.Object.Add(metadata); pooledStorage.Object.Add(storage); } return (AssemblyMetadata.Create(pooledMetadata.Object), pooledStorage.Object.ToImmutableArrayOrEmpty()); } Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); var moduleInfo = ReadModuleMetadataFrom(reader, kind, cancellationToken); return (moduleInfo.metadata, ImmutableArray.Create(moduleInfo.storage)); } private (ModuleMetadata metadata, ITemporaryStreamStorage storage) ReadModuleMetadataFrom( ObjectReader reader, SerializationKinds kind, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); GetTemporaryStorage(reader, kind, out var storage, out var length, cancellationToken); var storageStream = storage.ReadStream(cancellationToken); Contract.ThrowIfFalse(length == storageStream.Length); GetMetadata(storageStream, length, out var metadata, out var lifeTimeObject); // make sure we keep storageStream alive while Metadata is alive // we use conditional weak table since we can't control metadata liftetime s_lifetimeMap.Add(metadata, lifeTimeObject); return (metadata, storage); } private static ModuleMetadata ReadModuleMetadataFrom(ObjectReader reader, SerializationKinds kind) { Contract.ThrowIfFalse(SerializationKinds.Bits == kind); var array = reader.ReadArray<byte>(); var pinnedObject = new PinnedObject(array); var metadata = ModuleMetadata.CreateFromMetadata(pinnedObject.GetPointer(), array.Length); // make sure we keep storageStream alive while Metadata is alive // we use conditional weak table since we can't control metadata liftetime s_lifetimeMap.Add(metadata, pinnedObject); return metadata; } private void GetTemporaryStorage( ObjectReader reader, SerializationKinds kind, out ITemporaryStreamStorage storage, out long length, CancellationToken cancellationToken) { if (kind == SerializationKinds.Bits) { storage = _storageService.CreateTemporaryStreamStorage(cancellationToken); using var stream = SerializableBytes.CreateWritableStream(); CopyByteArrayToStream(reader, stream, cancellationToken); length = stream.Length; stream.Position = 0; storage.WriteStream(stream, cancellationToken); return; } if (kind == SerializationKinds.MemoryMapFile) { var service2 = (ITemporaryStorageService2)_storageService; var name = reader.ReadString(); var offset = reader.ReadInt64(); var size = reader.ReadInt64(); storage = service2.AttachTemporaryStreamStorage(name, offset, size, cancellationToken); length = size; return; } throw ExceptionUtilities.UnexpectedValue(kind); } private static void GetMetadata(Stream stream, long length, out ModuleMetadata metadata, out object lifeTimeObject) { if (stream is ISupportDirectMemoryAccess directAccess) { metadata = ModuleMetadata.CreateFromMetadata(directAccess.GetPointer(), (int)length); lifeTimeObject = stream; return; } PinnedObject pinnedObject; if (stream is MemoryStream memory && memory.TryGetBuffer(out var buffer) && buffer.Offset == 0) { pinnedObject = new PinnedObject(buffer.Array!); } else { var array = new byte[length]; stream.Read(array, 0, (int)length); pinnedObject = new PinnedObject(array); } metadata = ModuleMetadata.CreateFromMetadata(pinnedObject.GetPointer(), (int)length); lifeTimeObject = pinnedObject; } private static void CopyByteArrayToStream(ObjectReader reader, Stream stream, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // TODO: make reader be able to read byte[] chunk var content = reader.ReadArray<byte>(); stream.Write(content, 0, content.Length); } private static void WriteTo(ModuleMetadata metadata, ObjectWriter writer, CancellationToken cancellationToken) { writer.WriteInt32((int)metadata.Kind); WriteTo(metadata.GetMetadataReader(), writer, cancellationToken); } private static unsafe void WriteTo(MetadataReader reader, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); writer.WriteValue(new ReadOnlySpan<byte>(reader.MetadataPointer, reader.MetadataLength)); } private static void WriteUnresolvedAnalyzerReferenceTo(AnalyzerReference reference, ObjectWriter writer) { writer.WriteString(nameof(UnresolvedAnalyzerReference)); writer.WriteString(reference.FullPath); } private static Metadata? TryGetMetadata(PortableExecutableReference reference) { try { return reference.GetMetadata(); } catch { // we have a reference but the file the reference is pointing to // might not actually exist on disk. // in that case, rather than crashing, we will handle it gracefully. return null; } } private sealed class PinnedObject : IDisposable { // shouldn't be read-only since GCHandle is a mutable struct private GCHandle _gcHandle; public PinnedObject(byte[] array) => _gcHandle = GCHandle.Alloc(array, GCHandleType.Pinned); internal IntPtr GetPointer() => _gcHandle.AddrOfPinnedObject(); private void OnDispose() { if (_gcHandle.IsAllocated) { _gcHandle.Free(); } } ~PinnedObject() => OnDispose(); public void Dispose() { GC.SuppressFinalize(this); OnDispose(); } } private sealed class MissingMetadataReference : PortableExecutableReference { private readonly DocumentationProvider _provider; public MissingMetadataReference( MetadataReferenceProperties properties, string? fullPath, DocumentationProvider initialDocumentation) : base(properties, fullPath, initialDocumentation) { // TODO: doc comment provider is a bit weird. _provider = initialDocumentation; } protected override DocumentationProvider CreateDocumentationProvider() { // TODO: properly implement this throw new NotImplementedException(); } protected override Metadata GetMetadataImpl() { // we just throw "FileNotFoundException" even if it might not be actual reason // why metadata has failed to load. in this context, we don't care much on actual // reason. we just need to maintain failure when re-constructing solution to maintain // snapshot integrity. // // if anyone care actual reason, he should get that info from original Solution. throw new FileNotFoundException(FilePath); } protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) => new MissingMetadataReference(properties, FilePath, _provider); } [DebuggerDisplay("{" + nameof(Display) + ",nq}")] private sealed class SerializedMetadataReference : PortableExecutableReference, ISupportTemporaryStorage { private readonly Metadata _metadata; private readonly ImmutableArray<ITemporaryStreamStorage> _storagesOpt; private readonly DocumentationProvider _provider; public SerializedMetadataReference( MetadataReferenceProperties properties, string? fullPath, Metadata metadata, ImmutableArray<ITemporaryStreamStorage> storagesOpt, DocumentationProvider initialDocumentation) : base(properties, fullPath, initialDocumentation) { _metadata = metadata; _storagesOpt = storagesOpt; _provider = initialDocumentation; } protected override DocumentationProvider CreateDocumentationProvider() { // this uses documentation provider given at the constructor throw ExceptionUtilities.Unreachable; } protected override Metadata GetMetadataImpl() => _metadata; protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) => new SerializedMetadataReference(properties, FilePath, _metadata, _storagesOpt, _provider); public IEnumerable<ITemporaryStreamStorage>? GetStorages() => _storagesOpt.IsDefault ? (IEnumerable<ITemporaryStreamStorage>?)null : _storagesOpt; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/CSharp/Portable/Composition/CSharpWorkspaceFeatures.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Composition { #if false public class CSharpWorkspaceFeatures : FeaturePack { private CSharpWorkspaceFeatures() { } public static readonly FeaturePack Instance = new CSharpWorkspaceFeatures(); internal override ExportSource ComposeExports(ExportSource root) { return new ExportList() { // case correction new Lazy<ILanguageService, LanguageServiceMetadata>( () => new Microsoft.CodeAnalysis.CSharp.CaseCorrection.CSharpCaseCorrectionService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.CaseCorrection.ICaseCorrectionService), ServiceLayer.Default)), // code clean up new Lazy<ILanguageServiceFactory, LanguageServiceMetadata>( () => new Microsoft.CodeAnalysis.CSharp.CodeCleanup.CSharpCodeCleanerServiceFactory(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.CodeCleanup.ICodeCleanerService), ServiceLayer.Default)), // code generation new Lazy<ILanguageServiceFactory, LanguageServiceMetadata>( () => new Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationServiceFactory(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.CodeGeneration.ICodeGenerationService), ServiceLayer.Default)), new Lazy<ILanguageService, LanguageServiceMetadata>( () => new Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpSyntaxFactory(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.CodeGeneration.ISyntaxFactoryService), ServiceLayer.Default)), // formatting service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingService(root), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.Formatting.IFormattingService), ServiceLayer.Default)), // formatting rules new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.AlignTokensFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.AlignTokensFormattingRule.Name, LanguageNames.CSharp)), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.AnchorIndentationFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.AnchorIndentationFormattingRule.Name, LanguageNames.CSharp, after: new string[] { Microsoft.CodeAnalysis.CSharp.Formatting.SuppressFormattingRule.Name })), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.ElasticTriviaFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.ElasticTriviaFormattingRule.Name, LanguageNames.CSharp)), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.EndOfFileTokenFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.EndOfFileTokenFormattingRule.Name, LanguageNames.CSharp, after: new string[] { Microsoft.CodeAnalysis.CSharp.Formatting.ElasticTriviaFormattingRule.Name })), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.IndentBlockFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.IndentBlockFormattingRule.Name, LanguageNames.CSharp, after: new string[] { Microsoft.CodeAnalysis.CSharp.Formatting.StructuredTriviaFormattingRule.Name })), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.QueryExpressionFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.QueryExpressionFormattingRule.Name, LanguageNames.CSharp, after: new string[] { Microsoft.CodeAnalysis.CSharp.Formatting.AnchorIndentationFormattingRule.Name })), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.StructuredTriviaFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.StructuredTriviaFormattingRule.Name, LanguageNames.CSharp, after: new string[] { Microsoft.CodeAnalysis.CSharp.Formatting.EndOfFileTokenFormattingRule.Name })), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.SuppressFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.SuppressFormattingRule.Name, LanguageNames.CSharp, after: new string[] { Microsoft.CodeAnalysis.CSharp.Formatting.IndentBlockFormattingRule.Name })), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.TokenBasedFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.TokenBasedFormattingRule.Name, LanguageNames.CSharp, after: new string[] { Microsoft.CodeAnalysis.CSharp.Formatting.QueryExpressionFormattingRule.Name })), // formatting options new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.MethodDeclarationNameParenthesis), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.MethodDeclarationParenthesisArgumentList), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.MethodDeclarationEmptyArgument), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.MethodCallNameParenthesis), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.MethodCallArgumentList), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.MethodCallEmptyArgument), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OtherAfterControlFlowKeyword), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OtherBetweenParenthesisExpression), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OtherParenthesisTypeCast), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OtherParenControlFlow), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OtherParenAfterCast), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OtherSpacesDeclarationIgnore), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SquareBracesBefore), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SquareBracesEmpty), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SquareBracesAndValue), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersAfterColonInTypeDeclaration), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersAfterCommaInParameterArgument), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersAfterDotMemberAccessQualifiedName), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersAfterSemiColonInForStatement), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersBeforeColonInTypeDeclaration), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersBeforeCommaInParameterArgument), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersBeforeDotMemberAccessQualifiedName), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersBeforeSemiColonInForStatement), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpacingAroundBinaryOperator), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenCloseBracesIndent), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.IndentBlock), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.IndentSwitchSection), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.IndentSwitchCaseSection), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.LabelPositioning), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.LeaveStatementMethodDeclarationSameLine), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenBracesInNewLineForTypes), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenBracesInNewLineForMethods), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenBracesInNewLineForAnonymousMethods), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenBracesInNewLineForControl), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenBracesInNewLineForAnonymousType), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenBracesInNewLineForObjectInitializers), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenBracesInNewLineForLambda), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForElse), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForCatch), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForFinally), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForMembersInObjectInit), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForMembersInAnonymousTypes), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForClausesInQuery), // Recommendation service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpRecommendationService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.Recommendations.IRecommendationService), ServiceLayer.Default)), // Command line arguments service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpCommandLineArgumentsFactoryService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ICommandLineArgumentsFactoryService), ServiceLayer.Default)), // Compilation factory service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpCompilationFactoryService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ICompilationFactoryService), ServiceLayer.Default)), // Project File Loader service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpProjectFileLoaderService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.Host.ProjectFileLoader.IProjectFileLoaderLanguageService), ServiceLayer.Default)), // Semantic Facts service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpSemanticFactsService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ISemanticFactsService), ServiceLayer.Default)), // Symbol Declaration service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpSymbolDeclarationService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ISymbolDeclarationService), ServiceLayer.Default)), // Syntax Facts service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpSyntaxFactsService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ISyntaxFactsService), ServiceLayer.Default)), // SyntaxTree Factory service new Lazy<ILanguageServiceFactory, LanguageServiceMetadata>( () => new CSharpSyntaxTreeFactoryServiceFactory(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ISyntaxTreeFactoryService), ServiceLayer.Default)), // SyntaxVersion service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpSyntaxVersionService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ISyntaxVersionLanguageService), ServiceLayer.Default)), // Type Inference service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpTypeInferenceService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ITypeInferenceService), ServiceLayer.Default)), // Rename conflicts service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Rename.CSharpRenameConflictLanguageService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.Rename.IRenameRewriterLanguageService), ServiceLayer.Default)), // Simplification service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Simplification.CSharpSimplificationService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.Simplification.ISimplificationService), ServiceLayer.Default)) }; } } #endif }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Composition { #if false public class CSharpWorkspaceFeatures : FeaturePack { private CSharpWorkspaceFeatures() { } public static readonly FeaturePack Instance = new CSharpWorkspaceFeatures(); internal override ExportSource ComposeExports(ExportSource root) { return new ExportList() { // case correction new Lazy<ILanguageService, LanguageServiceMetadata>( () => new Microsoft.CodeAnalysis.CSharp.CaseCorrection.CSharpCaseCorrectionService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.CaseCorrection.ICaseCorrectionService), ServiceLayer.Default)), // code clean up new Lazy<ILanguageServiceFactory, LanguageServiceMetadata>( () => new Microsoft.CodeAnalysis.CSharp.CodeCleanup.CSharpCodeCleanerServiceFactory(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.CodeCleanup.ICodeCleanerService), ServiceLayer.Default)), // code generation new Lazy<ILanguageServiceFactory, LanguageServiceMetadata>( () => new Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationServiceFactory(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.CodeGeneration.ICodeGenerationService), ServiceLayer.Default)), new Lazy<ILanguageService, LanguageServiceMetadata>( () => new Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpSyntaxFactory(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.CodeGeneration.ISyntaxFactoryService), ServiceLayer.Default)), // formatting service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingService(root), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.Formatting.IFormattingService), ServiceLayer.Default)), // formatting rules new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.AlignTokensFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.AlignTokensFormattingRule.Name, LanguageNames.CSharp)), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.AnchorIndentationFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.AnchorIndentationFormattingRule.Name, LanguageNames.CSharp, after: new string[] { Microsoft.CodeAnalysis.CSharp.Formatting.SuppressFormattingRule.Name })), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.ElasticTriviaFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.ElasticTriviaFormattingRule.Name, LanguageNames.CSharp)), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.EndOfFileTokenFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.EndOfFileTokenFormattingRule.Name, LanguageNames.CSharp, after: new string[] { Microsoft.CodeAnalysis.CSharp.Formatting.ElasticTriviaFormattingRule.Name })), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.IndentBlockFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.IndentBlockFormattingRule.Name, LanguageNames.CSharp, after: new string[] { Microsoft.CodeAnalysis.CSharp.Formatting.StructuredTriviaFormattingRule.Name })), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.QueryExpressionFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.QueryExpressionFormattingRule.Name, LanguageNames.CSharp, after: new string[] { Microsoft.CodeAnalysis.CSharp.Formatting.AnchorIndentationFormattingRule.Name })), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.StructuredTriviaFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.StructuredTriviaFormattingRule.Name, LanguageNames.CSharp, after: new string[] { Microsoft.CodeAnalysis.CSharp.Formatting.EndOfFileTokenFormattingRule.Name })), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.SuppressFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.SuppressFormattingRule.Name, LanguageNames.CSharp, after: new string[] { Microsoft.CodeAnalysis.CSharp.Formatting.IndentBlockFormattingRule.Name })), new Lazy<Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Formatting.TokenBasedFormattingRule(), new OrderableLanguageMetadata(Microsoft.CodeAnalysis.CSharp.Formatting.TokenBasedFormattingRule.Name, LanguageNames.CSharp, after: new string[] { Microsoft.CodeAnalysis.CSharp.Formatting.QueryExpressionFormattingRule.Name })), // formatting options new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.MethodDeclarationNameParenthesis), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.MethodDeclarationParenthesisArgumentList), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.MethodDeclarationEmptyArgument), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.MethodCallNameParenthesis), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.MethodCallArgumentList), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.MethodCallEmptyArgument), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OtherAfterControlFlowKeyword), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OtherBetweenParenthesisExpression), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OtherParenthesisTypeCast), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OtherParenControlFlow), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OtherParenAfterCast), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OtherSpacesDeclarationIgnore), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SquareBracesBefore), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SquareBracesEmpty), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SquareBracesAndValue), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersAfterColonInTypeDeclaration), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersAfterCommaInParameterArgument), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersAfterDotMemberAccessQualifiedName), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersAfterSemiColonInForStatement), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersBeforeColonInTypeDeclaration), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersBeforeCommaInParameterArgument), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersBeforeDotMemberAccessQualifiedName), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.DelimitersBeforeSemiColonInForStatement), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpacingAroundBinaryOperator), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenCloseBracesIndent), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.IndentBlock), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.IndentSwitchSection), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.IndentSwitchCaseSection), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.LabelPositioning), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.LeaveStatementMethodDeclarationSameLine), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenBracesInNewLineForTypes), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenBracesInNewLineForMethods), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenBracesInNewLineForAnonymousMethods), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenBracesInNewLineForControl), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenBracesInNewLineForAnonymousType), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenBracesInNewLineForObjectInitializers), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.OpenBracesInNewLineForLambda), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForElse), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForCatch), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForFinally), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForMembersInObjectInit), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForMembersInAnonymousTypes), new Lazy<Options.IOption>( () => Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForClausesInQuery), // Recommendation service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpRecommendationService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.Recommendations.IRecommendationService), ServiceLayer.Default)), // Command line arguments service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpCommandLineArgumentsFactoryService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ICommandLineArgumentsFactoryService), ServiceLayer.Default)), // Compilation factory service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpCompilationFactoryService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ICompilationFactoryService), ServiceLayer.Default)), // Project File Loader service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpProjectFileLoaderService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.Host.ProjectFileLoader.IProjectFileLoaderLanguageService), ServiceLayer.Default)), // Semantic Facts service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpSemanticFactsService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ISemanticFactsService), ServiceLayer.Default)), // Symbol Declaration service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpSymbolDeclarationService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ISymbolDeclarationService), ServiceLayer.Default)), // Syntax Facts service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpSyntaxFactsService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ISyntaxFactsService), ServiceLayer.Default)), // SyntaxTree Factory service new Lazy<ILanguageServiceFactory, LanguageServiceMetadata>( () => new CSharpSyntaxTreeFactoryServiceFactory(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ISyntaxTreeFactoryService), ServiceLayer.Default)), // SyntaxVersion service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpSyntaxVersionService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ISyntaxVersionLanguageService), ServiceLayer.Default)), // Type Inference service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new CSharpTypeInferenceService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.LanguageServices.ITypeInferenceService), ServiceLayer.Default)), // Rename conflicts service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Rename.CSharpRenameConflictLanguageService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.Rename.IRenameRewriterLanguageService), ServiceLayer.Default)), // Simplification service new Lazy<ILanguageService, LanguageServiceMetadata>( () => new Microsoft.CodeAnalysis.CSharp.Simplification.CSharpSimplificationService(), new LanguageServiceMetadata(LanguageNames.CSharp, typeof(Microsoft.CodeAnalysis.Simplification.ISimplificationService), ServiceLayer.Default)) }; } } #endif }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/CSharp/Impl/ProjectSystemShim/Interop/ICSError.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("4CEEE5D4-FBB0-42ac-B558-5D764C8240C7")] internal interface ICSError { // members not ported } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("4CEEE5D4-FBB0-42ac-B558-5D764C8240C7")] internal interface ICSError { // members not ported } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Test/Semantic/Semantics/StackAllocInitializerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.StackAllocInitializer)] public class StackAllocInitializerTests : CompilingTestBase { [Fact, WorkItem(33945, "https://github.com/dotnet/roslyn/issues/33945")] public void RestrictedTypesAllowedInStackalloc() { var comp = CreateCompilationWithMscorlibAndSpan(@" public ref struct RefS { } public ref struct RefG<T> { public T field; } class C { unsafe void M() { var x1 = stackalloc RefS[10]; var x2 = stackalloc RefG<string>[10]; var x3 = stackalloc RefG<int>[10]; var x4 = stackalloc System.TypedReference[10]; // Note: this should be disallowed by adding a dummy field to the ref assembly for TypedReference var x5 = stackalloc System.ArgIterator[10]; var x6 = stackalloc System.RuntimeArgumentHandle[10]; var y1 = new RefS[10]; var y2 = new RefG<string>[10]; var y3 = new RefG<int>[10]; var y4 = new System.TypedReference[10]; var y5 = new System.ArgIterator[10]; var y6 = new System.RuntimeArgumentHandle[10]; RefS[] z1 = null; RefG<string>[] z2 = null; RefG<int>[] z3 = null; System.TypedReference[] z4 = null; System.ArgIterator[] z5 = null; System.RuntimeArgumentHandle[] z6 = null; _ = z1; _ = z2; _ = z3; _ = z4; _ = z5; _ = z6; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (10,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('RefG<string>') // var x2 = stackalloc RefG<string>[10]; Diagnostic(ErrorCode.ERR_ManagedAddr, "RefG<string>").WithArguments("RefG<string>").WithLocation(10, 29), // (16,22): error CS0611: Array elements cannot be of type 'RefS' // var y1 = new RefS[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(16, 22), // (17,22): error CS0611: Array elements cannot be of type 'RefG<string>' // var y2 = new RefG<string>[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(17, 22), // (18,22): error CS0611: Array elements cannot be of type 'RefG<int>' // var y3 = new RefG<int>[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(18, 22), // (19,22): error CS0611: Array elements cannot be of type 'TypedReference' // var y4 = new System.TypedReference[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(19, 22), // (20,22): error CS0611: Array elements cannot be of type 'ArgIterator' // var y5 = new System.ArgIterator[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(20, 22), // (21,22): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle' // var y6 = new System.RuntimeArgumentHandle[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(21, 22), // (23,9): error CS0611: Array elements cannot be of type 'RefS' // RefS[] z1 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(23, 9), // (24,9): error CS0611: Array elements cannot be of type 'RefG<string>' // RefG<string>[] z2 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(24, 9), // (25,9): error CS0611: Array elements cannot be of type 'RefG<int>' // RefG<int>[] z3 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(25, 9), // (26,9): error CS0611: Array elements cannot be of type 'TypedReference' // System.TypedReference[] z4 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(26, 9), // (27,9): error CS0611: Array elements cannot be of type 'ArgIterator' // System.ArgIterator[] z5 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(27, 9), // (28,9): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle' // System.RuntimeArgumentHandle[] z6 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(28, 9) ); } [Fact] public void NoBestType_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { struct A {} struct B {} void Method(dynamic d, RefStruct r) { var p0 = stackalloc[] { new A(), new B() }; var p1 = stackalloc[] { }; var p2 = stackalloc[] { VoidMethod() }; var p3 = stackalloc[] { null }; var p4 = stackalloc[] { (1, null) }; var p5 = stackalloc[] { () => { } }; var p6 = stackalloc[] { new {} , new { i = 0 } }; var p7 = stackalloc[] { d }; var p8 = stackalloc[] { _ }; } public void VoidMethod() {} } namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 a, T2 b) => throw null; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // void Method(dynamic d, RefStruct r) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "RefStruct").WithArguments("RefStruct").WithLocation(7, 28), // (9,18): error CS0826: No best type found for implicitly-typed array // var p0 = stackalloc[] { new A(), new B() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var p1 = stackalloc[] { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var p2 = stackalloc[] { VoidMethod() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 18), // (12,18): error CS0826: No best type found for implicitly-typed array // var p3 = stackalloc[] { null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 18), // (13,18): error CS0826: No best type found for implicitly-typed array // var p4 = stackalloc[] { (1, null) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var p5 = stackalloc[] { () => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { () => { } }").WithLocation(14, 18), // (15,18): error CS0826: No best type found for implicitly-typed array // var p6 = stackalloc[] { new {} , new { i = 0 } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 18), // (16,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var p7 = stackalloc[] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 18), // (17,33): error CS0103: The name '_' does not exist in the current context // var p8 = stackalloc[] { _ }; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 33) ); } [Fact] public void NoBestType_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { struct A {} struct B {} void Method(dynamic d, bool c) { var p0 = c ? default : stackalloc[] { new A(), new B() }; var p1 = c ? default : stackalloc[] { }; var p2 = c ? default : stackalloc[] { VoidMethod() }; var p3 = c ? default : stackalloc[] { null }; var p4 = c ? default : stackalloc[] { (1, null) }; var p5 = c ? default : stackalloc[] { () => { } }; var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } }; var p7 = c ? default : stackalloc[] { d }; var p8 = c ? default : stackalloc[] { _ }; } public void VoidMethod() {} } namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 a, T2 b) => throw null; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (9,32): error CS0826: No best type found for implicitly-typed array // var p0 = c ? default : stackalloc[] { new A(), new B() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 32), // (10,32): error CS0826: No best type found for implicitly-typed array // var p1 = c ? default : stackalloc[] { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 32), // (11,32): error CS0826: No best type found for implicitly-typed array // var p2 = c ? default : stackalloc[] { VoidMethod() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 32), // (12,32): error CS0826: No best type found for implicitly-typed array // var p3 = c ? default : stackalloc[] { null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 32), // (13,32): error CS0826: No best type found for implicitly-typed array // var p4 = c ? default : stackalloc[] { (1, null) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 32), // (14,32): error CS0826: No best type found for implicitly-typed array // var p5 = c ? default : stackalloc[] { () => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { () => { } }").WithLocation(14, 32), // (15,32): error CS0826: No best type found for implicitly-typed array // var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 32), // (16,32): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var p7 = c ? default : stackalloc[] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 32), // (17,47): error CS0103: The name '_' does not exist in the current context // var p8 = c ? default : stackalloc[] { _ }; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 47) ); } [Fact] public void InitializeWithSelf_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void Method1() { var obj1 = stackalloc int[1] { obj1 }; var obj2 = stackalloc int[ ] { obj2 }; var obj3 = stackalloc [ ] { obj3 }; } void Method2() { var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,40): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[1] { obj1 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 40), // (7,40): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 40), // (8,40): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 40), // (13,40): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 40), // (13,50): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 50), // (14,40): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 40), // (14,50): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 50), // (15,40): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 40), // (15,50): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 50) ); } [Fact] public void InitializeWithSelf_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void Method1(bool c) { var obj1 = c ? default : stackalloc int[1] { obj1 }; var obj2 = c ? default : stackalloc int[ ] { obj2 }; var obj3 = c ? default : stackalloc [ ] { obj3 }; } void Method2(bool c) { var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,54): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[1] { obj1 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 54), // (7,54): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 54), // (8,54): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 54), // (13,54): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 54), // (13,64): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 64), // (14,54): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 54), // (14,64): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 64), // (15,54): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 54), // (15,64): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 64) ); } [Fact] public void BadBestType_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { ref struct S {} void Method1(S s) { var obj1 = stackalloc[] { """" }; var obj2 = stackalloc[] { new {} }; var obj3 = stackalloc[] { s }; // OK } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // var obj1 = stackalloc[] { "" }; Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 20), // (8,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>') // var obj2 = stackalloc[] { new {} }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 20) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.String*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.String*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.String", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("<empty anonymous type>*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("Test.S*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("Test.S*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); } [Fact] public void BadBestType_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { ref struct S {} void Method1(S s, bool c) { var obj1 = c ? default : stackalloc[] { """" }; var obj2 = c ? default : stackalloc[] { new {} }; var obj3 = c ? default : stackalloc[] { s }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // var obj1 = c ? default : stackalloc[] { "" }; Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 34), // (8,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>') // var obj2 = c ? default : stackalloc[] { new {} }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 34), // (9,34): error CS0306: The type 'Test.S' may not be used as a type argument // var obj3 = c ? default : stackalloc[] { s }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "stackalloc[] { s }").WithArguments("Test.S").WithLocation(9, 34) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.String>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.String>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.String", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<Test.S>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<Test.S>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); } [Fact] public void TestFor_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { static void Method1() { int i = 0; for (var p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method2() { int i = 0; for (var p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method3() { int i = 0; for (var p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } public static void Main() { Method1(); Method2(); Method3(); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "123123123", verify: Verification.Fails); } [Fact] public void TestFor_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { static void Method1() { int i = 0; for (Span<int> p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method2() { int i = 0; for (Span<int> p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method3() { int i = 0; for (Span<int> p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } public static void Main() { Method1(); Method2(); Method3(); } }", TestOptions.DebugExe); comp.VerifyDiagnostics(); } [Fact] public void TestForTernary() { var comp = CreateCompilationWithMscorlibAndSpan(@" class Test { static void Method1(bool b) { for (var p = b ? stackalloc int[3] { 1, 2, 3 } : default; false;) {} for (var p = b ? stackalloc int[ ] { 1, 2, 3 } : default; false;) {} for (var p = b ? stackalloc [ ] { 1, 2, 3 } : default; false;) {} } }", TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [Fact] public void TestLock() { var source = @" class Test { static void Method1() { lock (stackalloc int[3] { 1, 2, 3 }) {} lock (stackalloc int[ ] { 1, 2, 3 }) {} lock (stackalloc [ ] { 1, 2, 3 }) {} } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (6,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 15), // (6,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int*").WithLocation(6, 15), // (7,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 15), // (7,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(7, 15), // (8,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 15), // (8,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(8, 15) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (6,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 15), // (7,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 15), // (8,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 15) ); } [Fact] public void TestSelect() { var source = @" using System.Linq; class Test { static void Method1(int[] array) { var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (7,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 44), // (8,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 44), // (9,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 44) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (7,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 37), // (8,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 37), // (9,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(9, 37) ); } [Fact] public void TestLet() { var source = @" using System.Linq; class Test { static void Method1(int[] array) { var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (7,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 45), // (8,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 45), // (9,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 45) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (7,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(7, 75), // (8,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(8, 75), // (9,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(9, 75) ); } [Fact] public void TestAwait_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System.Threading.Tasks; unsafe class Test { async void M() { var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,32): error CS4004: Cannot await in an unsafe context // var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(1)").WithLocation(7, 32), // (7,60): error CS4004: Cannot await in an unsafe context // var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(2)").WithLocation(7, 60) ); } [Fact] public void TestAwait_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; using System.Threading.Tasks; class Test { async void M() { Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (8,38): error CS0150: A constant value is expected // Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_ConstantExpected, "await Task.FromResult(1)").WithLocation(8, 38), // (8,9): error CS4012: Parameters or locals of type 'Span<int>' cannot be declared in async methods or async lambda expressions. // Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "Span<int>").WithArguments("System.Span<int>").WithLocation(8, 9) ); } [Fact] public void TestSelfInSize() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void M() { var x = stackalloc int[x] { }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,32): error CS0841: Cannot use local variable 'x' before it is declared // var x = stackalloc int[x] { }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 32) ); } [Fact] public void WrongLength() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[10] { }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,20): error CS0847: An array initializer of length '10' is expected // var obj1 = stackalloc int[10] { }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc int[10] { }").WithArguments("10").WithLocation(6, 20) ); } [Fact] public void NoInit() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[]; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,34): error CS1586: Array creation must have array size or array initializer // var obj1 = stackalloc int[]; Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 34) ); } [Fact] public void NestedInit() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[1] { { 42 } }; var obj2 = stackalloc int[ ] { { 42 } }; var obj3 = stackalloc [ ] { { 42 } }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj1 = stackalloc int[1] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(6, 40), // (7,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj2 = stackalloc int[ ] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(7, 40), // (8,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj3 = stackalloc [ ] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(8, 40) ); } [Fact] public void AsStatement() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { stackalloc[] {1}; stackalloc int[] {1}; stackalloc int[1] {1}; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc[] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc[] {1}").WithLocation(6, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc int[] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[] {1}").WithLocation(7, 9), // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc int[1] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[1] {1}").WithLocation(8, 9) ); } [Fact] public void BadRank() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[][] { 1 }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]') // var obj1 = stackalloc int[][] { 1 }; Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(6, 31), // (6,31): error CS1575: A stackalloc expression requires [] after type // var obj1 = stackalloc int[][] { 1 }; Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[][]").WithLocation(6, 31) ); } [Fact] public void BadDimension() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[,] { 1 }; var obj2 = stackalloc [,] { 1 }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,35): error CS8381: "Invalid rank specifier: expected ']' // var obj2 = stackalloc [,] { 1 }; Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(7, 35), // (6,31): error CS1575: A stackalloc expression requires [] after type // var obj1 = stackalloc int[,] { 1 }; Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[,]").WithLocation(6, 31) ); } [Fact] public void TestFlowPass1() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { int i, j, k; var obj1 = stackalloc int [1] { i = 1 }; var obj2 = stackalloc int [ ] { j = 2 }; var obj3 = stackalloc [ ] { k = 3 }; Console.Write(i); Console.Write(j); Console.Write(k); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestFlowPass2() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public static void Main() { int i, j, k; var obj1 = stackalloc int [1] { i }; var obj2 = stackalloc int [ ] { j }; var obj3 = stackalloc [ ] { k }; } }", TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,41): error CS0165: Use of unassigned local variable 'i' // var obj1 = stackalloc int [1] { i }; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(7, 41), // (8,41): error CS0165: Use of unassigned local variable 'j' // var obj2 = stackalloc int [ ] { j }; Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j").WithLocation(8, 41), // (9,41): error CS0165: Use of unassigned local variable 'k' // var obj3 = stackalloc [ ] { k }; Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k").WithLocation(9, 41) ); } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Implicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { Test obj1 = stackalloc int[3] { 1, 2, 3 }; var obj2 = stackalloc int[3] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[3] { 1, 2, 3 }; int* obj4 = stackalloc int[3] { 1, 2, 3 }; double* obj5 = stackalloc int[3] { 1, 2, 3 }; } public void Method2() { Test obj1 = stackalloc int[] { 1, 2, 3 }; var obj2 = stackalloc int[] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[] { 1, 2, 3 }; int* obj4 = stackalloc int[] { 1, 2, 3 }; double* obj5 = stackalloc int[] { 1, 2, 3 }; } public void Method3() { Test obj1 = stackalloc[] { 1, 2, 3 }; var obj2 = stackalloc[] { 1, 2, 3 }; Span<int> obj3 = stackalloc[] { 1, 2, 3 }; int* obj4 = stackalloc[] { 1, 2, 3 }; double* obj5 = stackalloc[] { 1, 2, 3 }; } public static implicit operator Test(int* value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24), // (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24), // (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(15, variables.Count()); for (int i = 0; i < 15; i += 5) { var obj1 = variables.ElementAt(i); Assert.Equal("obj1", obj1.Identifier.Text); var obj1Value = model.GetSemanticInfoSummary(obj1.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj1Value.Type).PointedAtType.SpecialType); Assert.Equal("Test", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.ImplicitUserDefined, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(i + 1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(i + 2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(i + 3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(i + 4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Explicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { Test obj1 = (Test)stackalloc int[3] { 1, 2, 3 }; var obj2 = stackalloc int[3] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[3] { 1, 2, 3 }; int* obj4 = stackalloc int[3] { 1, 2, 3 }; double* obj5 = stackalloc int[3] { 1, 2, 3 }; } public void Method2() { Test obj1 = (Test)stackalloc int[] { 1, 2, 3 }; var obj2 = stackalloc int[] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[] { 1, 2, 3 }; int* obj4 = stackalloc int[] { 1, 2, 3 }; double* obj5 = stackalloc int[] { 1, 2, 3 }; } public void Method3() { Test obj1 = (Test)stackalloc [] { 1, 2, 3 }; var obj2 = stackalloc[] { 1, 2, 3 }; Span<int> obj3 = stackalloc [] { 1, 2, 3 }; int* obj4 = stackalloc[] { 1, 2, 3 }; double* obj5 = stackalloc[] { 1, 2, 3 }; } public static explicit operator Test(Span<int> value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24), // (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24), // (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(15, variables.Count()); for (int i = 0; i < 15; i += 5) { var obj1 = variables.ElementAt(i); Assert.Equal("obj1", obj1.Identifier.Text); Assert.Equal(SyntaxKind.CastExpression, obj1.Initializer.Value.Kind()); var obj1Value = model.GetSemanticInfoSummary(((CastExpressionSyntax)obj1.Initializer.Value).Expression); Assert.Equal("Span", obj1Value.Type.Name); Assert.Equal("Span", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(i + 1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(i + 2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(i + 3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(i + 4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } } [Fact] public void ConversionError() { CreateCompilationWithMscorlibAndSpan(@" class Test { void Method1() { double x = stackalloc int[3] { 1, 2, 3 }; // implicit short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit } void Method2() { double x = stackalloc int[] { 1, 2, 3 }; // implicit short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit } void Method3() { double x = stackalloc[] { 1, 2, 3 }; // implicit short y = (short)stackalloc[] { 1, 2, 3 }; // explicit } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[3] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(6, 20), // (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(7, 19), // (12,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(12, 20), // (13,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(13, 19), // (18,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc[] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(18, 20), // (19,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc[] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(19, 19) ); } [Fact] public void MissingSpanType() { CreateCompilation(@" class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; } }").VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(6, 9), // (6,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(6, 24), // (7,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(7, 9), // (7,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(7, 24), // (8,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(8, 9), // (8,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(8, 24) ); } [Fact] public void MissingSpanConstructor() { CreateCompilation(@" namespace System { ref struct Span<T> { } class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; } } }").VerifyEmitDiagnostics( // (11,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(11, 28), // (12,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(12, 28), // (13,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(13, 28) ); } [Fact] public void ConditionalExpressionOnSpan_BothStackallocSpans() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3 } : stackalloc int [3] { 1, 2, 3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : stackalloc int [ ] { 1, 2, 3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : stackalloc [ ] { 1, 2, 3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_Convertible() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3 } : (Span<int>)stackalloc int [3] { 1, 2, 3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : (Span<int>)stackalloc int [ ] { 1, 2, 3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : (Span<int>)stackalloc [ ] { 1, 2, 3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_NoCast() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(7, 59), // (8,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(8, 59), // (9,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(9, 59) ); } [Fact] public void ConditionalExpressionOnSpan_CompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a1; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a2; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a3; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_IncompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<short> a = stackalloc short [10]; var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [3] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(8, 18), // (9,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(9, 18), // (10,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(10, 18) ); } [Fact] public void ConditionalExpressionOnSpan_Nested() { CreateCompilationWithMscorlibAndSpan(@" class Test { bool N() => true; void M() { var x = N() ? N() ? stackalloc int[1] { 42 } : stackalloc int[ ] { 42 } : N() ? stackalloc[] { 42 } : N() ? stackalloc int[2] : stackalloc int[3]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void BooleanOperatorOnSpan_NoTargetTyping() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { } if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { } if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { } } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(6, 13), // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(7, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(8, 13) ); } [Fact] public void StackAllocInitializerSyntaxProducesErrorsOnEarlierVersions() { var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7); CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> x1 = stackalloc int [3] { 1, 2, 3 }; Span<int> x2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> x3 = stackalloc [ ] { 1, 2, 3 }; } }", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics( // (7,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(7, 24), // (8,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(8, 24), // (9,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(9, 24) ); } [Fact] public void StackAllocSyntaxProducesUnsafeErrorInSafeCode() { CreateCompilation(@" class Test { void M() { var x1 = stackalloc int [3] { 1, 2, 3 }; var x2 = stackalloc int [ ] { 1, 2, 3 }; var x3 = stackalloc [ ] { 1, 2, 3 }; } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 18), // (7,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 18), // (8,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 18) ); } [Fact] public void StackAllocInUsing1() { var test = @" public class Test { unsafe public static void Main() { using (var v1 = stackalloc int [3] { 1, 2, 3 }) using (var v2 = stackalloc int [ ] { 1, 2, 3 }) using (var v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v1 = stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 16), // (7,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v2 = stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 16), // (8,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v3 = stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 16) ); } [Fact] public void StackAllocInUsing2() { var test = @" public class Test { unsafe public static void Main() { using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 }) using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 }) using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [3] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(6, 40), // (7,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(7, 40), // (8,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(8, 40) ); } [Fact] public void StackAllocInFixed() { var test = @" public class Test { unsafe public static void Main() { fixed (int* v1 = stackalloc int [3] { 1, 2, 3 }) fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 }) fixed (int* v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 26), // (7,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 26), // (8,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 26) ); } [Fact] public void ConstStackAllocExpression() { var test = @" unsafe public class Test { void M() { const int* p1 = stackalloc int [3] { 1, 2, 3 }; const int* p2 = stackalloc int [ ] { 1, 2, 3 }; const int* p3 = stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilation(test, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (6,15): error CS0283: The type 'int*' cannot be declared const // const int* p1 = stackalloc int[1] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(6, 15), // (7,15): error CS0283: The type 'int*' cannot be declared const // const int* p2 = stackalloc int[] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(7, 15), // (8,15): error CS0283: The type 'int*' cannot be declared const // const int* p3 = stackalloc [] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(8, 15) ); } [Fact] public void RefStackAllocAssignment_ValueToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p1 = stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 23), // (7,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 28), // (8,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p2 = stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 23), // (8,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 28), // (9,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p3 = stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 23), // (9,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 28) ); } [Fact] public void RefStackAllocAssignment_RefToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 }; ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 }; ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 32), // (8,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 32), // (9,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 32) ); } [Fact] public void InvalidPositionForStackAllocSpan() { var test = @" using System; public class Test { void M() { N(stackalloc int [3] { 1, 2, 3 }); N(stackalloc int [ ] { 1, 2, 3 }); N(stackalloc [ ] { 1, 2, 3 }); } void N(Span<int> span) { } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 11), // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11), // (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void CannotDotIntoStackAllocExpression() { var test = @" public class Test { void M() { int length1 = (stackalloc int [3] { 1, 2, 3 }).Length; int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length; int length3 = (stackalloc [ ] { 1, 2, 3 }).Length; int length4 = stackalloc int [3] { 1, 2, 3 }.Length; int length5 = stackalloc int [ ] { 1, 2, 3 }.Length; int length6 = stackalloc [ ] { 1, 2, 3 }.Length; } } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length1 = (stackalloc int [3] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 24), // (7,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 24), // (8,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length3 = (stackalloc [ ] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 24), // (10,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length4 = stackalloc int [3] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 23), // (11,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length5 = stackalloc int [ ] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(11, 23), // (12,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length6 = stackalloc [ ] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(12, 23) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll).VerifyDiagnostics( ); } [Fact] public void OverloadResolution_Fail() { var test = @" using System; unsafe public class Test { static void Main() { Invoke(stackalloc int [3] { 1, 2, 3 }); Invoke(stackalloc int [ ] { 1, 2, 3 }); Invoke(stackalloc [ ] { 1, 2, 3 }); } static void Invoke(Span<short> shortSpan) => Console.WriteLine(""shortSpan""); static void Invoke(Span<bool> boolSpan) => Console.WriteLine(""boolSpan""); static void Invoke(int* intPointer) => Console.WriteLine(""intPointer""); static void Invoke(void* voidPointer) => Console.WriteLine(""voidPointer""); } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 16), // (8,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 16), // (9,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 16) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe).VerifyDiagnostics( // (7,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(7, 16), // (8,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(8, 16), // (9,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(9, 16) ); } [Fact] public void StackAllocWithDynamic() { CreateCompilation(@" class Program { static void Main() { dynamic d = 1; var d1 = stackalloc dynamic [3] { d }; var d2 = stackalloc dynamic [ ] { d }; var d3 = stackalloc [ ] { d }; } }").VerifyDiagnostics( // (7,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(7, 29), // (7,18): error CS0847: An array initializer of length '3' is expected // var d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(7, 18), // (8,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d2 = stackalloc dynamic [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 29), // (9,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(9, 18), // (9,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { d }").WithLocation(9, 18) ); } [Fact] public void StackAllocWithDynamicSpan() { CreateCompilationWithMscorlibAndSpan(@" using System; class Program { static void Main() { dynamic d = 1; Span<dynamic> d1 = stackalloc dynamic [3] { d }; Span<dynamic> d2 = stackalloc dynamic [ ] { d }; Span<dynamic> d3 = stackalloc [ ] { d }; } }").VerifyDiagnostics( // (8,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 39), // (8,28): error CS0847: An array initializer of length '3' is expected // Span<dynamic> d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(8, 28), // (9,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d2 = stackalloc dynamic [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(9, 39), // (10,28): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(10, 28) ); } [Fact] public void StackAllocAsArgument() { var source = @" class Program { static void N(object p) { } static void Main() { N(stackalloc int [3] { 1, 2, 3 }); N(stackalloc int [ ] { 1, 2, 3 }); N(stackalloc [ ] { 1, 2, 3 }); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11), // (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11), // (10,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 11) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(8, 11), // (9,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(9, 11), // (10,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(10, 11) ); } [Fact] public void StackAllocInParenthesis() { var source = @" class Program { static void Main() { var x1 = (stackalloc int [3] { 1, 2, 3 }); var x2 = (stackalloc int [ ] { 1, 2, 3 }); var x3 = (stackalloc [ ] { 1, 2, 3 }); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = (stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 19), // (7,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = (stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 19), // (8,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = (stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 19) ); CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void StackAllocInNullConditionalOperator() { var source = @" class Program { static void Main() { var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 18), // (6,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 52), // (7,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 18), // (7,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 52), // (8,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 18), // (8,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 52) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(6, 18), // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(7, 18), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(8, 18) ); } [Fact] public void StackAllocInCastAndConditionalOperator() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public void Method() { Test value1 = true ? new Test() : (Test)stackalloc int [3] { 1, 2, 3 }; Test value2 = true ? new Test() : (Test)stackalloc int [ ] { 1, 2, 3 }; Test value3 = true ? new Test() : (Test)stackalloc [ ] { 1, 2, 3 }; } public static explicit operator Test(Span<int> value) { return new Test(); } }", TestOptions.ReleaseDll).VerifyDiagnostics(); } [Fact] public void ERR_StackallocInCatchFinally_Catch() { var text = @" unsafe class C { int x = M(() => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err11 = stackalloc int [3] { 1, 2, 3 }; int* err12 = stackalloc int [ ] { 1, 2, 3 }; int* err13 = stackalloc [ ] { 1, 2, 3 }; } }; } catch { int* err21 = stackalloc int [3] { 1, 2, 3 }; int* err22 = stackalloc int [ ] { 1, 2, 3 }; int* err23 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err31 = stackalloc int [3] { 1, 2, 3 }; int* err32 = stackalloc int [ ] { 1, 2, 3 }; int* err33 = stackalloc [ ] { 1, 2, 3 }; } }; } }); static int M(System.Action action) { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err41 = stackalloc int [3] { 1, 2, 3 }; int* err42 = stackalloc int [ ] { 1, 2, 3 }; int* err43 = stackalloc [ ] { 1, 2, 3 }; } }; } catch { int* err51 = stackalloc int [3] { 1, 2, 3 }; int* err52 = stackalloc int [ ] { 1, 2, 3 }; int* err53 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err61 = stackalloc int [3] { 1, 2, 3 }; int* err62 = stackalloc int [ ] { 1, 2, 3 }; int* err63 = stackalloc [ ] { 1, 2, 3 }; } }; } return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (23,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err11 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34), // (24,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err12 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34), // (25,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err13 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34), // (31,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err21 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26), // (32,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err22 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26), // (33,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err23 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26), // (45,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err31 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34), // (46,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err32 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34), // (47,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err33 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34), // (72,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err41 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34), // (73,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err42 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34), // (74,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err43 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34), // (80,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err51 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26), // (81,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err52 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26), // (82,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err53 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26), // (94,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err61 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34), // (95,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err62 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34), // (96,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err63 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34) ); } [Fact] public void ERR_StackallocInCatchFinally_Finally() { var text = @" unsafe class C { int x = M(() => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err11 = stackalloc int [3] { 1, 2, 3 }; int* err12 = stackalloc int [ ] { 1, 2, 3 }; int* err13 = stackalloc [ ] { 1, 2, 3 }; } }; } finally { int* err21 = stackalloc int [3] { 1, 2, 3 }; int* err22 = stackalloc int [ ] { 1, 2, 3 }; int* err23 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err31 = stackalloc int [3] { 1, 2, 3 }; int* err32 = stackalloc int [ ] { 1, 2, 3 }; int* err33 = stackalloc [ ] { 1, 2, 3 }; } }; } }); static int M(System.Action action) { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err41 = stackalloc int [3] { 1, 2, 3 }; int* err42 = stackalloc int [ ] { 1, 2, 3 }; int* err43 = stackalloc [ ] { 1, 2, 3 }; } }; } finally { int* err51 = stackalloc int [3] { 1, 2, 3 }; int* err52 = stackalloc int [ ] { 1, 2, 3 }; int* err53 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err61 = stackalloc int [3] { 1, 2, 3 }; int* err62 = stackalloc int [ ] { 1, 2, 3 }; int* err63 = stackalloc [ ] { 1, 2, 3 }; } }; } return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (23,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err11 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34), // (24,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err12 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34), // (25,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err13 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34), // (31,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err21 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26), // (32,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err22 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26), // (33,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err23 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26), // (45,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err31 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34), // (46,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err32 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34), // (47,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err33 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34), // (72,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err41 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34), // (73,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err42 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34), // (74,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err43 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34), // (80,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err51 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26), // (81,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err52 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26), // (82,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err53 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26), // (94,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err61 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34), // (95,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err62 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34), // (96,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err63 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34) ); } [Fact] public void StackAllocArrayCreationExpression_Symbols() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { var obj1 = stackalloc double[2] { 1, 1.2 }; Span<double> obj2 = stackalloc double[2] { 1, 1.2 }; _ = stackalloc double[2] { 1, 1.2 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method // _ = stackalloc double[2] { 1, 1.2 }; Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc double[2] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void ImplicitStackAllocArrayCreationExpression_Symbols() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { var obj1 = stackalloc[] { 1, 1.2 }; Span<double> obj2 = stackalloc[] { 1, 1.2 }; _ = stackalloc[] { 1, 1.2 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method // _ = stackalloc[] { 1, 1.2 }; Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc[] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void StackAllocArrayCreationExpression_Symbols_ErrorCase() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,41): error CS0150: A constant value is expected // short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_ConstantExpected, "*obj1").WithLocation(7, 41), // (8,46): error CS0150: A constant value is expected // Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_ConstantExpected, "obj2.Length").WithLocation(8, 46), // (7,42): error CS0165: Use of unassigned local variable 'obj1' // short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 42), // (8,46): error CS0165: Use of unassigned local variable 'obj2' // Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 46) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(2, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int16*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Int16", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int16", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Int16>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("ref System.Int16 System.Span<System.Int16>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", element1Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", sizeInfo.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void ImplicitStackAllocArrayCreationExpression_Symbols_ErrorCase() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { double* obj1 = stackalloc[] { obj1[0], *obj1 }; Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,39): error CS0165: Use of unassigned local variable 'obj1' // double* obj1 = stackalloc[] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 39), // (8,44): error CS0165: Use of unassigned local variable 'obj2' // Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 44) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(2, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("ref System.Double System.Span<System.Double>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Equal("System.Int32 System.Span<System.Double>.Length { get; }", element1Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.StackAllocInitializer)] public class StackAllocInitializerTests : CompilingTestBase { [Fact, WorkItem(33945, "https://github.com/dotnet/roslyn/issues/33945")] public void RestrictedTypesAllowedInStackalloc() { var comp = CreateCompilationWithMscorlibAndSpan(@" public ref struct RefS { } public ref struct RefG<T> { public T field; } class C { unsafe void M() { var x1 = stackalloc RefS[10]; var x2 = stackalloc RefG<string>[10]; var x3 = stackalloc RefG<int>[10]; var x4 = stackalloc System.TypedReference[10]; // Note: this should be disallowed by adding a dummy field to the ref assembly for TypedReference var x5 = stackalloc System.ArgIterator[10]; var x6 = stackalloc System.RuntimeArgumentHandle[10]; var y1 = new RefS[10]; var y2 = new RefG<string>[10]; var y3 = new RefG<int>[10]; var y4 = new System.TypedReference[10]; var y5 = new System.ArgIterator[10]; var y6 = new System.RuntimeArgumentHandle[10]; RefS[] z1 = null; RefG<string>[] z2 = null; RefG<int>[] z3 = null; System.TypedReference[] z4 = null; System.ArgIterator[] z5 = null; System.RuntimeArgumentHandle[] z6 = null; _ = z1; _ = z2; _ = z3; _ = z4; _ = z5; _ = z6; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (10,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('RefG<string>') // var x2 = stackalloc RefG<string>[10]; Diagnostic(ErrorCode.ERR_ManagedAddr, "RefG<string>").WithArguments("RefG<string>").WithLocation(10, 29), // (16,22): error CS0611: Array elements cannot be of type 'RefS' // var y1 = new RefS[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(16, 22), // (17,22): error CS0611: Array elements cannot be of type 'RefG<string>' // var y2 = new RefG<string>[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(17, 22), // (18,22): error CS0611: Array elements cannot be of type 'RefG<int>' // var y3 = new RefG<int>[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(18, 22), // (19,22): error CS0611: Array elements cannot be of type 'TypedReference' // var y4 = new System.TypedReference[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(19, 22), // (20,22): error CS0611: Array elements cannot be of type 'ArgIterator' // var y5 = new System.ArgIterator[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(20, 22), // (21,22): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle' // var y6 = new System.RuntimeArgumentHandle[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(21, 22), // (23,9): error CS0611: Array elements cannot be of type 'RefS' // RefS[] z1 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(23, 9), // (24,9): error CS0611: Array elements cannot be of type 'RefG<string>' // RefG<string>[] z2 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(24, 9), // (25,9): error CS0611: Array elements cannot be of type 'RefG<int>' // RefG<int>[] z3 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(25, 9), // (26,9): error CS0611: Array elements cannot be of type 'TypedReference' // System.TypedReference[] z4 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(26, 9), // (27,9): error CS0611: Array elements cannot be of type 'ArgIterator' // System.ArgIterator[] z5 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(27, 9), // (28,9): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle' // System.RuntimeArgumentHandle[] z6 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(28, 9) ); } [Fact] public void NoBestType_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { struct A {} struct B {} void Method(dynamic d, RefStruct r) { var p0 = stackalloc[] { new A(), new B() }; var p1 = stackalloc[] { }; var p2 = stackalloc[] { VoidMethod() }; var p3 = stackalloc[] { null }; var p4 = stackalloc[] { (1, null) }; var p5 = stackalloc[] { () => { } }; var p6 = stackalloc[] { new {} , new { i = 0 } }; var p7 = stackalloc[] { d }; var p8 = stackalloc[] { _ }; } public void VoidMethod() {} } namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 a, T2 b) => throw null; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // void Method(dynamic d, RefStruct r) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "RefStruct").WithArguments("RefStruct").WithLocation(7, 28), // (9,18): error CS0826: No best type found for implicitly-typed array // var p0 = stackalloc[] { new A(), new B() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var p1 = stackalloc[] { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var p2 = stackalloc[] { VoidMethod() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 18), // (12,18): error CS0826: No best type found for implicitly-typed array // var p3 = stackalloc[] { null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 18), // (13,18): error CS0826: No best type found for implicitly-typed array // var p4 = stackalloc[] { (1, null) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var p5 = stackalloc[] { () => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { () => { } }").WithLocation(14, 18), // (15,18): error CS0826: No best type found for implicitly-typed array // var p6 = stackalloc[] { new {} , new { i = 0 } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 18), // (16,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var p7 = stackalloc[] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 18), // (17,33): error CS0103: The name '_' does not exist in the current context // var p8 = stackalloc[] { _ }; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 33) ); } [Fact] public void NoBestType_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { struct A {} struct B {} void Method(dynamic d, bool c) { var p0 = c ? default : stackalloc[] { new A(), new B() }; var p1 = c ? default : stackalloc[] { }; var p2 = c ? default : stackalloc[] { VoidMethod() }; var p3 = c ? default : stackalloc[] { null }; var p4 = c ? default : stackalloc[] { (1, null) }; var p5 = c ? default : stackalloc[] { () => { } }; var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } }; var p7 = c ? default : stackalloc[] { d }; var p8 = c ? default : stackalloc[] { _ }; } public void VoidMethod() {} } namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 a, T2 b) => throw null; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (9,32): error CS0826: No best type found for implicitly-typed array // var p0 = c ? default : stackalloc[] { new A(), new B() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 32), // (10,32): error CS0826: No best type found for implicitly-typed array // var p1 = c ? default : stackalloc[] { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 32), // (11,32): error CS0826: No best type found for implicitly-typed array // var p2 = c ? default : stackalloc[] { VoidMethod() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 32), // (12,32): error CS0826: No best type found for implicitly-typed array // var p3 = c ? default : stackalloc[] { null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 32), // (13,32): error CS0826: No best type found for implicitly-typed array // var p4 = c ? default : stackalloc[] { (1, null) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 32), // (14,32): error CS0826: No best type found for implicitly-typed array // var p5 = c ? default : stackalloc[] { () => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { () => { } }").WithLocation(14, 32), // (15,32): error CS0826: No best type found for implicitly-typed array // var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 32), // (16,32): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var p7 = c ? default : stackalloc[] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 32), // (17,47): error CS0103: The name '_' does not exist in the current context // var p8 = c ? default : stackalloc[] { _ }; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 47) ); } [Fact] public void InitializeWithSelf_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void Method1() { var obj1 = stackalloc int[1] { obj1 }; var obj2 = stackalloc int[ ] { obj2 }; var obj3 = stackalloc [ ] { obj3 }; } void Method2() { var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,40): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[1] { obj1 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 40), // (7,40): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 40), // (8,40): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 40), // (13,40): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 40), // (13,50): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 50), // (14,40): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 40), // (14,50): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 50), // (15,40): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 40), // (15,50): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 50) ); } [Fact] public void InitializeWithSelf_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void Method1(bool c) { var obj1 = c ? default : stackalloc int[1] { obj1 }; var obj2 = c ? default : stackalloc int[ ] { obj2 }; var obj3 = c ? default : stackalloc [ ] { obj3 }; } void Method2(bool c) { var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,54): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[1] { obj1 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 54), // (7,54): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 54), // (8,54): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 54), // (13,54): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 54), // (13,64): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 64), // (14,54): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 54), // (14,64): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 64), // (15,54): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 54), // (15,64): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 64) ); } [Fact] public void BadBestType_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { ref struct S {} void Method1(S s) { var obj1 = stackalloc[] { """" }; var obj2 = stackalloc[] { new {} }; var obj3 = stackalloc[] { s }; // OK } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // var obj1 = stackalloc[] { "" }; Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 20), // (8,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>') // var obj2 = stackalloc[] { new {} }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 20) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.String*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.String*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.String", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("<empty anonymous type>*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("Test.S*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("Test.S*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); } [Fact] public void BadBestType_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { ref struct S {} void Method1(S s, bool c) { var obj1 = c ? default : stackalloc[] { """" }; var obj2 = c ? default : stackalloc[] { new {} }; var obj3 = c ? default : stackalloc[] { s }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // var obj1 = c ? default : stackalloc[] { "" }; Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 34), // (8,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>') // var obj2 = c ? default : stackalloc[] { new {} }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 34), // (9,34): error CS0306: The type 'Test.S' may not be used as a type argument // var obj3 = c ? default : stackalloc[] { s }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "stackalloc[] { s }").WithArguments("Test.S").WithLocation(9, 34) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.String>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.String>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.String", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<Test.S>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<Test.S>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); } [Fact] public void TestFor_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { static void Method1() { int i = 0; for (var p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method2() { int i = 0; for (var p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method3() { int i = 0; for (var p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } public static void Main() { Method1(); Method2(); Method3(); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "123123123", verify: Verification.Fails); } [Fact] public void TestFor_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { static void Method1() { int i = 0; for (Span<int> p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method2() { int i = 0; for (Span<int> p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method3() { int i = 0; for (Span<int> p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } public static void Main() { Method1(); Method2(); Method3(); } }", TestOptions.DebugExe); comp.VerifyDiagnostics(); } [Fact] public void TestForTernary() { var comp = CreateCompilationWithMscorlibAndSpan(@" class Test { static void Method1(bool b) { for (var p = b ? stackalloc int[3] { 1, 2, 3 } : default; false;) {} for (var p = b ? stackalloc int[ ] { 1, 2, 3 } : default; false;) {} for (var p = b ? stackalloc [ ] { 1, 2, 3 } : default; false;) {} } }", TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [Fact] public void TestLock() { var source = @" class Test { static void Method1() { lock (stackalloc int[3] { 1, 2, 3 }) {} lock (stackalloc int[ ] { 1, 2, 3 }) {} lock (stackalloc [ ] { 1, 2, 3 }) {} } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (6,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 15), // (6,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int*").WithLocation(6, 15), // (7,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 15), // (7,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(7, 15), // (8,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 15), // (8,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(8, 15) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (6,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 15), // (7,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 15), // (8,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 15) ); } [Fact] public void TestSelect() { var source = @" using System.Linq; class Test { static void Method1(int[] array) { var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (7,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 44), // (8,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 44), // (9,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 44) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (7,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 37), // (8,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 37), // (9,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(9, 37) ); } [Fact] public void TestLet() { var source = @" using System.Linq; class Test { static void Method1(int[] array) { var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (7,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 45), // (8,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 45), // (9,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 45) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (7,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(7, 75), // (8,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(8, 75), // (9,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(9, 75) ); } [Fact] public void TestAwait_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System.Threading.Tasks; unsafe class Test { async void M() { var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,32): error CS4004: Cannot await in an unsafe context // var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(1)").WithLocation(7, 32), // (7,60): error CS4004: Cannot await in an unsafe context // var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(2)").WithLocation(7, 60) ); } [Fact] public void TestAwait_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; using System.Threading.Tasks; class Test { async void M() { Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (8,38): error CS0150: A constant value is expected // Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_ConstantExpected, "await Task.FromResult(1)").WithLocation(8, 38), // (8,9): error CS4012: Parameters or locals of type 'Span<int>' cannot be declared in async methods or async lambda expressions. // Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "Span<int>").WithArguments("System.Span<int>").WithLocation(8, 9) ); } [Fact] public void TestSelfInSize() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void M() { var x = stackalloc int[x] { }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,32): error CS0841: Cannot use local variable 'x' before it is declared // var x = stackalloc int[x] { }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 32) ); } [Fact] public void WrongLength() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[10] { }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,20): error CS0847: An array initializer of length '10' is expected // var obj1 = stackalloc int[10] { }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc int[10] { }").WithArguments("10").WithLocation(6, 20) ); } [Fact] public void NoInit() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[]; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,34): error CS1586: Array creation must have array size or array initializer // var obj1 = stackalloc int[]; Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 34) ); } [Fact] public void NestedInit() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[1] { { 42 } }; var obj2 = stackalloc int[ ] { { 42 } }; var obj3 = stackalloc [ ] { { 42 } }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj1 = stackalloc int[1] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(6, 40), // (7,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj2 = stackalloc int[ ] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(7, 40), // (8,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj3 = stackalloc [ ] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(8, 40) ); } [Fact] public void AsStatement() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { stackalloc[] {1}; stackalloc int[] {1}; stackalloc int[1] {1}; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc[] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc[] {1}").WithLocation(6, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc int[] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[] {1}").WithLocation(7, 9), // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc int[1] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[1] {1}").WithLocation(8, 9) ); } [Fact] public void BadRank() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[][] { 1 }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]') // var obj1 = stackalloc int[][] { 1 }; Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(6, 31), // (6,31): error CS1575: A stackalloc expression requires [] after type // var obj1 = stackalloc int[][] { 1 }; Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[][]").WithLocation(6, 31) ); } [Fact] public void BadDimension() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[,] { 1 }; var obj2 = stackalloc [,] { 1 }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,35): error CS8381: "Invalid rank specifier: expected ']' // var obj2 = stackalloc [,] { 1 }; Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(7, 35), // (6,31): error CS1575: A stackalloc expression requires [] after type // var obj1 = stackalloc int[,] { 1 }; Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[,]").WithLocation(6, 31) ); } [Fact] public void TestFlowPass1() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { int i, j, k; var obj1 = stackalloc int [1] { i = 1 }; var obj2 = stackalloc int [ ] { j = 2 }; var obj3 = stackalloc [ ] { k = 3 }; Console.Write(i); Console.Write(j); Console.Write(k); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestFlowPass2() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public static void Main() { int i, j, k; var obj1 = stackalloc int [1] { i }; var obj2 = stackalloc int [ ] { j }; var obj3 = stackalloc [ ] { k }; } }", TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,41): error CS0165: Use of unassigned local variable 'i' // var obj1 = stackalloc int [1] { i }; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(7, 41), // (8,41): error CS0165: Use of unassigned local variable 'j' // var obj2 = stackalloc int [ ] { j }; Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j").WithLocation(8, 41), // (9,41): error CS0165: Use of unassigned local variable 'k' // var obj3 = stackalloc [ ] { k }; Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k").WithLocation(9, 41) ); } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Implicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { Test obj1 = stackalloc int[3] { 1, 2, 3 }; var obj2 = stackalloc int[3] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[3] { 1, 2, 3 }; int* obj4 = stackalloc int[3] { 1, 2, 3 }; double* obj5 = stackalloc int[3] { 1, 2, 3 }; } public void Method2() { Test obj1 = stackalloc int[] { 1, 2, 3 }; var obj2 = stackalloc int[] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[] { 1, 2, 3 }; int* obj4 = stackalloc int[] { 1, 2, 3 }; double* obj5 = stackalloc int[] { 1, 2, 3 }; } public void Method3() { Test obj1 = stackalloc[] { 1, 2, 3 }; var obj2 = stackalloc[] { 1, 2, 3 }; Span<int> obj3 = stackalloc[] { 1, 2, 3 }; int* obj4 = stackalloc[] { 1, 2, 3 }; double* obj5 = stackalloc[] { 1, 2, 3 }; } public static implicit operator Test(int* value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24), // (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24), // (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(15, variables.Count()); for (int i = 0; i < 15; i += 5) { var obj1 = variables.ElementAt(i); Assert.Equal("obj1", obj1.Identifier.Text); var obj1Value = model.GetSemanticInfoSummary(obj1.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj1Value.Type).PointedAtType.SpecialType); Assert.Equal("Test", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.ImplicitUserDefined, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(i + 1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(i + 2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(i + 3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(i + 4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Explicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { Test obj1 = (Test)stackalloc int[3] { 1, 2, 3 }; var obj2 = stackalloc int[3] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[3] { 1, 2, 3 }; int* obj4 = stackalloc int[3] { 1, 2, 3 }; double* obj5 = stackalloc int[3] { 1, 2, 3 }; } public void Method2() { Test obj1 = (Test)stackalloc int[] { 1, 2, 3 }; var obj2 = stackalloc int[] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[] { 1, 2, 3 }; int* obj4 = stackalloc int[] { 1, 2, 3 }; double* obj5 = stackalloc int[] { 1, 2, 3 }; } public void Method3() { Test obj1 = (Test)stackalloc [] { 1, 2, 3 }; var obj2 = stackalloc[] { 1, 2, 3 }; Span<int> obj3 = stackalloc [] { 1, 2, 3 }; int* obj4 = stackalloc[] { 1, 2, 3 }; double* obj5 = stackalloc[] { 1, 2, 3 }; } public static explicit operator Test(Span<int> value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24), // (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24), // (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(15, variables.Count()); for (int i = 0; i < 15; i += 5) { var obj1 = variables.ElementAt(i); Assert.Equal("obj1", obj1.Identifier.Text); Assert.Equal(SyntaxKind.CastExpression, obj1.Initializer.Value.Kind()); var obj1Value = model.GetSemanticInfoSummary(((CastExpressionSyntax)obj1.Initializer.Value).Expression); Assert.Equal("Span", obj1Value.Type.Name); Assert.Equal("Span", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(i + 1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(i + 2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(i + 3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(i + 4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } } [Fact] public void ConversionError() { CreateCompilationWithMscorlibAndSpan(@" class Test { void Method1() { double x = stackalloc int[3] { 1, 2, 3 }; // implicit short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit } void Method2() { double x = stackalloc int[] { 1, 2, 3 }; // implicit short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit } void Method3() { double x = stackalloc[] { 1, 2, 3 }; // implicit short y = (short)stackalloc[] { 1, 2, 3 }; // explicit } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[3] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(6, 20), // (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(7, 19), // (12,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(12, 20), // (13,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(13, 19), // (18,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc[] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(18, 20), // (19,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc[] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(19, 19) ); } [Fact] public void MissingSpanType() { CreateCompilation(@" class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; } }").VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(6, 9), // (6,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(6, 24), // (7,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(7, 9), // (7,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(7, 24), // (8,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(8, 9), // (8,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(8, 24) ); } [Fact] public void MissingSpanConstructor() { CreateCompilation(@" namespace System { ref struct Span<T> { } class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; } } }").VerifyEmitDiagnostics( // (11,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(11, 28), // (12,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(12, 28), // (13,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(13, 28) ); } [Fact] public void ConditionalExpressionOnSpan_BothStackallocSpans() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3 } : stackalloc int [3] { 1, 2, 3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : stackalloc int [ ] { 1, 2, 3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : stackalloc [ ] { 1, 2, 3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_Convertible() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3 } : (Span<int>)stackalloc int [3] { 1, 2, 3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : (Span<int>)stackalloc int [ ] { 1, 2, 3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : (Span<int>)stackalloc [ ] { 1, 2, 3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_NoCast() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(7, 59), // (8,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(8, 59), // (9,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(9, 59) ); } [Fact] public void ConditionalExpressionOnSpan_CompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a1; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a2; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a3; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_IncompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<short> a = stackalloc short [10]; var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [3] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(8, 18), // (9,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(9, 18), // (10,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(10, 18) ); } [Fact] public void ConditionalExpressionOnSpan_Nested() { CreateCompilationWithMscorlibAndSpan(@" class Test { bool N() => true; void M() { var x = N() ? N() ? stackalloc int[1] { 42 } : stackalloc int[ ] { 42 } : N() ? stackalloc[] { 42 } : N() ? stackalloc int[2] : stackalloc int[3]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void BooleanOperatorOnSpan_NoTargetTyping() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { } if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { } if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { } } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(6, 13), // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(7, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(8, 13) ); } [Fact] public void StackAllocInitializerSyntaxProducesErrorsOnEarlierVersions() { var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7); CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> x1 = stackalloc int [3] { 1, 2, 3 }; Span<int> x2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> x3 = stackalloc [ ] { 1, 2, 3 }; } }", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics( // (7,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(7, 24), // (8,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(8, 24), // (9,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(9, 24) ); } [Fact] public void StackAllocSyntaxProducesUnsafeErrorInSafeCode() { CreateCompilation(@" class Test { void M() { var x1 = stackalloc int [3] { 1, 2, 3 }; var x2 = stackalloc int [ ] { 1, 2, 3 }; var x3 = stackalloc [ ] { 1, 2, 3 }; } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 18), // (7,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 18), // (8,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 18) ); } [Fact] public void StackAllocInUsing1() { var test = @" public class Test { unsafe public static void Main() { using (var v1 = stackalloc int [3] { 1, 2, 3 }) using (var v2 = stackalloc int [ ] { 1, 2, 3 }) using (var v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v1 = stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 16), // (7,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v2 = stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 16), // (8,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v3 = stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 16) ); } [Fact] public void StackAllocInUsing2() { var test = @" public class Test { unsafe public static void Main() { using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 }) using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 }) using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [3] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(6, 40), // (7,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(7, 40), // (8,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(8, 40) ); } [Fact] public void StackAllocInFixed() { var test = @" public class Test { unsafe public static void Main() { fixed (int* v1 = stackalloc int [3] { 1, 2, 3 }) fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 }) fixed (int* v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 26), // (7,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 26), // (8,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 26) ); } [Fact] public void ConstStackAllocExpression() { var test = @" unsafe public class Test { void M() { const int* p1 = stackalloc int [3] { 1, 2, 3 }; const int* p2 = stackalloc int [ ] { 1, 2, 3 }; const int* p3 = stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilation(test, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (6,15): error CS0283: The type 'int*' cannot be declared const // const int* p1 = stackalloc int[1] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(6, 15), // (7,15): error CS0283: The type 'int*' cannot be declared const // const int* p2 = stackalloc int[] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(7, 15), // (8,15): error CS0283: The type 'int*' cannot be declared const // const int* p3 = stackalloc [] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(8, 15) ); } [Fact] public void RefStackAllocAssignment_ValueToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p1 = stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 23), // (7,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 28), // (8,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p2 = stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 23), // (8,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 28), // (9,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p3 = stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 23), // (9,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 28) ); } [Fact] public void RefStackAllocAssignment_RefToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 }; ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 }; ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 32), // (8,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 32), // (9,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 32) ); } [Fact] public void InvalidPositionForStackAllocSpan() { var test = @" using System; public class Test { void M() { N(stackalloc int [3] { 1, 2, 3 }); N(stackalloc int [ ] { 1, 2, 3 }); N(stackalloc [ ] { 1, 2, 3 }); } void N(Span<int> span) { } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 11), // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11), // (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void CannotDotIntoStackAllocExpression() { var test = @" public class Test { void M() { int length1 = (stackalloc int [3] { 1, 2, 3 }).Length; int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length; int length3 = (stackalloc [ ] { 1, 2, 3 }).Length; int length4 = stackalloc int [3] { 1, 2, 3 }.Length; int length5 = stackalloc int [ ] { 1, 2, 3 }.Length; int length6 = stackalloc [ ] { 1, 2, 3 }.Length; } } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length1 = (stackalloc int [3] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 24), // (7,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 24), // (8,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length3 = (stackalloc [ ] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 24), // (10,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length4 = stackalloc int [3] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 23), // (11,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length5 = stackalloc int [ ] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(11, 23), // (12,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length6 = stackalloc [ ] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(12, 23) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll).VerifyDiagnostics( ); } [Fact] public void OverloadResolution_Fail() { var test = @" using System; unsafe public class Test { static void Main() { Invoke(stackalloc int [3] { 1, 2, 3 }); Invoke(stackalloc int [ ] { 1, 2, 3 }); Invoke(stackalloc [ ] { 1, 2, 3 }); } static void Invoke(Span<short> shortSpan) => Console.WriteLine(""shortSpan""); static void Invoke(Span<bool> boolSpan) => Console.WriteLine(""boolSpan""); static void Invoke(int* intPointer) => Console.WriteLine(""intPointer""); static void Invoke(void* voidPointer) => Console.WriteLine(""voidPointer""); } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 16), // (8,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 16), // (9,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 16) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe).VerifyDiagnostics( // (7,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(7, 16), // (8,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(8, 16), // (9,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(9, 16) ); } [Fact] public void StackAllocWithDynamic() { CreateCompilation(@" class Program { static void Main() { dynamic d = 1; var d1 = stackalloc dynamic [3] { d }; var d2 = stackalloc dynamic [ ] { d }; var d3 = stackalloc [ ] { d }; } }").VerifyDiagnostics( // (7,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(7, 29), // (7,18): error CS0847: An array initializer of length '3' is expected // var d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(7, 18), // (8,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d2 = stackalloc dynamic [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 29), // (9,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(9, 18), // (9,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { d }").WithLocation(9, 18) ); } [Fact] public void StackAllocWithDynamicSpan() { CreateCompilationWithMscorlibAndSpan(@" using System; class Program { static void Main() { dynamic d = 1; Span<dynamic> d1 = stackalloc dynamic [3] { d }; Span<dynamic> d2 = stackalloc dynamic [ ] { d }; Span<dynamic> d3 = stackalloc [ ] { d }; } }").VerifyDiagnostics( // (8,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 39), // (8,28): error CS0847: An array initializer of length '3' is expected // Span<dynamic> d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(8, 28), // (9,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d2 = stackalloc dynamic [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(9, 39), // (10,28): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(10, 28) ); } [Fact] public void StackAllocAsArgument() { var source = @" class Program { static void N(object p) { } static void Main() { N(stackalloc int [3] { 1, 2, 3 }); N(stackalloc int [ ] { 1, 2, 3 }); N(stackalloc [ ] { 1, 2, 3 }); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11), // (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11), // (10,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 11) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(8, 11), // (9,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(9, 11), // (10,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(10, 11) ); } [Fact] public void StackAllocInParenthesis() { var source = @" class Program { static void Main() { var x1 = (stackalloc int [3] { 1, 2, 3 }); var x2 = (stackalloc int [ ] { 1, 2, 3 }); var x3 = (stackalloc [ ] { 1, 2, 3 }); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = (stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 19), // (7,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = (stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 19), // (8,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = (stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 19) ); CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void StackAllocInNullConditionalOperator() { var source = @" class Program { static void Main() { var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 18), // (6,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 52), // (7,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 18), // (7,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 52), // (8,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 18), // (8,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 52) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(6, 18), // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(7, 18), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(8, 18) ); } [Fact] public void StackAllocInCastAndConditionalOperator() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public void Method() { Test value1 = true ? new Test() : (Test)stackalloc int [3] { 1, 2, 3 }; Test value2 = true ? new Test() : (Test)stackalloc int [ ] { 1, 2, 3 }; Test value3 = true ? new Test() : (Test)stackalloc [ ] { 1, 2, 3 }; } public static explicit operator Test(Span<int> value) { return new Test(); } }", TestOptions.ReleaseDll).VerifyDiagnostics(); } [Fact] public void ERR_StackallocInCatchFinally_Catch() { var text = @" unsafe class C { int x = M(() => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err11 = stackalloc int [3] { 1, 2, 3 }; int* err12 = stackalloc int [ ] { 1, 2, 3 }; int* err13 = stackalloc [ ] { 1, 2, 3 }; } }; } catch { int* err21 = stackalloc int [3] { 1, 2, 3 }; int* err22 = stackalloc int [ ] { 1, 2, 3 }; int* err23 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err31 = stackalloc int [3] { 1, 2, 3 }; int* err32 = stackalloc int [ ] { 1, 2, 3 }; int* err33 = stackalloc [ ] { 1, 2, 3 }; } }; } }); static int M(System.Action action) { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err41 = stackalloc int [3] { 1, 2, 3 }; int* err42 = stackalloc int [ ] { 1, 2, 3 }; int* err43 = stackalloc [ ] { 1, 2, 3 }; } }; } catch { int* err51 = stackalloc int [3] { 1, 2, 3 }; int* err52 = stackalloc int [ ] { 1, 2, 3 }; int* err53 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err61 = stackalloc int [3] { 1, 2, 3 }; int* err62 = stackalloc int [ ] { 1, 2, 3 }; int* err63 = stackalloc [ ] { 1, 2, 3 }; } }; } return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (23,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err11 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34), // (24,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err12 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34), // (25,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err13 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34), // (31,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err21 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26), // (32,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err22 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26), // (33,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err23 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26), // (45,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err31 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34), // (46,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err32 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34), // (47,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err33 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34), // (72,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err41 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34), // (73,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err42 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34), // (74,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err43 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34), // (80,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err51 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26), // (81,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err52 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26), // (82,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err53 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26), // (94,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err61 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34), // (95,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err62 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34), // (96,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err63 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34) ); } [Fact] public void ERR_StackallocInCatchFinally_Finally() { var text = @" unsafe class C { int x = M(() => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err11 = stackalloc int [3] { 1, 2, 3 }; int* err12 = stackalloc int [ ] { 1, 2, 3 }; int* err13 = stackalloc [ ] { 1, 2, 3 }; } }; } finally { int* err21 = stackalloc int [3] { 1, 2, 3 }; int* err22 = stackalloc int [ ] { 1, 2, 3 }; int* err23 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err31 = stackalloc int [3] { 1, 2, 3 }; int* err32 = stackalloc int [ ] { 1, 2, 3 }; int* err33 = stackalloc [ ] { 1, 2, 3 }; } }; } }); static int M(System.Action action) { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err41 = stackalloc int [3] { 1, 2, 3 }; int* err42 = stackalloc int [ ] { 1, 2, 3 }; int* err43 = stackalloc [ ] { 1, 2, 3 }; } }; } finally { int* err51 = stackalloc int [3] { 1, 2, 3 }; int* err52 = stackalloc int [ ] { 1, 2, 3 }; int* err53 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err61 = stackalloc int [3] { 1, 2, 3 }; int* err62 = stackalloc int [ ] { 1, 2, 3 }; int* err63 = stackalloc [ ] { 1, 2, 3 }; } }; } return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (23,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err11 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34), // (24,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err12 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34), // (25,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err13 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34), // (31,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err21 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26), // (32,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err22 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26), // (33,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err23 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26), // (45,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err31 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34), // (46,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err32 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34), // (47,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err33 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34), // (72,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err41 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34), // (73,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err42 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34), // (74,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err43 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34), // (80,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err51 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26), // (81,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err52 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26), // (82,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err53 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26), // (94,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err61 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34), // (95,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err62 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34), // (96,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err63 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34) ); } [Fact] public void StackAllocArrayCreationExpression_Symbols() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { var obj1 = stackalloc double[2] { 1, 1.2 }; Span<double> obj2 = stackalloc double[2] { 1, 1.2 }; _ = stackalloc double[2] { 1, 1.2 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method // _ = stackalloc double[2] { 1, 1.2 }; Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc double[2] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void ImplicitStackAllocArrayCreationExpression_Symbols() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { var obj1 = stackalloc[] { 1, 1.2 }; Span<double> obj2 = stackalloc[] { 1, 1.2 }; _ = stackalloc[] { 1, 1.2 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method // _ = stackalloc[] { 1, 1.2 }; Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc[] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void StackAllocArrayCreationExpression_Symbols_ErrorCase() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,41): error CS0150: A constant value is expected // short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_ConstantExpected, "*obj1").WithLocation(7, 41), // (8,46): error CS0150: A constant value is expected // Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_ConstantExpected, "obj2.Length").WithLocation(8, 46), // (7,42): error CS0165: Use of unassigned local variable 'obj1' // short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 42), // (8,46): error CS0165: Use of unassigned local variable 'obj2' // Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 46) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(2, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int16*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Int16", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int16", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Int16>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("ref System.Int16 System.Span<System.Int16>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", element1Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", sizeInfo.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void ImplicitStackAllocArrayCreationExpression_Symbols_ErrorCase() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { double* obj1 = stackalloc[] { obj1[0], *obj1 }; Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,39): error CS0165: Use of unassigned local variable 'obj1' // double* obj1 = stackalloc[] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 39), // (8,44): error CS0165: Use of unassigned local variable 'obj2' // Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 44) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(2, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("ref System.Double System.Span<System.Double>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Equal("System.Int32 System.Span<System.Double>.Length { get; }", element1Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/Core/Shared/Options/PerformanceFunctionIdOptionsProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Editor.Shared.Options { [ExportOptionProvider, Shared] internal class PerformanceFunctionIdOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PerformanceFunctionIdOptionsProvider() { } public ImmutableArray<IOption> Options { get { using var resultDisposer = ArrayBuilder<IOption>.GetInstance(out var result); foreach (var id in (FunctionId[])Enum.GetValues(typeof(FunctionId))) { result.Add(FunctionIdOptions.GetOption(id)); } return result.ToImmutable(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Editor.Shared.Options { [ExportOptionProvider, Shared] internal class PerformanceFunctionIdOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PerformanceFunctionIdOptionsProvider() { } public ImmutableArray<IOption> Options { get { using var resultDisposer = ArrayBuilder<IOption>.GetInstance(out var result); foreach (var id in (FunctionId[])Enum.GetValues(typeof(FunctionId))) { result.Add(FunctionIdOptions.GetOption(id)); } return result.ToImmutable(); } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/Test/Utilities/CSharp/SymbolUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { internal class NameAndArityComparer : IComparer<NamedTypeSymbol> { public int Compare(NamedTypeSymbol x, NamedTypeSymbol y) // Implements IComparer<NamedTypeSymbol).Compare { int result = StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name); if (result != 0) { return result; } return x.Arity - y.Arity; } } internal static class SymbolUtilities { public static NamespaceSymbol ChildNamespace(this NamespaceSymbol ns, string name) { return ns.GetMembers() .Where(n => n.Name.Equals(name)) .Cast<NamespaceSymbol>() .Single(); } public static NamedTypeSymbol ChildType(this NamespaceSymbol ns, string name) { return ns.GetMembers() .OfType<NamedTypeSymbol>() .Single(n => n.Name.Equals(name)); } public static NamedTypeSymbol ChildType(this NamespaceSymbol ns, string name, int arity) { return ns.GetMembers() .OfType<NamedTypeSymbol>() .Single(n => n.Name.Equals(name) && n.Arity == arity); } public static Symbol ChildSymbol(this NamespaceOrTypeSymbol parent, string name) { return parent.GetMembers(name).First(); } public static T GetIndexer<T>(this NamespaceOrTypeSymbol type, string name) where T : PropertySymbol { T member = type.GetMembers(WellKnownMemberNames.Indexer).Where(i => i.MetadataName == name).Single() as T; Assert.NotNull(member); return member; } public static string ListToSortedString(this List<string> list) { string text = ""; list.Sort(); foreach (var element in list) { text = text + '\n' + element.ToString(); } return text; } public static string ListToSortedString<TSymbol>(this List<TSymbol> listOfSymbols) where TSymbol : ISymbol { string text = ""; List<string> listOfSymbolString = listOfSymbols.Select(e => e.ToTestDisplayString()).ToList(); listOfSymbolString.Sort(); foreach (var symbolString in listOfSymbolString) { text = text + '\n' + symbolString; } return text; } private static SymbolDisplayFormat GetDisplayFormat(bool includeNonNullable) { var format = SymbolDisplayFormat.TestFormat; if (includeNonNullable) { format = format.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier) .WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None); } return format; } public static string ToTestDisplayString(this TypeWithAnnotations type, bool includeNonNullable = false) { SymbolDisplayFormat format = GetDisplayFormat(includeNonNullable); return type.ToDisplayString(format); } public static string[] ToTestDisplayStrings(this IEnumerable<TypeWithAnnotations> types) { return types.Select(t => t.ToTestDisplayString()).ToArray(); } public static string[] ToTestDisplayStrings(this IEnumerable<ISymbol> symbols) { return symbols.Select(s => s.ToTestDisplayString()).ToArray(); } public static string[] ToTestDisplayStrings(this IEnumerable<Symbol> symbols, SymbolDisplayFormat format = null) { format ??= SymbolDisplayFormat.TestFormat; return symbols.Select(s => s.ToDisplayString(format)).ToArray(); } public static string ToTestDisplayString(this ISymbol symbol, bool includeNonNullable) { SymbolDisplayFormat format = GetDisplayFormat(includeNonNullable); return symbol.ToDisplayString(format); } public static string ToTestDisplayString(this Symbol symbol, bool includeNonNullable) { SymbolDisplayFormat format = GetDisplayFormat(includeNonNullable); return symbol.ToDisplayString(format); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { internal class NameAndArityComparer : IComparer<NamedTypeSymbol> { public int Compare(NamedTypeSymbol x, NamedTypeSymbol y) // Implements IComparer<NamedTypeSymbol).Compare { int result = StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name); if (result != 0) { return result; } return x.Arity - y.Arity; } } internal static class SymbolUtilities { public static NamespaceSymbol ChildNamespace(this NamespaceSymbol ns, string name) { return ns.GetMembers() .Where(n => n.Name.Equals(name)) .Cast<NamespaceSymbol>() .Single(); } public static NamedTypeSymbol ChildType(this NamespaceSymbol ns, string name) { return ns.GetMembers() .OfType<NamedTypeSymbol>() .Single(n => n.Name.Equals(name)); } public static NamedTypeSymbol ChildType(this NamespaceSymbol ns, string name, int arity) { return ns.GetMembers() .OfType<NamedTypeSymbol>() .Single(n => n.Name.Equals(name) && n.Arity == arity); } public static Symbol ChildSymbol(this NamespaceOrTypeSymbol parent, string name) { return parent.GetMembers(name).First(); } public static T GetIndexer<T>(this NamespaceOrTypeSymbol type, string name) where T : PropertySymbol { T member = type.GetMembers(WellKnownMemberNames.Indexer).Where(i => i.MetadataName == name).Single() as T; Assert.NotNull(member); return member; } public static string ListToSortedString(this List<string> list) { string text = ""; list.Sort(); foreach (var element in list) { text = text + '\n' + element.ToString(); } return text; } public static string ListToSortedString<TSymbol>(this List<TSymbol> listOfSymbols) where TSymbol : ISymbol { string text = ""; List<string> listOfSymbolString = listOfSymbols.Select(e => e.ToTestDisplayString()).ToList(); listOfSymbolString.Sort(); foreach (var symbolString in listOfSymbolString) { text = text + '\n' + symbolString; } return text; } private static SymbolDisplayFormat GetDisplayFormat(bool includeNonNullable) { var format = SymbolDisplayFormat.TestFormat; if (includeNonNullable) { format = format.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier) .WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None); } return format; } public static string ToTestDisplayString(this TypeWithAnnotations type, bool includeNonNullable = false) { SymbolDisplayFormat format = GetDisplayFormat(includeNonNullable); return type.ToDisplayString(format); } public static string[] ToTestDisplayStrings(this IEnumerable<TypeWithAnnotations> types) { return types.Select(t => t.ToTestDisplayString()).ToArray(); } public static string[] ToTestDisplayStrings(this IEnumerable<ISymbol> symbols) { return symbols.Select(s => s.ToTestDisplayString()).ToArray(); } public static string[] ToTestDisplayStrings(this IEnumerable<Symbol> symbols, SymbolDisplayFormat format = null) { format ??= SymbolDisplayFormat.TestFormat; return symbols.Select(s => s.ToDisplayString(format)).ToArray(); } public static string ToTestDisplayString(this ISymbol symbol, bool includeNonNullable) { SymbolDisplayFormat format = GetDisplayFormat(includeNonNullable); return symbol.ToDisplayString(format); } public static string ToTestDisplayString(this Symbol symbol, bool includeNonNullable) { SymbolDisplayFormat format = GetDisplayFormat(includeNonNullable); return symbol.ToDisplayString(format); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingInvocationReasonsWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal readonly struct UnitTestingInvocationReasonsWrapper { public static readonly UnitTestingInvocationReasonsWrapper SemanticChanged = new(InvocationReasons.SemanticChanged); public static readonly UnitTestingInvocationReasonsWrapper Reanalyze = new(InvocationReasons.Reanalyze); public static readonly UnitTestingInvocationReasonsWrapper ProjectConfigurationChanged = new(InvocationReasons.ProjectConfigurationChanged); public static readonly UnitTestingInvocationReasonsWrapper SyntaxChanged = new(InvocationReasons.SyntaxChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentAdded = new(PredefinedInvocationReasons.DocumentAdded); public static readonly UnitTestingInvocationReasonsWrapper PredefinedReanalyze = new(PredefinedInvocationReasons.Reanalyze); public static readonly UnitTestingInvocationReasonsWrapper PredefinedSemanticChanged = new(PredefinedInvocationReasons.SemanticChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedSyntaxChanged = new(PredefinedInvocationReasons.SyntaxChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedProjectConfigurationChanged = new(PredefinedInvocationReasons.ProjectConfigurationChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentOpened = new(PredefinedInvocationReasons.DocumentOpened); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentRemoved = new(PredefinedInvocationReasons.DocumentRemoved); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentClosed = new(PredefinedInvocationReasons.DocumentClosed); public static readonly UnitTestingInvocationReasonsWrapper PredefinedHighPriority = new(PredefinedInvocationReasons.HighPriority); public static readonly UnitTestingInvocationReasonsWrapper PredefinedProjectParseOptionsChanged = new(PredefinedInvocationReasons.ProjectParseOptionsChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedSolutionRemoved = new(PredefinedInvocationReasons.SolutionRemoved); internal InvocationReasons UnderlyingObject { get; } internal UnitTestingInvocationReasonsWrapper(InvocationReasons underlyingObject) => UnderlyingObject = underlyingObject; public UnitTestingInvocationReasonsWrapper(string reason) : this(new InvocationReasons(reason)) { } public UnitTestingInvocationReasonsWrapper With(UnitTestingInvocationReasonsWrapper reason) => new(reason.UnderlyingObject.With(UnderlyingObject)); public bool IsReanalyze() => UnderlyingObject.Contains(PredefinedInvocationReasons.Reanalyze); public bool HasSemanticChanged() => UnderlyingObject.Contains(PredefinedInvocationReasons.SemanticChanged); public bool HasProjectConfigurationChanged() => UnderlyingObject.Contains(PredefinedInvocationReasons.ProjectConfigurationChanged); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal readonly struct UnitTestingInvocationReasonsWrapper { public static readonly UnitTestingInvocationReasonsWrapper SemanticChanged = new(InvocationReasons.SemanticChanged); public static readonly UnitTestingInvocationReasonsWrapper Reanalyze = new(InvocationReasons.Reanalyze); public static readonly UnitTestingInvocationReasonsWrapper ProjectConfigurationChanged = new(InvocationReasons.ProjectConfigurationChanged); public static readonly UnitTestingInvocationReasonsWrapper SyntaxChanged = new(InvocationReasons.SyntaxChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentAdded = new(PredefinedInvocationReasons.DocumentAdded); public static readonly UnitTestingInvocationReasonsWrapper PredefinedReanalyze = new(PredefinedInvocationReasons.Reanalyze); public static readonly UnitTestingInvocationReasonsWrapper PredefinedSemanticChanged = new(PredefinedInvocationReasons.SemanticChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedSyntaxChanged = new(PredefinedInvocationReasons.SyntaxChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedProjectConfigurationChanged = new(PredefinedInvocationReasons.ProjectConfigurationChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentOpened = new(PredefinedInvocationReasons.DocumentOpened); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentRemoved = new(PredefinedInvocationReasons.DocumentRemoved); public static readonly UnitTestingInvocationReasonsWrapper PredefinedDocumentClosed = new(PredefinedInvocationReasons.DocumentClosed); public static readonly UnitTestingInvocationReasonsWrapper PredefinedHighPriority = new(PredefinedInvocationReasons.HighPriority); public static readonly UnitTestingInvocationReasonsWrapper PredefinedProjectParseOptionsChanged = new(PredefinedInvocationReasons.ProjectParseOptionsChanged); public static readonly UnitTestingInvocationReasonsWrapper PredefinedSolutionRemoved = new(PredefinedInvocationReasons.SolutionRemoved); internal InvocationReasons UnderlyingObject { get; } internal UnitTestingInvocationReasonsWrapper(InvocationReasons underlyingObject) => UnderlyingObject = underlyingObject; public UnitTestingInvocationReasonsWrapper(string reason) : this(new InvocationReasons(reason)) { } public UnitTestingInvocationReasonsWrapper With(UnitTestingInvocationReasonsWrapper reason) => new(reason.UnderlyingObject.With(UnderlyingObject)); public bool IsReanalyze() => UnderlyingObject.Contains(PredefinedInvocationReasons.Reanalyze); public bool HasSemanticChanged() => UnderlyingObject.Contains(PredefinedInvocationReasons.SemanticChanged); public bool HasProjectConfigurationChanged() => UnderlyingObject.Contains(PredefinedInvocationReasons.ProjectConfigurationChanged); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpGenerateFromUsage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpGenerateFromUsage : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpGenerateFromUsage(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpGenerateFromUsage)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateLocal)] public void GenerateLocal() { SetUpEditor( @"class Program { static void Main(string[] args) { string s = $$xyz; } }"); VisualStudio.Editor.Verify.CodeAction("Generate local 'xyz'", applyFix: true); VisualStudio.Editor.Verify.TextContains( @"class Program { static void Main(string[] args) { string xyz = null; string s = xyz; } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpGenerateFromUsage : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpGenerateFromUsage(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpGenerateFromUsage)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateLocal)] public void GenerateLocal() { SetUpEditor( @"class Program { static void Main(string[] args) { string s = $$xyz; } }"); VisualStudio.Editor.Verify.CodeAction("Generate local 'xyz'", applyFix: true); VisualStudio.Editor.Verify.TextContains( @"class Program { static void Main(string[] args) { string xyz = null; string s = xyz; } }"); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Range.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using System.Linq; using Roslyn.Utilities; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitRangeExpression(BoundRangeExpression node) { Debug.Assert(node != null && node.MethodOpt != null); bool needLifting = false; var F = _factory; var left = node.LeftOperandOpt; if (left != null) { left = tryOptimizeOperand(left); } var right = node.RightOperandOpt; if (right != null) { right = tryOptimizeOperand(right); } if (needLifting) { return LiftRangeExpression(node, left, right); } else { BoundExpression rangeCreation = MakeRangeExpression(node.MethodOpt, left, right); if (node.Type.IsNullableType()) { if (!TryGetNullableMethod(node.Syntax, node.Type, SpecialMember.System_Nullable_T__ctor, out MethodSymbol nullableCtor)) { return BadExpression(node.Syntax, node.Type, node); } return new BoundObjectCreationExpression(node.Syntax, nullableCtor, rangeCreation); } return rangeCreation; } BoundExpression tryOptimizeOperand(BoundExpression operand) { Debug.Assert(operand != null); operand = VisitExpression(operand); Debug.Assert(operand.Type is { }); if (NullableNeverHasValue(operand)) { operand = new BoundDefaultExpression(operand.Syntax, operand.Type.GetNullableUnderlyingType()); } else { operand = NullableAlwaysHasValue(operand) ?? operand; Debug.Assert(operand.Type is { }); if (operand.Type.IsNullableType()) { needLifting = true; } } return operand; } } private BoundExpression LiftRangeExpression(BoundRangeExpression node, BoundExpression? left, BoundExpression? right) { Debug.Assert(node.Type.IsNullableType()); Debug.Assert(left?.Type?.IsNullableType() == true || right?.Type?.IsNullableType() == true); Debug.Assert(!(left is null && right is null)); Debug.Assert(node.MethodOpt is { }); var sideeffects = ArrayBuilder<BoundExpression>.GetInstance(); var locals = ArrayBuilder<LocalSymbol>.GetInstance(); // makeRange(left.GetValueOrDefault(), right.GetValueOrDefault()) BoundExpression? condition = null; left = getIndexFromPossibleNullable(left); right = getIndexFromPossibleNullable(right); var rangeExpr = MakeRangeExpression(node.MethodOpt, left, right); Debug.Assert(condition != null); if (!TryGetNullableMethod(node.Syntax, node.Type, SpecialMember.System_Nullable_T__ctor, out MethodSymbol nullableCtor)) { return BadExpression(node.Syntax, node.Type, node); } // new Nullable(makeRange(left.GetValueOrDefault(), right.GetValueOrDefault())) BoundExpression consequence = new BoundObjectCreationExpression(node.Syntax, nullableCtor, rangeExpr); // default BoundExpression alternative = new BoundDefaultExpression(node.Syntax, node.Type); // left.HasValue && right.HasValue // ? new Nullable(makeRange(left.GetValueOrDefault(), right.GetValueOrDefault())) // : default BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: node.Syntax, rewrittenCondition: condition, rewrittenConsequence: consequence, rewrittenAlternative: alternative, constantValueOpt: null, rewrittenType: node.Type, isRef: false); return new BoundSequence( syntax: node.Syntax, locals: locals.ToImmutableAndFree(), sideEffects: sideeffects.ToImmutableAndFree(), value: conditionalExpression, type: node.Type); BoundExpression? getIndexFromPossibleNullable(BoundExpression? arg) { if (arg is null) return null; BoundExpression tempOperand = CaptureExpressionInTempIfNeeded(arg, sideeffects, locals); Debug.Assert(tempOperand.Type is { }); if (tempOperand.Type.IsNullableType()) { BoundExpression operandHasValue = MakeOptimizedHasValue(tempOperand.Syntax, tempOperand); if (condition is null) { condition = operandHasValue; } else { TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); condition = MakeBinaryOperator(node.Syntax, BinaryOperatorKind.BoolAnd, condition, operandHasValue, boolType, method: null, constrainedToTypeOpt: null); } return MakeOptimizedGetValueOrDefault(tempOperand.Syntax, tempOperand); } else { return tempOperand; } } } private BoundExpression MakeRangeExpression( MethodSymbol constructionMethod, BoundExpression? left, BoundExpression? right) { var F = _factory; // The construction method may vary based on what well-known // members were available during binding. Depending on which member // is chosen we need to change our adjust our calling node. switch (constructionMethod.MethodKind) { case MethodKind.Constructor: // Represents Range..ctor(Index left, Index right) // The constructor can always be used to construct a range, // but if any of the arguments are missing then we need to // construct replacement Indexes left = left ?? newIndexZero(fromEnd: false); right = right ?? newIndexZero(fromEnd: true); return F.New(constructionMethod, ImmutableArray.Create(left, right)); case MethodKind.Ordinary: // Represents either Range.StartAt or Range.EndAt, which // means that the `..` expression is missing an argument on // either the left or the right (i.e., `x..` or `..x`) Debug.Assert(left is null ^ right is null); Debug.Assert(constructionMethod.MetadataName == "StartAt" || constructionMethod.MetadataName == "EndAt"); Debug.Assert(constructionMethod.IsStatic); var arg = left ?? right; Debug.Assert(arg is { }); return F.StaticCall(constructionMethod, ImmutableArray.Create(arg)); case MethodKind.PropertyGet: // The only property is Range.All, so the expression must // be `..` with both arguments missing Debug.Assert(constructionMethod.MetadataName == "get_All"); Debug.Assert(constructionMethod.IsStatic); Debug.Assert(left is null && right is null); return F.StaticCall(constructionMethod, ImmutableArray<BoundExpression>.Empty); default: throw ExceptionUtilities.UnexpectedValue(constructionMethod.MethodKind); } BoundExpression newIndexZero(bool fromEnd) => // new Index(0, fromEnd: fromEnd) F.New( WellKnownMember.System_Index__ctor, ImmutableArray.Create<BoundExpression>(F.Literal(0), F.Literal(fromEnd))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using System.Linq; using Roslyn.Utilities; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitRangeExpression(BoundRangeExpression node) { Debug.Assert(node != null && node.MethodOpt != null); bool needLifting = false; var F = _factory; var left = node.LeftOperandOpt; if (left != null) { left = tryOptimizeOperand(left); } var right = node.RightOperandOpt; if (right != null) { right = tryOptimizeOperand(right); } if (needLifting) { return LiftRangeExpression(node, left, right); } else { BoundExpression rangeCreation = MakeRangeExpression(node.MethodOpt, left, right); if (node.Type.IsNullableType()) { if (!TryGetNullableMethod(node.Syntax, node.Type, SpecialMember.System_Nullable_T__ctor, out MethodSymbol nullableCtor)) { return BadExpression(node.Syntax, node.Type, node); } return new BoundObjectCreationExpression(node.Syntax, nullableCtor, rangeCreation); } return rangeCreation; } BoundExpression tryOptimizeOperand(BoundExpression operand) { Debug.Assert(operand != null); operand = VisitExpression(operand); Debug.Assert(operand.Type is { }); if (NullableNeverHasValue(operand)) { operand = new BoundDefaultExpression(operand.Syntax, operand.Type.GetNullableUnderlyingType()); } else { operand = NullableAlwaysHasValue(operand) ?? operand; Debug.Assert(operand.Type is { }); if (operand.Type.IsNullableType()) { needLifting = true; } } return operand; } } private BoundExpression LiftRangeExpression(BoundRangeExpression node, BoundExpression? left, BoundExpression? right) { Debug.Assert(node.Type.IsNullableType()); Debug.Assert(left?.Type?.IsNullableType() == true || right?.Type?.IsNullableType() == true); Debug.Assert(!(left is null && right is null)); Debug.Assert(node.MethodOpt is { }); var sideeffects = ArrayBuilder<BoundExpression>.GetInstance(); var locals = ArrayBuilder<LocalSymbol>.GetInstance(); // makeRange(left.GetValueOrDefault(), right.GetValueOrDefault()) BoundExpression? condition = null; left = getIndexFromPossibleNullable(left); right = getIndexFromPossibleNullable(right); var rangeExpr = MakeRangeExpression(node.MethodOpt, left, right); Debug.Assert(condition != null); if (!TryGetNullableMethod(node.Syntax, node.Type, SpecialMember.System_Nullable_T__ctor, out MethodSymbol nullableCtor)) { return BadExpression(node.Syntax, node.Type, node); } // new Nullable(makeRange(left.GetValueOrDefault(), right.GetValueOrDefault())) BoundExpression consequence = new BoundObjectCreationExpression(node.Syntax, nullableCtor, rangeExpr); // default BoundExpression alternative = new BoundDefaultExpression(node.Syntax, node.Type); // left.HasValue && right.HasValue // ? new Nullable(makeRange(left.GetValueOrDefault(), right.GetValueOrDefault())) // : default BoundExpression conditionalExpression = RewriteConditionalOperator( syntax: node.Syntax, rewrittenCondition: condition, rewrittenConsequence: consequence, rewrittenAlternative: alternative, constantValueOpt: null, rewrittenType: node.Type, isRef: false); return new BoundSequence( syntax: node.Syntax, locals: locals.ToImmutableAndFree(), sideEffects: sideeffects.ToImmutableAndFree(), value: conditionalExpression, type: node.Type); BoundExpression? getIndexFromPossibleNullable(BoundExpression? arg) { if (arg is null) return null; BoundExpression tempOperand = CaptureExpressionInTempIfNeeded(arg, sideeffects, locals); Debug.Assert(tempOperand.Type is { }); if (tempOperand.Type.IsNullableType()) { BoundExpression operandHasValue = MakeOptimizedHasValue(tempOperand.Syntax, tempOperand); if (condition is null) { condition = operandHasValue; } else { TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); condition = MakeBinaryOperator(node.Syntax, BinaryOperatorKind.BoolAnd, condition, operandHasValue, boolType, method: null, constrainedToTypeOpt: null); } return MakeOptimizedGetValueOrDefault(tempOperand.Syntax, tempOperand); } else { return tempOperand; } } } private BoundExpression MakeRangeExpression( MethodSymbol constructionMethod, BoundExpression? left, BoundExpression? right) { var F = _factory; // The construction method may vary based on what well-known // members were available during binding. Depending on which member // is chosen we need to change our adjust our calling node. switch (constructionMethod.MethodKind) { case MethodKind.Constructor: // Represents Range..ctor(Index left, Index right) // The constructor can always be used to construct a range, // but if any of the arguments are missing then we need to // construct replacement Indexes left = left ?? newIndexZero(fromEnd: false); right = right ?? newIndexZero(fromEnd: true); return F.New(constructionMethod, ImmutableArray.Create(left, right)); case MethodKind.Ordinary: // Represents either Range.StartAt or Range.EndAt, which // means that the `..` expression is missing an argument on // either the left or the right (i.e., `x..` or `..x`) Debug.Assert(left is null ^ right is null); Debug.Assert(constructionMethod.MetadataName == "StartAt" || constructionMethod.MetadataName == "EndAt"); Debug.Assert(constructionMethod.IsStatic); var arg = left ?? right; Debug.Assert(arg is { }); return F.StaticCall(constructionMethod, ImmutableArray.Create(arg)); case MethodKind.PropertyGet: // The only property is Range.All, so the expression must // be `..` with both arguments missing Debug.Assert(constructionMethod.MetadataName == "get_All"); Debug.Assert(constructionMethod.IsStatic); Debug.Assert(left is null && right is null); return F.StaticCall(constructionMethod, ImmutableArray<BoundExpression>.Empty); default: throw ExceptionUtilities.UnexpectedValue(constructionMethod.MethodKind); } BoundExpression newIndexZero(bool fromEnd) => // new Index(0, fromEnd: fromEnd) F.New( WellKnownMember.System_Index__ctor, ImmutableArray.Create<BoundExpression>(F.Literal(0), F.Literal(fromEnd))); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Test/Symbol/Symbols/SymbolDistinguisherTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class SymbolDistinguisherTests : CSharpTestBase { [Fact] public void TestSimpleDeclarations() { var source = @" public class C { public void M() { } public int P { get; set; } public int F; public event System.Action E { add { } remove { } } } "; var tree = Parse(source, "file.cs"); var libRef = CreateCompilation(tree, assemblyName: "Metadata").EmitToImageReference(); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); SymbolDistinguisher distinguisher; var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); Assert.Equal("C [file.cs(2)]", distinguisher.First.ToString()); Assert.Equal("C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); var sourceMethod = sourceType.GetMember<MethodSymbol>("M"); var referencedMethod = referencedType.GetMember<MethodSymbol>("M"); distinguisher = new SymbolDistinguisher(comp, sourceMethod, referencedMethod); Assert.Equal("C.M() [file.cs(4)]", distinguisher.First.ToString()); Assert.Equal("C.M() [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); var sourceProperty = sourceType.GetMember<PropertySymbol>("P"); var referencedProperty = referencedType.GetMember<PropertySymbol>("P"); distinguisher = new SymbolDistinguisher(comp, sourceProperty, referencedProperty); Assert.Equal("C.P [file.cs(5)]", distinguisher.First.ToString()); Assert.Equal("C.P [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); var sourceField = sourceType.GetMember<FieldSymbol>("F"); var referencedField = referencedType.GetMember<FieldSymbol>("F"); distinguisher = new SymbolDistinguisher(comp, sourceField, referencedField); Assert.Equal("C.F [file.cs(6)]", distinguisher.First.ToString()); Assert.Equal("C.F [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); var sourceEvent = sourceType.GetMember<EventSymbol>("E"); var referencedEvent = referencedType.GetMember<EventSymbol>("E"); distinguisher = new SymbolDistinguisher(comp, sourceEvent, referencedEvent); Assert.Equal("C.E [file.cs(7)]", distinguisher.First.ToString()); Assert.Equal("C.E [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestCompilationReferenceLocation() { var source = @"public class C { }"; var libRef = new CSharpCompilationReference(CreateCompilation(Parse(source, "file1.cs"), assemblyName: "Metadata")); var comp = CreateCompilation(Parse(source, "file2.cs"), new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); Assert.Equal("C [file2.cs(1)]", distinguisher.First.ToString()); Assert.Equal("C [file1.cs(1)]", distinguisher.Second.ToString()); } [Fact] public void TestFileReferenceLocation() { var source = @"public class C { }"; var tree = Parse(source, "file.cs"); var libComp = CreateCompilation(tree, assemblyName: "Metadata"); var libRef = MetadataReference.CreateFromImage(libComp.EmitToArray(), filePath: "Metadata.dll"); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); Assert.Equal("C [file.cs(1)]", distinguisher.First.ToString()); Assert.Equal(string.Format("C [Metadata.dll]"), distinguisher.Second.ToString()); } [Fact] public void TestDistinctSymbolsWithSameLocation() { var source = @"public class C { }"; var tree = Parse(source, "file.cs"); var libRef = new CSharpCompilationReference(CreateCompilation(tree, assemblyName: "Metadata")); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); Assert.Equal("C [Source, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.First.ToString()); Assert.Equal("C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestPathLocationsWithoutCompilation() { var source = @"public class C { }"; var tree = Parse(source, @"a\..\file.cs"); var libComp = CreateCompilation(tree, assemblyName: "Metadata"); var libRef = MetadataReference.CreateFromImage(libComp.EmitToArray(), filePath: "Metadata.dll"); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var distinguisher = new SymbolDistinguisher(null, sourceType, referencedType); Assert.Equal(@"C [a\..\file.cs(1)]", distinguisher.First.ToString()); // File path comes out of tree. Assert.Equal("C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestSourceLocationWithoutPath() { var source = @"public class C { }"; var libRef = CreateCompilation(source, assemblyName: "Metadata").EmitToImageReference(); var comp = CreateCompilation(source, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); Assert.Equal("C [Source, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.First.ToString()); Assert.Equal("C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestParameterLocation() { var source = @" public class C { public void M(ref C c) { } } "; var tree = Parse(source, "file.cs"); var libRef = CreateCompilation(tree, assemblyName: "Metadata").EmitToImageReference(); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceParameter = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M").Parameters.Single(); var referencedParameter = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M").Parameters.Single(); var distinguisher = new SymbolDistinguisher(comp, sourceParameter, referencedParameter); // NOTE: Locations come from parameter *types*. // NOTE: RefKind retained. Assert.Equal("ref C [file.cs(2)]", distinguisher.First.ToString()); Assert.Equal("ref C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestArrayLocation() { var source = @" public class C { public C[] F; } "; var tree = Parse(source, "file.cs"); var libRef = CreateCompilation(tree, assemblyName: "Metadata").EmitToImageReference(); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<FieldSymbol>("F").Type; var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<FieldSymbol>("F").Type; var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); // NOTE: Locations come from element types. Assert.Equal("C[] [file.cs(2)]", distinguisher.First.ToString()); Assert.Equal("C[] [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestPointerLocation() { var source = @" unsafe public struct S { public S* F; } "; var tree = Parse(source, "file.cs"); var libRef = CreateCompilation(tree, assemblyName: "Metadata", options: TestOptions.UnsafeReleaseDll).EmitToImageReference(); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source", options: TestOptions.UnsafeReleaseDll); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("S").GetMember<FieldSymbol>("F").Type; var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("S").GetMember<FieldSymbol>("F").Type; var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); // NOTE: Locations come from element types. Assert.Equal("S* [file.cs(2)]", distinguisher.First.ToString()); Assert.Equal("S* [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestArrayParameterLocation() { var source = @" public class C { public void M(params C[] c) { } } "; var tree = Parse(source, "file.cs"); var libRef = CreateCompilation(tree, assemblyName: "Metadata").EmitToImageReference(); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceParameter = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M").Parameters.Single(); var referencedParameter = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M").Parameters.Single(); var distinguisher = new SymbolDistinguisher(comp, sourceParameter, referencedParameter); // NOTE: Locations come from parameter element types. // NOTE: 'params' retained. Assert.Equal("params C[] [file.cs(2)]", distinguisher.First.ToString()); Assert.Equal("params C[] [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestTypeParameterLocation() { var source = @"public class C<T> { }"; var tree = Parse(source, "file.cs"); var libRef = CreateCompilation(tree, assemblyName: "Metadata").EmitToImageReference(); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").TypeParameters.Single(); var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").TypeParameters.Single(); var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); // NOTE: Locations come from element types. Assert.Equal("T [file.cs(1)]", distinguisher.First.ToString()); Assert.Equal("T [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestDynamicLocation() { var libRef = CreateCompilation("public class dynamic { }", assemblyName: "Metadata").EmitToImageReference(); var comp = CreateCompilation("", new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); // I don't see how these types be reported as ambiguous, but we shouldn't blow up. var sourceType = DynamicTypeSymbol.Instance; var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("dynamic"); var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); Assert.Equal("dynamic", distinguisher.First.ToString()); Assert.Equal("dynamic [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestMissingTypeLocation() { var dummyComp = CreateEmptyCompilation("", assemblyName: "Error"); var errorType = dummyComp.GetSpecialType(SpecialType.System_Int32); var validType = CreateEmptyCompilation("", new[] { MscorlibRef }).GetSpecialType(SpecialType.System_Int32); Assert.NotEqual(TypeKind.Error, validType.TypeKind); Assert.Equal(TypeKind.Error, errorType.TypeKind); var distinguisher = new SymbolDistinguisher(dummyComp, errorType, validType); Assert.Equal("int [Error, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.First.ToString()); Assert.Equal("int [mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]", distinguisher.Second.ToString()); } [Fact] public void ERR_NoImplicitConvCast() { var libSource = @" public interface I { } public static class Lib { public static I M() { return null; } } "; var source = @" public interface I { } public class C { public static void Main() { I i = Lib.M(); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(8,9): warning CS0436: The type 'I' in 'file.cs' conflicts with the imported type 'I' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // I i = Lib.M(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "I").WithArguments("file.cs", "I", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "I").WithLocation(8, 9), // file.cs(8,15): error CS0266: Cannot implicitly convert type 'I [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' to 'I [file.cs(2)]'. An explicit conversion exists (are you missing a cast?) // I i = Lib.M(); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "Lib.M()").WithArguments("I [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "I [file.cs(2)]").WithLocation(8, 15)); } [Fact] public void ERR_NoImplicitConv() { var libSource = @" public struct S { } public static class Lib { public static S M() { return default(S); } } "; var source = @" public struct S { } public class C { public static void Main() { S s = Lib.M(); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(8,9): warning CS0436: The type 'S' in 'file.cs' conflicts with the imported type 'S' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // S s = Lib.M(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "S").WithArguments("file.cs", "S", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "S").WithLocation(8, 9), // file.cs(8,15): error CS0029: Cannot implicitly convert type 'S [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' to 'S [file.cs(2)]' // S s = Lib.M(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Lib.M()").WithArguments("S [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "S [file.cs(2)]").WithLocation(8, 15)); } [Fact] public void ERR_NoExplicitConv() { var libSource = @" public struct S { } public static class Lib { public static S M() { return default(S); } } "; var source = @" public struct S { } public class C { public static void Main() { var s = (S)Lib.M(); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(8,18): warning CS0436: The type 'S' in 'file.cs' conflicts with the imported type 'S' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // var s = (S)Lib.M(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "S").WithArguments("file.cs", "S", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "S").WithLocation(8, 18), // file.cs(8,17): error CS0030: Cannot convert type 'S [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' to 'S [file.cs(2)]' // var s = (S)Lib.M(); Diagnostic(ErrorCode.ERR_NoExplicitConv, "(S)Lib.M()").WithArguments("S [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "S [file.cs(2)]").WithLocation(8, 17)); } [Fact] public void ERR_NoExplicitBuiltinConv() { var libSource = @" public class C { } public static class Lib { public static C M() { return default(C); } } "; var source = @" public class C { public static void Main() { var c = Lib.M() as C; } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(6,28): warning CS0436: The type 'C' in 'file.cs' conflicts with the imported type 'C' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // var c = Lib.M() as C; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "C").WithArguments("file.cs", "C", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C").WithLocation(6, 28), // file.cs(6,17): error CS0039: Cannot convert type 'C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' to 'C [file.cs(2)]' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion // var c = Lib.M() as C; Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "Lib.M() as C").WithArguments("C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "C [file.cs(2)]").WithLocation(6, 17)); } [Fact] public void ERR_InvalidQM() { var libSource = @" public class C { } public static class Lib { public static C M() { return default(C); } } "; var source = @" public class C { public static void Main(string[] args) { var c = args == null ? new C() : Lib.M(); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(6,36): warning CS0436: The type 'C' in 'file.cs' conflicts with the imported type 'C' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // var c = args == null ? new C() : Lib.M(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "C").WithArguments("file.cs", "C", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C").WithLocation(6, 36), // file.cs(6,17): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'C [file.cs(2)]' and 'C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' // var c = args == null ? new C() : Lib.M(); Diagnostic(ErrorCode.ERR_InvalidQM, "args == null ? new C() : Lib.M()").WithArguments("C [file.cs(2)]", "C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]").WithLocation(6, 17)); } [Fact] public void ERR_BadParamType() { var libSource = @" public class C { } public delegate void D(C c); "; var source = @" public class C { public static void Main() { D d = (C c) => { }; } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(7,16): warning CS0436: The type 'C' in 'file.cs' conflicts with the imported type 'C' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // D d = (C c) => { }; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "C").WithArguments("file.cs", "C", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C").WithLocation(7, 16), // file.cs(7,15): error CS1661: Cannot convert lambda expression to delegate type 'D' because the parameter types do not match the delegate parameter types // D d = (C c) => { }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(C c) => { }").WithArguments("lambda expression", "D").WithLocation(7, 15), // file.cs(7,18): error CS1678: Parameter 1 is declared as type 'C [file.cs(3)]' but should be 'C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' // D d = (C c) => { }; Diagnostic(ErrorCode.ERR_BadParamType, "c").WithArguments("1", "", "C [file.cs(3)]", "", "C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]").WithLocation(7, 18)); } [Fact] public void ERR_BadArgType() { var libSource = @" public class C { } public static class Lib { public static void M(C c) { } } "; var source = @" public class C { public static void Main() { Lib.M(new C()); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(6,19): warning CS0436: The type 'C' in 'file.cs' conflicts with the imported type 'C' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // Lib.M(new C()); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "C").WithArguments("file.cs", "C", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C").WithLocation(6, 19), // file.cs(6,15): error CS1503: Argument 1: cannot convert from 'C [file.cs(2)]' to 'C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' // Lib.M(new C()); Diagnostic(ErrorCode.ERR_BadArgType, "new C()").WithArguments("1", "C [file.cs(2)]", "C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]").WithLocation(6, 15)); } [Fact] public void ERR_BadArgType_SameSourceLocation() { var libSource = @" public class C { } public static class Lib { public static void M(ref C c) { } } "; var source = @" public class C { public static void Main() { var c = new C(); Lib.M(ref c); } } "; var libRef = new CSharpCompilationReference(CreateCompilation(Parse(libSource, "file.cs"), assemblyName: "Metadata")); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(6,21): warning CS0436: The type 'C' in 'file.cs' conflicts with the imported type 'C' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // var c = new C(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "C").WithArguments("file.cs", "C", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C").WithLocation(6, 21), // file.cs(7,19): error CS1503: Argument 1: cannot convert from 'ref C [Source, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' to 'ref C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' // Lib.M(ref c); Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref C [Source, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "ref C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]").WithLocation(7, 19)); } [Fact] public void ERR_GenericConstraintNotSatisfiedRefType() { var libSource = @" public class C { } public static class Lib { public static void M<T>() where T : C { } } "; var source = @" public class C { public static void Main() { Lib.M<C>(); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(6,15): warning CS0436: The type 'C' in 'file.cs' conflicts with the imported type 'C' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // Lib.M<C>(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "C").WithArguments("file.cs", "C", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C").WithLocation(6, 15), // file.cs(6,13): error CS0311: The type 'C [file.cs(2)]' cannot be used as type parameter 'T' in the generic type or method 'Lib.M<T>()'. There is no implicit reference conversion from 'C [file.cs(2)]' to 'C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]'. // Lib.M<C>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M<C>").WithArguments("Lib.M<T>()", "C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "T", "C [file.cs(2)]").WithLocation(6, 13)); } // Not relevant: will always have one nullable and one non-nullable. // public void ERR_GenericConstraintNotSatisfiedNullableEnum() // Not relevant: will always have one nullable and one interface. // public void ERR_GenericConstraintNotSatisfiedNullableInterface() [Fact] public void ERR_GenericConstraintNotSatisfiedTyVar() { var libSource = @" public class C { } public static class Lib { public static void M<T>() where T : C { } } "; var source = @" public class Test<C> where C : struct { public static void M() { Lib.M<C>(); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(6,13): error CS0314: The type 'C [file.cs(2)]' cannot be used as type parameter 'T' in the generic type or method 'Lib.M<T>()'. There is no boxing conversion or type parameter conversion from 'C [file.cs(2)]' to 'C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]'. // Lib.M<C>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "M<C>").WithArguments("Lib.M<T>()", "C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "T", "C [file.cs(2)]").WithLocation(6, 13)); } [Fact] public void ERR_GenericConstraintNotSatisfiedValType() { var libSource = @" public class C { } public static class Lib { public static void M<T>() where T : C { } } "; var source = @" public struct C { } // NOTE: struct, not class public class Test { public static void Main() { Lib.M<C>(); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(8,15): warning CS0436: The type 'C' in 'file.cs' conflicts with the imported type 'C' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // Lib.M<C>(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "C").WithArguments("file.cs", "C", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C").WithLocation(8, 15), // file.cs(8,13): error CS0315: The type 'C [file.cs(2)]' cannot be used as type parameter 'T' in the generic type or method 'Lib.M<T>()'. There is no boxing conversion from 'C [file.cs(2)]' to 'C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]'. // Lib.M<C>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<C>").WithArguments("Lib.M<T>()", "C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "T", "C [file.cs(2)]").WithLocation(8, 13)); } [WorkItem(6262, "https://github.com/dotnet/roslyn/issues/6262")] [Fact] public void SymbolDistinguisherEquality() { var source = @"class A { } class B { } class C { }"; var compilation = CreateCompilation(source); var sA = compilation.GetMember<NamedTypeSymbol>("A"); var sB = compilation.GetMember<NamedTypeSymbol>("B"); var sC = compilation.GetMember<NamedTypeSymbol>("C"); Assert.True(AreEqual(new SymbolDistinguisher(compilation, sA, sB), new SymbolDistinguisher(compilation, sA, sB))); Assert.False(AreEqual(new SymbolDistinguisher(compilation, sA, sB), new SymbolDistinguisher(compilation, sA, sC))); Assert.False(AreEqual(new SymbolDistinguisher(compilation, sA, sB), new SymbolDistinguisher(compilation, sC, sB))); } private static bool AreEqual(SymbolDistinguisher a, SymbolDistinguisher b) { return a.First.Equals(b.First) && a.Second.Equals(b.Second); } [WorkItem(8470, "https://github.com/dotnet/roslyn/issues/8470")] [Fact] public void DescriptionNoCompilation() { var source = @"class A { } class B { }"; var compilation = CreateCompilation(source); var typeA = compilation.GetMember<NamedTypeSymbol>("A"); var typeB = compilation.GetMember<NamedTypeSymbol>("B"); var distinguisher1 = new SymbolDistinguisher(compilation, typeA, typeB); var distinguisher2 = new SymbolDistinguisher(null, typeA, typeB); var arg1A = distinguisher1.First; var arg2A = distinguisher2.First; Assert.False(arg1A.Equals(arg2A)); Assert.False(arg2A.Equals(arg1A)); int hashCode1A = arg1A.GetHashCode(); int hashCode2A = arg2A.GetHashCode(); } [WorkItem(8470, "https://github.com/dotnet/roslyn/issues/8470")] [Fact] public void CompareDiagnosticsNoCompilation() { var source1 = @"public class A { } public class B<T> where T : A { }"; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics(); var ref1 = compilation1.EmitToImageReference(); var source2 = @"class C : B<object> { }"; var compilation2 = CreateCompilation(source2, references: new[] { ref1 }); var diagnostics = compilation2.GetDiagnostics(); diagnostics.Verify( // (1,7): error CS0311: The type 'object' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. There is no implicit reference conversion from 'object' to 'A'. // class C : B<object> { } Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "C").WithArguments("B<T>", "A", "T", "object").WithLocation(1, 7)); // Command-line compiler calls SymbolDistinguisher.Description.GetHashCode() // when adding diagnostics to a set. foreach (var diagnostic in diagnostics) { diagnostic.GetHashCode(); } } [WorkItem(8588, "https://github.com/dotnet/roslyn/issues/8588")] [Fact] public void SameErrorTypeArgumentsDifferentSourceAssemblies() { var source0 = @"public class A { public static void M(System.Collections.Generic.IEnumerable<E> e) { } }"; var source1 = @"class B { static void M(System.Collections.Generic.IEnumerable<E> e) { A.M(e); } }"; var comp0 = CreateCompilation(source0); comp0.VerifyDiagnostics( // (3,65): error CS0246: The type or namespace name 'E' could not be found (are you missing a using directive or an assembly reference?) // public static void M(System.Collections.Generic.IEnumerable<E> e) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "E").WithArguments("E").WithLocation(3, 65)); var ref0 = new CSharpCompilationReference(comp0); var comp1 = CreateCompilation(Parse(source1), new[] { ref0 }); comp1.VerifyDiagnostics( // (3,58): error CS0246: The type or namespace name 'E' could not be found (are you missing a using directive or an assembly reference?) // static void M(System.Collections.Generic.IEnumerable<E> e) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "E").WithArguments("E").WithLocation(3, 58), // (5,13): error CS1503: Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable<E>' to 'System.Collections.Generic.IEnumerable<E>' // A.M(e); Diagnostic(ErrorCode.ERR_BadArgType, "e").WithArguments("1", "System.Collections.Generic.IEnumerable<E>", "System.Collections.Generic.IEnumerable<E>").WithLocation(5, 13)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class SymbolDistinguisherTests : CSharpTestBase { [Fact] public void TestSimpleDeclarations() { var source = @" public class C { public void M() { } public int P { get; set; } public int F; public event System.Action E { add { } remove { } } } "; var tree = Parse(source, "file.cs"); var libRef = CreateCompilation(tree, assemblyName: "Metadata").EmitToImageReference(); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); SymbolDistinguisher distinguisher; var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); Assert.Equal("C [file.cs(2)]", distinguisher.First.ToString()); Assert.Equal("C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); var sourceMethod = sourceType.GetMember<MethodSymbol>("M"); var referencedMethod = referencedType.GetMember<MethodSymbol>("M"); distinguisher = new SymbolDistinguisher(comp, sourceMethod, referencedMethod); Assert.Equal("C.M() [file.cs(4)]", distinguisher.First.ToString()); Assert.Equal("C.M() [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); var sourceProperty = sourceType.GetMember<PropertySymbol>("P"); var referencedProperty = referencedType.GetMember<PropertySymbol>("P"); distinguisher = new SymbolDistinguisher(comp, sourceProperty, referencedProperty); Assert.Equal("C.P [file.cs(5)]", distinguisher.First.ToString()); Assert.Equal("C.P [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); var sourceField = sourceType.GetMember<FieldSymbol>("F"); var referencedField = referencedType.GetMember<FieldSymbol>("F"); distinguisher = new SymbolDistinguisher(comp, sourceField, referencedField); Assert.Equal("C.F [file.cs(6)]", distinguisher.First.ToString()); Assert.Equal("C.F [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); var sourceEvent = sourceType.GetMember<EventSymbol>("E"); var referencedEvent = referencedType.GetMember<EventSymbol>("E"); distinguisher = new SymbolDistinguisher(comp, sourceEvent, referencedEvent); Assert.Equal("C.E [file.cs(7)]", distinguisher.First.ToString()); Assert.Equal("C.E [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestCompilationReferenceLocation() { var source = @"public class C { }"; var libRef = new CSharpCompilationReference(CreateCompilation(Parse(source, "file1.cs"), assemblyName: "Metadata")); var comp = CreateCompilation(Parse(source, "file2.cs"), new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); Assert.Equal("C [file2.cs(1)]", distinguisher.First.ToString()); Assert.Equal("C [file1.cs(1)]", distinguisher.Second.ToString()); } [Fact] public void TestFileReferenceLocation() { var source = @"public class C { }"; var tree = Parse(source, "file.cs"); var libComp = CreateCompilation(tree, assemblyName: "Metadata"); var libRef = MetadataReference.CreateFromImage(libComp.EmitToArray(), filePath: "Metadata.dll"); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); Assert.Equal("C [file.cs(1)]", distinguisher.First.ToString()); Assert.Equal(string.Format("C [Metadata.dll]"), distinguisher.Second.ToString()); } [Fact] public void TestDistinctSymbolsWithSameLocation() { var source = @"public class C { }"; var tree = Parse(source, "file.cs"); var libRef = new CSharpCompilationReference(CreateCompilation(tree, assemblyName: "Metadata")); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); Assert.Equal("C [Source, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.First.ToString()); Assert.Equal("C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestPathLocationsWithoutCompilation() { var source = @"public class C { }"; var tree = Parse(source, @"a\..\file.cs"); var libComp = CreateCompilation(tree, assemblyName: "Metadata"); var libRef = MetadataReference.CreateFromImage(libComp.EmitToArray(), filePath: "Metadata.dll"); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var distinguisher = new SymbolDistinguisher(null, sourceType, referencedType); Assert.Equal(@"C [a\..\file.cs(1)]", distinguisher.First.ToString()); // File path comes out of tree. Assert.Equal("C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestSourceLocationWithoutPath() { var source = @"public class C { }"; var libRef = CreateCompilation(source, assemblyName: "Metadata").EmitToImageReference(); var comp = CreateCompilation(source, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); Assert.Equal("C [Source, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.First.ToString()); Assert.Equal("C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestParameterLocation() { var source = @" public class C { public void M(ref C c) { } } "; var tree = Parse(source, "file.cs"); var libRef = CreateCompilation(tree, assemblyName: "Metadata").EmitToImageReference(); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceParameter = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M").Parameters.Single(); var referencedParameter = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M").Parameters.Single(); var distinguisher = new SymbolDistinguisher(comp, sourceParameter, referencedParameter); // NOTE: Locations come from parameter *types*. // NOTE: RefKind retained. Assert.Equal("ref C [file.cs(2)]", distinguisher.First.ToString()); Assert.Equal("ref C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestArrayLocation() { var source = @" public class C { public C[] F; } "; var tree = Parse(source, "file.cs"); var libRef = CreateCompilation(tree, assemblyName: "Metadata").EmitToImageReference(); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<FieldSymbol>("F").Type; var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<FieldSymbol>("F").Type; var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); // NOTE: Locations come from element types. Assert.Equal("C[] [file.cs(2)]", distinguisher.First.ToString()); Assert.Equal("C[] [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestPointerLocation() { var source = @" unsafe public struct S { public S* F; } "; var tree = Parse(source, "file.cs"); var libRef = CreateCompilation(tree, assemblyName: "Metadata", options: TestOptions.UnsafeReleaseDll).EmitToImageReference(); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source", options: TestOptions.UnsafeReleaseDll); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("S").GetMember<FieldSymbol>("F").Type; var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("S").GetMember<FieldSymbol>("F").Type; var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); // NOTE: Locations come from element types. Assert.Equal("S* [file.cs(2)]", distinguisher.First.ToString()); Assert.Equal("S* [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestArrayParameterLocation() { var source = @" public class C { public void M(params C[] c) { } } "; var tree = Parse(source, "file.cs"); var libRef = CreateCompilation(tree, assemblyName: "Metadata").EmitToImageReference(); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceParameter = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M").Parameters.Single(); var referencedParameter = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M").Parameters.Single(); var distinguisher = new SymbolDistinguisher(comp, sourceParameter, referencedParameter); // NOTE: Locations come from parameter element types. // NOTE: 'params' retained. Assert.Equal("params C[] [file.cs(2)]", distinguisher.First.ToString()); Assert.Equal("params C[] [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestTypeParameterLocation() { var source = @"public class C<T> { }"; var tree = Parse(source, "file.cs"); var libRef = CreateCompilation(tree, assemblyName: "Metadata").EmitToImageReference(); var comp = CreateCompilation(tree, new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); var sourceType = sourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").TypeParameters.Single(); var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C").TypeParameters.Single(); var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); // NOTE: Locations come from element types. Assert.Equal("T [file.cs(1)]", distinguisher.First.ToString()); Assert.Equal("T [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestDynamicLocation() { var libRef = CreateCompilation("public class dynamic { }", assemblyName: "Metadata").EmitToImageReference(); var comp = CreateCompilation("", new[] { libRef }, assemblyName: "Source"); var sourceAssembly = comp.SourceAssembly; var referencedAssembly = (AssemblySymbol)comp.GetAssemblyOrModuleSymbol(libRef); // I don't see how these types be reported as ambiguous, but we shouldn't blow up. var sourceType = DynamicTypeSymbol.Instance; var referencedType = referencedAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("dynamic"); var distinguisher = new SymbolDistinguisher(comp, sourceType, referencedType); Assert.Equal("dynamic", distinguisher.First.ToString()); Assert.Equal("dynamic [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.Second.ToString()); } [Fact] public void TestMissingTypeLocation() { var dummyComp = CreateEmptyCompilation("", assemblyName: "Error"); var errorType = dummyComp.GetSpecialType(SpecialType.System_Int32); var validType = CreateEmptyCompilation("", new[] { MscorlibRef }).GetSpecialType(SpecialType.System_Int32); Assert.NotEqual(TypeKind.Error, validType.TypeKind); Assert.Equal(TypeKind.Error, errorType.TypeKind); var distinguisher = new SymbolDistinguisher(dummyComp, errorType, validType); Assert.Equal("int [Error, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", distinguisher.First.ToString()); Assert.Equal("int [mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]", distinguisher.Second.ToString()); } [Fact] public void ERR_NoImplicitConvCast() { var libSource = @" public interface I { } public static class Lib { public static I M() { return null; } } "; var source = @" public interface I { } public class C { public static void Main() { I i = Lib.M(); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(8,9): warning CS0436: The type 'I' in 'file.cs' conflicts with the imported type 'I' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // I i = Lib.M(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "I").WithArguments("file.cs", "I", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "I").WithLocation(8, 9), // file.cs(8,15): error CS0266: Cannot implicitly convert type 'I [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' to 'I [file.cs(2)]'. An explicit conversion exists (are you missing a cast?) // I i = Lib.M(); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "Lib.M()").WithArguments("I [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "I [file.cs(2)]").WithLocation(8, 15)); } [Fact] public void ERR_NoImplicitConv() { var libSource = @" public struct S { } public static class Lib { public static S M() { return default(S); } } "; var source = @" public struct S { } public class C { public static void Main() { S s = Lib.M(); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(8,9): warning CS0436: The type 'S' in 'file.cs' conflicts with the imported type 'S' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // S s = Lib.M(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "S").WithArguments("file.cs", "S", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "S").WithLocation(8, 9), // file.cs(8,15): error CS0029: Cannot implicitly convert type 'S [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' to 'S [file.cs(2)]' // S s = Lib.M(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Lib.M()").WithArguments("S [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "S [file.cs(2)]").WithLocation(8, 15)); } [Fact] public void ERR_NoExplicitConv() { var libSource = @" public struct S { } public static class Lib { public static S M() { return default(S); } } "; var source = @" public struct S { } public class C { public static void Main() { var s = (S)Lib.M(); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(8,18): warning CS0436: The type 'S' in 'file.cs' conflicts with the imported type 'S' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // var s = (S)Lib.M(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "S").WithArguments("file.cs", "S", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "S").WithLocation(8, 18), // file.cs(8,17): error CS0030: Cannot convert type 'S [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' to 'S [file.cs(2)]' // var s = (S)Lib.M(); Diagnostic(ErrorCode.ERR_NoExplicitConv, "(S)Lib.M()").WithArguments("S [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "S [file.cs(2)]").WithLocation(8, 17)); } [Fact] public void ERR_NoExplicitBuiltinConv() { var libSource = @" public class C { } public static class Lib { public static C M() { return default(C); } } "; var source = @" public class C { public static void Main() { var c = Lib.M() as C; } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(6,28): warning CS0436: The type 'C' in 'file.cs' conflicts with the imported type 'C' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // var c = Lib.M() as C; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "C").WithArguments("file.cs", "C", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C").WithLocation(6, 28), // file.cs(6,17): error CS0039: Cannot convert type 'C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' to 'C [file.cs(2)]' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion // var c = Lib.M() as C; Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "Lib.M() as C").WithArguments("C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "C [file.cs(2)]").WithLocation(6, 17)); } [Fact] public void ERR_InvalidQM() { var libSource = @" public class C { } public static class Lib { public static C M() { return default(C); } } "; var source = @" public class C { public static void Main(string[] args) { var c = args == null ? new C() : Lib.M(); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(6,36): warning CS0436: The type 'C' in 'file.cs' conflicts with the imported type 'C' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // var c = args == null ? new C() : Lib.M(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "C").WithArguments("file.cs", "C", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C").WithLocation(6, 36), // file.cs(6,17): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'C [file.cs(2)]' and 'C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' // var c = args == null ? new C() : Lib.M(); Diagnostic(ErrorCode.ERR_InvalidQM, "args == null ? new C() : Lib.M()").WithArguments("C [file.cs(2)]", "C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]").WithLocation(6, 17)); } [Fact] public void ERR_BadParamType() { var libSource = @" public class C { } public delegate void D(C c); "; var source = @" public class C { public static void Main() { D d = (C c) => { }; } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(7,16): warning CS0436: The type 'C' in 'file.cs' conflicts with the imported type 'C' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // D d = (C c) => { }; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "C").WithArguments("file.cs", "C", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C").WithLocation(7, 16), // file.cs(7,15): error CS1661: Cannot convert lambda expression to delegate type 'D' because the parameter types do not match the delegate parameter types // D d = (C c) => { }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(C c) => { }").WithArguments("lambda expression", "D").WithLocation(7, 15), // file.cs(7,18): error CS1678: Parameter 1 is declared as type 'C [file.cs(3)]' but should be 'C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' // D d = (C c) => { }; Diagnostic(ErrorCode.ERR_BadParamType, "c").WithArguments("1", "", "C [file.cs(3)]", "", "C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]").WithLocation(7, 18)); } [Fact] public void ERR_BadArgType() { var libSource = @" public class C { } public static class Lib { public static void M(C c) { } } "; var source = @" public class C { public static void Main() { Lib.M(new C()); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(6,19): warning CS0436: The type 'C' in 'file.cs' conflicts with the imported type 'C' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // Lib.M(new C()); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "C").WithArguments("file.cs", "C", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C").WithLocation(6, 19), // file.cs(6,15): error CS1503: Argument 1: cannot convert from 'C [file.cs(2)]' to 'C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' // Lib.M(new C()); Diagnostic(ErrorCode.ERR_BadArgType, "new C()").WithArguments("1", "C [file.cs(2)]", "C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]").WithLocation(6, 15)); } [Fact] public void ERR_BadArgType_SameSourceLocation() { var libSource = @" public class C { } public static class Lib { public static void M(ref C c) { } } "; var source = @" public class C { public static void Main() { var c = new C(); Lib.M(ref c); } } "; var libRef = new CSharpCompilationReference(CreateCompilation(Parse(libSource, "file.cs"), assemblyName: "Metadata")); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(6,21): warning CS0436: The type 'C' in 'file.cs' conflicts with the imported type 'C' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // var c = new C(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "C").WithArguments("file.cs", "C", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C").WithLocation(6, 21), // file.cs(7,19): error CS1503: Argument 1: cannot convert from 'ref C [Source, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' to 'ref C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' // Lib.M(ref c); Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref C [Source, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "ref C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]").WithLocation(7, 19)); } [Fact] public void ERR_GenericConstraintNotSatisfiedRefType() { var libSource = @" public class C { } public static class Lib { public static void M<T>() where T : C { } } "; var source = @" public class C { public static void Main() { Lib.M<C>(); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(6,15): warning CS0436: The type 'C' in 'file.cs' conflicts with the imported type 'C' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // Lib.M<C>(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "C").WithArguments("file.cs", "C", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C").WithLocation(6, 15), // file.cs(6,13): error CS0311: The type 'C [file.cs(2)]' cannot be used as type parameter 'T' in the generic type or method 'Lib.M<T>()'. There is no implicit reference conversion from 'C [file.cs(2)]' to 'C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]'. // Lib.M<C>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M<C>").WithArguments("Lib.M<T>()", "C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "T", "C [file.cs(2)]").WithLocation(6, 13)); } // Not relevant: will always have one nullable and one non-nullable. // public void ERR_GenericConstraintNotSatisfiedNullableEnum() // Not relevant: will always have one nullable and one interface. // public void ERR_GenericConstraintNotSatisfiedNullableInterface() [Fact] public void ERR_GenericConstraintNotSatisfiedTyVar() { var libSource = @" public class C { } public static class Lib { public static void M<T>() where T : C { } } "; var source = @" public class Test<C> where C : struct { public static void M() { Lib.M<C>(); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(6,13): error CS0314: The type 'C [file.cs(2)]' cannot be used as type parameter 'T' in the generic type or method 'Lib.M<T>()'. There is no boxing conversion or type parameter conversion from 'C [file.cs(2)]' to 'C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]'. // Lib.M<C>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "M<C>").WithArguments("Lib.M<T>()", "C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "T", "C [file.cs(2)]").WithLocation(6, 13)); } [Fact] public void ERR_GenericConstraintNotSatisfiedValType() { var libSource = @" public class C { } public static class Lib { public static void M<T>() where T : C { } } "; var source = @" public struct C { } // NOTE: struct, not class public class Test { public static void Main() { Lib.M<C>(); } } "; var libRef = CreateCompilation(libSource, assemblyName: "Metadata").EmitToImageReference(); CreateCompilation(Parse(source, "file.cs"), new[] { libRef }, assemblyName: "Source").VerifyDiagnostics( // file.cs(8,15): warning CS0436: The type 'C' in 'file.cs' conflicts with the imported type 'C' in 'Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'file.cs'. // Lib.M<C>(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "C").WithArguments("file.cs", "C", "Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C").WithLocation(8, 15), // file.cs(8,13): error CS0315: The type 'C [file.cs(2)]' cannot be used as type parameter 'T' in the generic type or method 'Lib.M<T>()'. There is no boxing conversion from 'C [file.cs(2)]' to 'C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]'. // Lib.M<C>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<C>").WithArguments("Lib.M<T>()", "C [Metadata, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", "T", "C [file.cs(2)]").WithLocation(8, 13)); } [WorkItem(6262, "https://github.com/dotnet/roslyn/issues/6262")] [Fact] public void SymbolDistinguisherEquality() { var source = @"class A { } class B { } class C { }"; var compilation = CreateCompilation(source); var sA = compilation.GetMember<NamedTypeSymbol>("A"); var sB = compilation.GetMember<NamedTypeSymbol>("B"); var sC = compilation.GetMember<NamedTypeSymbol>("C"); Assert.True(AreEqual(new SymbolDistinguisher(compilation, sA, sB), new SymbolDistinguisher(compilation, sA, sB))); Assert.False(AreEqual(new SymbolDistinguisher(compilation, sA, sB), new SymbolDistinguisher(compilation, sA, sC))); Assert.False(AreEqual(new SymbolDistinguisher(compilation, sA, sB), new SymbolDistinguisher(compilation, sC, sB))); } private static bool AreEqual(SymbolDistinguisher a, SymbolDistinguisher b) { return a.First.Equals(b.First) && a.Second.Equals(b.Second); } [WorkItem(8470, "https://github.com/dotnet/roslyn/issues/8470")] [Fact] public void DescriptionNoCompilation() { var source = @"class A { } class B { }"; var compilation = CreateCompilation(source); var typeA = compilation.GetMember<NamedTypeSymbol>("A"); var typeB = compilation.GetMember<NamedTypeSymbol>("B"); var distinguisher1 = new SymbolDistinguisher(compilation, typeA, typeB); var distinguisher2 = new SymbolDistinguisher(null, typeA, typeB); var arg1A = distinguisher1.First; var arg2A = distinguisher2.First; Assert.False(arg1A.Equals(arg2A)); Assert.False(arg2A.Equals(arg1A)); int hashCode1A = arg1A.GetHashCode(); int hashCode2A = arg2A.GetHashCode(); } [WorkItem(8470, "https://github.com/dotnet/roslyn/issues/8470")] [Fact] public void CompareDiagnosticsNoCompilation() { var source1 = @"public class A { } public class B<T> where T : A { }"; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics(); var ref1 = compilation1.EmitToImageReference(); var source2 = @"class C : B<object> { }"; var compilation2 = CreateCompilation(source2, references: new[] { ref1 }); var diagnostics = compilation2.GetDiagnostics(); diagnostics.Verify( // (1,7): error CS0311: The type 'object' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. There is no implicit reference conversion from 'object' to 'A'. // class C : B<object> { } Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "C").WithArguments("B<T>", "A", "T", "object").WithLocation(1, 7)); // Command-line compiler calls SymbolDistinguisher.Description.GetHashCode() // when adding diagnostics to a set. foreach (var diagnostic in diagnostics) { diagnostic.GetHashCode(); } } [WorkItem(8588, "https://github.com/dotnet/roslyn/issues/8588")] [Fact] public void SameErrorTypeArgumentsDifferentSourceAssemblies() { var source0 = @"public class A { public static void M(System.Collections.Generic.IEnumerable<E> e) { } }"; var source1 = @"class B { static void M(System.Collections.Generic.IEnumerable<E> e) { A.M(e); } }"; var comp0 = CreateCompilation(source0); comp0.VerifyDiagnostics( // (3,65): error CS0246: The type or namespace name 'E' could not be found (are you missing a using directive or an assembly reference?) // public static void M(System.Collections.Generic.IEnumerable<E> e) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "E").WithArguments("E").WithLocation(3, 65)); var ref0 = new CSharpCompilationReference(comp0); var comp1 = CreateCompilation(Parse(source1), new[] { ref0 }); comp1.VerifyDiagnostics( // (3,58): error CS0246: The type or namespace name 'E' could not be found (are you missing a using directive or an assembly reference?) // static void M(System.Collections.Generic.IEnumerable<E> e) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "E").WithArguments("E").WithLocation(3, 58), // (5,13): error CS1503: Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable<E>' to 'System.Collections.Generic.IEnumerable<E>' // A.M(e); Diagnostic(ErrorCode.ERR_BadArgType, "e").WithArguments("1", "System.Collections.Generic.IEnumerable<E>", "System.Collections.Generic.IEnumerable<E>").WithLocation(5, 13)); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/Core/Impl/Options/OptionStore.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// This class is intended to be used by Option pages. It will provide access to an options /// from an optionset but will not persist changes automatically. /// </summary> public class OptionStore { public event EventHandler<OptionKey> OptionChanged; private OptionSet _optionSet; private IEnumerable<IOption> _registeredOptions; public OptionStore(OptionSet optionSet, IEnumerable<IOption> registeredOptions) { _optionSet = optionSet; _registeredOptions = registeredOptions; } public object GetOption(OptionKey optionKey) => _optionSet.GetOption(optionKey); public T GetOption<T>(OptionKey optionKey) => _optionSet.GetOption<T>(optionKey); public T GetOption<T>(Option<T> option) => _optionSet.GetOption(option); internal T GetOption<T>(Option2<T> option) => _optionSet.GetOption(option); public T GetOption<T>(PerLanguageOption<T> option, string language) => _optionSet.GetOption(option, language); internal T GetOption<T>(PerLanguageOption2<T> option, string language) => _optionSet.GetOption(option, language); public OptionSet GetOptions() => _optionSet; public void SetOption(OptionKey optionKey, object value) { _optionSet = _optionSet.WithChangedOption(optionKey, value); OnOptionChanged(optionKey); } public void SetOption<T>(Option<T> option, T value) { _optionSet = _optionSet.WithChangedOption(option, value); OnOptionChanged(new OptionKey(option)); } internal void SetOption<T>(Option2<T> option, T value) { _optionSet = _optionSet.WithChangedOption(option, value); OnOptionChanged(new OptionKey(option)); } public void SetOption<T>(PerLanguageOption<T> option, string language, T value) { _optionSet = _optionSet.WithChangedOption(option, language, value); OnOptionChanged(new OptionKey(option, language)); } internal void SetOption<T>(PerLanguageOption2<T> option, string language, T value) { _optionSet = _optionSet.WithChangedOption(option, language, value); OnOptionChanged(new OptionKey(option, language)); } public IEnumerable<IOption> GetRegisteredOptions() => _registeredOptions; public void SetOptions(OptionSet optionSet) => _optionSet = optionSet; public void SetRegisteredOptions(IEnumerable<IOption> registeredOptions) => _registeredOptions = registeredOptions; private void OnOptionChanged(OptionKey optionKey) => OptionChanged?.Invoke(this, optionKey); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// This class is intended to be used by Option pages. It will provide access to an options /// from an optionset but will not persist changes automatically. /// </summary> public class OptionStore { public event EventHandler<OptionKey> OptionChanged; private OptionSet _optionSet; private IEnumerable<IOption> _registeredOptions; public OptionStore(OptionSet optionSet, IEnumerable<IOption> registeredOptions) { _optionSet = optionSet; _registeredOptions = registeredOptions; } public object GetOption(OptionKey optionKey) => _optionSet.GetOption(optionKey); public T GetOption<T>(OptionKey optionKey) => _optionSet.GetOption<T>(optionKey); public T GetOption<T>(Option<T> option) => _optionSet.GetOption(option); internal T GetOption<T>(Option2<T> option) => _optionSet.GetOption(option); public T GetOption<T>(PerLanguageOption<T> option, string language) => _optionSet.GetOption(option, language); internal T GetOption<T>(PerLanguageOption2<T> option, string language) => _optionSet.GetOption(option, language); public OptionSet GetOptions() => _optionSet; public void SetOption(OptionKey optionKey, object value) { _optionSet = _optionSet.WithChangedOption(optionKey, value); OnOptionChanged(optionKey); } public void SetOption<T>(Option<T> option, T value) { _optionSet = _optionSet.WithChangedOption(option, value); OnOptionChanged(new OptionKey(option)); } internal void SetOption<T>(Option2<T> option, T value) { _optionSet = _optionSet.WithChangedOption(option, value); OnOptionChanged(new OptionKey(option)); } public void SetOption<T>(PerLanguageOption<T> option, string language, T value) { _optionSet = _optionSet.WithChangedOption(option, language, value); OnOptionChanged(new OptionKey(option, language)); } internal void SetOption<T>(PerLanguageOption2<T> option, string language, T value) { _optionSet = _optionSet.WithChangedOption(option, language, value); OnOptionChanged(new OptionKey(option, language)); } public IEnumerable<IOption> GetRegisteredOptions() => _registeredOptions; public void SetOptions(OptionSet optionSet) => _optionSet = optionSet; public void SetRegisteredOptions(IEnumerable<IOption> registeredOptions) => _registeredOptions = registeredOptions; private void OnOptionChanged(OptionKey optionKey) => OptionChanged?.Invoke(this, optionKey); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/RQName/Nodes/RQEvent.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQEvent : RQMethodPropertyOrEvent { public RQEvent(RQUnconstructedType containingType, RQMethodPropertyOrEventName memberName) : base(containingType, memberName) { } protected override string RQKeyword { get { return RQNameStrings.Event; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQEvent : RQMethodPropertyOrEvent { public RQEvent(RQUnconstructedType containingType, RQMethodPropertyOrEventName memberName) : base(containingType, memberName) { } protected override string RQKeyword { get { return RQNameStrings.Event; } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/IntegrationTest/TestUtilities/FeedbackItemDotNetEntry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.Eventing.Reader; using System.Linq; using System.Runtime.Serialization; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { /// <summary> /// Mapper for the .NetRuntime entry in the Event Log /// </summary> [DataContract] internal class FeedbackItemDotNetEntry { /// <summary> /// The time the event happened (UTC) /// </summary> [DataMember(Name = "eventTime")] public DateTime EventTime { get; set; } /// <summary> /// The .NET Runtime event id (this is set by .NET and we get it from the Event Log, so we can better differentiate between them) /// As defined in CLR code: ndp\clr\src\vm\eventreporter.cpp, these IDs are: /// 1023 - ERT_UnmanagedFailFast, 1025 - ERT_ManagedFailFast, 1026 - ERT_UnhandledException, 1027 - ERT_StackOverflow, 1028 - ERT_CodeContractFailed /// </summary> [DataMember(Name = "eventId")] public int EventId { get; set; } /// <summary> /// The event log properties to be passed as one string. E.g. /// Application: CSAv.exe, Framework version: v4.0.30319, /// Description: The application requested termination through System.Environment.FailFast(string message) /// Stack: at CSAv.Program.GetModuleFileName(IntPtr, Int32, Int32) /// </summary> [DataMember(Name = "data")] public string Data { get; set; } /// <summary> /// Constructor for the FeedbackItemDotNetEntry based on an EventRecord from the EventLog /// </summary> public FeedbackItemDotNetEntry(EventRecord eventLogRecord) { EventTime = eventLogRecord.TimeCreated?.ToUniversalTime() ?? DateTime.MinValue; EventId = eventLogRecord.Id; Data = string.Join(";", eventLogRecord.Properties.Select(pr => pr.Value ?? string.Empty)); } /// <summary> /// Used to make sure we aren't adding dupe entries to the list of Watson entries /// </summary> public override bool Equals(object obj) { if ((obj is FeedbackItemDotNetEntry dotNetEntry) && (EventId == dotNetEntry.EventId) && (Data == dotNetEntry.Data)) { return true; } return false; } public override int GetHashCode() { return EventId.GetHashCode() ^ Data.GetHashCode(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.Eventing.Reader; using System.Linq; using System.Runtime.Serialization; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { /// <summary> /// Mapper for the .NetRuntime entry in the Event Log /// </summary> [DataContract] internal class FeedbackItemDotNetEntry { /// <summary> /// The time the event happened (UTC) /// </summary> [DataMember(Name = "eventTime")] public DateTime EventTime { get; set; } /// <summary> /// The .NET Runtime event id (this is set by .NET and we get it from the Event Log, so we can better differentiate between them) /// As defined in CLR code: ndp\clr\src\vm\eventreporter.cpp, these IDs are: /// 1023 - ERT_UnmanagedFailFast, 1025 - ERT_ManagedFailFast, 1026 - ERT_UnhandledException, 1027 - ERT_StackOverflow, 1028 - ERT_CodeContractFailed /// </summary> [DataMember(Name = "eventId")] public int EventId { get; set; } /// <summary> /// The event log properties to be passed as one string. E.g. /// Application: CSAv.exe, Framework version: v4.0.30319, /// Description: The application requested termination through System.Environment.FailFast(string message) /// Stack: at CSAv.Program.GetModuleFileName(IntPtr, Int32, Int32) /// </summary> [DataMember(Name = "data")] public string Data { get; set; } /// <summary> /// Constructor for the FeedbackItemDotNetEntry based on an EventRecord from the EventLog /// </summary> public FeedbackItemDotNetEntry(EventRecord eventLogRecord) { EventTime = eventLogRecord.TimeCreated?.ToUniversalTime() ?? DateTime.MinValue; EventId = eventLogRecord.Id; Data = string.Join(";", eventLogRecord.Properties.Select(pr => pr.Value ?? string.Empty)); } /// <summary> /// Used to make sure we aren't adding dupe entries to the list of Watson entries /// </summary> public override bool Equals(object obj) { if ((obj is FeedbackItemDotNetEntry dotNetEntry) && (EventId == dotNetEntry.EventId) && (Data == dotNetEntry.Data)) { return true; } return false; } public override int GetHashCode() { return EventId.GetHashCode() ^ Data.GetHashCode(); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/CSharp/Impl/Options/Formatting/NewLinesViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { /// <summary> /// Interaction logic for FormattingNewLinesOptionControl.xaml /// </summary> internal class NewLinesViewModel : AbstractOptionPreviewViewModel { private const string s_previewText = @"//[ class C { } //]"; private const string s_methodPreview = @"class c { //[ void Goo(){ Console.WriteLine(); int LocalFunction(int x) { return 2 * x; } Console.ReadLine(); } //] }"; private const string s_propertyPreview = @"class c { //[ public int Property { get { return 42; } set { } } //] }"; private const string s_tryCatchFinallyPreview = @"using System; class C { void Goo() { //[ try { } catch (Exception e) { } finally { } //] } }"; private const string s_ifElsePreview = @"class C { void Goo() { //[ if (false) { } else { } //] } }"; private const string s_forBlockPreview = @"class C { void Goo() { //[ for (int i; i < 10; i++){ } //] } }"; private const string s_lambdaPreview = @"using System; class C { void Goo() { //[ Func<int, int> f = x => { return 2 * x; }; //] } }"; private const string s_anonymousMethodPreview = @"using System; delegate int D(int x); class C { void Goo() { //[ D d = delegate(int x) { return 2 * x; }; //] } }"; private const string s_anonymousTypePreview = @"using System; class C { void Goo() { //[ var z = new { A = 3, B = 4 }; //] } }"; private const string s_InitializerPreviewTrue = @"using System; using System.Collections.Generic; class C { void Goo() { //[ var z = new B() { A = 3, B = 4 }; // During Brace Completion or Only if Empty Body var collectionVariable = new List<int> { } // During Brace Completion var arrayVariable = new int[] { } //] } } class B { public int A { get; set; } public int B { get; set; } }"; private const string s_InitializerPreviewFalse = @"using System; using System.Collections.Generic; class C { void Goo() { //[ var z = new B() { A = 3, B = 4 }; // During Brace Completion or Only if Empty Body var collectionVariable = new List<int> { } // During Brace Completion var arrayVariable = new int[] { } //] } } class B { public int A { get; set; } public int B { get; set; } }"; private const string s_objectInitializerPreview = @"using System; class C { void Goo() { //[ var z = new B() { A = 3, B = 4 }; //] } } class B { public int A { get; set; } public int B { get; set; } }"; private const string s_queryExpressionPreview = @"using System; using System.Linq; using System.Collections.Generic; class C { void Goo(IEnumerable<int> e) { //[ var q = from a in e from b in e select a * b; //] } class B { public int A { get; set; } public int B { get; set; } }"; public NewLinesViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp) { Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.New_line_options_for_braces }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInTypes, CSharpVSResources.Place_open_brace_on_new_line_for_types, s_previewText, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInMethods, CSharpVSResources.Place_open_brace_on_new_line_for_methods_local_functions, s_methodPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInProperties, CSharpVSResources.Place_open_brace_on_new_line_for_properties_indexers_and_events, s_propertyPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInAccessors, CSharpVSResources.Place_open_brace_on_new_line_for_property_indexer_and_event_accessors, s_propertyPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods, CSharpVSResources.Place_open_brace_on_new_line_for_anonymous_methods, s_anonymousMethodPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, CSharpVSResources.Place_open_brace_on_new_line_for_control_blocks, s_forBlockPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes, CSharpVSResources.Place_open_brace_on_new_line_for_anonymous_types, s_anonymousTypePreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, CSharpVSResources.Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers, s_InitializerPreviewTrue, s_InitializerPreviewFalse, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody, CSharpVSResources.Place_open_brace_on_new_line_for_lambda_expression, s_lambdaPreview, this, optionStore)); Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.New_line_options_for_keywords }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForElse, CSharpVSResources.Place_else_on_new_line, s_ifElsePreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForCatch, CSharpVSResources.Place_catch_on_new_line, s_tryCatchFinallyPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForFinally, CSharpVSResources.Place_finally_on_new_line, s_tryCatchFinallyPreview, this, optionStore)); Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.New_line_options_for_expressions }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForMembersInObjectInit, CSharpVSResources.Place_members_in_object_initializers_on_new_line, s_objectInitializerPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes, CSharpVSResources.Place_members_in_anonymous_types_on_new_line, s_anonymousTypePreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForClausesInQuery, CSharpVSResources.Place_query_expression_clauses_on_new_line, s_queryExpressionPreview, this, optionStore)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { /// <summary> /// Interaction logic for FormattingNewLinesOptionControl.xaml /// </summary> internal class NewLinesViewModel : AbstractOptionPreviewViewModel { private const string s_previewText = @"//[ class C { } //]"; private const string s_methodPreview = @"class c { //[ void Goo(){ Console.WriteLine(); int LocalFunction(int x) { return 2 * x; } Console.ReadLine(); } //] }"; private const string s_propertyPreview = @"class c { //[ public int Property { get { return 42; } set { } } //] }"; private const string s_tryCatchFinallyPreview = @"using System; class C { void Goo() { //[ try { } catch (Exception e) { } finally { } //] } }"; private const string s_ifElsePreview = @"class C { void Goo() { //[ if (false) { } else { } //] } }"; private const string s_forBlockPreview = @"class C { void Goo() { //[ for (int i; i < 10; i++){ } //] } }"; private const string s_lambdaPreview = @"using System; class C { void Goo() { //[ Func<int, int> f = x => { return 2 * x; }; //] } }"; private const string s_anonymousMethodPreview = @"using System; delegate int D(int x); class C { void Goo() { //[ D d = delegate(int x) { return 2 * x; }; //] } }"; private const string s_anonymousTypePreview = @"using System; class C { void Goo() { //[ var z = new { A = 3, B = 4 }; //] } }"; private const string s_InitializerPreviewTrue = @"using System; using System.Collections.Generic; class C { void Goo() { //[ var z = new B() { A = 3, B = 4 }; // During Brace Completion or Only if Empty Body var collectionVariable = new List<int> { } // During Brace Completion var arrayVariable = new int[] { } //] } } class B { public int A { get; set; } public int B { get; set; } }"; private const string s_InitializerPreviewFalse = @"using System; using System.Collections.Generic; class C { void Goo() { //[ var z = new B() { A = 3, B = 4 }; // During Brace Completion or Only if Empty Body var collectionVariable = new List<int> { } // During Brace Completion var arrayVariable = new int[] { } //] } } class B { public int A { get; set; } public int B { get; set; } }"; private const string s_objectInitializerPreview = @"using System; class C { void Goo() { //[ var z = new B() { A = 3, B = 4 }; //] } } class B { public int A { get; set; } public int B { get; set; } }"; private const string s_queryExpressionPreview = @"using System; using System.Linq; using System.Collections.Generic; class C { void Goo(IEnumerable<int> e) { //[ var q = from a in e from b in e select a * b; //] } class B { public int A { get; set; } public int B { get; set; } }"; public NewLinesViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp) { Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.New_line_options_for_braces }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInTypes, CSharpVSResources.Place_open_brace_on_new_line_for_types, s_previewText, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInMethods, CSharpVSResources.Place_open_brace_on_new_line_for_methods_local_functions, s_methodPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInProperties, CSharpVSResources.Place_open_brace_on_new_line_for_properties_indexers_and_events, s_propertyPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInAccessors, CSharpVSResources.Place_open_brace_on_new_line_for_property_indexer_and_event_accessors, s_propertyPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods, CSharpVSResources.Place_open_brace_on_new_line_for_anonymous_methods, s_anonymousMethodPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, CSharpVSResources.Place_open_brace_on_new_line_for_control_blocks, s_forBlockPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes, CSharpVSResources.Place_open_brace_on_new_line_for_anonymous_types, s_anonymousTypePreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, CSharpVSResources.Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers, s_InitializerPreviewTrue, s_InitializerPreviewFalse, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody, CSharpVSResources.Place_open_brace_on_new_line_for_lambda_expression, s_lambdaPreview, this, optionStore)); Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.New_line_options_for_keywords }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForElse, CSharpVSResources.Place_else_on_new_line, s_ifElsePreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForCatch, CSharpVSResources.Place_catch_on_new_line, s_tryCatchFinallyPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForFinally, CSharpVSResources.Place_finally_on_new_line, s_tryCatchFinallyPreview, this, optionStore)); Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.New_line_options_for_expressions }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForMembersInObjectInit, CSharpVSResources.Place_members_in_object_initializers_on_new_line, s_objectInitializerPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes, CSharpVSResources.Place_members_in_anonymous_types_on_new_line, s_anonymousTypePreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.NewLineForClausesInQuery, CSharpVSResources.Place_query_expression_clauses_on_new_line, s_queryExpressionPreview, this, optionStore)); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Test/Emit/PDB/PDBLambdaTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests.EditAndContinueTestBase; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBLambdaTests : CSharpPDBTestBase { [WorkItem(539898, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539898")] [Fact] public void SequencePoints_Body() { var source = WithWindowsLineBreaks(@" using System; delegate void D(); class C { public static void Main() { D d = () => Console.Write(1); d(); } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""23"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""38"" document=""1"" /> <entry offset=""0x21"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""13"" document=""1"" /> <entry offset=""0x28"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x29""> <namespace name=""System"" /> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" /> </scope> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;Main&gt;b__0_0""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""21"" endLine=""8"" endColumn=""37"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(543479, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543479")] [Fact] public void Nested() { var source = MarkedSource(WithWindowsLineBreaks(@" using System; class Test { public static int Main() { if (M(1) != 10) return 1; return 0; } static public int M(int p) <M><C:0>{ Func<int, int> f1 = delegate(int x) <C:1><L:0.0>{ int q = 2; Func<int, int> f2 = (y) => <L:1.1>{ return p + q + x + y; }; return f2(3); }; return f1(4); } } "), removeTags: true); // We're validating offsets so need to remove tags entirely var compilation = CreateCompilationWithMscorlib40AndSystemCore(source.Tree, options: TestOptions.DebugDll); compilation.VerifyPdbLambdasAndClosures(source); } [WorkItem(543479, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543479")] [Fact] public void InitialSequencePoints() { var source = WithWindowsLineBreaks(@" class Test { void Goo(int p) { System.Func<int> f1 = () => p; f1(); } } "); // Specifically note the sequence points at 0x0 in Test.Main, Test.M, and the lambda bodies. var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Goo"" parameterNames=""p""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""0"" offset=""28"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""39"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""39"" document=""1"" /> <entry offset=""0x1b"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""14"" document=""1"" /> <entry offset=""0x22"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x23""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x23"" attributes=""0"" /> <local name=""f1"" il_index=""1"" il_start=""0x0"" il_end=""0x23"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c__DisplayClass0_0"" name=""&lt;Goo&gt;b__0""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Goo"" parameterNames=""p"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""37"" endLine=""6"" endColumn=""38"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(543479, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543479")] [Fact] public void Nested_InitialSequencePoints() { var source = WithWindowsLineBreaks(@" using System; class Test { public static int Main() { if (M(1) != 10) // can't step into M() at all return 1; return 0; } static public int M(int p) { Func<int, int> f1 = delegate(int x) { int q = 2; Func<int, int> f2 = (y) => { return p + q + x + y; }; return f2(3); }; return f1(4); } } "); // Specifically note the sequence points at 0x0 in Test.Main, Test.M, and the lambda bodies. var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" document=""1"" /> <entry offset=""0xf"" hidden=""true"" document=""1"" /> <entry offset=""0x12"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""22"" document=""1"" /> <entry offset=""0x16"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""1"" /> <entry offset=""0x1a"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <namespace name=""System"" /> </scope> </method> <method containingType=""Test"" name=""M"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""0"" offset=""26"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""0"" /> <closure offset=""56"" /> <lambda offset=""56"" closure=""0"" /> <lambda offset=""122"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" startLine=""14"" startColumn=""9"" endLine=""19"" endColumn=""11"" document=""1"" /> <entry offset=""0x1b"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""22"" document=""1"" /> <entry offset=""0x25"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x27""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x27"" attributes=""0"" /> <local name=""f1"" il_index=""1"" il_start=""0x0"" il_end=""0x27"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c__DisplayClass1_0"" name=""&lt;M&gt;b__0"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""30"" offset=""56"" /> <slot kind=""0"" offset=""110"" /> <slot kind=""21"" offset=""56"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x15"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""23"" document=""1"" /> <entry offset=""0x1c"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""66"" document=""1"" /> <entry offset=""0x29"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""26"" document=""1"" /> <entry offset=""0x33"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x35""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> <local name=""f2"" il_index=""1"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c__DisplayClass1_1"" name=""&lt;M&gt;b__1"" parameterNames=""y""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""21"" offset=""122"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""17"" startColumn=""40"" endLine=""17"" endColumn=""41"" document=""1"" /> <entry offset=""0x1"" startLine=""17"" startColumn=""42"" endLine=""17"" endColumn=""63"" document=""1"" /> <entry offset=""0x1f"" startLine=""17"" startColumn=""64"" endLine=""17"" endColumn=""65"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void FieldAndPropertyInitializers() { var source = WithWindowsLineBreaks(@" using System; class B { public B(Func<int> f) { } } class C : B { Func<int> FI = () => 1; static Func<int> FS = () => 2; Func<int> P { get; } = () => FS(); public C() : base(() => 3) {} } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""B"" name="".ctor"" parameterNames=""f""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""28"" document=""1"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""29"" endLine=""6"" endColumn=""30"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <namespace name=""System"" /> </scope> </method> <method containingType=""C"" name=""get_P""> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""19"" endLine=""13"" endColumn=""23"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> <encLambdaMap> <methodOrdinal>5</methodOrdinal> <lambda offset=""-2"" /> <lambda offset=""-28"" /> <lambda offset=""-19"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""28"" document=""1"" /> <entry offset=""0x25"" startLine=""13"" startColumn=""28"" endLine=""13"" endColumn=""38"" document=""1"" /> <entry offset=""0x4a"" startLine=""14"" startColumn=""18"" endLine=""14"" endColumn=""31"" document=""1"" /> <entry offset=""0x70"" startLine=""14"" startColumn=""32"" endLine=""14"" endColumn=""33"" document=""1"" /> <entry offset=""0x71"" startLine=""14"" startColumn=""33"" endLine=""14"" endColumn=""34"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name="".cctor""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> <encLambdaMap> <methodOrdinal>6</methodOrdinal> <lambda offset=""-1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""35"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.ctor&gt;b__5_0""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""29"" endLine=""14"" endColumn=""30"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.ctor&gt;b__5_1""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""26"" endLine=""11"" endColumn=""27"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.ctor&gt;b__5_2""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""34"" endLine=""13"" endColumn=""38"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.cctor&gt;b__6_0""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""33"" endLine=""12"" endColumn=""34"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ClosuresInCtor() { var source = WithWindowsLineBreaks(@" using System; class B { public B(Func<int> f) { } } class C : B { Func<int> f, g, h; public C(int a, int b) : base(() => a) { int c = 1; f = () => b; g = () => f(); h = () => c; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""B"" name="".ctor"" parameterNames=""f""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""28"" document=""1"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""29"" endLine=""6"" endColumn=""30"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <namespace name=""System"" /> </scope> </method> <method containingType=""C"" name="".ctor"" parameterNames=""a, b""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""30"" offset=""-1"" /> <slot kind=""30"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>3</methodOrdinal> <closure offset=""-1"" /> <closure offset=""0"" /> <lambda offset=""-2"" closure=""0"" /> <lambda offset=""41"" closure=""0"" /> <lambda offset=""63"" closure=""0"" /> <lambda offset=""87"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" startLine=""13"" startColumn=""30"" endLine=""13"" endColumn=""43"" document=""1"" /> <entry offset=""0x2e"" hidden=""true"" document=""1"" /> <entry offset=""0x34"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> <entry offset=""0x35"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""19"" document=""1"" /> <entry offset=""0x3c"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""21"" document=""1"" /> <entry offset=""0x4e"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""23"" document=""1"" /> <entry offset=""0x60"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""21"" document=""1"" /> <entry offset=""0x72"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x73""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x73"" attributes=""0"" /> <scope startOffset=""0x2e"" endOffset=""0x73""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0x2e"" il_end=""0x73"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C+&lt;&gt;c__DisplayClass3_0"" name=""&lt;.ctor&gt;b__0""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""41"" endLine=""13"" endColumn=""42"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c__DisplayClass3_0"" name=""&lt;.ctor&gt;b__1""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""16"" startColumn=""19"" endLine=""16"" endColumn=""20"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c__DisplayClass3_0"" name=""&lt;.ctor&gt;b__2""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""17"" startColumn=""19"" endLine=""17"" endColumn=""22"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c__DisplayClass3_1"" name=""&lt;.ctor&gt;b__3""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""19"" endLine=""18"" endColumn=""20"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void Queries1() { var source = WithWindowsLineBreaks(@" using System.Linq; class C { public void M() { int c = 1; var x = from a in new[] { 1, 2, 3 } let b = a + c where b > 10 select b * 10; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""0"" offset=""35"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""92"" closure=""0"" /> <lambda offset=""121"" /> <lambda offset=""152"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""1"" /> <entry offset=""0xe"" startLine=""9"" startColumn=""9"" endLine=""12"" endColumn=""31"" document=""1"" /> <entry offset=""0x79"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x7a""> <namespace name=""System.Linq"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x7a"" attributes=""0"" /> <local name=""x"" il_index=""1"" il_start=""0x0"" il_end=""0x7a"" attributes=""0"" /> </scope> </method> <method containingType=""C+&lt;&gt;c__DisplayClass0_0"" name=""&lt;M&gt;b__0"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""30"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;M&gt;b__0_1"" parameterNames=""&lt;&gt;h__TransparentIdentifier0""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""23"" endLine=""11"" endColumn=""29"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;M&gt;b__0_2"" parameterNames=""&lt;&gt;h__TransparentIdentifier0""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""24"" endLine=""12"" endColumn=""30"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void Queries_GroupBy1() { var source = WithWindowsLineBreaks(@" using System.Linq; class C { void F() { var result = from/*0*/ a in new[] { 1, 2, 3 } join/*1*/ b in new[] { 5 } on a + 1 equals b - 1 group/*2*/ new { a, b = a + 5 } by new { c = a + 4 } into d select/*3*/ d.Key; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""109"" /> <lambda offset=""122"" /> <lambda offset=""79"" /> <lambda offset=""185"" /> <lambda offset=""161"" /> <lambda offset=""244"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""11"" endColumn=""40"" document=""1"" /> <entry offset=""0xe6"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xe7""> <namespace name=""System.Linq"" /> <local name=""result"" il_index=""0"" il_start=""0x0"" il_end=""0xe7"" attributes=""0"" /> </scope> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_0"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""52"" endLine=""9"" endColumn=""57"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_1"" parameterNames=""b""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""65"" endLine=""9"" endColumn=""70"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_2"" parameterNames=""a, b""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""70"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_3"" parameterNames=""&lt;&gt;h__TransparentIdentifier0""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""57"" endLine=""10"" endColumn=""74"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_4"" parameterNames=""&lt;&gt;h__TransparentIdentifier0""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""33"" endLine=""10"" endColumn=""53"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_5"" parameterNames=""d""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""34"" endLine=""11"" endColumn=""39"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ForEachStatement_Array() { string source = WithWindowsLineBreaks(@" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""6"" offset=""41"" /> <slot kind=""8"" offset=""41"" /> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""108"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""41"" /> <closure offset=""108"" /> <lambda offset=""259"" closure=""0"" /> <lambda offset=""287"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""28"" endLine=""10"" endColumn=""39"" document=""1"" /> <entry offset=""0xf"" hidden=""true"" document=""1"" /> <entry offset=""0x11"" hidden=""true"" document=""1"" /> <entry offset=""0x17"" startLine=""10"" startColumn=""18"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x20"" hidden=""true"" document=""1"" /> <entry offset=""0x26"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x27"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x2e"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""1"" /> <entry offset=""0x41"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""1"" /> <entry offset=""0x54"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> <entry offset=""0x55"" hidden=""true"" document=""1"" /> <entry offset=""0x59"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""1"" /> <entry offset=""0x5f"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x60""> <scope startOffset=""0x11"" endOffset=""0x55""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""2"" il_start=""0x11"" il_end=""0x55"" attributes=""0"" /> <scope startOffset=""0x20"" endOffset=""0x55""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""3"" il_start=""0x20"" il_end=""0x55"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void ForEachStatement_MultidimensionalArray() { string source = WithWindowsLineBreaks(@" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[,] { { 1 } }) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""6"" offset=""41"" /> <slot kind=""7"" offset=""41"" /> <slot kind=""7"" offset=""41"" ordinal=""1"" /> <slot kind=""8"" offset=""41"" /> <slot kind=""8"" offset=""41"" ordinal=""1"" /> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""113"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""41"" /> <closure offset=""113"" /> <lambda offset=""269"" closure=""0"" /> <lambda offset=""297"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""28"" endLine=""10"" endColumn=""44"" document=""1"" /> <entry offset=""0x2b"" hidden=""true"" document=""1"" /> <entry offset=""0x36"" hidden=""true"" document=""1"" /> <entry offset=""0x38"" hidden=""true"" document=""1"" /> <entry offset=""0x3f"" startLine=""10"" startColumn=""18"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x4f"" hidden=""true"" document=""1"" /> <entry offset=""0x56"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x57"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x5f"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""1"" /> <entry offset=""0x73"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""1"" /> <entry offset=""0x87"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> <entry offset=""0x88"" hidden=""true"" document=""1"" /> <entry offset=""0x8e"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""1"" /> <entry offset=""0x93"" hidden=""true"" document=""1"" /> <entry offset=""0x97"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""1"" /> <entry offset=""0x9b"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9c""> <scope startOffset=""0x38"" endOffset=""0x88""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""5"" il_start=""0x38"" il_end=""0x88"" attributes=""0"" /> <scope startOffset=""0x4f"" endOffset=""0x88""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""6"" il_start=""0x4f"" il_end=""0x88"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void ForEachStatement_String() { string source = WithWindowsLineBreaks(@" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in ""1"") // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""6"" offset=""41"" /> <slot kind=""8"" offset=""41"" /> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""100"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""41"" /> <closure offset=""100"" /> <lambda offset=""245"" closure=""0"" /> <lambda offset=""273"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""28"" endLine=""10"" endColumn=""31"" document=""1"" /> <entry offset=""0xa"" hidden=""true"" document=""1"" /> <entry offset=""0xc"" hidden=""true"" document=""1"" /> <entry offset=""0x12"" startLine=""10"" startColumn=""18"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x26"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x2d"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""1"" /> <entry offset=""0x40"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""1"" /> <entry offset=""0x53"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> <entry offset=""0x54"" hidden=""true"" document=""1"" /> <entry offset=""0x58"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""1"" /> <entry offset=""0x61"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x62""> <scope startOffset=""0xc"" endOffset=""0x54""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""2"" il_start=""0xc"" il_end=""0x54"" attributes=""0"" /> <scope startOffset=""0x1f"" endOffset=""0x54""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""3"" il_start=""0x1f"" il_end=""0x54"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void ForEachStatement_Enumerable() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new List<int>()) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""5"" offset=""41"" /> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""112"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""41"" /> <closure offset=""112"" /> <lambda offset=""268"" closure=""0"" /> <lambda offset=""296"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""11"" startColumn=""28"" endLine=""11"" endColumn=""43"" document=""1"" /> <entry offset=""0xd"" hidden=""true"" document=""1"" /> <entry offset=""0xf"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" startLine=""11"" startColumn=""18"" endLine=""11"" endColumn=""24"" document=""1"" /> <entry offset=""0x22"" hidden=""true"" document=""1"" /> <entry offset=""0x28"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0x29"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""24"" document=""1"" /> <entry offset=""0x30"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""1"" /> <entry offset=""0x43"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""24"" document=""1"" /> <entry offset=""0x56"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x57"" startLine=""11"" startColumn=""25"" endLine=""11"" endColumn=""27"" document=""1"" /> <entry offset=""0x62"" hidden=""true"" document=""1"" /> <entry offset=""0x71"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x72""> <scope startOffset=""0xf"" endOffset=""0x57""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""1"" il_start=""0xf"" il_end=""0x57"" attributes=""0"" /> <scope startOffset=""0x22"" endOffset=""0x57""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""2"" il_start=""0x22"" il_end=""0x57"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void ForStatement1() { string source = WithWindowsLineBreaks(@" using System; class C { bool G(Func<int, int> f) => true; void F() { for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);) { int x2 = 0; G(a => x2); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""102"" /> <slot kind=""1"" offset=""41"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""41"" /> <closure offset=""102"" /> <lambda offset=""149"" closure=""1"" /> <lambda offset=""73"" closure=""0"" /> <lambda offset=""87"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""14"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0xe"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""32"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x17"" hidden=""true"" document=""1"" /> <entry offset=""0x1d"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x1e"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x25"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""24"" document=""1"" /> <entry offset=""0x38"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x39"" startLine=""10"" startColumn=""34"" endLine=""10"" endColumn=""58"" document=""1"" /> <entry offset=""0x63"" hidden=""true"" document=""1"" /> <entry offset=""0x66"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x67""> <scope startOffset=""0x1"" endOffset=""0x66""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x66"" attributes=""0"" /> <scope startOffset=""0x17"" endOffset=""0x39""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0x17"" il_end=""0x39"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void SwitchStatement1() { var source = WithWindowsLineBreaks(@" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; G(() => x2); switch (a) { case 1: int x0 = 1; G(() => x0); break; case 2: int x1 = 1; G(() => x1); break; } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""30"" offset=""86"" /> <slot kind=""35"" offset=""86"" /> <slot kind=""1"" offset=""86"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <closure offset=""0"" /> <closure offset=""86"" /> <lambda offset=""48"" closure=""0"" /> <lambda offset=""183"" closure=""1"" /> <lambda offset=""289"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""20"" document=""1"" /> <entry offset=""0xe"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""21"" document=""1"" /> <entry offset=""0x21"" hidden=""true"" document=""1"" /> <entry offset=""0x2e"" hidden=""true"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""28"" document=""1"" /> <entry offset=""0x43"" startLine=""19"" startColumn=""17"" endLine=""19"" endColumn=""29"" document=""1"" /> <entry offset=""0x56"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""23"" document=""1"" /> <entry offset=""0x58"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""28"" document=""1"" /> <entry offset=""0x5f"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""29"" document=""1"" /> <entry offset=""0x72"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""23"" document=""1"" /> <entry offset=""0x74"" startLine=""27"" startColumn=""5"" endLine=""27"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x75""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x75"" attributes=""0"" /> <scope startOffset=""0x21"" endOffset=""0x74""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0x21"" il_end=""0x74"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchExpressionWithLambda1() { string source = WithWindowsLineBreaks(@" using System; class C { static string M(object o) { return o switch { int i => new Func<string>(() => $""Number: {i} + {o} == {i + (int)o}"")(), _ => ""Don't know"" }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <closure offset=""11"" /> <lambda offset=""83"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" hidden=""true"" document=""1"" /> <entry offset=""0x1e"" startLine=""8"" startColumn=""18"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x47"" hidden=""true"" document=""1"" /> <entry offset=""0x49"" hidden=""true"" document=""1"" /> <entry offset=""0x4b"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""84"" document=""1"" /> <entry offset=""0x5f"" startLine=""11"" startColumn=""18"" endLine=""11"" endColumn=""30"" document=""1"" /> <entry offset=""0x67"" hidden=""true"" document=""1"" /> <entry offset=""0x6a"" startLine=""8"" startColumn=""9"" endLine=""12"" endColumn=""11"" document=""1"" /> <entry offset=""0x6b"" hidden=""true"" document=""1"" /> <entry offset=""0x6f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x71""> <namespace name=""System"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x71"" attributes=""0"" /> <scope startOffset=""0xe"" endOffset=""0x6f""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0x6f"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchExpressionWithLambda2() { string source = WithWindowsLineBreaks(@" using System; class C { static string M(object o) { return o switch { int i when new Func<string>(() => $""Number: {i} + {o} == {i + (int)o}"")() != null => $""Definitely a number: {i}"", int i => new Func<string>(() => $""Number: {i} + {o} == {i + (int)o}"")(), _ => ""Don't know"" }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""20"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <closure offset=""11"" /> <lambda offset=""85"" closure=""1"" /> <lambda offset=""210"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" hidden=""true"" document=""1"" /> <entry offset=""0x2a"" startLine=""8"" startColumn=""18"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x2b"" hidden=""true"" document=""1"" /> <entry offset=""0x3f"" hidden=""true"" document=""1"" /> <entry offset=""0x41"" startLine=""10"" startColumn=""19"" endLine=""10"" endColumn=""94"" document=""1"" /> <entry offset=""0x54"" hidden=""true"" document=""1"" /> <entry offset=""0x56"" startLine=""10"" startColumn=""98"" endLine=""10"" endColumn=""125"" document=""1"" /> <entry offset=""0x6e"" hidden=""true"" document=""1"" /> <entry offset=""0x7c"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""84"" document=""1"" /> <entry offset=""0x90"" startLine=""12"" startColumn=""18"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0x98"" hidden=""true"" document=""1"" /> <entry offset=""0x9b"" startLine=""8"" startColumn=""9"" endLine=""13"" endColumn=""11"" document=""1"" /> <entry offset=""0x9c"" hidden=""true"" document=""1"" /> <entry offset=""0xa1"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa4""> <namespace name=""System"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xa4"" attributes=""0"" /> <scope startOffset=""0xe"" endOffset=""0xa1""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xa1"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchExpressionWithLambda3() { string source = WithWindowsLineBreaks(@" using System; class C { static string M(object o) { return new Func<string>(() => o.ToString())() switch { ""goo"" => o.ToString(), _ => ""Don't know"" }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""57"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""41"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" startLine=""8"" startColumn=""9"" endLine=""12"" endColumn=""11"" document=""1"" /> <entry offset=""0x23"" startLine=""8"" startColumn=""55"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0x24"" hidden=""true"" document=""1"" /> <entry offset=""0x33"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""34"" document=""1"" /> <entry offset=""0x41"" startLine=""11"" startColumn=""18"" endLine=""11"" endColumn=""30"" document=""1"" /> <entry offset=""0x49"" hidden=""true"" document=""1"" /> <entry offset=""0x4c"" startLine=""8"" startColumn=""9"" endLine=""12"" endColumn=""11"" document=""1"" /> <entry offset=""0x4d"" hidden=""true"" document=""1"" /> <entry offset=""0x51"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x53""> <namespace name=""System"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x53"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchExpressionWithLambda4() { string source = WithWindowsLineBreaks(@" using System; class C { static string M(object o) { return o switch { string s => new Func<string>(() => string.Concat(""s"", s))(), int i => new Func<string>(() => i.ToString() + i switch { 1 => new Func<string>(() => string.Concat(""One"", i))(), _ => ""Don't know"" })(), _ => ""Don't know"" }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""11"" /> <lambda offset=""86"" closure=""0"" /> <lambda offset=""157"" closure=""0"" /> <lambda offset=""241"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""8"" startColumn=""18"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0xb"" hidden=""true"" document=""1"" /> <entry offset=""0x33"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" hidden=""true"" document=""1"" /> <entry offset=""0x37"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""72"" document=""1"" /> <entry offset=""0x4b"" hidden=""true"" document=""1"" /> <entry offset=""0x4d"" startLine=""11"" startColumn=""22"" endLine=""15"" endColumn=""17"" document=""1"" /> <entry offset=""0x61"" startLine=""16"" startColumn=""18"" endLine=""16"" endColumn=""30"" document=""1"" /> <entry offset=""0x69"" hidden=""true"" document=""1"" /> <entry offset=""0x6c"" startLine=""8"" startColumn=""9"" endLine=""17"" endColumn=""11"" document=""1"" /> <entry offset=""0x6d"" hidden=""true"" document=""1"" /> <entry offset=""0x71"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x73""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x71""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x71"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchExpressionWithLambda5() { string source = WithWindowsLineBreaks(@" using System; class C { static string M(object o) { return o switch { string s => new Func<string>(() => string.Concat(o, s))(), int i => new Func<string>(() => i.ToString() + i switch { 1 => new Func<string>(() => string.Concat(""One"", i, o))(), _ => ""Don't know"" })(), _ => ""Don't know"" }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <closure offset=""11"" /> <lambda offset=""86"" closure=""1"" /> <lambda offset=""155"" closure=""1"" /> <lambda offset=""239"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" hidden=""true"" document=""1"" /> <entry offset=""0x1e"" startLine=""8"" startColumn=""18"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x65"" hidden=""true"" document=""1"" /> <entry offset=""0x67"" hidden=""true"" document=""1"" /> <entry offset=""0x69"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""70"" document=""1"" /> <entry offset=""0x7d"" hidden=""true"" document=""1"" /> <entry offset=""0x7f"" startLine=""11"" startColumn=""22"" endLine=""15"" endColumn=""17"" document=""1"" /> <entry offset=""0x93"" startLine=""16"" startColumn=""18"" endLine=""16"" endColumn=""30"" document=""1"" /> <entry offset=""0x9b"" hidden=""true"" document=""1"" /> <entry offset=""0x9e"" startLine=""8"" startColumn=""9"" endLine=""17"" endColumn=""11"" document=""1"" /> <entry offset=""0x9f"" hidden=""true"" document=""1"" /> <entry offset=""0xa3"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa5""> <namespace name=""System"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xa5"" attributes=""0"" /> <scope startOffset=""0xe"" endOffset=""0xa3""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xa3"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchExpressionWithLambda6() { string source = WithWindowsLineBreaks(@" using System; class C { static string M(object o) { return o switch { string s => new Func<string>(() => string.Concat(""s"", s))(), int i => new Func<string>(() => i.ToString() + new Func<int>(() => i + 1)())(), _ => ""Don't know"" }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""11"" /> <lambda offset=""86"" closure=""0"" /> <lambda offset=""157"" closure=""0"" /> <lambda offset=""192"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""8"" startColumn=""18"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0xb"" hidden=""true"" document=""1"" /> <entry offset=""0x33"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" hidden=""true"" document=""1"" /> <entry offset=""0x37"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""72"" document=""1"" /> <entry offset=""0x4b"" hidden=""true"" document=""1"" /> <entry offset=""0x4d"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""91"" document=""1"" /> <entry offset=""0x61"" startLine=""12"" startColumn=""18"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0x69"" hidden=""true"" document=""1"" /> <entry offset=""0x6c"" startLine=""8"" startColumn=""9"" endLine=""13"" endColumn=""11"" document=""1"" /> <entry offset=""0x6d"" hidden=""true"" document=""1"" /> <entry offset=""0x71"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x73""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x71""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x71"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void UsingStatement1() { string source = WithWindowsLineBreaks(@" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static IDisposable D() => null; static void F() { using (IDisposable x0 = D(), y0 = D()) { int x1 = 1; G(() => x0); G(() => y0); G(() => x1); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F"" parameterNames=""a, b""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""41"" endLine=""7"" endColumn=""42"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""89"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>3</methodOrdinal> <closure offset=""41"" /> <closure offset=""89"" /> <lambda offset=""147"" closure=""0"" /> <lambda offset=""173"" closure=""0"" /> <lambda offset=""199"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""36"" document=""1"" /> <entry offset=""0x12"" startLine=""12"" startColumn=""38"" endLine=""12"" endColumn=""46"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x23"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x24"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""1"" /> <entry offset=""0x2b"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""25"" document=""1"" /> <entry offset=""0x3d"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""25"" document=""1"" /> <entry offset=""0x4f"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" /> <entry offset=""0x61"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x64"" hidden=""true"" document=""1"" /> <entry offset=""0x78"" hidden=""true"" document=""1"" /> <entry offset=""0x79"" hidden=""true"" document=""1"" /> <entry offset=""0x7b"" hidden=""true"" document=""1"" /> <entry offset=""0x8f"" hidden=""true"" document=""1"" /> <entry offset=""0x90"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x91""> <scope startOffset=""0x1"" endOffset=""0x90""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x90"" attributes=""0"" /> <scope startOffset=""0x1d"" endOffset=""0x62""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0x1d"" il_end=""0x62"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void IfStatement1() { string source = @" class C { static void F() { new System.Action(() => { bool result = false; if (result) System.Console.WriteLine(1); })(); } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("C.<>c.<F>b__0_0", @" { // Code size 16 (0x10) .maxstack 1 .locals init (bool V_0, //result bool V_1) -IL_0000: nop -IL_0001: ldc.i4.0 IL_0002: stloc.0 -IL_0003: ldloc.0 IL_0004: stloc.1 ~IL_0005: ldloc.1 IL_0006: brfalse.s IL_000f -IL_0008: ldc.i4.1 IL_0009: call ""void System.Console.WriteLine(int)"" IL_000e: nop -IL_000f: ret } ", sequencePoints: "C+<>c.<F>b__0_0"); } [Fact] public void IfStatement2() { string source = @" class C { static void F() { new System.Action(() => { { bool result = false; if (result) System.Console.WriteLine(1); } })(); } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("C.<>c.<F>b__0_0", @" { // Code size 18 (0x12) .maxstack 1 .locals init (bool V_0, //result bool V_1) -IL_0000: nop -IL_0001: nop -IL_0002: ldc.i4.0 IL_0003: stloc.0 -IL_0004: ldloc.0 IL_0005: stloc.1 ~IL_0006: ldloc.1 IL_0007: brfalse.s IL_0010 -IL_0009: ldc.i4.1 IL_000a: call ""void System.Console.WriteLine(int)"" IL_000f: nop -IL_0010: nop -IL_0011: ret } ", sequencePoints: "C+<>c.<F>b__0_0"); } [Fact] public void WithExpression() { var source = MarkedSource(WithWindowsLineBreaks(@" using System; record R(int X); class Test { public static void M(int a) <M><C:0>{ var x = new R(1); var y = x with { X = new Func<int>(() => <L:0.0>a)() }; } } "), removeTags: true); // We're validating offsets so need to remove tags entirely // Use NetCoreApp in order to use records var compilation = CreateCompilation(source.Tree, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugDll); compilation.VerifyPdbLambdasAndClosures(source); } [Fact] public void WithExpression_2() { var source = MarkedSource(WithWindowsLineBreaks(@" using System; record R(int X, int Y); class Test { public static void M(int a) <M><C:0>{ var x = new R(1, 2); var b = 1; var y = x with { X = new Func<int>(() => <L:0.0>a)(), Y = new Func<int>(() => <L:1.0>b)() }; } } "), removeTags: true); // We're validating offsets so need to remove tags entirely // Use NetCoreApp in order to use records var compilation = CreateCompilation(source.Tree, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugDll); compilation.VerifyPdbLambdasAndClosures(source); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/52068")] public void WithExpression_3() { var source = MarkedSource(WithWindowsLineBreaks(@" using System; record R(int X, int Y); record Z(int A, R R); class Test { public static void M(int a) <M><C:0>{ var r = new R(1, 2); var x = new Z(1, new R(2, 3)); var b = 1; var y = x with { A = new Func<int>(() => <L:0.0>a)(), R = r with { X = 4, Y = new Func<int>(() => <L:1.0>b)() } }; } } "), removeTags: true); // We're validating offsets so need to remove tags entirely // Use NetCoreApp in order to use records var compilation = CreateCompilation(source.Tree, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugDll); compilation.VerifyPdbLambdasAndClosures(source); } [Fact] public void Record_1() { var source = WithWindowsLineBreaks(@" using System; record D(int X) { public int Y { get; set; } = new Func<int, int>(a => a + X).Invoke(1); } "); // Use NetCoreApp in order to use records var compilation = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugDll); compilation.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""D"" name="".ctor"" parameterNames=""X""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""-1"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""-1"" /> <lambda offset=""-16"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""3"" startColumn=""10"" endLine=""3"" endColumn=""15"" document=""1"" /> <entry offset=""0x19"" startLine=""5"" startColumn=""34"" endLine=""5"" endColumn=""74"" document=""1"" /> <entry offset=""0x31"" startLine=""3"" startColumn=""1"" endLine=""6"" endColumn=""2"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x39""> <namespace name=""System"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x39"" attributes=""0"" /> </scope> </method> <method containingType=""D"" name=""get_X""> <sequencePoints> <entry offset=""0x0"" startLine=""3"" startColumn=""10"" endLine=""3"" endColumn=""15"" document=""1"" /> </sequencePoints> </method> <method containingType=""D"" name=""set_X"" parameterNames=""value""> <sequencePoints> <entry offset=""0x0"" startLine=""3"" startColumn=""10"" endLine=""3"" endColumn=""15"" document=""1"" /> </sequencePoints> </method> <method containingType=""D"" name=""get_Y""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""20"" endLine=""5"" endColumn=""24"" document=""1"" /> </sequencePoints> </method> <method containingType=""D"" name=""set_Y"" parameterNames=""value""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""25"" endLine=""5"" endColumn=""29"" document=""1"" /> </sequencePoints> </method> <method containingType=""D+&lt;&gt;c__DisplayClass0_0"" name=""&lt;.ctor&gt;b__0"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""D"" methodName="".ctor"" parameterNames=""X"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""58"" endLine=""5"" endColumn=""63"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: CodeAnalysis.Emit.DebugInformationFormat.Pdb); } [Fact] public void Record_2() { var source = WithWindowsLineBreaks(@" using System; record C(int X) { public C(int x, Func<int> f) : this(x) { } } record D(int X) : C(F(X, out int z), () => z) { static int F(int x, out int p) { p = 1; return x + 1; } } "); // Use NetCoreApp in order to use records var compilation = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugDll); compilation.VerifyDiagnostics(); compilation.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor"" parameterNames=""X""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""3"" startColumn=""10"" endLine=""3"" endColumn=""15"" document=""1"" /> <entry offset=""0x7"" startLine=""3"" startColumn=""1"" endLine=""9"" endColumn=""2"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xf""> <namespace name=""System"" /> </scope> </method> <method containingType=""C"" name=""get_X""> <sequencePoints> <entry offset=""0x0"" startLine=""3"" startColumn=""10"" endLine=""3"" endColumn=""15"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""set_X"" parameterNames=""value""> <sequencePoints> <entry offset=""0x0"" startLine=""3"" startColumn=""10"" endLine=""3"" endColumn=""15"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name="".ctor"" parameterNames=""x, f""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" parameterNames=""X"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""11"" endLine=""6"" endColumn=""18"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x9"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method containingType=""D"" name="".ctor"" parameterNames=""X""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" parameterNames=""X"" /> <encLocalSlotMap> <slot kind=""30"" offset=""-1"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""-1"" /> <lambda offset=""-2"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""11"" startColumn=""19"" endLine=""11"" endColumn=""46"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x26""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x26"" attributes=""0"" /> </scope> </method> <method containingType=""D"" name=""F"" parameterNames=""x, p""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" parameterNames=""X"" /> <encLocalSlotMap> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""15"" document=""1"" /> <entry offset=""0x4"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""22"" document=""1"" /> <entry offset=""0xa"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method containingType=""D+&lt;&gt;c__DisplayClass0_0"" name=""&lt;.ctor&gt;b__0""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" parameterNames=""X"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""44"" endLine=""11"" endColumn=""45"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: CodeAnalysis.Emit.DebugInformationFormat.Pdb); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests.EditAndContinueTestBase; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBLambdaTests : CSharpPDBTestBase { [WorkItem(539898, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539898")] [Fact] public void SequencePoints_Body() { var source = WithWindowsLineBreaks(@" using System; delegate void D(); class C { public static void Main() { D d = () => Console.Write(1); d(); } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""23"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""38"" document=""1"" /> <entry offset=""0x21"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""13"" document=""1"" /> <entry offset=""0x28"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x29""> <namespace name=""System"" /> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" /> </scope> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;Main&gt;b__0_0""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""21"" endLine=""8"" endColumn=""37"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(543479, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543479")] [Fact] public void Nested() { var source = MarkedSource(WithWindowsLineBreaks(@" using System; class Test { public static int Main() { if (M(1) != 10) return 1; return 0; } static public int M(int p) <M><C:0>{ Func<int, int> f1 = delegate(int x) <C:1><L:0.0>{ int q = 2; Func<int, int> f2 = (y) => <L:1.1>{ return p + q + x + y; }; return f2(3); }; return f1(4); } } "), removeTags: true); // We're validating offsets so need to remove tags entirely var compilation = CreateCompilationWithMscorlib40AndSystemCore(source.Tree, options: TestOptions.DebugDll); compilation.VerifyPdbLambdasAndClosures(source); } [WorkItem(543479, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543479")] [Fact] public void InitialSequencePoints() { var source = WithWindowsLineBreaks(@" class Test { void Goo(int p) { System.Func<int> f1 = () => p; f1(); } } "); // Specifically note the sequence points at 0x0 in Test.Main, Test.M, and the lambda bodies. var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Goo"" parameterNames=""p""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""0"" offset=""28"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""39"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""39"" document=""1"" /> <entry offset=""0x1b"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""14"" document=""1"" /> <entry offset=""0x22"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x23""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x23"" attributes=""0"" /> <local name=""f1"" il_index=""1"" il_start=""0x0"" il_end=""0x23"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c__DisplayClass0_0"" name=""&lt;Goo&gt;b__0""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Goo"" parameterNames=""p"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""37"" endLine=""6"" endColumn=""38"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(543479, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543479")] [Fact] public void Nested_InitialSequencePoints() { var source = WithWindowsLineBreaks(@" using System; class Test { public static int Main() { if (M(1) != 10) // can't step into M() at all return 1; return 0; } static public int M(int p) { Func<int, int> f1 = delegate(int x) { int q = 2; Func<int, int> f2 = (y) => { return p + q + x + y; }; return f2(3); }; return f1(4); } } "); // Specifically note the sequence points at 0x0 in Test.Main, Test.M, and the lambda bodies. var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" document=""1"" /> <entry offset=""0xf"" hidden=""true"" document=""1"" /> <entry offset=""0x12"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""22"" document=""1"" /> <entry offset=""0x16"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""1"" /> <entry offset=""0x1a"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <namespace name=""System"" /> </scope> </method> <method containingType=""Test"" name=""M"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""0"" offset=""26"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""0"" /> <closure offset=""56"" /> <lambda offset=""56"" closure=""0"" /> <lambda offset=""122"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" startLine=""14"" startColumn=""9"" endLine=""19"" endColumn=""11"" document=""1"" /> <entry offset=""0x1b"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""22"" document=""1"" /> <entry offset=""0x25"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x27""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x27"" attributes=""0"" /> <local name=""f1"" il_index=""1"" il_start=""0x0"" il_end=""0x27"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c__DisplayClass1_0"" name=""&lt;M&gt;b__0"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""30"" offset=""56"" /> <slot kind=""0"" offset=""110"" /> <slot kind=""21"" offset=""56"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x15"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""23"" document=""1"" /> <entry offset=""0x1c"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""66"" document=""1"" /> <entry offset=""0x29"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""26"" document=""1"" /> <entry offset=""0x33"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x35""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> <local name=""f2"" il_index=""1"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c__DisplayClass1_1"" name=""&lt;M&gt;b__1"" parameterNames=""y""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""21"" offset=""122"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""17"" startColumn=""40"" endLine=""17"" endColumn=""41"" document=""1"" /> <entry offset=""0x1"" startLine=""17"" startColumn=""42"" endLine=""17"" endColumn=""63"" document=""1"" /> <entry offset=""0x1f"" startLine=""17"" startColumn=""64"" endLine=""17"" endColumn=""65"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void FieldAndPropertyInitializers() { var source = WithWindowsLineBreaks(@" using System; class B { public B(Func<int> f) { } } class C : B { Func<int> FI = () => 1; static Func<int> FS = () => 2; Func<int> P { get; } = () => FS(); public C() : base(() => 3) {} } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""B"" name="".ctor"" parameterNames=""f""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""28"" document=""1"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""29"" endLine=""6"" endColumn=""30"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <namespace name=""System"" /> </scope> </method> <method containingType=""C"" name=""get_P""> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""19"" endLine=""13"" endColumn=""23"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> <encLambdaMap> <methodOrdinal>5</methodOrdinal> <lambda offset=""-2"" /> <lambda offset=""-28"" /> <lambda offset=""-19"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""28"" document=""1"" /> <entry offset=""0x25"" startLine=""13"" startColumn=""28"" endLine=""13"" endColumn=""38"" document=""1"" /> <entry offset=""0x4a"" startLine=""14"" startColumn=""18"" endLine=""14"" endColumn=""31"" document=""1"" /> <entry offset=""0x70"" startLine=""14"" startColumn=""32"" endLine=""14"" endColumn=""33"" document=""1"" /> <entry offset=""0x71"" startLine=""14"" startColumn=""33"" endLine=""14"" endColumn=""34"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name="".cctor""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> <encLambdaMap> <methodOrdinal>6</methodOrdinal> <lambda offset=""-1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""35"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.ctor&gt;b__5_0""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""29"" endLine=""14"" endColumn=""30"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.ctor&gt;b__5_1""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""26"" endLine=""11"" endColumn=""27"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.ctor&gt;b__5_2""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""34"" endLine=""13"" endColumn=""38"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.cctor&gt;b__6_0""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""33"" endLine=""12"" endColumn=""34"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ClosuresInCtor() { var source = WithWindowsLineBreaks(@" using System; class B { public B(Func<int> f) { } } class C : B { Func<int> f, g, h; public C(int a, int b) : base(() => a) { int c = 1; f = () => b; g = () => f(); h = () => c; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""B"" name="".ctor"" parameterNames=""f""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""28"" document=""1"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""29"" endLine=""6"" endColumn=""30"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <namespace name=""System"" /> </scope> </method> <method containingType=""C"" name="".ctor"" parameterNames=""a, b""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""30"" offset=""-1"" /> <slot kind=""30"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>3</methodOrdinal> <closure offset=""-1"" /> <closure offset=""0"" /> <lambda offset=""-2"" closure=""0"" /> <lambda offset=""41"" closure=""0"" /> <lambda offset=""63"" closure=""0"" /> <lambda offset=""87"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" startLine=""13"" startColumn=""30"" endLine=""13"" endColumn=""43"" document=""1"" /> <entry offset=""0x2e"" hidden=""true"" document=""1"" /> <entry offset=""0x34"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> <entry offset=""0x35"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""19"" document=""1"" /> <entry offset=""0x3c"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""21"" document=""1"" /> <entry offset=""0x4e"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""23"" document=""1"" /> <entry offset=""0x60"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""21"" document=""1"" /> <entry offset=""0x72"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x73""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x73"" attributes=""0"" /> <scope startOffset=""0x2e"" endOffset=""0x73""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0x2e"" il_end=""0x73"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C+&lt;&gt;c__DisplayClass3_0"" name=""&lt;.ctor&gt;b__0""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""41"" endLine=""13"" endColumn=""42"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c__DisplayClass3_0"" name=""&lt;.ctor&gt;b__1""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""16"" startColumn=""19"" endLine=""16"" endColumn=""20"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c__DisplayClass3_0"" name=""&lt;.ctor&gt;b__2""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""17"" startColumn=""19"" endLine=""17"" endColumn=""22"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c__DisplayClass3_1"" name=""&lt;.ctor&gt;b__3""> <customDebugInfo> <forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""19"" endLine=""18"" endColumn=""20"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void Queries1() { var source = WithWindowsLineBreaks(@" using System.Linq; class C { public void M() { int c = 1; var x = from a in new[] { 1, 2, 3 } let b = a + c where b > 10 select b * 10; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""0"" offset=""35"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""92"" closure=""0"" /> <lambda offset=""121"" /> <lambda offset=""152"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""1"" /> <entry offset=""0xe"" startLine=""9"" startColumn=""9"" endLine=""12"" endColumn=""31"" document=""1"" /> <entry offset=""0x79"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x7a""> <namespace name=""System.Linq"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x7a"" attributes=""0"" /> <local name=""x"" il_index=""1"" il_start=""0x0"" il_end=""0x7a"" attributes=""0"" /> </scope> </method> <method containingType=""C+&lt;&gt;c__DisplayClass0_0"" name=""&lt;M&gt;b__0"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""30"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;M&gt;b__0_1"" parameterNames=""&lt;&gt;h__TransparentIdentifier0""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""23"" endLine=""11"" endColumn=""29"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;M&gt;b__0_2"" parameterNames=""&lt;&gt;h__TransparentIdentifier0""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""24"" endLine=""12"" endColumn=""30"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void Queries_GroupBy1() { var source = WithWindowsLineBreaks(@" using System.Linq; class C { void F() { var result = from/*0*/ a in new[] { 1, 2, 3 } join/*1*/ b in new[] { 5 } on a + 1 equals b - 1 group/*2*/ new { a, b = a + 5 } by new { c = a + 4 } into d select/*3*/ d.Key; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""109"" /> <lambda offset=""122"" /> <lambda offset=""79"" /> <lambda offset=""185"" /> <lambda offset=""161"" /> <lambda offset=""244"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""11"" endColumn=""40"" document=""1"" /> <entry offset=""0xe6"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xe7""> <namespace name=""System.Linq"" /> <local name=""result"" il_index=""0"" il_start=""0x0"" il_end=""0xe7"" attributes=""0"" /> </scope> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_0"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""52"" endLine=""9"" endColumn=""57"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_1"" parameterNames=""b""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""65"" endLine=""9"" endColumn=""70"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_2"" parameterNames=""a, b""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""70"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_3"" parameterNames=""&lt;&gt;h__TransparentIdentifier0""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""57"" endLine=""10"" endColumn=""74"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_4"" parameterNames=""&lt;&gt;h__TransparentIdentifier0""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""33"" endLine=""10"" endColumn=""53"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;F&gt;b__0_5"" parameterNames=""d""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""34"" endLine=""11"" endColumn=""39"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ForEachStatement_Array() { string source = WithWindowsLineBreaks(@" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""6"" offset=""41"" /> <slot kind=""8"" offset=""41"" /> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""108"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""41"" /> <closure offset=""108"" /> <lambda offset=""259"" closure=""0"" /> <lambda offset=""287"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""28"" endLine=""10"" endColumn=""39"" document=""1"" /> <entry offset=""0xf"" hidden=""true"" document=""1"" /> <entry offset=""0x11"" hidden=""true"" document=""1"" /> <entry offset=""0x17"" startLine=""10"" startColumn=""18"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x20"" hidden=""true"" document=""1"" /> <entry offset=""0x26"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x27"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x2e"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""1"" /> <entry offset=""0x41"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""1"" /> <entry offset=""0x54"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> <entry offset=""0x55"" hidden=""true"" document=""1"" /> <entry offset=""0x59"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""1"" /> <entry offset=""0x5f"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x60""> <scope startOffset=""0x11"" endOffset=""0x55""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""2"" il_start=""0x11"" il_end=""0x55"" attributes=""0"" /> <scope startOffset=""0x20"" endOffset=""0x55""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""3"" il_start=""0x20"" il_end=""0x55"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void ForEachStatement_MultidimensionalArray() { string source = WithWindowsLineBreaks(@" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[,] { { 1 } }) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""6"" offset=""41"" /> <slot kind=""7"" offset=""41"" /> <slot kind=""7"" offset=""41"" ordinal=""1"" /> <slot kind=""8"" offset=""41"" /> <slot kind=""8"" offset=""41"" ordinal=""1"" /> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""113"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""41"" /> <closure offset=""113"" /> <lambda offset=""269"" closure=""0"" /> <lambda offset=""297"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""28"" endLine=""10"" endColumn=""44"" document=""1"" /> <entry offset=""0x2b"" hidden=""true"" document=""1"" /> <entry offset=""0x36"" hidden=""true"" document=""1"" /> <entry offset=""0x38"" hidden=""true"" document=""1"" /> <entry offset=""0x3f"" startLine=""10"" startColumn=""18"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x4f"" hidden=""true"" document=""1"" /> <entry offset=""0x56"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x57"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x5f"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""1"" /> <entry offset=""0x73"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""1"" /> <entry offset=""0x87"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> <entry offset=""0x88"" hidden=""true"" document=""1"" /> <entry offset=""0x8e"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""1"" /> <entry offset=""0x93"" hidden=""true"" document=""1"" /> <entry offset=""0x97"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""1"" /> <entry offset=""0x9b"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9c""> <scope startOffset=""0x38"" endOffset=""0x88""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""5"" il_start=""0x38"" il_end=""0x88"" attributes=""0"" /> <scope startOffset=""0x4f"" endOffset=""0x88""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""6"" il_start=""0x4f"" il_end=""0x88"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void ForEachStatement_String() { string source = WithWindowsLineBreaks(@" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in ""1"") // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""6"" offset=""41"" /> <slot kind=""8"" offset=""41"" /> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""100"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""41"" /> <closure offset=""100"" /> <lambda offset=""245"" closure=""0"" /> <lambda offset=""273"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""28"" endLine=""10"" endColumn=""31"" document=""1"" /> <entry offset=""0xa"" hidden=""true"" document=""1"" /> <entry offset=""0xc"" hidden=""true"" document=""1"" /> <entry offset=""0x12"" startLine=""10"" startColumn=""18"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x26"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x2d"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""1"" /> <entry offset=""0x40"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""1"" /> <entry offset=""0x53"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> <entry offset=""0x54"" hidden=""true"" document=""1"" /> <entry offset=""0x58"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""1"" /> <entry offset=""0x61"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x62""> <scope startOffset=""0xc"" endOffset=""0x54""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""2"" il_start=""0xc"" il_end=""0x54"" attributes=""0"" /> <scope startOffset=""0x1f"" endOffset=""0x54""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""3"" il_start=""0x1f"" il_end=""0x54"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void ForEachStatement_Enumerable() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new List<int>()) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""5"" offset=""41"" /> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""112"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""41"" /> <closure offset=""112"" /> <lambda offset=""268"" closure=""0"" /> <lambda offset=""296"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""11"" startColumn=""28"" endLine=""11"" endColumn=""43"" document=""1"" /> <entry offset=""0xd"" hidden=""true"" document=""1"" /> <entry offset=""0xf"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" startLine=""11"" startColumn=""18"" endLine=""11"" endColumn=""24"" document=""1"" /> <entry offset=""0x22"" hidden=""true"" document=""1"" /> <entry offset=""0x28"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0x29"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""24"" document=""1"" /> <entry offset=""0x30"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""1"" /> <entry offset=""0x43"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""24"" document=""1"" /> <entry offset=""0x56"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x57"" startLine=""11"" startColumn=""25"" endLine=""11"" endColumn=""27"" document=""1"" /> <entry offset=""0x62"" hidden=""true"" document=""1"" /> <entry offset=""0x71"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x72""> <scope startOffset=""0xf"" endOffset=""0x57""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""1"" il_start=""0xf"" il_end=""0x57"" attributes=""0"" /> <scope startOffset=""0x22"" endOffset=""0x57""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""2"" il_start=""0x22"" il_end=""0x57"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void ForStatement1() { string source = WithWindowsLineBreaks(@" using System; class C { bool G(Func<int, int> f) => true; void F() { for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);) { int x2 = 0; G(a => x2); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""102"" /> <slot kind=""1"" offset=""41"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""41"" /> <closure offset=""102"" /> <lambda offset=""149"" closure=""1"" /> <lambda offset=""73"" closure=""0"" /> <lambda offset=""87"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""14"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0xe"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""32"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x17"" hidden=""true"" document=""1"" /> <entry offset=""0x1d"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x1e"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x25"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""24"" document=""1"" /> <entry offset=""0x38"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x39"" startLine=""10"" startColumn=""34"" endLine=""10"" endColumn=""58"" document=""1"" /> <entry offset=""0x63"" hidden=""true"" document=""1"" /> <entry offset=""0x66"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x67""> <scope startOffset=""0x1"" endOffset=""0x66""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x66"" attributes=""0"" /> <scope startOffset=""0x17"" endOffset=""0x39""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0x17"" il_end=""0x39"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void SwitchStatement1() { var source = WithWindowsLineBreaks(@" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; G(() => x2); switch (a) { case 1: int x0 = 1; G(() => x0); break; case 2: int x1 = 1; G(() => x1); break; } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""30"" offset=""86"" /> <slot kind=""35"" offset=""86"" /> <slot kind=""1"" offset=""86"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <closure offset=""0"" /> <closure offset=""86"" /> <lambda offset=""48"" closure=""0"" /> <lambda offset=""183"" closure=""1"" /> <lambda offset=""289"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""20"" document=""1"" /> <entry offset=""0xe"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""21"" document=""1"" /> <entry offset=""0x21"" hidden=""true"" document=""1"" /> <entry offset=""0x2e"" hidden=""true"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""28"" document=""1"" /> <entry offset=""0x43"" startLine=""19"" startColumn=""17"" endLine=""19"" endColumn=""29"" document=""1"" /> <entry offset=""0x56"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""23"" document=""1"" /> <entry offset=""0x58"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""28"" document=""1"" /> <entry offset=""0x5f"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""29"" document=""1"" /> <entry offset=""0x72"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""23"" document=""1"" /> <entry offset=""0x74"" startLine=""27"" startColumn=""5"" endLine=""27"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x75""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x75"" attributes=""0"" /> <scope startOffset=""0x21"" endOffset=""0x74""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0x21"" il_end=""0x74"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchExpressionWithLambda1() { string source = WithWindowsLineBreaks(@" using System; class C { static string M(object o) { return o switch { int i => new Func<string>(() => $""Number: {i} + {o} == {i + (int)o}"")(), _ => ""Don't know"" }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <closure offset=""11"" /> <lambda offset=""83"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" hidden=""true"" document=""1"" /> <entry offset=""0x1e"" startLine=""8"" startColumn=""18"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x47"" hidden=""true"" document=""1"" /> <entry offset=""0x49"" hidden=""true"" document=""1"" /> <entry offset=""0x4b"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""84"" document=""1"" /> <entry offset=""0x5f"" startLine=""11"" startColumn=""18"" endLine=""11"" endColumn=""30"" document=""1"" /> <entry offset=""0x67"" hidden=""true"" document=""1"" /> <entry offset=""0x6a"" startLine=""8"" startColumn=""9"" endLine=""12"" endColumn=""11"" document=""1"" /> <entry offset=""0x6b"" hidden=""true"" document=""1"" /> <entry offset=""0x6f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x71""> <namespace name=""System"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x71"" attributes=""0"" /> <scope startOffset=""0xe"" endOffset=""0x6f""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0x6f"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchExpressionWithLambda2() { string source = WithWindowsLineBreaks(@" using System; class C { static string M(object o) { return o switch { int i when new Func<string>(() => $""Number: {i} + {o} == {i + (int)o}"")() != null => $""Definitely a number: {i}"", int i => new Func<string>(() => $""Number: {i} + {o} == {i + (int)o}"")(), _ => ""Don't know"" }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""20"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <closure offset=""11"" /> <lambda offset=""85"" closure=""1"" /> <lambda offset=""210"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" hidden=""true"" document=""1"" /> <entry offset=""0x2a"" startLine=""8"" startColumn=""18"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x2b"" hidden=""true"" document=""1"" /> <entry offset=""0x3f"" hidden=""true"" document=""1"" /> <entry offset=""0x41"" startLine=""10"" startColumn=""19"" endLine=""10"" endColumn=""94"" document=""1"" /> <entry offset=""0x54"" hidden=""true"" document=""1"" /> <entry offset=""0x56"" startLine=""10"" startColumn=""98"" endLine=""10"" endColumn=""125"" document=""1"" /> <entry offset=""0x6e"" hidden=""true"" document=""1"" /> <entry offset=""0x7c"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""84"" document=""1"" /> <entry offset=""0x90"" startLine=""12"" startColumn=""18"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0x98"" hidden=""true"" document=""1"" /> <entry offset=""0x9b"" startLine=""8"" startColumn=""9"" endLine=""13"" endColumn=""11"" document=""1"" /> <entry offset=""0x9c"" hidden=""true"" document=""1"" /> <entry offset=""0xa1"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa4""> <namespace name=""System"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xa4"" attributes=""0"" /> <scope startOffset=""0xe"" endOffset=""0xa1""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xa1"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchExpressionWithLambda3() { string source = WithWindowsLineBreaks(@" using System; class C { static string M(object o) { return new Func<string>(() => o.ToString())() switch { ""goo"" => o.ToString(), _ => ""Don't know"" }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""57"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""41"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" startLine=""8"" startColumn=""9"" endLine=""12"" endColumn=""11"" document=""1"" /> <entry offset=""0x23"" startLine=""8"" startColumn=""55"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0x24"" hidden=""true"" document=""1"" /> <entry offset=""0x33"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""34"" document=""1"" /> <entry offset=""0x41"" startLine=""11"" startColumn=""18"" endLine=""11"" endColumn=""30"" document=""1"" /> <entry offset=""0x49"" hidden=""true"" document=""1"" /> <entry offset=""0x4c"" startLine=""8"" startColumn=""9"" endLine=""12"" endColumn=""11"" document=""1"" /> <entry offset=""0x4d"" hidden=""true"" document=""1"" /> <entry offset=""0x51"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x53""> <namespace name=""System"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x53"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchExpressionWithLambda4() { string source = WithWindowsLineBreaks(@" using System; class C { static string M(object o) { return o switch { string s => new Func<string>(() => string.Concat(""s"", s))(), int i => new Func<string>(() => i.ToString() + i switch { 1 => new Func<string>(() => string.Concat(""One"", i))(), _ => ""Don't know"" })(), _ => ""Don't know"" }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""11"" /> <lambda offset=""86"" closure=""0"" /> <lambda offset=""157"" closure=""0"" /> <lambda offset=""241"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""8"" startColumn=""18"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0xb"" hidden=""true"" document=""1"" /> <entry offset=""0x33"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" hidden=""true"" document=""1"" /> <entry offset=""0x37"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""72"" document=""1"" /> <entry offset=""0x4b"" hidden=""true"" document=""1"" /> <entry offset=""0x4d"" startLine=""11"" startColumn=""22"" endLine=""15"" endColumn=""17"" document=""1"" /> <entry offset=""0x61"" startLine=""16"" startColumn=""18"" endLine=""16"" endColumn=""30"" document=""1"" /> <entry offset=""0x69"" hidden=""true"" document=""1"" /> <entry offset=""0x6c"" startLine=""8"" startColumn=""9"" endLine=""17"" endColumn=""11"" document=""1"" /> <entry offset=""0x6d"" hidden=""true"" document=""1"" /> <entry offset=""0x71"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x73""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x71""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x71"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchExpressionWithLambda5() { string source = WithWindowsLineBreaks(@" using System; class C { static string M(object o) { return o switch { string s => new Func<string>(() => string.Concat(o, s))(), int i => new Func<string>(() => i.ToString() + i switch { 1 => new Func<string>(() => string.Concat(""One"", i, o))(), _ => ""Don't know"" })(), _ => ""Don't know"" }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <closure offset=""11"" /> <lambda offset=""86"" closure=""1"" /> <lambda offset=""155"" closure=""1"" /> <lambda offset=""239"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" hidden=""true"" document=""1"" /> <entry offset=""0x1e"" startLine=""8"" startColumn=""18"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x65"" hidden=""true"" document=""1"" /> <entry offset=""0x67"" hidden=""true"" document=""1"" /> <entry offset=""0x69"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""70"" document=""1"" /> <entry offset=""0x7d"" hidden=""true"" document=""1"" /> <entry offset=""0x7f"" startLine=""11"" startColumn=""22"" endLine=""15"" endColumn=""17"" document=""1"" /> <entry offset=""0x93"" startLine=""16"" startColumn=""18"" endLine=""16"" endColumn=""30"" document=""1"" /> <entry offset=""0x9b"" hidden=""true"" document=""1"" /> <entry offset=""0x9e"" startLine=""8"" startColumn=""9"" endLine=""17"" endColumn=""11"" document=""1"" /> <entry offset=""0x9f"" hidden=""true"" document=""1"" /> <entry offset=""0xa3"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa5""> <namespace name=""System"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xa5"" attributes=""0"" /> <scope startOffset=""0xe"" endOffset=""0xa3""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xa3"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchExpressionWithLambda6() { string source = WithWindowsLineBreaks(@" using System; class C { static string M(object o) { return o switch { string s => new Func<string>(() => string.Concat(""s"", s))(), int i => new Func<string>(() => i.ToString() + new Func<int>(() => i + 1)())(), _ => ""Don't know"" }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""11"" /> <lambda offset=""86"" closure=""0"" /> <lambda offset=""157"" closure=""0"" /> <lambda offset=""192"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""8"" startColumn=""18"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0xb"" hidden=""true"" document=""1"" /> <entry offset=""0x33"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" hidden=""true"" document=""1"" /> <entry offset=""0x37"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""72"" document=""1"" /> <entry offset=""0x4b"" hidden=""true"" document=""1"" /> <entry offset=""0x4d"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""91"" document=""1"" /> <entry offset=""0x61"" startLine=""12"" startColumn=""18"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0x69"" hidden=""true"" document=""1"" /> <entry offset=""0x6c"" startLine=""8"" startColumn=""9"" endLine=""13"" endColumn=""11"" document=""1"" /> <entry offset=""0x6d"" hidden=""true"" document=""1"" /> <entry offset=""0x71"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x73""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x71""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x71"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void UsingStatement1() { string source = WithWindowsLineBreaks(@" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static IDisposable D() => null; static void F() { using (IDisposable x0 = D(), y0 = D()) { int x1 = 1; G(() => x0); G(() => y0); G(() => x1); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics(); // note that the two closures have a different syntax offset c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F"" parameterNames=""a, b""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""41"" endLine=""7"" endColumn=""42"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""f"" /> <encLocalSlotMap> <slot kind=""30"" offset=""41"" /> <slot kind=""30"" offset=""89"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>3</methodOrdinal> <closure offset=""41"" /> <closure offset=""89"" /> <lambda offset=""147"" closure=""0"" /> <lambda offset=""173"" closure=""0"" /> <lambda offset=""199"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""36"" document=""1"" /> <entry offset=""0x12"" startLine=""12"" startColumn=""38"" endLine=""12"" endColumn=""46"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x23"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x24"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""1"" /> <entry offset=""0x2b"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""25"" document=""1"" /> <entry offset=""0x3d"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""25"" document=""1"" /> <entry offset=""0x4f"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" /> <entry offset=""0x61"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x64"" hidden=""true"" document=""1"" /> <entry offset=""0x78"" hidden=""true"" document=""1"" /> <entry offset=""0x79"" hidden=""true"" document=""1"" /> <entry offset=""0x7b"" hidden=""true"" document=""1"" /> <entry offset=""0x8f"" hidden=""true"" document=""1"" /> <entry offset=""0x90"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x91""> <scope startOffset=""0x1"" endOffset=""0x90""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x90"" attributes=""0"" /> <scope startOffset=""0x1d"" endOffset=""0x62""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0x1d"" il_end=""0x62"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void IfStatement1() { string source = @" class C { static void F() { new System.Action(() => { bool result = false; if (result) System.Console.WriteLine(1); })(); } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("C.<>c.<F>b__0_0", @" { // Code size 16 (0x10) .maxstack 1 .locals init (bool V_0, //result bool V_1) -IL_0000: nop -IL_0001: ldc.i4.0 IL_0002: stloc.0 -IL_0003: ldloc.0 IL_0004: stloc.1 ~IL_0005: ldloc.1 IL_0006: brfalse.s IL_000f -IL_0008: ldc.i4.1 IL_0009: call ""void System.Console.WriteLine(int)"" IL_000e: nop -IL_000f: ret } ", sequencePoints: "C+<>c.<F>b__0_0"); } [Fact] public void IfStatement2() { string source = @" class C { static void F() { new System.Action(() => { { bool result = false; if (result) System.Console.WriteLine(1); } })(); } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("C.<>c.<F>b__0_0", @" { // Code size 18 (0x12) .maxstack 1 .locals init (bool V_0, //result bool V_1) -IL_0000: nop -IL_0001: nop -IL_0002: ldc.i4.0 IL_0003: stloc.0 -IL_0004: ldloc.0 IL_0005: stloc.1 ~IL_0006: ldloc.1 IL_0007: brfalse.s IL_0010 -IL_0009: ldc.i4.1 IL_000a: call ""void System.Console.WriteLine(int)"" IL_000f: nop -IL_0010: nop -IL_0011: ret } ", sequencePoints: "C+<>c.<F>b__0_0"); } [Fact] public void WithExpression() { var source = MarkedSource(WithWindowsLineBreaks(@" using System; record R(int X); class Test { public static void M(int a) <M><C:0>{ var x = new R(1); var y = x with { X = new Func<int>(() => <L:0.0>a)() }; } } "), removeTags: true); // We're validating offsets so need to remove tags entirely // Use NetCoreApp in order to use records var compilation = CreateCompilation(source.Tree, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugDll); compilation.VerifyPdbLambdasAndClosures(source); } [Fact] public void WithExpression_2() { var source = MarkedSource(WithWindowsLineBreaks(@" using System; record R(int X, int Y); class Test { public static void M(int a) <M><C:0>{ var x = new R(1, 2); var b = 1; var y = x with { X = new Func<int>(() => <L:0.0>a)(), Y = new Func<int>(() => <L:1.0>b)() }; } } "), removeTags: true); // We're validating offsets so need to remove tags entirely // Use NetCoreApp in order to use records var compilation = CreateCompilation(source.Tree, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugDll); compilation.VerifyPdbLambdasAndClosures(source); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/52068")] public void WithExpression_3() { var source = MarkedSource(WithWindowsLineBreaks(@" using System; record R(int X, int Y); record Z(int A, R R); class Test { public static void M(int a) <M><C:0>{ var r = new R(1, 2); var x = new Z(1, new R(2, 3)); var b = 1; var y = x with { A = new Func<int>(() => <L:0.0>a)(), R = r with { X = 4, Y = new Func<int>(() => <L:1.0>b)() } }; } } "), removeTags: true); // We're validating offsets so need to remove tags entirely // Use NetCoreApp in order to use records var compilation = CreateCompilation(source.Tree, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugDll); compilation.VerifyPdbLambdasAndClosures(source); } [Fact] public void Record_1() { var source = WithWindowsLineBreaks(@" using System; record D(int X) { public int Y { get; set; } = new Func<int, int>(a => a + X).Invoke(1); } "); // Use NetCoreApp in order to use records var compilation = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugDll); compilation.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""D"" name="".ctor"" parameterNames=""X""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""-1"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""-1"" /> <lambda offset=""-16"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""3"" startColumn=""10"" endLine=""3"" endColumn=""15"" document=""1"" /> <entry offset=""0x19"" startLine=""5"" startColumn=""34"" endLine=""5"" endColumn=""74"" document=""1"" /> <entry offset=""0x31"" startLine=""3"" startColumn=""1"" endLine=""6"" endColumn=""2"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x39""> <namespace name=""System"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x39"" attributes=""0"" /> </scope> </method> <method containingType=""D"" name=""get_X""> <sequencePoints> <entry offset=""0x0"" startLine=""3"" startColumn=""10"" endLine=""3"" endColumn=""15"" document=""1"" /> </sequencePoints> </method> <method containingType=""D"" name=""set_X"" parameterNames=""value""> <sequencePoints> <entry offset=""0x0"" startLine=""3"" startColumn=""10"" endLine=""3"" endColumn=""15"" document=""1"" /> </sequencePoints> </method> <method containingType=""D"" name=""get_Y""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""20"" endLine=""5"" endColumn=""24"" document=""1"" /> </sequencePoints> </method> <method containingType=""D"" name=""set_Y"" parameterNames=""value""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""25"" endLine=""5"" endColumn=""29"" document=""1"" /> </sequencePoints> </method> <method containingType=""D+&lt;&gt;c__DisplayClass0_0"" name=""&lt;.ctor&gt;b__0"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""D"" methodName="".ctor"" parameterNames=""X"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""58"" endLine=""5"" endColumn=""63"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: CodeAnalysis.Emit.DebugInformationFormat.Pdb); } [Fact] public void Record_2() { var source = WithWindowsLineBreaks(@" using System; record C(int X) { public C(int x, Func<int> f) : this(x) { } } record D(int X) : C(F(X, out int z), () => z) { static int F(int x, out int p) { p = 1; return x + 1; } } "); // Use NetCoreApp in order to use records var compilation = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugDll); compilation.VerifyDiagnostics(); compilation.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor"" parameterNames=""X""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""3"" startColumn=""10"" endLine=""3"" endColumn=""15"" document=""1"" /> <entry offset=""0x7"" startLine=""3"" startColumn=""1"" endLine=""9"" endColumn=""2"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xf""> <namespace name=""System"" /> </scope> </method> <method containingType=""C"" name=""get_X""> <sequencePoints> <entry offset=""0x0"" startLine=""3"" startColumn=""10"" endLine=""3"" endColumn=""15"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""set_X"" parameterNames=""value""> <sequencePoints> <entry offset=""0x0"" startLine=""3"" startColumn=""10"" endLine=""3"" endColumn=""15"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name="".ctor"" parameterNames=""x, f""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" parameterNames=""X"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""11"" endLine=""6"" endColumn=""18"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x9"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method containingType=""D"" name="".ctor"" parameterNames=""X""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" parameterNames=""X"" /> <encLocalSlotMap> <slot kind=""30"" offset=""-1"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""-1"" /> <lambda offset=""-2"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""11"" startColumn=""19"" endLine=""11"" endColumn=""46"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x26""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x26"" attributes=""0"" /> </scope> </method> <method containingType=""D"" name=""F"" parameterNames=""x, p""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" parameterNames=""X"" /> <encLocalSlotMap> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""15"" document=""1"" /> <entry offset=""0x4"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""22"" document=""1"" /> <entry offset=""0xa"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method containingType=""D+&lt;&gt;c__DisplayClass0_0"" name=""&lt;.ctor&gt;b__0""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" parameterNames=""X"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""44"" endLine=""11"" endColumn=""45"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: CodeAnalysis.Emit.DebugInformationFormat.Pdb); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Portable/Symbols/TypeParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a type parameter in a generic type or generic method. /// </summary> internal abstract partial class TypeParameterSymbol : TypeSymbol, ITypeParameterSymbolInternal { /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new virtual TypeParameterSymbol OriginalDefinition { get { return this; } } protected sealed override TypeSymbol OriginalTypeSymbolDefinition { get { return this.OriginalDefinition; } } /// <summary> /// If this is a type parameter of a reduced extension method, gets the type parameter definition that /// this type parameter was reduced from. Otherwise, returns Nothing. /// </summary> public virtual TypeParameterSymbol ReducedFrom { get { return null; } } /// <summary> /// The ordinal position of the type parameter in the parameter list which declares /// it. The first type parameter has ordinal zero. /// </summary> public abstract int Ordinal { // This is needed to determine hiding in C#: // // interface IB { void M<T>(C<T> x); } // interface ID : IB { new void M<U>(C<U> x); } // // ID.M<U> hides IB.M<T> even though their formal parameters have different // types. When comparing formal parameter types for hiding purposes we must // compare method type parameters by ordinal, not by identity. get; } internal virtual UseSiteInfo<AssemblySymbol> GetConstraintsUseSiteErrorInfo() { return default; } /// <summary> /// The types that were directly specified as constraints on the type parameter. /// Duplicates and cycles are removed, although the collection may include /// redundant constraints where one constraint is a base type of another. /// </summary> internal ImmutableArray<TypeWithAnnotations> ConstraintTypesNoUseSiteDiagnostics { get { this.EnsureAllConstraintsAreResolved(); return this.GetConstraintTypes(ConsList<TypeParameterSymbol>.Empty); } } internal ImmutableArray<TypeWithAnnotations> ConstraintTypesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = ConstraintTypesNoUseSiteDiagnostics; AppendConstraintsUseSiteErrorInfo(ref useSiteInfo); foreach (var constraint in result) { ((TypeSymbol)constraint.Type.OriginalDefinition).AddUseSiteInfo(ref useSiteInfo); } return result; } private void AppendConstraintsUseSiteErrorInfo(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { useSiteInfo.Add(this.GetConstraintsUseSiteErrorInfo()); } /// <summary> /// True if the parameterless constructor constraint was specified for the type parameter. /// </summary> public abstract bool HasConstructorConstraint { get; } /// <summary> /// The type parameter kind of this type parameter. /// </summary> public abstract TypeParameterKind TypeParameterKind { get; } /// <summary> /// The method that declared this type parameter, or null. /// </summary> public MethodSymbol DeclaringMethod { get { return this.ContainingSymbol as MethodSymbol; } } /// <summary> /// The type that declared this type parameter, or null. /// </summary> public NamedTypeSymbol DeclaringType { get { return this.ContainingSymbol as NamedTypeSymbol; } } // Type parameters do not have members public sealed override ImmutableArray<Symbol> GetMembers() { return ImmutableArray<Symbol>.Empty; } // Type parameters do not have members public sealed override ImmutableArray<Symbol> GetMembers(string name) { return ImmutableArray<Symbol>.Empty; } // Type parameters do not have members public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return ImmutableArray<NamedTypeSymbol>.Empty; } // Type parameters do not have members public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { return ImmutableArray<NamedTypeSymbol>.Empty; } // Type parameters do not have members public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return ImmutableArray<NamedTypeSymbol>.Empty; } internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitTypeParameter(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitTypeParameter(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitTypeParameter(this); } public sealed override SymbolKind Kind { get { return SymbolKind.TypeParameter; } } public sealed override TypeKind TypeKind { get { return TypeKind.TypeParameter; } } // Only the compiler can create TypeParameterSymbols. internal TypeParameterSymbol() { } public sealed override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } public sealed override bool IsStatic { get { return false; } } public sealed override bool IsAbstract { get { return false; } } public sealed override bool IsSealed { get { return false; } } internal sealed override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => null; internal sealed override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null) { return ImmutableArray<NamedTypeSymbol>.Empty; } protected override ImmutableArray<NamedTypeSymbol> GetAllInterfaces() { return ImmutableArray<NamedTypeSymbol>.Empty; } /// <summary> /// The effective base class of the type parameter (spec 10.1.5). If the deduced /// base type is a reference type, the effective base type will be the same as /// the deduced base type. Otherwise if the deduced base type is a value type, /// the effective base type will be the most derived reference type from which /// deduced base type is derived. /// </summary> internal NamedTypeSymbol EffectiveBaseClassNoUseSiteDiagnostics { get { this.EnsureAllConstraintsAreResolved(); return this.GetEffectiveBaseClass(ConsList<TypeParameterSymbol>.Empty); } } internal NamedTypeSymbol EffectiveBaseClass(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { AppendConstraintsUseSiteErrorInfo(ref useSiteInfo); var result = EffectiveBaseClassNoUseSiteDiagnostics; if ((object)result != null) { result.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// The effective interface set (spec 10.1.5). /// </summary> internal ImmutableArray<NamedTypeSymbol> EffectiveInterfacesNoUseSiteDiagnostics { get { this.EnsureAllConstraintsAreResolved(); return this.GetInterfaces(ConsList<TypeParameterSymbol>.Empty); } } /// <summary> /// The most encompassed type (spec 6.4.2) from the constraints. /// </summary> internal TypeSymbol DeducedBaseTypeNoUseSiteDiagnostics { get { this.EnsureAllConstraintsAreResolved(); return this.GetDeducedBaseType(ConsList<TypeParameterSymbol>.Empty); } } internal TypeSymbol DeducedBaseType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { AppendConstraintsUseSiteErrorInfo(ref useSiteInfo); var result = DeducedBaseTypeNoUseSiteDiagnostics; if ((object)result != null) { ((TypeSymbol)result.OriginalDefinition).AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// The effective interface set and any base interfaces of those /// interfaces. This is AllInterfaces excluding interfaces that are /// only implemented by the effective base type. /// </summary> internal ImmutableArray<NamedTypeSymbol> AllEffectiveInterfacesNoUseSiteDiagnostics { get { return base.GetAllInterfaces(); } } internal ImmutableArray<NamedTypeSymbol> AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = AllEffectiveInterfacesNoUseSiteDiagnostics; // Since bases affect content of AllInterfaces set, we need to make sure they all are good. var current = DeducedBaseType(ref useSiteInfo); while ((object)current != null) { current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } foreach (var iface in result) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// Called by <see cref="ConstraintTypesNoUseSiteDiagnostics"/>, <see cref="InterfacesNoUseSiteDiagnostics"/>, <see cref="EffectiveBaseClass"/>, and <see cref="DeducedBaseType"/>. /// to allow derived classes to ensure constraints within the containing /// type or method are resolved in a consistent order, regardless of the /// order the callers query individual type parameters. /// </summary> internal abstract void EnsureAllConstraintsAreResolved(); /// <summary> /// Helper method to force type parameter constraints to be resolved. /// </summary> protected static void EnsureAllConstraintsAreResolved(ImmutableArray<TypeParameterSymbol> typeParameters) { foreach (var typeParameter in typeParameters) { // Invoke any method that forces constraints to be resolved. var unused = typeParameter.GetConstraintTypes(ConsList<TypeParameterSymbol>.Empty); } } internal abstract ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress); internal abstract ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress); internal abstract NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress); internal abstract TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress); private static bool ConstraintImpliesReferenceType(TypeSymbol constraint) { if (constraint.TypeKind == TypeKind.TypeParameter) { return ((TypeParameterSymbol)constraint).IsReferenceTypeFromConstraintTypes; } return NonTypeParameterConstraintImpliesReferenceType(constraint); } internal static bool NonTypeParameterConstraintImpliesReferenceType(TypeSymbol constraint) { Debug.Assert(constraint.TypeKind != TypeKind.TypeParameter); if (!constraint.IsReferenceType) { return false; } else { switch (constraint.TypeKind) { case TypeKind.Interface: return false; // can be satisfied by value types case TypeKind.Error: return false; } switch (constraint.SpecialType) { case SpecialType.System_Object: case SpecialType.System_ValueType: case SpecialType.System_Enum: return false; // can be satisfied by value types } return true; } } // From typedesc.cpp : // > A recursive helper that helps determine whether this variable is constrained as ObjRef. // > Please note that we do not check the gpReferenceTypeConstraint special constraint here // > because this property does not propagate up the constraining hierarchy. // > (e.g. "class A<S, T> where S : T, where T : class" does not guarantee that S is ObjRef) internal static bool CalculateIsReferenceTypeFromConstraintTypes(ImmutableArray<TypeWithAnnotations> constraintTypes) { foreach (var constraintType in constraintTypes) { if (ConstraintImpliesReferenceType(constraintType.Type)) { return true; } } return false; } internal static bool? IsNotNullableFromConstraintTypes(ImmutableArray<TypeWithAnnotations> constraintTypes) { Debug.Assert(!constraintTypes.IsDefaultOrEmpty); bool? result = false; foreach (TypeWithAnnotations constraintType in constraintTypes) { bool? fromType = IsNotNullableFromConstraintType(constraintType, out _); if (fromType == true) { return true; } else if (fromType == null) { result = null; } } return result; } internal static bool? IsNotNullableFromConstraintType(TypeWithAnnotations constraintType, out bool isNonNullableValueType) { if (constraintType.Type.IsNonNullableValueType()) { isNonNullableValueType = true; return true; } isNonNullableValueType = false; if (constraintType.NullableAnnotation.IsAnnotated()) { return false; } if (constraintType.TypeKind == TypeKind.TypeParameter) { bool? isNotNullable = ((TypeParameterSymbol)constraintType.Type).IsNotNullable; if (isNotNullable == false) { return false; } else if (isNotNullable == null) { return null; } } if (constraintType.NullableAnnotation.IsOblivious()) { return null; } return true; } internal static bool CalculateIsValueTypeFromConstraintTypes(ImmutableArray<TypeWithAnnotations> constraintTypes) { foreach (var constraintType in constraintTypes) { if (constraintType.Type.IsValueType) { return true; } } return false; } public sealed override bool IsReferenceType { get { if (this.HasReferenceTypeConstraint) { return true; } return IsReferenceTypeFromConstraintTypes; } } protected bool? CalculateIsNotNullableFromNonTypeConstraints() { if (this.HasNotNullConstraint || this.HasValueTypeConstraint) { return true; } if (this.HasReferenceTypeConstraint) { return !this.ReferenceTypeConstraintIsNullable; } return false; } protected bool? CalculateIsNotNullable() { bool? fromNonTypeConstraints = CalculateIsNotNullableFromNonTypeConstraints(); if (fromNonTypeConstraints == true) { return fromNonTypeConstraints; } ImmutableArray<TypeWithAnnotations> constraintTypes = this.ConstraintTypesNoUseSiteDiagnostics; if (constraintTypes.IsEmpty) { return fromNonTypeConstraints; } bool? fromTypes = IsNotNullableFromConstraintTypes(constraintTypes); if (fromTypes == true || fromNonTypeConstraints == false) { return fromTypes; } Debug.Assert(fromNonTypeConstraints == null); Debug.Assert(fromTypes != true); return null; } internal abstract bool? IsNotNullable { get; } public sealed override bool IsValueType { get { if (this.HasValueTypeConstraint) { return true; } return IsValueTypeFromConstraintTypes; } } internal sealed override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return HasUnmanagedTypeConstraint ? ManagedKind.Unmanaged : ManagedKind.Managed; } public sealed override bool IsRefLikeType { get { return false; } } public sealed override bool IsReadOnly { get { // even if T is indirectly constrained to a struct, // we only can use members via constrained calls, so "true" would have no effect return false; } } internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } public abstract bool HasReferenceTypeConstraint { get; } public abstract bool IsReferenceTypeFromConstraintTypes { get; } /// <summary> /// Returns whether the reference type constraint (the 'class' constraint) should also be treated as nullable ('class?') or non-nullable (class!). /// In some cases this aspect is unknown (null value is returned). For example, when 'class' constraint is specified in a NonNullTypes(false) context. /// This API returns false when <see cref="HasReferenceTypeConstraint"/> is false. /// </summary> internal abstract bool? ReferenceTypeConstraintIsNullable { get; } public abstract bool HasNotNullConstraint { get; } public abstract bool HasValueTypeConstraint { get; } public abstract bool IsValueTypeFromConstraintTypes { get; } public abstract bool HasUnmanagedTypeConstraint { get; } public abstract VarianceKind Variance { get; } internal sealed override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { return false; } internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return this.Equals(t2 as TypeParameterSymbol, comparison); } internal bool Equals(TypeParameterSymbol other) { return Equals(other, TypeCompareKind.ConsiderEverything); } private bool Equals(TypeParameterSymbol other, TypeCompareKind comparison) { if (ReferenceEquals(this, other)) { return true; } if ((object)other == null || !ReferenceEquals(other.OriginalDefinition, this.OriginalDefinition)) { return false; } // Type parameters may be equal but not reference equal due to independent alpha renamings. return other.ContainingSymbol.ContainingType.Equals(this.ContainingSymbol.ContainingType, comparison); } public override int GetHashCode() { return Hash.Combine(ContainingSymbol, Ordinal); } internal override void AddNullableTransforms(ArrayBuilder<byte> transforms) { } internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result) { result = this; return true; } internal override TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform) { return this; } internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) { Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); return this; } protected sealed override ISymbol CreateISymbol() { return new PublicModel.TypeParameterSymbol(this, DefaultNullableAnnotation); } protected sealed override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { Debug.Assert(nullableAnnotation != DefaultNullableAnnotation); return new PublicModel.TypeParameterSymbol(this, nullableAnnotation); } internal override bool IsRecord => false; internal override bool IsRecordStruct => false; internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a type parameter in a generic type or generic method. /// </summary> internal abstract partial class TypeParameterSymbol : TypeSymbol, ITypeParameterSymbolInternal { /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new virtual TypeParameterSymbol OriginalDefinition { get { return this; } } protected sealed override TypeSymbol OriginalTypeSymbolDefinition { get { return this.OriginalDefinition; } } /// <summary> /// If this is a type parameter of a reduced extension method, gets the type parameter definition that /// this type parameter was reduced from. Otherwise, returns Nothing. /// </summary> public virtual TypeParameterSymbol ReducedFrom { get { return null; } } /// <summary> /// The ordinal position of the type parameter in the parameter list which declares /// it. The first type parameter has ordinal zero. /// </summary> public abstract int Ordinal { // This is needed to determine hiding in C#: // // interface IB { void M<T>(C<T> x); } // interface ID : IB { new void M<U>(C<U> x); } // // ID.M<U> hides IB.M<T> even though their formal parameters have different // types. When comparing formal parameter types for hiding purposes we must // compare method type parameters by ordinal, not by identity. get; } internal virtual UseSiteInfo<AssemblySymbol> GetConstraintsUseSiteErrorInfo() { return default; } /// <summary> /// The types that were directly specified as constraints on the type parameter. /// Duplicates and cycles are removed, although the collection may include /// redundant constraints where one constraint is a base type of another. /// </summary> internal ImmutableArray<TypeWithAnnotations> ConstraintTypesNoUseSiteDiagnostics { get { this.EnsureAllConstraintsAreResolved(); return this.GetConstraintTypes(ConsList<TypeParameterSymbol>.Empty); } } internal ImmutableArray<TypeWithAnnotations> ConstraintTypesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = ConstraintTypesNoUseSiteDiagnostics; AppendConstraintsUseSiteErrorInfo(ref useSiteInfo); foreach (var constraint in result) { ((TypeSymbol)constraint.Type.OriginalDefinition).AddUseSiteInfo(ref useSiteInfo); } return result; } private void AppendConstraintsUseSiteErrorInfo(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { useSiteInfo.Add(this.GetConstraintsUseSiteErrorInfo()); } /// <summary> /// True if the parameterless constructor constraint was specified for the type parameter. /// </summary> public abstract bool HasConstructorConstraint { get; } /// <summary> /// The type parameter kind of this type parameter. /// </summary> public abstract TypeParameterKind TypeParameterKind { get; } /// <summary> /// The method that declared this type parameter, or null. /// </summary> public MethodSymbol DeclaringMethod { get { return this.ContainingSymbol as MethodSymbol; } } /// <summary> /// The type that declared this type parameter, or null. /// </summary> public NamedTypeSymbol DeclaringType { get { return this.ContainingSymbol as NamedTypeSymbol; } } // Type parameters do not have members public sealed override ImmutableArray<Symbol> GetMembers() { return ImmutableArray<Symbol>.Empty; } // Type parameters do not have members public sealed override ImmutableArray<Symbol> GetMembers(string name) { return ImmutableArray<Symbol>.Empty; } // Type parameters do not have members public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return ImmutableArray<NamedTypeSymbol>.Empty; } // Type parameters do not have members public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { return ImmutableArray<NamedTypeSymbol>.Empty; } // Type parameters do not have members public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return ImmutableArray<NamedTypeSymbol>.Empty; } internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitTypeParameter(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitTypeParameter(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitTypeParameter(this); } public sealed override SymbolKind Kind { get { return SymbolKind.TypeParameter; } } public sealed override TypeKind TypeKind { get { return TypeKind.TypeParameter; } } // Only the compiler can create TypeParameterSymbols. internal TypeParameterSymbol() { } public sealed override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } public sealed override bool IsStatic { get { return false; } } public sealed override bool IsAbstract { get { return false; } } public sealed override bool IsSealed { get { return false; } } internal sealed override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => null; internal sealed override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null) { return ImmutableArray<NamedTypeSymbol>.Empty; } protected override ImmutableArray<NamedTypeSymbol> GetAllInterfaces() { return ImmutableArray<NamedTypeSymbol>.Empty; } /// <summary> /// The effective base class of the type parameter (spec 10.1.5). If the deduced /// base type is a reference type, the effective base type will be the same as /// the deduced base type. Otherwise if the deduced base type is a value type, /// the effective base type will be the most derived reference type from which /// deduced base type is derived. /// </summary> internal NamedTypeSymbol EffectiveBaseClassNoUseSiteDiagnostics { get { this.EnsureAllConstraintsAreResolved(); return this.GetEffectiveBaseClass(ConsList<TypeParameterSymbol>.Empty); } } internal NamedTypeSymbol EffectiveBaseClass(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { AppendConstraintsUseSiteErrorInfo(ref useSiteInfo); var result = EffectiveBaseClassNoUseSiteDiagnostics; if ((object)result != null) { result.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// The effective interface set (spec 10.1.5). /// </summary> internal ImmutableArray<NamedTypeSymbol> EffectiveInterfacesNoUseSiteDiagnostics { get { this.EnsureAllConstraintsAreResolved(); return this.GetInterfaces(ConsList<TypeParameterSymbol>.Empty); } } /// <summary> /// The most encompassed type (spec 6.4.2) from the constraints. /// </summary> internal TypeSymbol DeducedBaseTypeNoUseSiteDiagnostics { get { this.EnsureAllConstraintsAreResolved(); return this.GetDeducedBaseType(ConsList<TypeParameterSymbol>.Empty); } } internal TypeSymbol DeducedBaseType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { AppendConstraintsUseSiteErrorInfo(ref useSiteInfo); var result = DeducedBaseTypeNoUseSiteDiagnostics; if ((object)result != null) { ((TypeSymbol)result.OriginalDefinition).AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// The effective interface set and any base interfaces of those /// interfaces. This is AllInterfaces excluding interfaces that are /// only implemented by the effective base type. /// </summary> internal ImmutableArray<NamedTypeSymbol> AllEffectiveInterfacesNoUseSiteDiagnostics { get { return base.GetAllInterfaces(); } } internal ImmutableArray<NamedTypeSymbol> AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = AllEffectiveInterfacesNoUseSiteDiagnostics; // Since bases affect content of AllInterfaces set, we need to make sure they all are good. var current = DeducedBaseType(ref useSiteInfo); while ((object)current != null) { current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } foreach (var iface in result) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// Called by <see cref="ConstraintTypesNoUseSiteDiagnostics"/>, <see cref="InterfacesNoUseSiteDiagnostics"/>, <see cref="EffectiveBaseClass"/>, and <see cref="DeducedBaseType"/>. /// to allow derived classes to ensure constraints within the containing /// type or method are resolved in a consistent order, regardless of the /// order the callers query individual type parameters. /// </summary> internal abstract void EnsureAllConstraintsAreResolved(); /// <summary> /// Helper method to force type parameter constraints to be resolved. /// </summary> protected static void EnsureAllConstraintsAreResolved(ImmutableArray<TypeParameterSymbol> typeParameters) { foreach (var typeParameter in typeParameters) { // Invoke any method that forces constraints to be resolved. var unused = typeParameter.GetConstraintTypes(ConsList<TypeParameterSymbol>.Empty); } } internal abstract ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress); internal abstract ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress); internal abstract NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress); internal abstract TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress); private static bool ConstraintImpliesReferenceType(TypeSymbol constraint) { if (constraint.TypeKind == TypeKind.TypeParameter) { return ((TypeParameterSymbol)constraint).IsReferenceTypeFromConstraintTypes; } return NonTypeParameterConstraintImpliesReferenceType(constraint); } internal static bool NonTypeParameterConstraintImpliesReferenceType(TypeSymbol constraint) { Debug.Assert(constraint.TypeKind != TypeKind.TypeParameter); if (!constraint.IsReferenceType) { return false; } else { switch (constraint.TypeKind) { case TypeKind.Interface: return false; // can be satisfied by value types case TypeKind.Error: return false; } switch (constraint.SpecialType) { case SpecialType.System_Object: case SpecialType.System_ValueType: case SpecialType.System_Enum: return false; // can be satisfied by value types } return true; } } // From typedesc.cpp : // > A recursive helper that helps determine whether this variable is constrained as ObjRef. // > Please note that we do not check the gpReferenceTypeConstraint special constraint here // > because this property does not propagate up the constraining hierarchy. // > (e.g. "class A<S, T> where S : T, where T : class" does not guarantee that S is ObjRef) internal static bool CalculateIsReferenceTypeFromConstraintTypes(ImmutableArray<TypeWithAnnotations> constraintTypes) { foreach (var constraintType in constraintTypes) { if (ConstraintImpliesReferenceType(constraintType.Type)) { return true; } } return false; } internal static bool? IsNotNullableFromConstraintTypes(ImmutableArray<TypeWithAnnotations> constraintTypes) { Debug.Assert(!constraintTypes.IsDefaultOrEmpty); bool? result = false; foreach (TypeWithAnnotations constraintType in constraintTypes) { bool? fromType = IsNotNullableFromConstraintType(constraintType, out _); if (fromType == true) { return true; } else if (fromType == null) { result = null; } } return result; } internal static bool? IsNotNullableFromConstraintType(TypeWithAnnotations constraintType, out bool isNonNullableValueType) { if (constraintType.Type.IsNonNullableValueType()) { isNonNullableValueType = true; return true; } isNonNullableValueType = false; if (constraintType.NullableAnnotation.IsAnnotated()) { return false; } if (constraintType.TypeKind == TypeKind.TypeParameter) { bool? isNotNullable = ((TypeParameterSymbol)constraintType.Type).IsNotNullable; if (isNotNullable == false) { return false; } else if (isNotNullable == null) { return null; } } if (constraintType.NullableAnnotation.IsOblivious()) { return null; } return true; } internal static bool CalculateIsValueTypeFromConstraintTypes(ImmutableArray<TypeWithAnnotations> constraintTypes) { foreach (var constraintType in constraintTypes) { if (constraintType.Type.IsValueType) { return true; } } return false; } public sealed override bool IsReferenceType { get { if (this.HasReferenceTypeConstraint) { return true; } return IsReferenceTypeFromConstraintTypes; } } protected bool? CalculateIsNotNullableFromNonTypeConstraints() { if (this.HasNotNullConstraint || this.HasValueTypeConstraint) { return true; } if (this.HasReferenceTypeConstraint) { return !this.ReferenceTypeConstraintIsNullable; } return false; } protected bool? CalculateIsNotNullable() { bool? fromNonTypeConstraints = CalculateIsNotNullableFromNonTypeConstraints(); if (fromNonTypeConstraints == true) { return fromNonTypeConstraints; } ImmutableArray<TypeWithAnnotations> constraintTypes = this.ConstraintTypesNoUseSiteDiagnostics; if (constraintTypes.IsEmpty) { return fromNonTypeConstraints; } bool? fromTypes = IsNotNullableFromConstraintTypes(constraintTypes); if (fromTypes == true || fromNonTypeConstraints == false) { return fromTypes; } Debug.Assert(fromNonTypeConstraints == null); Debug.Assert(fromTypes != true); return null; } internal abstract bool? IsNotNullable { get; } public sealed override bool IsValueType { get { if (this.HasValueTypeConstraint) { return true; } return IsValueTypeFromConstraintTypes; } } internal sealed override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return HasUnmanagedTypeConstraint ? ManagedKind.Unmanaged : ManagedKind.Managed; } public sealed override bool IsRefLikeType { get { return false; } } public sealed override bool IsReadOnly { get { // even if T is indirectly constrained to a struct, // we only can use members via constrained calls, so "true" would have no effect return false; } } internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } public abstract bool HasReferenceTypeConstraint { get; } public abstract bool IsReferenceTypeFromConstraintTypes { get; } /// <summary> /// Returns whether the reference type constraint (the 'class' constraint) should also be treated as nullable ('class?') or non-nullable (class!). /// In some cases this aspect is unknown (null value is returned). For example, when 'class' constraint is specified in a NonNullTypes(false) context. /// This API returns false when <see cref="HasReferenceTypeConstraint"/> is false. /// </summary> internal abstract bool? ReferenceTypeConstraintIsNullable { get; } public abstract bool HasNotNullConstraint { get; } public abstract bool HasValueTypeConstraint { get; } public abstract bool IsValueTypeFromConstraintTypes { get; } public abstract bool HasUnmanagedTypeConstraint { get; } public abstract VarianceKind Variance { get; } internal sealed override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { return false; } internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return this.Equals(t2 as TypeParameterSymbol, comparison); } internal bool Equals(TypeParameterSymbol other) { return Equals(other, TypeCompareKind.ConsiderEverything); } private bool Equals(TypeParameterSymbol other, TypeCompareKind comparison) { if (ReferenceEquals(this, other)) { return true; } if ((object)other == null || !ReferenceEquals(other.OriginalDefinition, this.OriginalDefinition)) { return false; } // Type parameters may be equal but not reference equal due to independent alpha renamings. return other.ContainingSymbol.ContainingType.Equals(this.ContainingSymbol.ContainingType, comparison); } public override int GetHashCode() { return Hash.Combine(ContainingSymbol, Ordinal); } internal override void AddNullableTransforms(ArrayBuilder<byte> transforms) { } internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result) { result = this; return true; } internal override TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform) { return this; } internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) { Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); return this; } protected sealed override ISymbol CreateISymbol() { return new PublicModel.TypeParameterSymbol(this, DefaultNullableAnnotation); } protected sealed override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { Debug.Assert(nullableAnnotation != DefaultNullableAnnotation); return new PublicModel.TypeParameterSymbol(this, nullableAnnotation); } internal override bool IsRecord => false; internal override bool IsRecordStruct => false; internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/Core.Cocoa/RoslynClassificationFormatDefinitions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Windows.Media; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification { internal sealed class ClassificationTypeFormatDefinitions { #region Control Keyword [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ControlKeyword)] [Name(ClassificationTypeNames.ControlKeyword)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class ControlKeywordFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ControlKeywordFormatDefinition() { this.DisplayName = EditorFeaturesResources.Keyword_Control; this.ForegroundColor = Color.FromRgb(0x8F, 0x08, 0xC4); } } #endregion #region Local Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.LocalName)] [Name(ClassificationTypeNames.LocalName)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class LocalNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LocalNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Members_Locals; this.ForegroundColor = Color.FromRgb(0x1F, 0x37, 0x7F); } } #endregion #region Method Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.MethodName)] [Name(ClassificationTypeNames.MethodName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class MethodNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MethodNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Members_Methods; this.ForegroundColor = Color.FromRgb(0x74, 0x53, 0x1F); } } #endregion #region Operator Overloaded [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.OperatorOverloaded)] [Name(ClassificationTypeNames.OperatorOverloaded)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class OperatorOverloadedFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OperatorOverloadedFormatDefinition() { this.DisplayName = EditorFeaturesResources.Operator_Overloaded; this.ForegroundColor = Color.FromRgb(0x74, 0x53, 0x1F); } } #endregion #region Parameter Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ParameterName)] [Name(ClassificationTypeNames.ParameterName)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class ParameterNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ParameterNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Members_Parameters; this.ForegroundColor = Color.FromRgb(0x1F, 0x37, 0x7F); } } #endregion #region Preprocessor Text [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.PreprocessorText)] [Name(ClassificationTypeNames.PreprocessorText)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class PreprocessorTextFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreprocessorTextFormatDefinition() { this.DisplayName = EditorFeaturesResources.Preprocessor_Text; this.ForegroundColor = Colors.Black; } } #endregion #region Punctuation [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.Punctuation)] [Name(ClassificationTypeNames.Punctuation)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class PunctuationFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PunctuationFormatDefinition() { this.DisplayName = EditorFeaturesResources.Punctuation; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Alternation [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexAlternation)] [Name(ClassificationTypeNames.RegexAlternation)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexAlternationFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexAlternationFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexAlternation; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Anchor [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexAnchor)] [Name(ClassificationTypeNames.RegexAnchor)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexAnchorFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexAnchorFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexAnchor; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Character Class [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexCharacterClass)] [Name(ClassificationTypeNames.RegexCharacterClass)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexCharacterClassFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexCharacterClassFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexCharacterClass; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Comment [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexComment)] [Name(ClassificationTypeNames.RegexComment)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexCommentFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexCommentFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexComment; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Grouping [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexGrouping)] [Name(ClassificationTypeNames.RegexGrouping)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexGroupingFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexGroupingFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexGrouping; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Other Escape [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexOtherEscape)] [Name(ClassificationTypeNames.RegexOtherEscape)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexOtherEscapeFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexOtherEscapeFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexOtherEscape; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Quantifier [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexQuantifier)] [Name(ClassificationTypeNames.RegexQuantifier)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexQuantifierFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexQuantifierFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexQuantifier; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Self Escaped Character [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexSelfEscapedCharacter)] [Name(ClassificationTypeNames.RegexSelfEscapedCharacter)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexSelfEscapedCharacterFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexSelfEscapedCharacterFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexSelfEscapedCharacter; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Text [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexText)] [Name(ClassificationTypeNames.RegexText)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexTextFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexTextFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexText; this.ForegroundColor = Colors.Black; } } #endregion #region String - Escape Character [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.StringEscapeCharacter)] [Name(ClassificationTypeNames.StringEscapeCharacter)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class StringEscapeCharacterFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StringEscapeCharacterFormatDefinition() { this.DisplayName = EditorFeaturesResources.String_Escape_Character; this.ForegroundColor = Colors.LightYellow; } } #endregion #region String - Verbatim [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.VerbatimStringLiteral)] [Name(ClassificationTypeNames.VerbatimStringLiteral)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class StringVerbatimFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StringVerbatimFormatDefinition() { this.DisplayName = EditorFeaturesResources.String_Verbatim; this.ForegroundColor = Colors.Maroon; } } #endregion #region User Types - Classes [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ClassName)] [Name(ClassificationTypeNames.ClassName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [Order(After = PredefinedClassificationTypeNames.Keyword)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class UserTypeClassesFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserTypeClassesFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Types_Classes; this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF); } } #endregion #region User Types - Delegates [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.DelegateName)] [Name(ClassificationTypeNames.DelegateName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [Order(After = PredefinedClassificationTypeNames.Keyword)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class UserTypeDelegatesFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserTypeDelegatesFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Types_Delegates; this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF); } } #endregion #region User Types - Enums [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.EnumName)] [Name(ClassificationTypeNames.EnumName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [Order(After = PredefinedClassificationTypeNames.Keyword)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class UserTypeEnumsFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserTypeEnumsFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Types_Enums; this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF); } } #endregion #region User Types - Interfaces [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.InterfaceName)] [Name(ClassificationTypeNames.InterfaceName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [Order(After = PredefinedClassificationTypeNames.Keyword)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class UserTypeInterfacesFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserTypeInterfacesFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Types_Interfaces; this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF); } } #endregion #region User Types - Modules [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ModuleName)] [Name(ClassificationTypeNames.ModuleName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [Order(After = PredefinedClassificationTypeNames.Keyword)] [UserVisible(true)] private class UserTypeModulesFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserTypeModulesFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Types_Modules; this.ForegroundColor = Color.FromRgb(43, 145, 175); } } #endregion #region User Types - Structures [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.StructName)] [Name(ClassificationTypeNames.StructName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [Order(After = PredefinedClassificationTypeNames.Keyword)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class UserTypeStructuresFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserTypeStructuresFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Types_Structures; this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF); } } #endregion #region User Types - Type Parameters [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.TypeParameterName)] [Name(ClassificationTypeNames.TypeParameterName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [Order(After = PredefinedClassificationTypeNames.Keyword)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class UserTypeTypeParametersFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserTypeTypeParametersFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Types_Type_Parameters; this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF); } } #endregion #region User Members - Extension Method Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ExtensionMethodName)] [Name(ClassificationTypeNames.ExtensionMethodName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class UserMembersExtensionMethodNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserMembersExtensionMethodNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Members_Extension_Methods; this.ForegroundColor = Color.FromRgb(85, 85, 85); } } #endregion #region XML Doc Comments - Attribute Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentAttributeName)] [Name(ClassificationTypeNames.XmlDocCommentAttributeName)] [Order(After = Priority.Default, Before = Priority.High)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentAttributeNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentAttributeNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Attribute_Name; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - Attribute Quotes [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentAttributeQuotes)] [Name(ClassificationTypeNames.XmlDocCommentAttributeQuotes)] [Order(After = Priority.Default, Before = Priority.High)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentAttributeQuotesFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentAttributeQuotesFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Attribute_Quotes; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - Attribute Value // definition of how format is represented in tools options. // also specifies the default format. [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentAttributeValue)] [Name(ClassificationTypeNames.XmlDocCommentAttributeValue)] [Order(After = Priority.Default, Before = Priority.High)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentAttributeValueFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentAttributeValueFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Attribute_Value; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - CData Section [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentCDataSection)] [Name(ClassificationTypeNames.XmlDocCommentCDataSection)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentCDataSectionFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentCDataSectionFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_CData_Section; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - Comment [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentComment)] [Name(ClassificationTypeNames.XmlDocCommentComment)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentCommentFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentCommentFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Comment; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - Delimiter [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentDelimiter)] [Name(ClassificationTypeNames.XmlDocCommentDelimiter)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentDelimiterFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentDelimiterFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Delimiter; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - Entity Reference [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentEntityReference)] [Name(ClassificationTypeNames.XmlDocCommentEntityReference)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentEntityReferenceFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentEntityReferenceFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Entity_Reference; this.ForegroundColor = Colors.Green; } } #endregion #region XML Doc Comments - Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentName)] [Name(ClassificationTypeNames.XmlDocCommentName)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Name; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - Processing Instruction [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentProcessingInstruction)] [Name(ClassificationTypeNames.XmlDocCommentProcessingInstruction)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentProcessingInstructionFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentProcessingInstructionFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Processing_Instruction; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - Text [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentText)] [Name(ClassificationTypeNames.XmlDocCommentText)] [Order(After = Priority.Default, Before = Priority.High)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentTextFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentTextFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Text; this.ForegroundColor = Colors.Green; } } #endregion #region VB XML Literals - Attribute Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralAttributeName)] [Name(ClassificationTypeNames.XmlLiteralAttributeName)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralAttributeNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralAttributeNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Attribute_Name; this.ForegroundColor = Color.FromRgb(185, 100, 100); // HC_LIGHTRED } } #endregion #region VB XML Literals - Attribute Quotes [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralAttributeQuotes)] [Name(ClassificationTypeNames.XmlLiteralAttributeQuotes)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralAttributeQuotesFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralAttributeQuotesFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Attribute_Quotes; this.ForegroundColor = Color.FromRgb(85, 85, 85); // HC_LIGHTBLACK } } #endregion #region VB XML Literals - Attribute Value [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralAttributeValue)] [Name(ClassificationTypeNames.XmlLiteralAttributeValue)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralAttributeValueFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralAttributeValueFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Attribute_Value; this.ForegroundColor = Color.FromRgb(100, 100, 185); // HC_LIGHTBLUE } } #endregion #region VB XML Literals - CData Section [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralCDataSection)] [Name(ClassificationTypeNames.XmlLiteralCDataSection)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralCDataSectionFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralCDataSectionFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_CData_Section; this.ForegroundColor = Color.FromRgb(192, 192, 192); // HC_LIGHTGRAY } } #endregion #region VB XML Literals - Comment [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralComment)] [Name(ClassificationTypeNames.XmlLiteralComment)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralCommentFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralCommentFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Comment; this.ForegroundColor = Color.FromRgb(98, 151, 85); // HC_LIGHTGREEN } } #endregion #region VB XML Literals - Delimiter [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralDelimiter)] [Name(ClassificationTypeNames.XmlLiteralDelimiter)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralDelimiterFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralDelimiterFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Delimiter; this.ForegroundColor = Color.FromRgb(100, 100, 185); // HC_LIGHTBLUE } } #endregion #region VB XML Literals - Embedded Expression [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralEmbeddedExpression)] [Name(ClassificationTypeNames.XmlLiteralEmbeddedExpression)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralEmbeddedExpressionFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralEmbeddedExpressionFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Embedded_Expression; this.ForegroundColor = Color.FromRgb(85, 85, 85); // HC_LIGHTBLACK this.BackgroundColor = Color.FromRgb(255, 254, 191); // HC_LIGHTYELLOW } } #endregion #region VB XML Literals - Entity Reference [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralEntityReference)] [Name(ClassificationTypeNames.XmlLiteralEntityReference)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralEntityReferenceFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralEntityReferenceFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Entity_Reference; this.ForegroundColor = Color.FromRgb(185, 100, 100); // HC_LIGHTRED } } #endregion #region VB XML Literals - Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralName)] [Name(ClassificationTypeNames.XmlLiteralName)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Name; this.ForegroundColor = Color.FromRgb(132, 70, 70); // HC_LIGHTMAROON } } #endregion #region VB XML Literals - Processing Instruction [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralProcessingInstruction)] [Name(ClassificationTypeNames.XmlLiteralProcessingInstruction)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralProcessingInstructionFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralProcessingInstructionFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Processing_Instruction; this.ForegroundColor = Color.FromRgb(192, 192, 192); // HC_LIGHTGRAY } } #endregion #region VB XML Literals - Text [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralText)] [Name(ClassificationTypeNames.XmlLiteralText)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralTextFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralTextFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Text; this.ForegroundColor = Color.FromRgb(85, 85, 85); // HC_LIGHTBLACK } } #endregion [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.ClassificationTypeDefinitions.UnnecessaryCode)] [Name(Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.ClassificationTypeDefinitions.UnnecessaryCode)] [Order(After = Priority.High)] [UserVisible(false)] internal sealed class UnnecessaryCodeFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UnnecessaryCodeFormatDefinition() { this.DisplayName = EditorFeaturesResources.Unnecessary_Code; this.ForegroundOpacity = 0.6; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Windows.Media; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification { internal sealed class ClassificationTypeFormatDefinitions { #region Control Keyword [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ControlKeyword)] [Name(ClassificationTypeNames.ControlKeyword)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class ControlKeywordFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ControlKeywordFormatDefinition() { this.DisplayName = EditorFeaturesResources.Keyword_Control; this.ForegroundColor = Color.FromRgb(0x8F, 0x08, 0xC4); } } #endregion #region Local Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.LocalName)] [Name(ClassificationTypeNames.LocalName)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class LocalNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LocalNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Members_Locals; this.ForegroundColor = Color.FromRgb(0x1F, 0x37, 0x7F); } } #endregion #region Method Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.MethodName)] [Name(ClassificationTypeNames.MethodName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class MethodNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MethodNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Members_Methods; this.ForegroundColor = Color.FromRgb(0x74, 0x53, 0x1F); } } #endregion #region Operator Overloaded [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.OperatorOverloaded)] [Name(ClassificationTypeNames.OperatorOverloaded)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class OperatorOverloadedFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OperatorOverloadedFormatDefinition() { this.DisplayName = EditorFeaturesResources.Operator_Overloaded; this.ForegroundColor = Color.FromRgb(0x74, 0x53, 0x1F); } } #endregion #region Parameter Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ParameterName)] [Name(ClassificationTypeNames.ParameterName)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class ParameterNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ParameterNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Members_Parameters; this.ForegroundColor = Color.FromRgb(0x1F, 0x37, 0x7F); } } #endregion #region Preprocessor Text [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.PreprocessorText)] [Name(ClassificationTypeNames.PreprocessorText)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class PreprocessorTextFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreprocessorTextFormatDefinition() { this.DisplayName = EditorFeaturesResources.Preprocessor_Text; this.ForegroundColor = Colors.Black; } } #endregion #region Punctuation [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.Punctuation)] [Name(ClassificationTypeNames.Punctuation)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class PunctuationFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PunctuationFormatDefinition() { this.DisplayName = EditorFeaturesResources.Punctuation; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Alternation [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexAlternation)] [Name(ClassificationTypeNames.RegexAlternation)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexAlternationFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexAlternationFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexAlternation; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Anchor [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexAnchor)] [Name(ClassificationTypeNames.RegexAnchor)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexAnchorFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexAnchorFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexAnchor; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Character Class [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexCharacterClass)] [Name(ClassificationTypeNames.RegexCharacterClass)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexCharacterClassFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexCharacterClassFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexCharacterClass; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Comment [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexComment)] [Name(ClassificationTypeNames.RegexComment)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexCommentFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexCommentFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexComment; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Grouping [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexGrouping)] [Name(ClassificationTypeNames.RegexGrouping)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexGroupingFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexGroupingFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexGrouping; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Other Escape [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexOtherEscape)] [Name(ClassificationTypeNames.RegexOtherEscape)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexOtherEscapeFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexOtherEscapeFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexOtherEscape; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Quantifier [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexQuantifier)] [Name(ClassificationTypeNames.RegexQuantifier)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexQuantifierFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexQuantifierFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexQuantifier; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Self Escaped Character [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexSelfEscapedCharacter)] [Name(ClassificationTypeNames.RegexSelfEscapedCharacter)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexSelfEscapedCharacterFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexSelfEscapedCharacterFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexSelfEscapedCharacter; this.ForegroundColor = Colors.Black; } } #endregion #region Regex Text [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexText)] [Name(ClassificationTypeNames.RegexText)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class RegexTextFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RegexTextFormatDefinition() { this.DisplayName = ClassificationTypeNames.RegexText; this.ForegroundColor = Colors.Black; } } #endregion #region String - Escape Character [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.StringEscapeCharacter)] [Name(ClassificationTypeNames.StringEscapeCharacter)] [Order(After = PredefinedClassificationTypeNames.String)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class StringEscapeCharacterFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StringEscapeCharacterFormatDefinition() { this.DisplayName = EditorFeaturesResources.String_Escape_Character; this.ForegroundColor = Colors.LightYellow; } } #endregion #region String - Verbatim [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.VerbatimStringLiteral)] [Name(ClassificationTypeNames.VerbatimStringLiteral)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class StringVerbatimFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StringVerbatimFormatDefinition() { this.DisplayName = EditorFeaturesResources.String_Verbatim; this.ForegroundColor = Colors.Maroon; } } #endregion #region User Types - Classes [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ClassName)] [Name(ClassificationTypeNames.ClassName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [Order(After = PredefinedClassificationTypeNames.Keyword)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class UserTypeClassesFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserTypeClassesFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Types_Classes; this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF); } } #endregion #region User Types - Delegates [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.DelegateName)] [Name(ClassificationTypeNames.DelegateName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [Order(After = PredefinedClassificationTypeNames.Keyword)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class UserTypeDelegatesFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserTypeDelegatesFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Types_Delegates; this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF); } } #endregion #region User Types - Enums [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.EnumName)] [Name(ClassificationTypeNames.EnumName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [Order(After = PredefinedClassificationTypeNames.Keyword)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class UserTypeEnumsFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserTypeEnumsFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Types_Enums; this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF); } } #endregion #region User Types - Interfaces [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.InterfaceName)] [Name(ClassificationTypeNames.InterfaceName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [Order(After = PredefinedClassificationTypeNames.Keyword)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class UserTypeInterfacesFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserTypeInterfacesFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Types_Interfaces; this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF); } } #endregion #region User Types - Modules [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ModuleName)] [Name(ClassificationTypeNames.ModuleName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [Order(After = PredefinedClassificationTypeNames.Keyword)] [UserVisible(true)] private class UserTypeModulesFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserTypeModulesFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Types_Modules; this.ForegroundColor = Color.FromRgb(43, 145, 175); } } #endregion #region User Types - Structures [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.StructName)] [Name(ClassificationTypeNames.StructName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [Order(After = PredefinedClassificationTypeNames.Keyword)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class UserTypeStructuresFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserTypeStructuresFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Types_Structures; this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF); } } #endregion #region User Types - Type Parameters [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.TypeParameterName)] [Name(ClassificationTypeNames.TypeParameterName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [Order(After = PredefinedClassificationTypeNames.Keyword)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class UserTypeTypeParametersFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserTypeTypeParametersFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Types_Type_Parameters; this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF); } } #endregion #region User Members - Extension Method Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ExtensionMethodName)] [Name(ClassificationTypeNames.ExtensionMethodName)] [Order(After = PredefinedClassificationTypeNames.Identifier)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class UserMembersExtensionMethodNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UserMembersExtensionMethodNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.User_Members_Extension_Methods; this.ForegroundColor = Color.FromRgb(85, 85, 85); } } #endregion #region XML Doc Comments - Attribute Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentAttributeName)] [Name(ClassificationTypeNames.XmlDocCommentAttributeName)] [Order(After = Priority.Default, Before = Priority.High)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentAttributeNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentAttributeNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Attribute_Name; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - Attribute Quotes [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentAttributeQuotes)] [Name(ClassificationTypeNames.XmlDocCommentAttributeQuotes)] [Order(After = Priority.Default, Before = Priority.High)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentAttributeQuotesFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentAttributeQuotesFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Attribute_Quotes; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - Attribute Value // definition of how format is represented in tools options. // also specifies the default format. [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentAttributeValue)] [Name(ClassificationTypeNames.XmlDocCommentAttributeValue)] [Order(After = Priority.Default, Before = Priority.High)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentAttributeValueFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentAttributeValueFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Attribute_Value; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - CData Section [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentCDataSection)] [Name(ClassificationTypeNames.XmlDocCommentCDataSection)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentCDataSectionFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentCDataSectionFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_CData_Section; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - Comment [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentComment)] [Name(ClassificationTypeNames.XmlDocCommentComment)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentCommentFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentCommentFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Comment; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - Delimiter [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentDelimiter)] [Name(ClassificationTypeNames.XmlDocCommentDelimiter)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentDelimiterFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentDelimiterFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Delimiter; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - Entity Reference [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentEntityReference)] [Name(ClassificationTypeNames.XmlDocCommentEntityReference)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentEntityReferenceFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentEntityReferenceFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Entity_Reference; this.ForegroundColor = Colors.Green; } } #endregion #region XML Doc Comments - Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentName)] [Name(ClassificationTypeNames.XmlDocCommentName)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Name; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - Processing Instruction [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentProcessingInstruction)] [Name(ClassificationTypeNames.XmlDocCommentProcessingInstruction)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentProcessingInstructionFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentProcessingInstructionFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Processing_Instruction; this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY } } #endregion #region XML Doc Comments - Text [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentText)] [Name(ClassificationTypeNames.XmlDocCommentText)] [Order(After = Priority.Default, Before = Priority.High)] [UserVisible(true)] [ExcludeFromCodeCoverage] private class XmlDocCommentTextFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlDocCommentTextFormatDefinition() { this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Text; this.ForegroundColor = Colors.Green; } } #endregion #region VB XML Literals - Attribute Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralAttributeName)] [Name(ClassificationTypeNames.XmlLiteralAttributeName)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralAttributeNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralAttributeNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Attribute_Name; this.ForegroundColor = Color.FromRgb(185, 100, 100); // HC_LIGHTRED } } #endregion #region VB XML Literals - Attribute Quotes [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralAttributeQuotes)] [Name(ClassificationTypeNames.XmlLiteralAttributeQuotes)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralAttributeQuotesFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralAttributeQuotesFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Attribute_Quotes; this.ForegroundColor = Color.FromRgb(85, 85, 85); // HC_LIGHTBLACK } } #endregion #region VB XML Literals - Attribute Value [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralAttributeValue)] [Name(ClassificationTypeNames.XmlLiteralAttributeValue)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralAttributeValueFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralAttributeValueFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Attribute_Value; this.ForegroundColor = Color.FromRgb(100, 100, 185); // HC_LIGHTBLUE } } #endregion #region VB XML Literals - CData Section [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralCDataSection)] [Name(ClassificationTypeNames.XmlLiteralCDataSection)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralCDataSectionFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralCDataSectionFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_CData_Section; this.ForegroundColor = Color.FromRgb(192, 192, 192); // HC_LIGHTGRAY } } #endregion #region VB XML Literals - Comment [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralComment)] [Name(ClassificationTypeNames.XmlLiteralComment)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralCommentFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralCommentFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Comment; this.ForegroundColor = Color.FromRgb(98, 151, 85); // HC_LIGHTGREEN } } #endregion #region VB XML Literals - Delimiter [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralDelimiter)] [Name(ClassificationTypeNames.XmlLiteralDelimiter)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralDelimiterFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralDelimiterFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Delimiter; this.ForegroundColor = Color.FromRgb(100, 100, 185); // HC_LIGHTBLUE } } #endregion #region VB XML Literals - Embedded Expression [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralEmbeddedExpression)] [Name(ClassificationTypeNames.XmlLiteralEmbeddedExpression)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralEmbeddedExpressionFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralEmbeddedExpressionFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Embedded_Expression; this.ForegroundColor = Color.FromRgb(85, 85, 85); // HC_LIGHTBLACK this.BackgroundColor = Color.FromRgb(255, 254, 191); // HC_LIGHTYELLOW } } #endregion #region VB XML Literals - Entity Reference [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralEntityReference)] [Name(ClassificationTypeNames.XmlLiteralEntityReference)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralEntityReferenceFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralEntityReferenceFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Entity_Reference; this.ForegroundColor = Color.FromRgb(185, 100, 100); // HC_LIGHTRED } } #endregion #region VB XML Literals - Name [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralName)] [Name(ClassificationTypeNames.XmlLiteralName)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralNameFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralNameFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Name; this.ForegroundColor = Color.FromRgb(132, 70, 70); // HC_LIGHTMAROON } } #endregion #region VB XML Literals - Processing Instruction [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralProcessingInstruction)] [Name(ClassificationTypeNames.XmlLiteralProcessingInstruction)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralProcessingInstructionFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralProcessingInstructionFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Processing_Instruction; this.ForegroundColor = Color.FromRgb(192, 192, 192); // HC_LIGHTGRAY } } #endregion #region VB XML Literals - Text [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralText)] [Name(ClassificationTypeNames.XmlLiteralText)] [Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)] [UserVisible(true)] private class XmlLiteralTextFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XmlLiteralTextFormatDefinition() { this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Text; this.ForegroundColor = Color.FromRgb(85, 85, 85); // HC_LIGHTBLACK } } #endregion [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.ClassificationTypeDefinitions.UnnecessaryCode)] [Name(Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.ClassificationTypeDefinitions.UnnecessaryCode)] [Order(After = Priority.High)] [UserVisible(false)] internal sealed class UnnecessaryCodeFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UnnecessaryCodeFormatDefinition() { this.DisplayName = EditorFeaturesResources.Unnecessary_Code; this.ForegroundOpacity = 0.6; } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/Core.Wpf/SignatureHelp/Model.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal class Model { private readonly DisconnectedBufferGraph _disconnectedBufferGraph; public TextSpan TextSpan { get; } public IList<SignatureHelpItem> Items { get; } public SignatureHelpItem SelectedItem { get; } /// <summary>UserSelected is true if the SelectedItem is the result of a user selection (up/down arrows).</summary> public bool UserSelected { get; } public int ArgumentIndex { get; } public int ArgumentCount { get; } public string ArgumentName { get; } public int? SelectedParameter { get; } public ISignatureHelpProvider Provider { get; } public Model( DisconnectedBufferGraph disconnectedBufferGraph, TextSpan textSpan, ISignatureHelpProvider provider, IList<SignatureHelpItem> items, SignatureHelpItem selectedItem, int argumentIndex, int argumentCount, string argumentName, int? selectedParameter, bool userSelected) { Contract.ThrowIfNull(selectedItem); Contract.ThrowIfFalse(items.Count != 0, "Must have at least one item."); Contract.ThrowIfFalse(items.Contains(selectedItem), "Selected item must be in list of items."); _disconnectedBufferGraph = disconnectedBufferGraph; this.TextSpan = textSpan; this.Items = items; this.Provider = provider; this.SelectedItem = selectedItem; this.UserSelected = userSelected; this.ArgumentIndex = argumentIndex; this.ArgumentCount = argumentCount; this.ArgumentName = argumentName; this.SelectedParameter = selectedParameter; } public Model WithSelectedItem(SignatureHelpItem selectedItem, bool userSelected) { return selectedItem == this.SelectedItem && userSelected == this.UserSelected ? this : new Model(_disconnectedBufferGraph, TextSpan, Provider, Items, selectedItem, ArgumentIndex, ArgumentCount, ArgumentName, SelectedParameter, userSelected); } public Model WithSelectedParameter(int? selectedParameter) { return selectedParameter == this.SelectedParameter ? this : new Model(_disconnectedBufferGraph, TextSpan, Provider, Items, SelectedItem, ArgumentIndex, ArgumentCount, ArgumentName, selectedParameter, UserSelected); } public SnapshotSpan GetCurrentSpanInSubjectBuffer(ITextSnapshot bufferSnapshot) { return _disconnectedBufferGraph.SubjectBufferSnapshot .CreateTrackingSpan(this.TextSpan.ToSpan(), SpanTrackingMode.EdgeInclusive) .GetSpan(bufferSnapshot); } public SnapshotSpan GetCurrentSpanInView(ITextSnapshot textSnapshot) { var originalSpan = _disconnectedBufferGraph.GetSubjectBufferTextSpanInViewBuffer(this.TextSpan); var trackingSpan = _disconnectedBufferGraph.ViewSnapshot.CreateTrackingSpan(originalSpan.TextSpan.ToSpan(), SpanTrackingMode.EdgeInclusive); return trackingSpan.GetSpan(textSnapshot); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal class Model { private readonly DisconnectedBufferGraph _disconnectedBufferGraph; public TextSpan TextSpan { get; } public IList<SignatureHelpItem> Items { get; } public SignatureHelpItem SelectedItem { get; } /// <summary>UserSelected is true if the SelectedItem is the result of a user selection (up/down arrows).</summary> public bool UserSelected { get; } public int ArgumentIndex { get; } public int ArgumentCount { get; } public string ArgumentName { get; } public int? SelectedParameter { get; } public ISignatureHelpProvider Provider { get; } public Model( DisconnectedBufferGraph disconnectedBufferGraph, TextSpan textSpan, ISignatureHelpProvider provider, IList<SignatureHelpItem> items, SignatureHelpItem selectedItem, int argumentIndex, int argumentCount, string argumentName, int? selectedParameter, bool userSelected) { Contract.ThrowIfNull(selectedItem); Contract.ThrowIfFalse(items.Count != 0, "Must have at least one item."); Contract.ThrowIfFalse(items.Contains(selectedItem), "Selected item must be in list of items."); _disconnectedBufferGraph = disconnectedBufferGraph; this.TextSpan = textSpan; this.Items = items; this.Provider = provider; this.SelectedItem = selectedItem; this.UserSelected = userSelected; this.ArgumentIndex = argumentIndex; this.ArgumentCount = argumentCount; this.ArgumentName = argumentName; this.SelectedParameter = selectedParameter; } public Model WithSelectedItem(SignatureHelpItem selectedItem, bool userSelected) { return selectedItem == this.SelectedItem && userSelected == this.UserSelected ? this : new Model(_disconnectedBufferGraph, TextSpan, Provider, Items, selectedItem, ArgumentIndex, ArgumentCount, ArgumentName, SelectedParameter, userSelected); } public Model WithSelectedParameter(int? selectedParameter) { return selectedParameter == this.SelectedParameter ? this : new Model(_disconnectedBufferGraph, TextSpan, Provider, Items, SelectedItem, ArgumentIndex, ArgumentCount, ArgumentName, selectedParameter, UserSelected); } public SnapshotSpan GetCurrentSpanInSubjectBuffer(ITextSnapshot bufferSnapshot) { return _disconnectedBufferGraph.SubjectBufferSnapshot .CreateTrackingSpan(this.TextSpan.ToSpan(), SpanTrackingMode.EdgeInclusive) .GetSpan(bufferSnapshot); } public SnapshotSpan GetCurrentSpanInView(ITextSnapshot textSnapshot) { var originalSpan = _disconnectedBufferGraph.GetSubjectBufferTextSpanInViewBuffer(this.TextSpan); var trackingSpan = _disconnectedBufferGraph.ViewSnapshot.CreateTrackingSpan(originalSpan.TextSpan.ToSpan(), SpanTrackingMode.EdgeInclusive); return trackingSpan.GetSpan(textSnapshot); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/TypeImportCompletionServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportLanguageServiceFactory(typeof(ITypeImportCompletionService), LanguageNames.CSharp), Shared] internal sealed class TypeImportCompletionServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TypeImportCompletionServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => new CSharpTypeImportCompletionService(languageServices.WorkspaceServices.Workspace); private class CSharpTypeImportCompletionService : AbstractTypeImportCompletionService { public CSharpTypeImportCompletionService(Workspace workspace) : base(workspace) { } protected override string GenericTypeSuffix => "<>"; protected override bool IsCaseSensitive => true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportLanguageServiceFactory(typeof(ITypeImportCompletionService), LanguageNames.CSharp), Shared] internal sealed class TypeImportCompletionServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TypeImportCompletionServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => new CSharpTypeImportCompletionService(languageServices.WorkspaceServices.Workspace); private class CSharpTypeImportCompletionService : AbstractTypeImportCompletionService { public CSharpTypeImportCompletionService(Workspace workspace) : base(workspace) { } protected override string GenericTypeSuffix => "<>"; protected override bool IsCaseSensitive => true; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/Core/Def/Implementation/Utilities/VisualStudioNavigateToLinkService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { [ExportWorkspaceService(typeof(INavigateToLinkService), layer: ServiceLayer.Host)] [Shared] internal sealed class VisualStudioNavigateToLinkService : INavigateToLinkService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioNavigateToLinkService() { } public Task<bool> TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken) { if (!uri.IsAbsoluteUri) { return SpecializedTasks.False; } if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) { return SpecializedTasks.False; } StartBrowser(uri); return SpecializedTasks.True; } public static void StartBrowser(string uri) => VsShellUtilities.OpenSystemBrowser(uri); public static void StartBrowser(Uri uri) => VsShellUtilities.OpenSystemBrowser(uri.AbsoluteUri); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { [ExportWorkspaceService(typeof(INavigateToLinkService), layer: ServiceLayer.Host)] [Shared] internal sealed class VisualStudioNavigateToLinkService : INavigateToLinkService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioNavigateToLinkService() { } public Task<bool> TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken) { if (!uri.IsAbsoluteUri) { return SpecializedTasks.False; } if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) { return SpecializedTasks.False; } StartBrowser(uri); return SpecializedTasks.True; } public static void StartBrowser(string uri) => VsShellUtilities.OpenSystemBrowser(uri); public static void StartBrowser(Uri uri) => VsShellUtilities.OpenSystemBrowser(uri.AbsoluteUri); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/Core/Portable/Collections/Rope.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A representation of a string of characters that requires O(1) extra space to concatenate two ropes. /// </summary> internal abstract class Rope { public static readonly Rope Empty = ForString(""); public abstract override string ToString(); public abstract int Length { get; } protected abstract IEnumerable<char> GetChars(); private Rope() { } /// <summary> /// A rope can wrap a simple string. /// </summary> public static Rope ForString(string s) { if (s == null) throw new ArgumentNullException(nameof(s)); return new StringRope(s); } /// <summary> /// A rope can be formed from the concatenation of two ropes. /// </summary> public static Rope Concat(Rope r1, Rope r2) { if (r1 == null) throw new ArgumentNullException(nameof(r1)); if (r2 == null) throw new ArgumentNullException(nameof(r2)); return r1.Length == 0 ? r2 : r2.Length == 0 ? r1 : checked(r1.Length + r2.Length < 32) ? ForString(r1.ToString() + r2.ToString()) : new ConcatRope(r1, r2); } /// <summary> /// Two ropes are "the same" if they represent the same sequence of characters. /// </summary> public override bool Equals(object? obj) { if (!(obj is Rope other) || Length != other.Length) return false; if (Length == 0) return true; var chars0 = GetChars().GetEnumerator(); var chars1 = other.GetChars().GetEnumerator(); while (chars0.MoveNext() && chars1.MoveNext()) { if (chars0.Current != chars1.Current) return false; } return true; } public override int GetHashCode() { int result = Length; foreach (char c in GetChars()) result = Hash.Combine((int)c, result); return result; } /// <summary> /// A rope that wraps a simple string. /// </summary> private sealed class StringRope : Rope { private readonly string _value; public StringRope(string value) => _value = value; public override string ToString() => _value; public override int Length => _value.Length; protected override IEnumerable<char> GetChars() => _value; } /// <summary> /// A rope that represents the concatenation of two ropes. /// </summary> private sealed class ConcatRope : Rope { private readonly Rope _left, _right; public override int Length { get; } public ConcatRope(Rope left, Rope right) { _left = left; _right = right; Length = checked(left.Length + right.Length); } public override string ToString() { var psb = PooledStringBuilder.GetInstance(); var stack = new Stack<Rope>(); stack.Push(this); while (stack.Count != 0) { switch (stack.Pop()) { case StringRope s: psb.Builder.Append(s.ToString()); break; case ConcatRope c: stack.Push(c._right); stack.Push(c._left); break; case var v: throw ExceptionUtilities.UnexpectedValue(v.GetType().Name); } } return psb.ToStringAndFree(); } protected override IEnumerable<char> GetChars() { var stack = new Stack<Rope>(); stack.Push(this); while (stack.Count != 0) { switch (stack.Pop()) { case StringRope s: foreach (var c in s.ToString()) yield return c; break; case ConcatRope c: stack.Push(c._right); stack.Push(c._left); break; case var v: throw ExceptionUtilities.UnexpectedValue(v.GetType().Name); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A representation of a string of characters that requires O(1) extra space to concatenate two ropes. /// </summary> internal abstract class Rope { public static readonly Rope Empty = ForString(""); public abstract override string ToString(); public abstract int Length { get; } protected abstract IEnumerable<char> GetChars(); private Rope() { } /// <summary> /// A rope can wrap a simple string. /// </summary> public static Rope ForString(string s) { if (s == null) throw new ArgumentNullException(nameof(s)); return new StringRope(s); } /// <summary> /// A rope can be formed from the concatenation of two ropes. /// </summary> public static Rope Concat(Rope r1, Rope r2) { if (r1 == null) throw new ArgumentNullException(nameof(r1)); if (r2 == null) throw new ArgumentNullException(nameof(r2)); return r1.Length == 0 ? r2 : r2.Length == 0 ? r1 : checked(r1.Length + r2.Length < 32) ? ForString(r1.ToString() + r2.ToString()) : new ConcatRope(r1, r2); } /// <summary> /// Two ropes are "the same" if they represent the same sequence of characters. /// </summary> public override bool Equals(object? obj) { if (!(obj is Rope other) || Length != other.Length) return false; if (Length == 0) return true; var chars0 = GetChars().GetEnumerator(); var chars1 = other.GetChars().GetEnumerator(); while (chars0.MoveNext() && chars1.MoveNext()) { if (chars0.Current != chars1.Current) return false; } return true; } public override int GetHashCode() { int result = Length; foreach (char c in GetChars()) result = Hash.Combine((int)c, result); return result; } /// <summary> /// A rope that wraps a simple string. /// </summary> private sealed class StringRope : Rope { private readonly string _value; public StringRope(string value) => _value = value; public override string ToString() => _value; public override int Length => _value.Length; protected override IEnumerable<char> GetChars() => _value; } /// <summary> /// A rope that represents the concatenation of two ropes. /// </summary> private sealed class ConcatRope : Rope { private readonly Rope _left, _right; public override int Length { get; } public ConcatRope(Rope left, Rope right) { _left = left; _right = right; Length = checked(left.Length + right.Length); } public override string ToString() { var psb = PooledStringBuilder.GetInstance(); var stack = new Stack<Rope>(); stack.Push(this); while (stack.Count != 0) { switch (stack.Pop()) { case StringRope s: psb.Builder.Append(s.ToString()); break; case ConcatRope c: stack.Push(c._right); stack.Push(c._left); break; case var v: throw ExceptionUtilities.UnexpectedValue(v.GetType().Name); } } return psb.ToStringAndFree(); } protected override IEnumerable<char> GetChars() { var stack = new Stack<Rope>(); stack.Push(this); while (stack.Count != 0) { switch (stack.Pop()) { case StringRope s: foreach (var c in s.ToString()) yield return c; break; case ConcatRope c: stack.Push(c._right); stack.Push(c._left); break; case var v: throw ExceptionUtilities.UnexpectedValue(v.GetType().Name); } } } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/Core/Shared/Extensions/ITextSelectionExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class ITextSelectionExtensions { public static NormalizedSnapshotSpanCollection GetSnapshotSpansOnBuffer(this ITextSelection selection, ITextBuffer subjectBuffer) { Contract.ThrowIfNull(selection); Contract.ThrowIfNull(subjectBuffer); var list = new List<SnapshotSpan>(); foreach (var snapshotSpan in selection.SelectedSpans) { list.AddRange(selection.TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, subjectBuffer)); } return new NormalizedSnapshotSpanCollection(list); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class ITextSelectionExtensions { public static NormalizedSnapshotSpanCollection GetSnapshotSpansOnBuffer(this ITextSelection selection, ITextBuffer subjectBuffer) { Contract.ThrowIfNull(selection); Contract.ThrowIfNull(subjectBuffer); var list = new List<SnapshotSpan>(); foreach (var snapshotSpan in selection.SelectedSpans) { list.AddRange(selection.TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, subjectBuffer)); } return new NormalizedSnapshotSpanCollection(list); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/RQName/Nodes/RQMethodBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal abstract class RQMethodBase : RQMethodOrProperty { public RQMethodBase( RQUnconstructedType containingType, RQMethodPropertyOrEventName memberName, int typeParameterCount, IList<RQParameter> parameters) : base(containingType, memberName, typeParameterCount, parameters) { } protected override string RQKeyword { get { return RQNameStrings.Meth; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal abstract class RQMethodBase : RQMethodOrProperty { public RQMethodBase( RQUnconstructedType containingType, RQMethodPropertyOrEventName memberName, int typeParameterCount, IList<RQParameter> parameters) : base(containingType, memberName, typeParameterCount, parameters) { } protected override string RQKeyword { get { return RQNameStrings.Meth; } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/Workspace/Solution/BranchId.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// solution branch Id /// </summary> internal class BranchId { private static int s_nextId; #pragma warning disable IDE0052 // Remove unread private members private readonly int _id; #pragma warning restore IDE0052 // Remove unread private members private BranchId(int id) => _id = id; internal static BranchId GetNextId() => new(Interlocked.Increment(ref s_nextId)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// solution branch Id /// </summary> internal class BranchId { private static int s_nextId; #pragma warning disable IDE0052 // Remove unread private members private readonly int _id; #pragma warning restore IDE0052 // Remove unread private members private BranchId(int id) => _id = id; internal static BranchId GetNextId() => new(Interlocked.Increment(ref s_nextId)); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/CoreTest/TestCompositionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests.Persistence; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class TestCompositionTests { [Fact] public void FactoryReuse() { var composition1 = FeaturesTestCompositions.Features.AddParts(typeof(TestPersistenceService), typeof(TestOptionsServiceFactory)); var composition2 = FeaturesTestCompositions.Features.AddParts(typeof(TestOptionsServiceFactory), typeof(TestPersistenceService)); Assert.Same(composition1.ExportProviderFactory, composition2.ExportProviderFactory); } [Fact] public void Assemblies() { var assembly1 = typeof(Workspace).Assembly; var assembly2 = typeof(object).Assembly; var composition1 = TestComposition.Empty; var composition2 = composition1.AddAssemblies(assembly1); AssertEx.SetEqual(new[] { assembly1 }, composition2.Assemblies); Assert.Empty(composition2.RemoveAssemblies(assembly1).Assemblies); var composition3 = composition2.WithAssemblies(ImmutableHashSet.Create(assembly2)); AssertEx.SetEqual(new[] { assembly2 }, composition3.Assemblies); } [Fact] public void Parts() { var type1 = typeof(int); var type2 = typeof(bool); var composition1 = TestComposition.Empty; var composition2 = composition1.AddParts(type1); var composition3 = composition2.RemoveParts(type1); AssertEx.SetEqual(new[] { type1 }, composition2.Parts); Assert.Empty(composition3.Parts); Assert.Empty(composition3.ExcludedPartTypes); var composition4 = composition2.WithParts(ImmutableHashSet.Create(type2)); AssertEx.SetEqual(new[] { type2 }, composition4.Parts); Assert.Empty(composition3.ExcludedPartTypes); } [Fact] public void ExcludedPartTypes() { var type1 = typeof(int); var type2 = typeof(bool); var composition1 = TestComposition.Empty; var composition2 = composition1.AddExcludedPartTypes(type1); var composition3 = composition2.RemoveExcludedPartTypes(type1); AssertEx.SetEqual(new[] { type1 }, composition2.ExcludedPartTypes); Assert.Empty(composition3.Parts); Assert.Empty(composition3.ExcludedPartTypes); Assert.Empty(composition3.Parts); var composition4 = composition2.WithExcludedPartTypes(ImmutableHashSet.Create(type2)); AssertEx.SetEqual(new[] { type2 }, composition4.ExcludedPartTypes); Assert.Empty(composition4.Parts); } [Fact] public void Composition() { var assembly1 = typeof(Workspace).Assembly; var assembly2 = typeof(object).Assembly; var type1 = typeof(int); var type2 = typeof(long); var excluded1 = typeof(bool); var excluded2 = typeof(byte); var composition1 = TestComposition.Empty.AddAssemblies(assembly1).AddParts(type1).AddExcludedPartTypes(excluded1); var composition2 = TestComposition.Empty.AddAssemblies(assembly2).AddParts(type1, type2).AddExcludedPartTypes(excluded2); var composition3 = composition1.Add(composition2); AssertEx.SetEqual(new[] { assembly1, assembly2 }, composition3.Assemblies); AssertEx.SetEqual(new[] { type1, type2 }, composition3.Parts); AssertEx.SetEqual(new[] { excluded1, excluded2 }, composition3.ExcludedPartTypes); var composition4 = composition3.Remove(composition1); AssertEx.SetEqual(new[] { assembly2 }, composition4.Assemblies); AssertEx.SetEqual(new[] { type2 }, composition4.Parts); AssertEx.SetEqual(new[] { excluded2 }, composition4.ExcludedPartTypes); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests.Persistence; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class TestCompositionTests { [Fact] public void FactoryReuse() { var composition1 = FeaturesTestCompositions.Features.AddParts(typeof(TestPersistenceService), typeof(TestOptionsServiceFactory)); var composition2 = FeaturesTestCompositions.Features.AddParts(typeof(TestOptionsServiceFactory), typeof(TestPersistenceService)); Assert.Same(composition1.ExportProviderFactory, composition2.ExportProviderFactory); } [Fact] public void Assemblies() { var assembly1 = typeof(Workspace).Assembly; var assembly2 = typeof(object).Assembly; var composition1 = TestComposition.Empty; var composition2 = composition1.AddAssemblies(assembly1); AssertEx.SetEqual(new[] { assembly1 }, composition2.Assemblies); Assert.Empty(composition2.RemoveAssemblies(assembly1).Assemblies); var composition3 = composition2.WithAssemblies(ImmutableHashSet.Create(assembly2)); AssertEx.SetEqual(new[] { assembly2 }, composition3.Assemblies); } [Fact] public void Parts() { var type1 = typeof(int); var type2 = typeof(bool); var composition1 = TestComposition.Empty; var composition2 = composition1.AddParts(type1); var composition3 = composition2.RemoveParts(type1); AssertEx.SetEqual(new[] { type1 }, composition2.Parts); Assert.Empty(composition3.Parts); Assert.Empty(composition3.ExcludedPartTypes); var composition4 = composition2.WithParts(ImmutableHashSet.Create(type2)); AssertEx.SetEqual(new[] { type2 }, composition4.Parts); Assert.Empty(composition3.ExcludedPartTypes); } [Fact] public void ExcludedPartTypes() { var type1 = typeof(int); var type2 = typeof(bool); var composition1 = TestComposition.Empty; var composition2 = composition1.AddExcludedPartTypes(type1); var composition3 = composition2.RemoveExcludedPartTypes(type1); AssertEx.SetEqual(new[] { type1 }, composition2.ExcludedPartTypes); Assert.Empty(composition3.Parts); Assert.Empty(composition3.ExcludedPartTypes); Assert.Empty(composition3.Parts); var composition4 = composition2.WithExcludedPartTypes(ImmutableHashSet.Create(type2)); AssertEx.SetEqual(new[] { type2 }, composition4.ExcludedPartTypes); Assert.Empty(composition4.Parts); } [Fact] public void Composition() { var assembly1 = typeof(Workspace).Assembly; var assembly2 = typeof(object).Assembly; var type1 = typeof(int); var type2 = typeof(long); var excluded1 = typeof(bool); var excluded2 = typeof(byte); var composition1 = TestComposition.Empty.AddAssemblies(assembly1).AddParts(type1).AddExcludedPartTypes(excluded1); var composition2 = TestComposition.Empty.AddAssemblies(assembly2).AddParts(type1, type2).AddExcludedPartTypes(excluded2); var composition3 = composition1.Add(composition2); AssertEx.SetEqual(new[] { assembly1, assembly2 }, composition3.Assemblies); AssertEx.SetEqual(new[] { type1, type2 }, composition3.Parts); AssertEx.SetEqual(new[] { excluded1, excluded2 }, composition3.ExcludedPartTypes); var composition4 = composition3.Remove(composition1); AssertEx.SetEqual(new[] { assembly2 }, composition4.Assemblies); AssertEx.SetEqual(new[] { type2 }, composition4.Parts); AssertEx.SetEqual(new[] { excluded2 }, composition4.ExcludedPartTypes); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/CodeStyle/CSharp/Analyzers/xlf/CSharpCodeStyleResources.es.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../CSharpCodeStyleResources.resx"> <body> <trans-unit id="Indentation_preferences"> <source>Indentation preferences</source> <target state="translated">Preferencias de indentación</target> <note /> </trans-unit> <trans-unit id="Space_preferences"> <source>Space preferences</source> <target state="translated">Preferencias de espacio</target> <note /> </trans-unit> <trans-unit id="Wrapping_preferences"> <source>Wrapping preferences</source> <target state="translated">Preferencias de ajuste</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../CSharpCodeStyleResources.resx"> <body> <trans-unit id="Indentation_preferences"> <source>Indentation preferences</source> <target state="translated">Preferencias de indentación</target> <note /> </trans-unit> <trans-unit id="Space_preferences"> <source>Space preferences</source> <target state="translated">Preferencias de espacio</target> <note /> </trans-unit> <trans-unit id="Wrapping_preferences"> <source>Wrapping preferences</source> <target state="translated">Preferencias de ajuste</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/Core/Impl/CodeModel/Collections/Snapshot.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { internal abstract class Snapshot { public abstract int Count { get; } public abstract EnvDTE.CodeElement this[int index] { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { internal abstract class Snapshot { public abstract int Count { get; } public abstract EnvDTE.CodeElement this[int index] { get; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/Core/Portable/Symbols/Attributes/CommonEventEarlyWellKnownAttributeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from early well-known custom attributes applied on an event. /// </summary> internal class CommonEventEarlyWellKnownAttributeData : EarlyWellKnownAttributeData { #region ObsoleteAttribute private ObsoleteAttributeData _obsoleteAttributeData = ObsoleteAttributeData.Uninitialized; public ObsoleteAttributeData ObsoleteAttributeData { get { VerifySealed(expected: true); return _obsoleteAttributeData.IsUninitialized ? null : _obsoleteAttributeData; } set { VerifySealed(expected: false); Debug.Assert(value != null); Debug.Assert(!value.IsUninitialized); _obsoleteAttributeData = value; SetDataStored(); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from early well-known custom attributes applied on an event. /// </summary> internal class CommonEventEarlyWellKnownAttributeData : EarlyWellKnownAttributeData { #region ObsoleteAttribute private ObsoleteAttributeData _obsoleteAttributeData = ObsoleteAttributeData.Uninitialized; public ObsoleteAttributeData ObsoleteAttributeData { get { VerifySealed(expected: true); return _obsoleteAttributeData.IsUninitialized ? null : _obsoleteAttributeData; } set { VerifySealed(expected: false); Debug.Assert(value != null); Debug.Assert(!value.IsUninitialized); _obsoleteAttributeData = value; SetDataStored(); } } #endregion } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Scripting/Core/ScriptBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Scripting.Hosting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// Represents a runtime execution context for scripts. /// </summary> internal sealed class ScriptBuilder { /// <summary> /// Unique prefix for generated assemblies. /// </summary> /// <remarks> /// The full names of uncollectible assemblies generated by this context must be unique, /// so that we can resolve references among them. Note that CLR can load two different assemblies of the very same /// identity into the same load context. /// /// We are using a certain naming scheme for the generated assemblies (a fixed name prefix followed by a number). /// If we allowed the compiled code to add references that match this exact pattern it might happen that /// the user supplied reference identity conflicts with the identity we use for our generated assemblies and /// the AppDomain assembly resolve event won't be able to correctly identify the target assembly. /// /// To avoid this problem we use a prefix for assemblies we generate that is unlikely to conflict with user specified references. /// We also check that no user provided references are allowed to be used in the compiled code and report an error ("reserved assembly name"). /// </remarks> private static readonly string s_globalAssemblyNamePrefix; private static int s_engineIdDispenser; private int _submissionIdDispenser = -1; private readonly string _assemblyNamePrefix; private readonly InteractiveAssemblyLoader _assemblyLoader; private static readonly EmitOptions s_EmitOptionsWithDebuggingInformation = new EmitOptions( debugInformationFormat: PdbHelpers.GetPlatformSpecificDebugInformationFormat(), pdbChecksumAlgorithm: default(HashAlgorithmName)); static ScriptBuilder() { s_globalAssemblyNamePrefix = "\u211B*" + Guid.NewGuid().ToString(); } public ScriptBuilder(InteractiveAssemblyLoader assemblyLoader) { Debug.Assert(assemblyLoader != null); _assemblyNamePrefix = s_globalAssemblyNamePrefix + "#" + Interlocked.Increment(ref s_engineIdDispenser).ToString(); _assemblyLoader = assemblyLoader; } public int GenerateSubmissionId(out string assemblyName, out string typeName) { int id = Interlocked.Increment(ref _submissionIdDispenser); string idAsString = id.ToString(); assemblyName = _assemblyNamePrefix + "-" + idAsString; typeName = "Submission#" + idAsString; return id; } /// <exception cref="CompilationErrorException">Compilation has errors.</exception> internal Func<object[], Task<T>> CreateExecutor<T>(ScriptCompiler compiler, Compilation compilation, bool emitDebugInformation, CancellationToken cancellationToken) { var diagnostics = DiagnosticBag.GetInstance(); try { // get compilation diagnostics first. diagnostics.AddRange(compilation.GetParseDiagnostics(cancellationToken)); ThrowIfAnyCompilationErrors(diagnostics, compiler.DiagnosticFormatter); diagnostics.Clear(); var executor = Build<T>(compilation, diagnostics, emitDebugInformation, cancellationToken); // emit can fail due to compilation errors or because there is nothing to emit: ThrowIfAnyCompilationErrors(diagnostics, compiler.DiagnosticFormatter); if (executor == null) { executor = (s) => Task.FromResult(default(T)); } return executor; } finally { diagnostics.Free(); } } private static void ThrowIfAnyCompilationErrors(DiagnosticBag diagnostics, DiagnosticFormatter formatter) { if (diagnostics.IsEmptyWithoutResolution) { return; } var filtered = diagnostics.AsEnumerable().Where(d => d.Severity == DiagnosticSeverity.Error).AsImmutable(); if (filtered.IsEmpty) { return; } throw new CompilationErrorException( formatter.Format(filtered[0], CultureInfo.CurrentCulture), filtered); } /// <summary> /// Builds a delegate that will execute just this scripts code. /// </summary> private Func<object[], Task<T>> Build<T>( Compilation compilation, DiagnosticBag diagnostics, bool emitDebugInformation, CancellationToken cancellationToken) { var entryPoint = compilation.GetEntryPoint(cancellationToken); using (var peStream = new MemoryStream()) using (var pdbStreamOpt = emitDebugInformation ? new MemoryStream() : null) { var emitResult = Emit(peStream, pdbStreamOpt, compilation, GetEmitOptions(emitDebugInformation), cancellationToken); diagnostics.AddRange(emitResult.Diagnostics); if (!emitResult.Success) { return null; } // let the loader know where to find assemblies: foreach (var referencedAssembly in compilation.GetBoundReferenceManager().GetReferencedAssemblies()) { var path = (referencedAssembly.Key as PortableExecutableReference)?.FilePath; if (path != null) { // TODO: Should the #r resolver return contract metadata and runtime assembly path - // Contract assembly used in the compiler, RT assembly path here. _assemblyLoader.RegisterDependency(referencedAssembly.Value.Identity, path); } } peStream.Position = 0; if (pdbStreamOpt != null) { pdbStreamOpt.Position = 0; } var assembly = _assemblyLoader.LoadAssemblyFromStream(peStream, pdbStreamOpt); var runtimeEntryPoint = GetEntryPointRuntimeMethod(entryPoint, assembly, cancellationToken); return runtimeEntryPoint.CreateDelegate<Func<object[], Task<T>>>(); } } // internal for testing internal static EmitOptions GetEmitOptions(bool emitDebugInformation) => emitDebugInformation ? s_EmitOptionsWithDebuggingInformation : EmitOptions.Default; // internal for testing internal static EmitResult Emit( Stream peStream, Stream pdbStreamOpt, Compilation compilation, EmitOptions options, CancellationToken cancellationToken) { return compilation.Emit( peStream: peStream, pdbStream: pdbStreamOpt, xmlDocumentationStream: null, win32Resources: null, manifestResources: null, options: options, cancellationToken: cancellationToken); } internal static MethodInfo GetEntryPointRuntimeMethod(IMethodSymbol entryPoint, Assembly assembly, CancellationToken cancellationToken) { string entryPointTypeName = MetadataHelpers.BuildQualifiedName(entryPoint.ContainingNamespace.MetadataName, entryPoint.ContainingType.MetadataName); string entryPointMethodName = entryPoint.MetadataName; var entryPointType = assembly.GetType(entryPointTypeName, throwOnError: true, ignoreCase: false).GetTypeInfo(); return entryPointType.GetDeclaredMethod(entryPointMethodName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Scripting.Hosting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// Represents a runtime execution context for scripts. /// </summary> internal sealed class ScriptBuilder { /// <summary> /// Unique prefix for generated assemblies. /// </summary> /// <remarks> /// The full names of uncollectible assemblies generated by this context must be unique, /// so that we can resolve references among them. Note that CLR can load two different assemblies of the very same /// identity into the same load context. /// /// We are using a certain naming scheme for the generated assemblies (a fixed name prefix followed by a number). /// If we allowed the compiled code to add references that match this exact pattern it might happen that /// the user supplied reference identity conflicts with the identity we use for our generated assemblies and /// the AppDomain assembly resolve event won't be able to correctly identify the target assembly. /// /// To avoid this problem we use a prefix for assemblies we generate that is unlikely to conflict with user specified references. /// We also check that no user provided references are allowed to be used in the compiled code and report an error ("reserved assembly name"). /// </remarks> private static readonly string s_globalAssemblyNamePrefix; private static int s_engineIdDispenser; private int _submissionIdDispenser = -1; private readonly string _assemblyNamePrefix; private readonly InteractiveAssemblyLoader _assemblyLoader; private static readonly EmitOptions s_EmitOptionsWithDebuggingInformation = new EmitOptions( debugInformationFormat: PdbHelpers.GetPlatformSpecificDebugInformationFormat(), pdbChecksumAlgorithm: default(HashAlgorithmName)); static ScriptBuilder() { s_globalAssemblyNamePrefix = "\u211B*" + Guid.NewGuid().ToString(); } public ScriptBuilder(InteractiveAssemblyLoader assemblyLoader) { Debug.Assert(assemblyLoader != null); _assemblyNamePrefix = s_globalAssemblyNamePrefix + "#" + Interlocked.Increment(ref s_engineIdDispenser).ToString(); _assemblyLoader = assemblyLoader; } public int GenerateSubmissionId(out string assemblyName, out string typeName) { int id = Interlocked.Increment(ref _submissionIdDispenser); string idAsString = id.ToString(); assemblyName = _assemblyNamePrefix + "-" + idAsString; typeName = "Submission#" + idAsString; return id; } /// <exception cref="CompilationErrorException">Compilation has errors.</exception> internal Func<object[], Task<T>> CreateExecutor<T>(ScriptCompiler compiler, Compilation compilation, bool emitDebugInformation, CancellationToken cancellationToken) { var diagnostics = DiagnosticBag.GetInstance(); try { // get compilation diagnostics first. diagnostics.AddRange(compilation.GetParseDiagnostics(cancellationToken)); ThrowIfAnyCompilationErrors(diagnostics, compiler.DiagnosticFormatter); diagnostics.Clear(); var executor = Build<T>(compilation, diagnostics, emitDebugInformation, cancellationToken); // emit can fail due to compilation errors or because there is nothing to emit: ThrowIfAnyCompilationErrors(diagnostics, compiler.DiagnosticFormatter); if (executor == null) { executor = (s) => Task.FromResult(default(T)); } return executor; } finally { diagnostics.Free(); } } private static void ThrowIfAnyCompilationErrors(DiagnosticBag diagnostics, DiagnosticFormatter formatter) { if (diagnostics.IsEmptyWithoutResolution) { return; } var filtered = diagnostics.AsEnumerable().Where(d => d.Severity == DiagnosticSeverity.Error).AsImmutable(); if (filtered.IsEmpty) { return; } throw new CompilationErrorException( formatter.Format(filtered[0], CultureInfo.CurrentCulture), filtered); } /// <summary> /// Builds a delegate that will execute just this scripts code. /// </summary> private Func<object[], Task<T>> Build<T>( Compilation compilation, DiagnosticBag diagnostics, bool emitDebugInformation, CancellationToken cancellationToken) { var entryPoint = compilation.GetEntryPoint(cancellationToken); using (var peStream = new MemoryStream()) using (var pdbStreamOpt = emitDebugInformation ? new MemoryStream() : null) { var emitResult = Emit(peStream, pdbStreamOpt, compilation, GetEmitOptions(emitDebugInformation), cancellationToken); diagnostics.AddRange(emitResult.Diagnostics); if (!emitResult.Success) { return null; } // let the loader know where to find assemblies: foreach (var referencedAssembly in compilation.GetBoundReferenceManager().GetReferencedAssemblies()) { var path = (referencedAssembly.Key as PortableExecutableReference)?.FilePath; if (path != null) { // TODO: Should the #r resolver return contract metadata and runtime assembly path - // Contract assembly used in the compiler, RT assembly path here. _assemblyLoader.RegisterDependency(referencedAssembly.Value.Identity, path); } } peStream.Position = 0; if (pdbStreamOpt != null) { pdbStreamOpt.Position = 0; } var assembly = _assemblyLoader.LoadAssemblyFromStream(peStream, pdbStreamOpt); var runtimeEntryPoint = GetEntryPointRuntimeMethod(entryPoint, assembly, cancellationToken); return runtimeEntryPoint.CreateDelegate<Func<object[], Task<T>>>(); } } // internal for testing internal static EmitOptions GetEmitOptions(bool emitDebugInformation) => emitDebugInformation ? s_EmitOptionsWithDebuggingInformation : EmitOptions.Default; // internal for testing internal static EmitResult Emit( Stream peStream, Stream pdbStreamOpt, Compilation compilation, EmitOptions options, CancellationToken cancellationToken) { return compilation.Emit( peStream: peStream, pdbStream: pdbStreamOpt, xmlDocumentationStream: null, win32Resources: null, manifestResources: null, options: options, cancellationToken: cancellationToken); } internal static MethodInfo GetEntryPointRuntimeMethod(IMethodSymbol entryPoint, Assembly assembly, CancellationToken cancellationToken) { string entryPointTypeName = MetadataHelpers.BuildQualifiedName(entryPoint.ContainingNamespace.MetadataName, entryPoint.ContainingType.MetadataName); string entryPointMethodName = entryPoint.MetadataName; var entryPointType = assembly.GetType(entryPointTypeName, throwOnError: true, ignoreCase: false).GetTypeInfo(); return entryPointType.GetDeclaredMethod(entryPointMethodName); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Tools/BuildBoss/ProjectEntry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { /// <summary> /// All of the project entry contained in a solution file. /// </summary> internal struct ProjectEntry { internal string RelativeFilePath { get; } internal string Name { get; } internal Guid ProjectGuid { get; } internal Guid TypeGuid { get; } internal bool IsFolder => TypeGuid == ProjectEntryUtil.FolderProjectType; internal ProjectFileType ProjectType => ProjectEntryUtil.GetProjectFileType(RelativeFilePath); internal ProjectEntry( string relativeFilePath, string name, Guid projectGuid, Guid typeGuid) { RelativeFilePath = relativeFilePath; Name = name; ProjectGuid = projectGuid; TypeGuid = typeGuid; } public override string ToString() => Name; } internal static class ProjectEntryUtil { internal static readonly Guid FolderProjectType = new Guid("2150E333-8FDC-42A3-9474-1A3956D46DE8"); internal static readonly Guid VsixProjectType = new Guid("82B43B9B-A64C-4715-B499-D71E9CA2BD60"); internal static readonly Guid SharedProject = new Guid("D954291E-2A0B-460D-934E-DC6B0785DB48"); internal static readonly Guid ManagedProjectSystemCSharp = new Guid("9A19103F-16F7-4668-BE54-9A1E7A4F7556"); internal static readonly Guid ManagedProjectSystemVisualBasic = new Guid("778DAE3C-4631-46EA-AA77-85C1314464D9"); internal static ProjectFileType GetProjectFileType(string path) { switch (Path.GetExtension(path)) { case ".csproj": return ProjectFileType.CSharp; case ".vbproj": return ProjectFileType.Basic; case ".shproj": return ProjectFileType.Shared; case ".proj": return ProjectFileType.Tool; default: return ProjectFileType.Unknown; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { /// <summary> /// All of the project entry contained in a solution file. /// </summary> internal struct ProjectEntry { internal string RelativeFilePath { get; } internal string Name { get; } internal Guid ProjectGuid { get; } internal Guid TypeGuid { get; } internal bool IsFolder => TypeGuid == ProjectEntryUtil.FolderProjectType; internal ProjectFileType ProjectType => ProjectEntryUtil.GetProjectFileType(RelativeFilePath); internal ProjectEntry( string relativeFilePath, string name, Guid projectGuid, Guid typeGuid) { RelativeFilePath = relativeFilePath; Name = name; ProjectGuid = projectGuid; TypeGuid = typeGuid; } public override string ToString() => Name; } internal static class ProjectEntryUtil { internal static readonly Guid FolderProjectType = new Guid("2150E333-8FDC-42A3-9474-1A3956D46DE8"); internal static readonly Guid VsixProjectType = new Guid("82B43B9B-A64C-4715-B499-D71E9CA2BD60"); internal static readonly Guid SharedProject = new Guid("D954291E-2A0B-460D-934E-DC6B0785DB48"); internal static readonly Guid ManagedProjectSystemCSharp = new Guid("9A19103F-16F7-4668-BE54-9A1E7A4F7556"); internal static readonly Guid ManagedProjectSystemVisualBasic = new Guid("778DAE3C-4631-46EA-AA77-85C1314464D9"); internal static ProjectFileType GetProjectFileType(string path) { switch (Path.GetExtension(path)) { case ".csproj": return ProjectFileType.CSharp; case ".vbproj": return ProjectFileType.Basic; case ".shproj": return ProjectFileType.Shared; case ".proj": return ProjectFileType.Tool; default: return ProjectFileType.Unknown; } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/MSBuildTest/Resources/SourceFiles/CSharp/CSharpExternAlias.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. extern alias Sys1; extern alias Sys2; class Program { static Sys1.System.Uri f1 = null; static Sys2::System.Uri f2; static void Main() { f2 = f1; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. extern alias Sys1; extern alias Sys2; class Program { static Sys1.System.Uri f1 = null; static Sys2::System.Uri f2; static void Main() { f2 = f1; } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/TestUtilities/QuickInfo/ToolTipAssert.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo; using Microsoft.VisualStudio.Core.Imaging; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities.QuickInfo { public static class ToolTipAssert { public static void EqualContent(object expected, object actual) { try { Assert.IsType(expected.GetType(), actual); if (expected is ContainerElement containerElement) { EqualContainerElement(containerElement, (ContainerElement)actual); return; } if (expected is ImageElement imageElement) { EqualImageElement(imageElement, (ImageElement)actual); return; } if (expected is ClassifiedTextElement classifiedTextElement) { EqualClassifiedTextElement(classifiedTextElement, (ClassifiedTextElement)actual); return; } if (expected is ClassifiedTextRun classifiedTextRun) { EqualClassifiedTextRun(classifiedTextRun, (ClassifiedTextRun)actual); return; } throw ExceptionUtilities.Unreachable; } catch (Exception) { var renderedExpected = ContainerToString(expected); var renderedActual = ContainerToString(actual); AssertEx.EqualOrDiff(renderedExpected, renderedActual); // This is not expected to be hit, but it will be hit if the difference cannot be detected within the diff throw; } } private static void EqualContainerElement(ContainerElement expected, ContainerElement actual) { Assert.Equal(expected.Style, actual.Style); Assert.Equal(expected.Elements.Count(), actual.Elements.Count()); foreach (var (expectedElement, actualElement) in expected.Elements.Zip(actual.Elements, (expectedElement, actualElement) => (expectedElement, actualElement))) { EqualContent(expectedElement, actualElement); } } private static void EqualImageElement(ImageElement expected, ImageElement actual) { Assert.Equal(expected.ImageId.Guid, actual.ImageId.Guid); Assert.Equal(expected.ImageId.Id, actual.ImageId.Id); Assert.Equal(expected.AutomationName, actual.AutomationName); } private static void EqualClassifiedTextElement(ClassifiedTextElement expected, ClassifiedTextElement actual) { Assert.Equal(expected.Runs.Count(), actual.Runs.Count()); foreach (var (expectedRun, actualRun) in expected.Runs.Zip(actual.Runs, (expectedRun, actualRun) => (expectedRun, actualRun))) { EqualClassifiedTextRun(expectedRun, actualRun); } } private static void EqualClassifiedTextRun(ClassifiedTextRun expected, ClassifiedTextRun actual) { Assert.Equal(expected.ClassificationTypeName, actual.ClassificationTypeName); Assert.Equal(expected.Text, actual.Text); Assert.Equal(expected.Tooltip, actual.Tooltip); Assert.Equal(expected.Style, actual.Style); if (expected.NavigationAction is null) { Assert.Equal(expected.NavigationAction, actual.NavigationAction); } else if (expected.NavigationAction.Target is QuickInfoHyperLink hyperLink) { Assert.Same(expected.NavigationAction, hyperLink.NavigationAction); var actualTarget = Assert.IsType<QuickInfoHyperLink>(actual.NavigationAction.Target); Assert.Same(actual.NavigationAction, actualTarget.NavigationAction); Assert.Equal(hyperLink, actualTarget); } else { // Cannot validate this navigation action Assert.NotNull(actual.NavigationAction); Assert.IsNotType<QuickInfoHyperLink>(actual.NavigationAction.Target); } } private static string ContainerToString(object element) { var result = new StringBuilder(); ContainerToString(element, "", result); return result.ToString(); } private static void ContainerToString(object element, string indent, StringBuilder result) { result.Append($"{indent}New {element.GetType().Name}("); if (element is ContainerElement container) { result.AppendLine(); indent += " "; result.AppendLine($"{indent}{ContainerStyleToString(container.Style)},"); var elements = container.Elements.ToArray(); for (var i = 0; i < elements.Length; i++) { ContainerToString(elements[i], indent, result); if (i < elements.Length - 1) result.AppendLine(","); else result.Append(")"); } return; } if (element is ImageElement image) { var guid = GetKnownImageGuid(image.ImageId.Guid); var id = GetKnownImageId(image.ImageId.Id); result.Append($"New {nameof(ImageId)}({guid}, {id}))"); return; } if (element is ClassifiedTextElement classifiedTextElement) { result.AppendLine(); indent += " "; var runs = classifiedTextElement.Runs.ToArray(); for (var i = 0; i < runs.Length; i++) { ContainerToString(runs[i], indent, result); if (i < runs.Length - 1) result.AppendLine(","); else result.Append(")"); } return; } if (element is ClassifiedTextRun classifiedTextRun) { var classification = GetKnownClassification(classifiedTextRun.ClassificationTypeName); result.Append($"{classification}, \"{classifiedTextRun.Text.Replace("\"", "\"\"")}\""); if (classifiedTextRun.NavigationAction is object || !string.IsNullOrEmpty(classifiedTextRun.Tooltip)) { var tooltip = classifiedTextRun.Tooltip is object ? $"\"{classifiedTextRun.Tooltip.Replace("\"", "\"\"")}\"" : "Nothing"; if (classifiedTextRun.NavigationAction?.Target is QuickInfoHyperLink hyperLink) { result.Append($", QuickInfoHyperLink.TestAccessor.CreateNavigationAction(new Uri(\"{hyperLink.Uri}\", UriKind.Absolute))"); } else { result.Append(", navigationAction:=Sub() Return"); } result.Append($", {tooltip}"); } if (classifiedTextRun.Style != ClassifiedTextRunStyle.Plain) { result.Append($", {TextRunStyleToString(classifiedTextRun.Style)}"); } result.Append(")"); return; } throw ExceptionUtilities.Unreachable; } private static string ContainerStyleToString(ContainerElementStyle style) { var stringValue = style.ToString(); return string.Join(" Or ", stringValue.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(value => $"{nameof(ContainerElementStyle)}.{value}")); } private static string TextRunStyleToString(ClassifiedTextRunStyle style) { var stringValue = style.ToString(); return string.Join(" Or ", stringValue.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(value => $"{nameof(ClassifiedTextRunStyle)}.{value}")); } private static string GetKnownClassification(string classification) { foreach (var field in typeof(ClassificationTypeNames).GetFields()) { if (!field.IsStatic) continue; var value = field.GetValue(null) as string; if (value == classification) return $"{nameof(ClassificationTypeNames)}.{field.Name}"; } return $"\"{classification}\""; } private static string GetKnownImageGuid(Guid guid) { foreach (var field in typeof(KnownImageIds).GetFields()) { if (!field.IsStatic) continue; var value = field.GetValue(null) as Guid?; if (value == guid) return $"{nameof(KnownImageIds)}.{field.Name}"; } return guid.ToString(); } private static string GetKnownImageId(int id) { foreach (var field in typeof(KnownImageIds).GetFields()) { if (!field.IsStatic) continue; var value = field.GetValue(null) as int?; if (value == id) return $"{nameof(KnownImageIds)}.{field.Name}"; } return id.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo; using Microsoft.VisualStudio.Core.Imaging; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities.QuickInfo { public static class ToolTipAssert { public static void EqualContent(object expected, object actual) { try { Assert.IsType(expected.GetType(), actual); if (expected is ContainerElement containerElement) { EqualContainerElement(containerElement, (ContainerElement)actual); return; } if (expected is ImageElement imageElement) { EqualImageElement(imageElement, (ImageElement)actual); return; } if (expected is ClassifiedTextElement classifiedTextElement) { EqualClassifiedTextElement(classifiedTextElement, (ClassifiedTextElement)actual); return; } if (expected is ClassifiedTextRun classifiedTextRun) { EqualClassifiedTextRun(classifiedTextRun, (ClassifiedTextRun)actual); return; } throw ExceptionUtilities.Unreachable; } catch (Exception) { var renderedExpected = ContainerToString(expected); var renderedActual = ContainerToString(actual); AssertEx.EqualOrDiff(renderedExpected, renderedActual); // This is not expected to be hit, but it will be hit if the difference cannot be detected within the diff throw; } } private static void EqualContainerElement(ContainerElement expected, ContainerElement actual) { Assert.Equal(expected.Style, actual.Style); Assert.Equal(expected.Elements.Count(), actual.Elements.Count()); foreach (var (expectedElement, actualElement) in expected.Elements.Zip(actual.Elements, (expectedElement, actualElement) => (expectedElement, actualElement))) { EqualContent(expectedElement, actualElement); } } private static void EqualImageElement(ImageElement expected, ImageElement actual) { Assert.Equal(expected.ImageId.Guid, actual.ImageId.Guid); Assert.Equal(expected.ImageId.Id, actual.ImageId.Id); Assert.Equal(expected.AutomationName, actual.AutomationName); } private static void EqualClassifiedTextElement(ClassifiedTextElement expected, ClassifiedTextElement actual) { Assert.Equal(expected.Runs.Count(), actual.Runs.Count()); foreach (var (expectedRun, actualRun) in expected.Runs.Zip(actual.Runs, (expectedRun, actualRun) => (expectedRun, actualRun))) { EqualClassifiedTextRun(expectedRun, actualRun); } } private static void EqualClassifiedTextRun(ClassifiedTextRun expected, ClassifiedTextRun actual) { Assert.Equal(expected.ClassificationTypeName, actual.ClassificationTypeName); Assert.Equal(expected.Text, actual.Text); Assert.Equal(expected.Tooltip, actual.Tooltip); Assert.Equal(expected.Style, actual.Style); if (expected.NavigationAction is null) { Assert.Equal(expected.NavigationAction, actual.NavigationAction); } else if (expected.NavigationAction.Target is QuickInfoHyperLink hyperLink) { Assert.Same(expected.NavigationAction, hyperLink.NavigationAction); var actualTarget = Assert.IsType<QuickInfoHyperLink>(actual.NavigationAction.Target); Assert.Same(actual.NavigationAction, actualTarget.NavigationAction); Assert.Equal(hyperLink, actualTarget); } else { // Cannot validate this navigation action Assert.NotNull(actual.NavigationAction); Assert.IsNotType<QuickInfoHyperLink>(actual.NavigationAction.Target); } } private static string ContainerToString(object element) { var result = new StringBuilder(); ContainerToString(element, "", result); return result.ToString(); } private static void ContainerToString(object element, string indent, StringBuilder result) { result.Append($"{indent}New {element.GetType().Name}("); if (element is ContainerElement container) { result.AppendLine(); indent += " "; result.AppendLine($"{indent}{ContainerStyleToString(container.Style)},"); var elements = container.Elements.ToArray(); for (var i = 0; i < elements.Length; i++) { ContainerToString(elements[i], indent, result); if (i < elements.Length - 1) result.AppendLine(","); else result.Append(")"); } return; } if (element is ImageElement image) { var guid = GetKnownImageGuid(image.ImageId.Guid); var id = GetKnownImageId(image.ImageId.Id); result.Append($"New {nameof(ImageId)}({guid}, {id}))"); return; } if (element is ClassifiedTextElement classifiedTextElement) { result.AppendLine(); indent += " "; var runs = classifiedTextElement.Runs.ToArray(); for (var i = 0; i < runs.Length; i++) { ContainerToString(runs[i], indent, result); if (i < runs.Length - 1) result.AppendLine(","); else result.Append(")"); } return; } if (element is ClassifiedTextRun classifiedTextRun) { var classification = GetKnownClassification(classifiedTextRun.ClassificationTypeName); result.Append($"{classification}, \"{classifiedTextRun.Text.Replace("\"", "\"\"")}\""); if (classifiedTextRun.NavigationAction is object || !string.IsNullOrEmpty(classifiedTextRun.Tooltip)) { var tooltip = classifiedTextRun.Tooltip is object ? $"\"{classifiedTextRun.Tooltip.Replace("\"", "\"\"")}\"" : "Nothing"; if (classifiedTextRun.NavigationAction?.Target is QuickInfoHyperLink hyperLink) { result.Append($", QuickInfoHyperLink.TestAccessor.CreateNavigationAction(new Uri(\"{hyperLink.Uri}\", UriKind.Absolute))"); } else { result.Append(", navigationAction:=Sub() Return"); } result.Append($", {tooltip}"); } if (classifiedTextRun.Style != ClassifiedTextRunStyle.Plain) { result.Append($", {TextRunStyleToString(classifiedTextRun.Style)}"); } result.Append(")"); return; } throw ExceptionUtilities.Unreachable; } private static string ContainerStyleToString(ContainerElementStyle style) { var stringValue = style.ToString(); return string.Join(" Or ", stringValue.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(value => $"{nameof(ContainerElementStyle)}.{value}")); } private static string TextRunStyleToString(ClassifiedTextRunStyle style) { var stringValue = style.ToString(); return string.Join(" Or ", stringValue.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(value => $"{nameof(ClassifiedTextRunStyle)}.{value}")); } private static string GetKnownClassification(string classification) { foreach (var field in typeof(ClassificationTypeNames).GetFields()) { if (!field.IsStatic) continue; var value = field.GetValue(null) as string; if (value == classification) return $"{nameof(ClassificationTypeNames)}.{field.Name}"; } return $"\"{classification}\""; } private static string GetKnownImageGuid(Guid guid) { foreach (var field in typeof(KnownImageIds).GetFields()) { if (!field.IsStatic) continue; var value = field.GetValue(null) as Guid?; if (value == guid) return $"{nameof(KnownImageIds)}.{field.Name}"; } return guid.ToString(); } private static string GetKnownImageId(int id) { foreach (var field in typeof(KnownImageIds).GetFields()) { if (!field.IsStatic) continue; var value = field.GetValue(null) as int?; if (value == id) return $"{nameof(KnownImageIds)}.{field.Name}"; } return id.ToString(); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/Workspace/Host/Mef/ExportWorkspaceServiceAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// Use this attribute to declare a <see cref="IWorkspaceService"/> implementation for inclusion in a MEF-based workspace. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public class ExportWorkspaceServiceAttribute : ExportAttribute { /// <summary> /// The assembly qualified name of the service's type. /// </summary> public string ServiceType { get; } /// <summary> /// The layer that the service is specified for; ServiceLayer.Default, etc. /// </summary> public string Layer { get; } /// <summary> /// Declares a <see cref="IWorkspaceService"/> implementation for inclusion in a MEF-based workspace. /// </summary> /// <param name="serviceType">The type that will be used to retrieve the service from a <see cref="HostWorkspaceServices"/>.</param> /// <param name="layer">The layer that the service is specified for; <see cref="ServiceLayer.Default" />, etc.</param> public ExportWorkspaceServiceAttribute(Type serviceType, string layer = ServiceLayer.Default) : base(typeof(IWorkspaceService)) { if (serviceType == null) { throw new ArgumentNullException(nameof(serviceType)); } this.ServiceType = serviceType.AssemblyQualifiedName; this.Layer = layer ?? throw new ArgumentNullException(nameof(layer)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// Use this attribute to declare a <see cref="IWorkspaceService"/> implementation for inclusion in a MEF-based workspace. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public class ExportWorkspaceServiceAttribute : ExportAttribute { /// <summary> /// The assembly qualified name of the service's type. /// </summary> public string ServiceType { get; } /// <summary> /// The layer that the service is specified for; ServiceLayer.Default, etc. /// </summary> public string Layer { get; } /// <summary> /// Declares a <see cref="IWorkspaceService"/> implementation for inclusion in a MEF-based workspace. /// </summary> /// <param name="serviceType">The type that will be used to retrieve the service from a <see cref="HostWorkspaceServices"/>.</param> /// <param name="layer">The layer that the service is specified for; <see cref="ServiceLayer.Default" />, etc.</param> public ExportWorkspaceServiceAttribute(Type serviceType, string layer = ServiceLayer.Default) : base(typeof(IWorkspaceService)) { if (serviceType == null) { throw new ArgumentNullException(nameof(serviceType)); } this.ServiceType = serviceType.AssemblyQualifiedName; this.Layer = layer ?? throw new ArgumentNullException(nameof(layer)); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Portable/Binder/WithClassTypeParametersBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A binder that places class/interface/struct/delegate type parameters in scope /// </summary> internal sealed class WithClassTypeParametersBinder : WithTypeParametersBinder { private readonly NamedTypeSymbol _namedType; private MultiDictionary<string, TypeParameterSymbol> _lazyTypeParameterMap; internal WithClassTypeParametersBinder(NamedTypeSymbol container, Binder next) : base(next) { Debug.Assert((object)container != null); _namedType = container; } internal override bool IsAccessibleHelper(Symbol symbol, TypeSymbol accessThroughType, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConsList<TypeSymbol> basesBeingResolved) { return this.IsSymbolAccessibleConditional(symbol, _namedType, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved); } protected override MultiDictionary<string, TypeParameterSymbol> TypeParameterMap { get { if (_lazyTypeParameterMap == null) { var result = new MultiDictionary<string, TypeParameterSymbol>(); foreach (TypeParameterSymbol tps in _namedType.TypeParameters) { result.Add(tps.Name, tps); } Interlocked.CompareExchange(ref _lazyTypeParameterMap, result, null); } return _lazyTypeParameterMap; } } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { if (CanConsiderTypeParameters(options)) { foreach (var parameter in _namedType.TypeParameters) { if (originalBinder.CanAddLookupSymbolInfo(parameter, options, result, null)) { result.AddSymbol(parameter, parameter.Name, 0); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A binder that places class/interface/struct/delegate type parameters in scope /// </summary> internal sealed class WithClassTypeParametersBinder : WithTypeParametersBinder { private readonly NamedTypeSymbol _namedType; private MultiDictionary<string, TypeParameterSymbol> _lazyTypeParameterMap; internal WithClassTypeParametersBinder(NamedTypeSymbol container, Binder next) : base(next) { Debug.Assert((object)container != null); _namedType = container; } internal override bool IsAccessibleHelper(Symbol symbol, TypeSymbol accessThroughType, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConsList<TypeSymbol> basesBeingResolved) { return this.IsSymbolAccessibleConditional(symbol, _namedType, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved); } protected override MultiDictionary<string, TypeParameterSymbol> TypeParameterMap { get { if (_lazyTypeParameterMap == null) { var result = new MultiDictionary<string, TypeParameterSymbol>(); foreach (TypeParameterSymbol tps in _namedType.TypeParameters) { result.Add(tps.Name, tps); } Interlocked.CompareExchange(ref _lazyTypeParameterMap, result, null); } return _lazyTypeParameterMap; } } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { if (CanConsiderTypeParameters(options)) { foreach (var parameter in _namedType.TypeParameters) { if (originalBinder.CanAddLookupSymbolInfo(parameter, options, result, null)) { result.AddSymbol(parameter, parameter.Name, 0); } } } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/ProjectTelemetry/ProjectTelemetryData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Serialization; namespace Microsoft.CodeAnalysis.ProjectTelemetry { /// <summary> /// Serialization typed used to pass information to/from OOP and VS. /// </summary> [DataContract] internal readonly struct ProjectTelemetryData { [DataMember(Order = 0)] public readonly ProjectId ProjectId; [DataMember(Order = 1)] public readonly string Language; [DataMember(Order = 2)] public readonly int AnalyzerReferencesCount; [DataMember(Order = 3)] public readonly int ProjectReferencesCount; [DataMember(Order = 4)] public readonly int MetadataReferencesCount; [DataMember(Order = 5)] public readonly int DocumentsCount; [DataMember(Order = 6)] public readonly int AdditionalDocumentsCount; public ProjectTelemetryData(ProjectId projectId, string language, int analyzerReferencesCount, int projectReferencesCount, int metadataReferencesCount, int documentsCount, int additionalDocumentsCount) { ProjectId = projectId; Language = language; AnalyzerReferencesCount = analyzerReferencesCount; ProjectReferencesCount = projectReferencesCount; MetadataReferencesCount = metadataReferencesCount; DocumentsCount = documentsCount; AdditionalDocumentsCount = additionalDocumentsCount; } public bool Equals(ProjectTelemetryData other) => Language.Equals(other.Language) && AnalyzerReferencesCount == other.AnalyzerReferencesCount && ProjectReferencesCount == other.ProjectReferencesCount && MetadataReferencesCount == other.MetadataReferencesCount && DocumentsCount == other.DocumentsCount && AdditionalDocumentsCount == other.AdditionalDocumentsCount; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Serialization; namespace Microsoft.CodeAnalysis.ProjectTelemetry { /// <summary> /// Serialization typed used to pass information to/from OOP and VS. /// </summary> [DataContract] internal readonly struct ProjectTelemetryData { [DataMember(Order = 0)] public readonly ProjectId ProjectId; [DataMember(Order = 1)] public readonly string Language; [DataMember(Order = 2)] public readonly int AnalyzerReferencesCount; [DataMember(Order = 3)] public readonly int ProjectReferencesCount; [DataMember(Order = 4)] public readonly int MetadataReferencesCount; [DataMember(Order = 5)] public readonly int DocumentsCount; [DataMember(Order = 6)] public readonly int AdditionalDocumentsCount; public ProjectTelemetryData(ProjectId projectId, string language, int analyzerReferencesCount, int projectReferencesCount, int metadataReferencesCount, int documentsCount, int additionalDocumentsCount) { ProjectId = projectId; Language = language; AnalyzerReferencesCount = analyzerReferencesCount; ProjectReferencesCount = projectReferencesCount; MetadataReferencesCount = metadataReferencesCount; DocumentsCount = documentsCount; AdditionalDocumentsCount = additionalDocumentsCount; } public bool Equals(ProjectTelemetryData other) => Language.Equals(other.Language) && AnalyzerReferencesCount == other.AnalyzerReferencesCount && ProjectReferencesCount == other.ProjectReferencesCount && MetadataReferencesCount == other.MetadataReferencesCount && DocumentsCount == other.DocumentsCount && AdditionalDocumentsCount == other.AdditionalDocumentsCount; } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/StackExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class StackExtensions { public static void Push<T>(this Stack<T> stack, IEnumerable<T> values) { foreach (var v in values) stack.Push(v); } public static void Push<T>(this Stack<T> stack, HashSet<T> values) { foreach (var v in values) stack.Push(v); } public static void Push<T>(this Stack<T> stack, ImmutableArray<T> values) { foreach (var v in values) stack.Push(v); } internal static void PushReverse<T, U>(this Stack<T> stack, IList<U> range) where U : T { Contract.ThrowIfNull(stack); Contract.ThrowIfNull(range); for (var i = range.Count - 1; i >= 0; i--) { stack.Push(range[i]); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class StackExtensions { public static void Push<T>(this Stack<T> stack, IEnumerable<T> values) { foreach (var v in values) stack.Push(v); } public static void Push<T>(this Stack<T> stack, HashSet<T> values) { foreach (var v in values) stack.Push(v); } public static void Push<T>(this Stack<T> stack, ImmutableArray<T> values) { foreach (var v in values) stack.Push(v); } internal static void PushReverse<T, U>(this Stack<T> stack, IList<U> range) where U : T { Contract.ThrowIfNull(stack); Contract.ThrowIfNull(range); for (var i = range.Count - 1; i >= 0; i--) { stack.Push(range[i]); } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/Remote/IRemoteHostClientProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Returns a <see cref="RemoteHostClient"/> that a user can use to communicate with a remote host (i.e. ServiceHub) /// </summary> internal interface IRemoteHostClientProvider : IWorkspaceService { /// <summary> /// Get <see cref="RemoteHostClient"/> to current RemoteHost /// </summary> Task<RemoteHostClient?> TryGetRemoteHostClientAsync(CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Returns a <see cref="RemoteHostClient"/> that a user can use to communicate with a remote host (i.e. ServiceHub) /// </summary> internal interface IRemoteHostClientProvider : IWorkspaceService { /// <summary> /// Get <see cref="RemoteHostClient"/> to current RemoteHost /// </summary> Task<RemoteHostClient?> TryGetRemoteHostClientAsync(CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractExtensionMethodImportCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractExtensionMethodImportCompletionProvider : AbstractImportCompletionProvider { private bool? _isTargetTypeCompletionFilterExperimentEnabled = null; protected abstract string GenericSuffix { get; } protected override bool ShouldProvideCompletion(CompletionContext completionContext, SyntaxContext syntaxContext) => syntaxContext.IsRightOfNameSeparator && IsAddingImportsSupported(completionContext.Document); protected override void LogCommit() => CompletionProvidersLogger.LogCommitOfExtensionMethodImportCompletionItem(); protected override async Task AddCompletionItemsAsync( CompletionContext completionContext, SyntaxContext syntaxContext, HashSet<string> namespaceInScope, bool isExpandedCompletion, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Completion_ExtensionMethodImportCompletionProvider_GetCompletionItemsAsync, cancellationToken)) { var syntaxFacts = completionContext.Document.GetRequiredLanguageService<ISyntaxFactsService>(); if (TryGetReceiverTypeSymbol(syntaxContext, syntaxFacts, cancellationToken, out var receiverTypeSymbol)) { using var nestedTokenSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(nestedTokenSource.Token, cancellationToken); var inferredTypes = IsTargetTypeCompletionFilterExperimentEnabled(completionContext.Document.Project.Solution.Workspace) ? syntaxContext.InferredTypes : ImmutableArray<ITypeSymbol>.Empty; var getItemsTask = Task.Run(() => ExtensionMethodImportCompletionHelper.GetUnimportedExtensionMethodsAsync( completionContext.Document, completionContext.Position, receiverTypeSymbol, namespaceInScope, inferredTypes, forceIndexCreation: isExpandedCompletion, linkedTokenSource.Token)); var timeoutInMilliseconds = completionContext.Options.GetOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion); // Timebox is enabled if timeout value is >= 0 and we are not triggered via expander if (timeoutInMilliseconds >= 0 && !isExpandedCompletion) { // timeout == 0 means immediate timeout (for testing purpose) if (timeoutInMilliseconds == 0 || await Task.WhenAny(getItemsTask, Task.Delay(timeoutInMilliseconds, linkedTokenSource.Token)).ConfigureAwait(false) != getItemsTask) { nestedTokenSource.Cancel(); CompletionProvidersLogger.LogExtensionMethodCompletionTimeoutCount(); return; } } // Either the timebox is not enabled, so we need to wait until the operation for complete, // or there's no timeout, and we now have all completion items ready. var items = await getItemsTask.ConfigureAwait(false); var receiverTypeKey = SymbolKey.CreateString(receiverTypeSymbol, cancellationToken); completionContext.AddItems(items.Select(i => Convert(i, receiverTypeKey))); } else { // If we can't get a valid receiver type, then we don't show expander as available. // We need to set this explicitly here because we didn't do the (more expensive) symbol check inside // `ShouldProvideCompletion` method above, which is intended for quick syntax based check. completionContext.ExpandItemsAvailable = false; } } } private bool IsTargetTypeCompletionFilterExperimentEnabled(Workspace workspace) { if (!_isTargetTypeCompletionFilterExperimentEnabled.HasValue) { var experimentationService = workspace.Services.GetRequiredService<IExperimentationService>(); _isTargetTypeCompletionFilterExperimentEnabled = experimentationService.IsExperimentEnabled(WellKnownExperimentNames.TargetTypedCompletionFilter); } return _isTargetTypeCompletionFilterExperimentEnabled == true; } private static bool TryGetReceiverTypeSymbol( SyntaxContext syntaxContext, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken, [NotNullWhen(true)] out ITypeSymbol? receiverTypeSymbol) { var parentNode = syntaxContext.TargetToken.Parent; // Even though implicit access to extension method is allowed, we decide not support it for simplicity // e.g. we will not provide completion for unimported extension method in this case // New Bar() {.X = .$$ } var expressionNode = syntaxFacts.GetLeftSideOfDot(parentNode, allowImplicitTarget: false); if (expressionNode != null) { // Check if we are accessing members of a type, no extension methods are exposed off of types. if (syntaxContext.SemanticModel.GetSymbolInfo(expressionNode, cancellationToken).GetAnySymbol() is not ITypeSymbol) { // The expression we're calling off of needs to have an actual instance type. // We try to be more tolerant to errors here so completion would still be available in certain case of partially typed code. receiverTypeSymbol = syntaxContext.SemanticModel.GetTypeInfo(expressionNode, cancellationToken).Type; if (receiverTypeSymbol is IErrorTypeSymbol errorTypeSymbol) { receiverTypeSymbol = errorTypeSymbol.CandidateSymbols.Select(s => GetSymbolType(s)).FirstOrDefault(s => s != null); } return receiverTypeSymbol != null; } } receiverTypeSymbol = null; return false; } private static ITypeSymbol? GetSymbolType(ISymbol symbol) => symbol switch { ILocalSymbol localSymbol => localSymbol.Type, IFieldSymbol fieldSymbol => fieldSymbol.Type, IPropertySymbol propertySymbol => propertySymbol.Type, IParameterSymbol parameterSymbol => parameterSymbol.Type, IAliasSymbol aliasSymbol => aliasSymbol.Target as ITypeSymbol, _ => symbol as ITypeSymbol, }; private CompletionItem Convert(SerializableImportCompletionItem serializableItem, string receiverTypeSymbolKey) => ImportCompletionItem.Create( serializableItem.Name, serializableItem.Arity, serializableItem.ContainingNamespace, serializableItem.Glyph, GenericSuffix, CompletionItemFlags.Expanded, (serializableItem.SymbolKeyData, receiverTypeSymbolKey, serializableItem.AdditionalOverloadCount), serializableItem.IncludedInTargetTypeCompletion); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractExtensionMethodImportCompletionProvider : AbstractImportCompletionProvider { private bool? _isTargetTypeCompletionFilterExperimentEnabled = null; protected abstract string GenericSuffix { get; } protected override bool ShouldProvideCompletion(CompletionContext completionContext, SyntaxContext syntaxContext) => syntaxContext.IsRightOfNameSeparator && IsAddingImportsSupported(completionContext.Document); protected override void LogCommit() => CompletionProvidersLogger.LogCommitOfExtensionMethodImportCompletionItem(); protected override async Task AddCompletionItemsAsync( CompletionContext completionContext, SyntaxContext syntaxContext, HashSet<string> namespaceInScope, bool isExpandedCompletion, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Completion_ExtensionMethodImportCompletionProvider_GetCompletionItemsAsync, cancellationToken)) { var syntaxFacts = completionContext.Document.GetRequiredLanguageService<ISyntaxFactsService>(); if (TryGetReceiverTypeSymbol(syntaxContext, syntaxFacts, cancellationToken, out var receiverTypeSymbol)) { using var nestedTokenSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(nestedTokenSource.Token, cancellationToken); var inferredTypes = IsTargetTypeCompletionFilterExperimentEnabled(completionContext.Document.Project.Solution.Workspace) ? syntaxContext.InferredTypes : ImmutableArray<ITypeSymbol>.Empty; var getItemsTask = Task.Run(() => ExtensionMethodImportCompletionHelper.GetUnimportedExtensionMethodsAsync( completionContext.Document, completionContext.Position, receiverTypeSymbol, namespaceInScope, inferredTypes, forceIndexCreation: isExpandedCompletion, linkedTokenSource.Token)); var timeoutInMilliseconds = completionContext.Options.GetOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion); // Timebox is enabled if timeout value is >= 0 and we are not triggered via expander if (timeoutInMilliseconds >= 0 && !isExpandedCompletion) { // timeout == 0 means immediate timeout (for testing purpose) if (timeoutInMilliseconds == 0 || await Task.WhenAny(getItemsTask, Task.Delay(timeoutInMilliseconds, linkedTokenSource.Token)).ConfigureAwait(false) != getItemsTask) { nestedTokenSource.Cancel(); CompletionProvidersLogger.LogExtensionMethodCompletionTimeoutCount(); return; } } // Either the timebox is not enabled, so we need to wait until the operation for complete, // or there's no timeout, and we now have all completion items ready. var items = await getItemsTask.ConfigureAwait(false); var receiverTypeKey = SymbolKey.CreateString(receiverTypeSymbol, cancellationToken); completionContext.AddItems(items.Select(i => Convert(i, receiverTypeKey))); } else { // If we can't get a valid receiver type, then we don't show expander as available. // We need to set this explicitly here because we didn't do the (more expensive) symbol check inside // `ShouldProvideCompletion` method above, which is intended for quick syntax based check. completionContext.ExpandItemsAvailable = false; } } } private bool IsTargetTypeCompletionFilterExperimentEnabled(Workspace workspace) { if (!_isTargetTypeCompletionFilterExperimentEnabled.HasValue) { var experimentationService = workspace.Services.GetRequiredService<IExperimentationService>(); _isTargetTypeCompletionFilterExperimentEnabled = experimentationService.IsExperimentEnabled(WellKnownExperimentNames.TargetTypedCompletionFilter); } return _isTargetTypeCompletionFilterExperimentEnabled == true; } private static bool TryGetReceiverTypeSymbol( SyntaxContext syntaxContext, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken, [NotNullWhen(true)] out ITypeSymbol? receiverTypeSymbol) { var parentNode = syntaxContext.TargetToken.Parent; // Even though implicit access to extension method is allowed, we decide not support it for simplicity // e.g. we will not provide completion for unimported extension method in this case // New Bar() {.X = .$$ } var expressionNode = syntaxFacts.GetLeftSideOfDot(parentNode, allowImplicitTarget: false); if (expressionNode != null) { // Check if we are accessing members of a type, no extension methods are exposed off of types. if (syntaxContext.SemanticModel.GetSymbolInfo(expressionNode, cancellationToken).GetAnySymbol() is not ITypeSymbol) { // The expression we're calling off of needs to have an actual instance type. // We try to be more tolerant to errors here so completion would still be available in certain case of partially typed code. receiverTypeSymbol = syntaxContext.SemanticModel.GetTypeInfo(expressionNode, cancellationToken).Type; if (receiverTypeSymbol is IErrorTypeSymbol errorTypeSymbol) { receiverTypeSymbol = errorTypeSymbol.CandidateSymbols.Select(s => GetSymbolType(s)).FirstOrDefault(s => s != null); } return receiverTypeSymbol != null; } } receiverTypeSymbol = null; return false; } private static ITypeSymbol? GetSymbolType(ISymbol symbol) => symbol switch { ILocalSymbol localSymbol => localSymbol.Type, IFieldSymbol fieldSymbol => fieldSymbol.Type, IPropertySymbol propertySymbol => propertySymbol.Type, IParameterSymbol parameterSymbol => parameterSymbol.Type, IAliasSymbol aliasSymbol => aliasSymbol.Target as ITypeSymbol, _ => symbol as ITypeSymbol, }; private CompletionItem Convert(SerializableImportCompletionItem serializableItem, string receiverTypeSymbolKey) => ImportCompletionItem.Create( serializableItem.Name, serializableItem.Arity, serializableItem.ContainingNamespace, serializableItem.Glyph, GenericSuffix, CompletionItemFlags.Expanded, (serializableItem.SymbolKeyData, receiverTypeSymbolKey, serializableItem.AdditionalOverloadCount), serializableItem.IncludedInTargetTypeCompletion); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/LanguageServer/Protocol/Handler/RequestExecutionQueue.RequestMetrics.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { internal partial class RequestExecutionQueue { internal class RequestMetrics { private readonly string _methodName; private readonly SharedStopwatch _sharedStopWatch; private TimeSpan? _queuedDuration; private readonly RequestTelemetryLogger _requestTelemetryLogger; public RequestMetrics(string methodName, RequestTelemetryLogger requestTelemetryLogger) { _methodName = methodName; _requestTelemetryLogger = requestTelemetryLogger; _sharedStopWatch = SharedStopwatch.StartNew(); } public void RecordExecutionStart() { // Request has de-queued and is starting execution. Record the time it spent in queue. _queuedDuration = _sharedStopWatch.Elapsed; } public void RecordSuccess() { RecordCompletion(RequestTelemetryLogger.Result.Succeeded); } public void RecordFailure() { RecordCompletion(RequestTelemetryLogger.Result.Failed); } public void RecordCancellation() { RecordCompletion(RequestTelemetryLogger.Result.Cancelled); } private void RecordCompletion(RequestTelemetryLogger.Result result) { Contract.ThrowIfNull(_queuedDuration, "RecordExecutionStart was not called"); var overallDuration = _sharedStopWatch.Elapsed; _requestTelemetryLogger.UpdateTelemetryData(_methodName, _queuedDuration.Value, overallDuration, result); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { internal partial class RequestExecutionQueue { internal class RequestMetrics { private readonly string _methodName; private readonly SharedStopwatch _sharedStopWatch; private TimeSpan? _queuedDuration; private readonly RequestTelemetryLogger _requestTelemetryLogger; public RequestMetrics(string methodName, RequestTelemetryLogger requestTelemetryLogger) { _methodName = methodName; _requestTelemetryLogger = requestTelemetryLogger; _sharedStopWatch = SharedStopwatch.StartNew(); } public void RecordExecutionStart() { // Request has de-queued and is starting execution. Record the time it spent in queue. _queuedDuration = _sharedStopWatch.Elapsed; } public void RecordSuccess() { RecordCompletion(RequestTelemetryLogger.Result.Succeeded); } public void RecordFailure() { RecordCompletion(RequestTelemetryLogger.Result.Failed); } public void RecordCancellation() { RecordCompletion(RequestTelemetryLogger.Result.Cancelled); } private void RecordCompletion(RequestTelemetryLogger.Result result) { Contract.ThrowIfNull(_queuedDuration, "RecordExecutionStart was not called"); var overallDuration = _sharedStopWatch.Elapsed; _requestTelemetryLogger.UpdateTelemetryData(_methodName, _queuedDuration.Value, overallDuration, result); } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/CSharp/Portable/GenerateDefaultConstructors/CSharpGenerateDefaultConstructorsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.GenerateDefaultConstructors; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.GenerateDefaultConstructors { [ExportLanguageService(typeof(IGenerateDefaultConstructorsService), LanguageNames.CSharp), Shared] internal class CSharpGenerateDefaultConstructorsService : AbstractGenerateDefaultConstructorsService<CSharpGenerateDefaultConstructorsService> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateDefaultConstructorsService() { } protected override bool TryInitializeState( SemanticDocument semanticDocument, TextSpan textSpan, CancellationToken cancellationToken, [NotNullWhen(true)] out INamedTypeSymbol? classType) { cancellationToken.ThrowIfCancellationRequested(); // Offer the feature if we're on the header / between members of the class/struct, // or if we're on the first base-type of a class var syntaxFacts = semanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>(); if (syntaxFacts.IsOnTypeHeader(semanticDocument.Root, textSpan.Start, out var typeDeclaration) || syntaxFacts.IsBetweenTypeMembers(semanticDocument.Text, semanticDocument.Root, textSpan.Start, out typeDeclaration)) { classType = semanticDocument.SemanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken) as INamedTypeSymbol; return classType?.TypeKind == TypeKind.Class; } var syntaxTree = semanticDocument.SyntaxTree; var node = semanticDocument.Root.FindToken(textSpan.Start).GetAncestor<TypeSyntax>(); if (node != null) { if (node.Parent is BaseTypeSyntax && node.Parent.IsParentKind(SyntaxKind.BaseList, out BaseListSyntax? baseList)) { if (baseList.Parent != null && baseList.Types.Count > 0 && baseList.Types[0].Type == node && baseList.IsParentKind(SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration)) { var semanticModel = semanticDocument.SemanticModel; classType = semanticModel.GetDeclaredSymbol(baseList.Parent, cancellationToken) as INamedTypeSymbol; return classType != null; } } } classType = null; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.GenerateDefaultConstructors; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.GenerateDefaultConstructors { [ExportLanguageService(typeof(IGenerateDefaultConstructorsService), LanguageNames.CSharp), Shared] internal class CSharpGenerateDefaultConstructorsService : AbstractGenerateDefaultConstructorsService<CSharpGenerateDefaultConstructorsService> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateDefaultConstructorsService() { } protected override bool TryInitializeState( SemanticDocument semanticDocument, TextSpan textSpan, CancellationToken cancellationToken, [NotNullWhen(true)] out INamedTypeSymbol? classType) { cancellationToken.ThrowIfCancellationRequested(); // Offer the feature if we're on the header / between members of the class/struct, // or if we're on the first base-type of a class var syntaxFacts = semanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>(); if (syntaxFacts.IsOnTypeHeader(semanticDocument.Root, textSpan.Start, out var typeDeclaration) || syntaxFacts.IsBetweenTypeMembers(semanticDocument.Text, semanticDocument.Root, textSpan.Start, out typeDeclaration)) { classType = semanticDocument.SemanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken) as INamedTypeSymbol; return classType?.TypeKind == TypeKind.Class; } var syntaxTree = semanticDocument.SyntaxTree; var node = semanticDocument.Root.FindToken(textSpan.Start).GetAncestor<TypeSyntax>(); if (node != null) { if (node.Parent is BaseTypeSyntax && node.Parent.IsParentKind(SyntaxKind.BaseList, out BaseListSyntax? baseList)) { if (baseList.Parent != null && baseList.Types.Count > 0 && baseList.Types[0].Type == node && baseList.IsParentKind(SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration)) { var semanticModel = semanticDocument.SemanticModel; classType = semanticModel.GetDeclaredSymbol(baseList.Parent, cancellationToken) as INamedTypeSymbol; return classType != null; } } } classType = null; return false; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CompilationContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class CompilationContext { internal readonly CSharpCompilation Compilation; internal readonly Binder NamespaceBinder; // Internal for test purposes. private readonly MethodSymbol _currentFrame; private readonly ImmutableArray<LocalSymbol> _locals; private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables; private readonly ImmutableArray<string> _sourceMethodParametersInOrder; private readonly ImmutableArray<LocalSymbol> _localsForBinding; private readonly bool _methodNotType; /// <summary> /// Create a context to compile expressions within a method scope. /// </summary> internal CompilationContext( CSharpCompilation compilation, MethodSymbol currentFrame, MethodSymbol? currentSourceMethod, ImmutableArray<LocalSymbol> locals, ImmutableSortedSet<int> inScopeHoistedLocalSlots, MethodDebugInfo<TypeSymbol, LocalSymbol> methodDebugInfo) { _currentFrame = currentFrame; _methodNotType = !locals.IsDefault; // NOTE: Since this is done within CompilationContext, it will not be cached. // CONSIDER: The values should be the same everywhere in the module, so they // could be cached. // (Catch: what happens in a type context without a method def?) Compilation = GetCompilationWithExternAliases(compilation, methodDebugInfo.ExternAliasRecords); // Each expression compile should use a unique compilation // to ensure expression-specific synthesized members can be // added (anonymous types, for instance). Debug.Assert(Compilation != compilation); NamespaceBinder = CreateBinderChain( Compilation, currentFrame.ContainingNamespace, methodDebugInfo.ImportRecordGroups); if (_methodNotType) { _locals = locals; _sourceMethodParametersInOrder = GetSourceMethodParametersInOrder(currentFrame, currentSourceMethod); GetDisplayClassVariables( currentFrame, _locals, inScopeHoistedLocalSlots, _sourceMethodParametersInOrder, out var displayClassVariableNamesInOrder, out _displayClassVariables); Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count); _localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables); } else { _locals = ImmutableArray<LocalSymbol>.Empty; _displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; _localsForBinding = ImmutableArray<LocalSymbol>.Empty; } // Assert that the cheap check for "this" is equivalent to the expensive check for "this". Debug.Assert( (GetThisProxy(_displayClassVariables) != null) == _displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This)); } internal bool TryCompileExpressions( ImmutableArray<CSharpSyntaxNode> syntaxNodes, string typeNameBase, string methodName, DiagnosticBag diagnostics, [NotNullWhen(true)] out CommonPEModuleBuilder? module) { // Create a separate synthesized type for each evaluation method. // (Necessary for VB in particular since the EENamedTypeSymbol.Locations // is tied to the expression syntax in VB.) var synthesizedTypes = syntaxNodes.SelectAsArray( (syntax, i, _) => (NamedTypeSymbol)CreateSynthesizedType(syntax, typeNameBase + i, methodName, ImmutableArray<Alias>.Empty), arg: (object?)null); if (synthesizedTypes.Length == 0) { module = null; return false; } module = CreateModuleBuilder( Compilation, additionalTypes: synthesizedTypes, testData: null, diagnostics: diagnostics); Compilation.Compile( module, emittingPdb: false, diagnostics: diagnostics, filterOpt: null, CancellationToken.None); return !diagnostics.HasAnyErrors(); } internal bool TryCompileExpression( CSharpSyntaxNode syntax, string typeName, string methodName, ImmutableArray<Alias> aliases, CompilationTestData? testData, DiagnosticBag diagnostics, [NotNullWhen(true)] out CommonPEModuleBuilder? module, [NotNullWhen(true)] out EEMethodSymbol? synthesizedMethod) { var synthesizedType = CreateSynthesizedType(syntax, typeName, methodName, aliases); module = CreateModuleBuilder( Compilation, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), testData, diagnostics); Compilation.Compile( module, emittingPdb: false, diagnostics, filterOpt: null, CancellationToken.None); if (diagnostics.HasAnyErrors()) { module = null; synthesizedMethod = null; return false; } synthesizedMethod = GetSynthesizedMethod(synthesizedType); return true; } private EENamedTypeSymbol CreateSynthesizedType( CSharpSyntaxNode syntax, string typeName, string methodName, ImmutableArray<Alias> aliases) { var objectType = Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, syntax, _currentFrame, typeName, methodName, this, (EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { var hasDisplayClassThis = GetThisProxy(_displayClassVariables) != null; var binder = ExtendBinderChain( syntax, aliases, method, NamespaceBinder, hasDisplayClassThis, _methodNotType, out declaredLocals); return (syntax is StatementSyntax statementSyntax) ? BindStatement(binder, statementSyntax, diags, out properties) : BindExpression(binder, (ExpressionSyntax)syntax, diags, out properties); }); return synthesizedType; } internal bool TryCompileAssignment( ExpressionSyntax syntax, string typeName, string methodName, ImmutableArray<Alias> aliases, CompilationTestData? testData, DiagnosticBag diagnostics, [NotNullWhen(true)] out CommonPEModuleBuilder? module, [NotNullWhen(true)] out EEMethodSymbol? synthesizedMethod) { var objectType = Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, syntax, _currentFrame, typeName, methodName, this, (EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { var hasDisplayClassThis = GetThisProxy(_displayClassVariables) != null; var binder = ExtendBinderChain( syntax, aliases, method, NamespaceBinder, hasDisplayClassThis, methodNotType: true, out declaredLocals); properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect); return BindAssignment(binder, syntax, diags); }); module = CreateModuleBuilder( Compilation, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), testData, diagnostics); Compilation.Compile( module, emittingPdb: false, diagnostics, filterOpt: null, CancellationToken.None); if (diagnostics.HasAnyErrors()) { module = null; synthesizedMethod = null; return false; } synthesizedMethod = GetSynthesizedMethod(synthesizedType); return true; } private static EEMethodSymbol GetSynthesizedMethod(EENamedTypeSymbol synthesizedType) => (EEMethodSymbol)synthesizedType.Methods[0]; private static string GetNextMethodName(ArrayBuilder<MethodSymbol> builder) => "<>m" + builder.Count; /// <summary> /// Generate a class containing methods that represent /// the set of arguments and locals at the current scope. /// </summary> internal CommonPEModuleBuilder? CompileGetLocals( string typeName, ArrayBuilder<LocalAndMethod> localBuilder, bool argumentsOnly, ImmutableArray<Alias> aliases, CompilationTestData? testData, DiagnosticBag diagnostics) { var objectType = Compilation.GetSpecialType(SpecialType.System_Object); var allTypeParameters = _currentFrame.GetAllTypeParameters(); var additionalTypes = ArrayBuilder<NamedTypeSymbol>.GetInstance(); EENamedTypeSymbol? typeVariablesType = null; if (!argumentsOnly && allTypeParameters.Length > 0) { // Generate a generic type with matching type parameters. // A null instance of the type will be used to represent the // "Type variables" local. typeVariablesType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, _currentFrame, ExpressionCompilerConstants.TypeVariablesClassName, (m, t) => ImmutableArray.Create<MethodSymbol>(new EEConstructorSymbol(t)), allTypeParameters, (t1, t2) => allTypeParameters.SelectAsArray((tp, i, t) => (TypeParameterSymbol)new SimpleTypeParameterSymbol(t, i, tp.Name), t2)); additionalTypes.Add(typeVariablesType); } var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, _currentFrame, typeName, (m, container) => { var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance(); if (!argumentsOnly) { // Pseudo-variables: $exception, $ReturnValue, etc. if (aliases.Length > 0) { var sourceAssembly = Compilation.SourceAssembly; var typeNameDecoder = new EETypeNameDecoder(Compilation, (PEModuleSymbol)_currentFrame.ContainingModule); foreach (var alias in aliases) { if (alias.IsReturnValueWithoutIndex()) { Debug.Assert(aliases.Count(a => a.Kind == DkmClrAliasKind.ReturnValue) > 1); continue; } var local = PlaceholderLocalSymbol.Create( typeNameDecoder, _currentFrame, sourceAssembly, alias); // Skip pseudo-variables with errors. if (local.HasUseSiteError) { continue; } var methodName = GetNextMethodName(methodBuilder); var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); var aliasMethod = CreateMethod( container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var expression = new BoundLocal(syntax, local, constantValueOpt: null, type: local.Type); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); var flags = local.IsWritableVariable ? DkmClrCompilationResultFlags.None : DkmClrCompilationResultFlags.ReadOnlyResult; localBuilder.Add(MakeLocalAndMethod(local, aliasMethod, flags)); methodBuilder.Add(aliasMethod); } } // "this" for non-static methods that are not display class methods or // display class methods where the display class contains "<>4__this". if (!m.IsStatic && !IsDisplayClassType(m.ContainingType) || GetThisProxy(_displayClassVariables) != null) { var methodName = GetNextMethodName(methodBuilder); var method = GetThisMethod(container, methodName); localBuilder.Add(new CSharpLocalAndMethod("this", "this", method, DkmClrCompilationResultFlags.None)); // Note: writable in dev11. methodBuilder.Add(method); } } var itemsAdded = PooledHashSet<string>.GetInstance(); // Method parameters int parameterIndex = m.IsStatic ? 0 : 1; foreach (var parameter in m.Parameters) { var parameterName = parameter.Name; if (GeneratedNameParser.GetKind(parameterName) == GeneratedNameKind.None && !IsDisplayClassParameter(parameter)) { itemsAdded.Add(parameterName); AppendParameterAndMethod(localBuilder, methodBuilder, parameter, container, parameterIndex); } parameterIndex++; } // In case of iterator or async state machine, the 'm' method has no parameters // but the source method can have parameters to iterate over. if (itemsAdded.Count == 0 && _sourceMethodParametersInOrder.Length != 0) { var localsDictionary = PooledDictionary<string, (LocalSymbol, int)>.GetInstance(); int localIndex = 0; foreach (var local in _localsForBinding) { localsDictionary.Add(local.Name, (local, localIndex)); localIndex++; } foreach (var argumentName in _sourceMethodParametersInOrder) { (LocalSymbol local, int localIndex) localSymbolAndIndex; if (localsDictionary.TryGetValue(argumentName, out localSymbolAndIndex)) { itemsAdded.Add(argumentName); var local = localSymbolAndIndex.local; AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localSymbolAndIndex.localIndex, GetLocalResultFlags(local)); } } localsDictionary.Free(); } if (!argumentsOnly) { // Locals which were not added as parameters or parameters of the source method. int localIndex = 0; foreach (var local in _localsForBinding) { if (!itemsAdded.Contains(local.Name)) { AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local)); } localIndex++; } // "Type variables". if (typeVariablesType is object) { var methodName = GetNextMethodName(methodBuilder); var returnType = typeVariablesType.Construct(allTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>()); var method = GetTypeVariablesMethod(container, methodName, returnType); localBuilder.Add(new CSharpLocalAndMethod( ExpressionCompilerConstants.TypeVariablesLocalName, ExpressionCompilerConstants.TypeVariablesLocalName, method, DkmClrCompilationResultFlags.ReadOnlyResult)); methodBuilder.Add(method); } } itemsAdded.Free(); return methodBuilder.ToImmutableAndFree(); }); additionalTypes.Add(synthesizedType); var module = CreateModuleBuilder( Compilation, additionalTypes.ToImmutableAndFree(), testData, diagnostics); RoslynDebug.AssertNotNull(module); Compilation.Compile( module, emittingPdb: false, diagnostics, filterOpt: null, CancellationToken.None); return diagnostics.HasAnyErrors() ? null : module; } private void AppendLocalAndMethod( ArrayBuilder<LocalAndMethod> localBuilder, ArrayBuilder<MethodSymbol> methodBuilder, LocalSymbol local, EENamedTypeSymbol container, int localIndex, DkmClrCompilationResultFlags resultFlags) { var methodName = GetNextMethodName(methodBuilder); var method = GetLocalMethod(container, methodName, local.Name, localIndex); localBuilder.Add(MakeLocalAndMethod(local, method, resultFlags)); methodBuilder.Add(method); } private void AppendParameterAndMethod( ArrayBuilder<LocalAndMethod> localBuilder, ArrayBuilder<MethodSymbol> methodBuilder, ParameterSymbol parameter, EENamedTypeSymbol container, int parameterIndex) { // Note: The native EE doesn't do this, but if we don't escape keyword identifiers, // the ResultProvider needs to be able to disambiguate cases like "this" and "@this", // which it can't do correctly without semantic information. var name = SyntaxHelpers.EscapeKeywordIdentifiers(parameter.Name); var methodName = GetNextMethodName(methodBuilder); var method = GetParameterMethod(container, methodName, name, parameterIndex); localBuilder.Add(new CSharpLocalAndMethod(name, name, method, DkmClrCompilationResultFlags.None)); methodBuilder.Add(method); } private static LocalAndMethod MakeLocalAndMethod(LocalSymbol local, MethodSymbol method, DkmClrCompilationResultFlags flags) { // Note: The native EE doesn't do this, but if we don't escape keyword identifiers, // the ResultProvider needs to be able to disambiguate cases like "this" and "@this", // which it can't do correctly without semantic information. var escapedName = SyntaxHelpers.EscapeKeywordIdentifiers(local.Name); var displayName = (local as PlaceholderLocalSymbol)?.DisplayName ?? escapedName; return new CSharpLocalAndMethod(escapedName, displayName, method, flags); } private static EEAssemblyBuilder CreateModuleBuilder( CSharpCompilation compilation, ImmutableArray<NamedTypeSymbol> additionalTypes, CompilationTestData? testData, DiagnosticBag diagnostics) { // Each assembly must have a unique name. var emitOptions = new EmitOptions(outputNameOverride: ExpressionCompilerUtilities.GenerateUniqueName()); string? runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics); var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion); return new EEAssemblyBuilder( compilation.SourceAssembly, emitOptions, serializationProperties, additionalTypes, contextType => GetNonDisplayClassContainer(((EENamedTypeSymbol)contextType).SubstitutedSourceType), testData); } internal EEMethodSymbol CreateMethod( EENamedTypeSymbol container, string methodName, CSharpSyntaxNode syntax, GenerateMethodBody generateMethodBody) { return new EEMethodSymbol( container, methodName, syntax.Location, _currentFrame, _locals, _localsForBinding, _displayClassVariables, generateMethodBody); } private EEMethodSymbol GetLocalMethod(EENamedTypeSymbol container, string methodName, string localName, int localIndex) { var syntax = SyntaxFactory.IdentifierName(localName); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var local = method.LocalsForBinding[localIndex]; var expression = new BoundLocal(syntax, local, constantValueOpt: local.GetConstantValue(null, null, new BindingDiagnosticBag(diagnostics)), type: local.Type); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetParameterMethod(EENamedTypeSymbol container, string methodName, string parameterName, int parameterIndex) { var syntax = SyntaxFactory.IdentifierName(parameterName); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var parameter = method.Parameters[parameterIndex]; var expression = new BoundParameter(syntax, parameter); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetThisMethod(EENamedTypeSymbol container, string methodName) { var syntax = SyntaxFactory.ThisExpression(); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var expression = new BoundThisReference(syntax, GetNonDisplayClassContainer(container.SubstitutedSourceType)); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetTypeVariablesMethod(EENamedTypeSymbol container, string methodName, NamedTypeSymbol typeVariablesType) { var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var type = method.TypeMap.SubstituteNamedType(typeVariablesType); var expression = new BoundObjectCreationExpression(syntax, type.InstanceConstructors[0]); var statement = new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; properties = default; return statement; }); } private static BoundStatement? BindExpression(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics, out ResultProperties resultProperties) { var flags = DkmClrCompilationResultFlags.None; var bindingDiagnostics = new BindingDiagnosticBag(diagnostics); // In addition to C# expressions, the native EE also supports // type names which are bound to a representation of the type // (but not System.Type) that the user can expand to see the // base type. Instead, we only allow valid C# expressions. var expression = IsDeconstruction(syntax) ? binder.BindDeconstruction((AssignmentExpressionSyntax)syntax, bindingDiagnostics, resultIsUsedOverride: true) : binder.BindRValueWithoutTargetType(syntax, bindingDiagnostics); if (diagnostics.HasAnyErrors()) { resultProperties = default; return null; } try { if (MayHaveSideEffectsVisitor.MayHaveSideEffects(expression)) { flags |= DkmClrCompilationResultFlags.PotentialSideEffect; } } catch (BoundTreeVisitor.CancelledByStackGuardException ex) { ex.AddAnError(diagnostics); resultProperties = default; return null; } var expressionType = expression.Type; if (expressionType is null) { expression = binder.CreateReturnConversion( syntax, bindingDiagnostics, expression, RefKind.None, binder.Compilation.GetSpecialType(SpecialType.System_Object)); if (diagnostics.HasAnyErrors()) { resultProperties = default; return null; } } else if (expressionType.SpecialType == SpecialType.System_Void) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; Debug.Assert(expression.ConstantValue == null); resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, isConstant: false); return new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true }; } else if (expressionType.SpecialType == SpecialType.System_Boolean) { flags |= DkmClrCompilationResultFlags.BoolResult; } if (!IsAssignableExpression(binder, expression)) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; } resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, expression.ConstantValue != null); return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; } private static bool IsDeconstruction(ExpressionSyntax syntax) { if (syntax.Kind() != SyntaxKind.SimpleAssignmentExpression) { return false; } var node = (AssignmentExpressionSyntax)syntax; return node.Left.Kind() == SyntaxKind.TupleExpression || node.Left.Kind() == SyntaxKind.DeclarationExpression; } private static BoundStatement BindStatement(Binder binder, StatementSyntax syntax, DiagnosticBag diagnostics, out ResultProperties properties) { properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); return binder.BindStatement(syntax, new BindingDiagnosticBag(diagnostics)); } private static bool IsAssignableExpression(Binder binder, BoundExpression expression) { var result = binder.CheckValueKind(expression.Syntax, expression, Binder.BindValueKind.Assignable, checkingReceiver: false, BindingDiagnosticBag.Discarded); return result; } private static BoundStatement? BindAssignment(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics) { var expression = binder.BindValue(syntax, new BindingDiagnosticBag(diagnostics), Binder.BindValueKind.RValue); if (diagnostics.HasAnyErrors()) { return null; } return new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true }; } private static Binder CreateBinderChain( CSharpCompilation compilation, NamespaceSymbol @namespace, ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups) { var stack = ArrayBuilder<string>.GetInstance(); while (@namespace is object) { stack.Push(@namespace.Name); @namespace = @namespace.ContainingNamespace; } Binder binder = new BuckStopsHereBinder(compilation); var hasImports = !importRecordGroups.IsDefaultOrEmpty; var numImportStringGroups = hasImports ? importRecordGroups.Length : 0; var currentStringGroup = numImportStringGroups - 1; // PERF: We used to call compilation.GetCompilationNamespace on every iteration, // but that involved walking up to the global namespace, which we have to do // anyway. Instead, we'll inline the functionality into our own walk of the // namespace chain. @namespace = compilation.GlobalNamespace; while (stack.Count > 0) { var namespaceName = stack.Pop(); if (namespaceName.Length > 0) { // We're re-getting the namespace, rather than using the one containing // the current frame method, because we want the merged namespace. @namespace = @namespace.GetNestedNamespace(namespaceName); RoslynDebug.AssertNotNull(@namespace); } else { Debug.Assert((object)@namespace == compilation.GlobalNamespace); } if (hasImports) { if (currentStringGroup < 0) { Debug.WriteLine($"No import string group for namespace '{@namespace}'"); break; } var importsBinder = new InContainerBinder(@namespace, binder); Imports imports = BuildImports(compilation, importRecordGroups[currentStringGroup], importsBinder); currentStringGroup--; binder = WithExternAndUsingAliasesBinder.Create(imports.ExternAliases, imports.UsingAliases, WithUsingNamespacesAndTypesBinder.Create(imports.Usings, binder)); } binder = new InContainerBinder(@namespace, binder); } stack.Free(); if (currentStringGroup >= 0) { // CONSIDER: We could lump these into the outermost namespace. It's probably not worthwhile since // the usings are already for the wrong method. Debug.WriteLine($"Found {currentStringGroup + 1} import string groups without corresponding namespaces"); } return binder; } private static CSharpCompilation GetCompilationWithExternAliases(CSharpCompilation compilation, ImmutableArray<ExternAliasRecord> externAliasRecords) { if (externAliasRecords.IsDefaultOrEmpty) { return compilation.Clone(); } var updatedReferences = ArrayBuilder<MetadataReference>.GetInstance(); var assembliesAndModulesBuilder = ArrayBuilder<Symbol>.GetInstance(); foreach (var reference in compilation.References) { updatedReferences.Add(reference); assembliesAndModulesBuilder.Add(compilation.GetAssemblyOrModuleSymbol(reference)!); } Debug.Assert(assembliesAndModulesBuilder.Count == updatedReferences.Count); var assembliesAndModules = assembliesAndModulesBuilder.ToImmutableAndFree(); foreach (var externAliasRecord in externAliasRecords) { var targetAssembly = externAliasRecord.TargetAssembly as AssemblySymbol; int index; if (targetAssembly != null) { index = assembliesAndModules.IndexOf(targetAssembly); } else { index = IndexOfMatchingAssembly((AssemblyIdentity)externAliasRecord.TargetAssembly, assembliesAndModules, compilation.Options.AssemblyIdentityComparer); } if (index < 0) { Debug.WriteLine($"Unable to find corresponding assembly reference for extern alias '{externAliasRecord}'"); continue; } var externAlias = externAliasRecord.Alias; var assemblyReference = updatedReferences[index]; var oldAliases = assemblyReference.Properties.Aliases; var newAliases = oldAliases.IsEmpty ? ImmutableArray.Create(MetadataReferenceProperties.GlobalAlias, externAlias) : oldAliases.Concat(ImmutableArray.Create(externAlias)); // NOTE: Dev12 didn't emit custom debug info about "global", so we don't have // a good way to distinguish between a module aliased with both (e.g.) "X" and // "global" and a module aliased with only "X". As in Dev12, we assume that // "global" is a valid alias to remain at least as permissive as source. // NOTE: In the event that this introduces ambiguities between two assemblies // (e.g. because one was "global" in source and the other was "X"), it should be // possible to disambiguate as long as each assembly has a distinct extern alias, // not necessarily used in source. Debug.Assert(newAliases.Contains(MetadataReferenceProperties.GlobalAlias)); // Replace the value in the map with the updated reference. updatedReferences[index] = assemblyReference.WithAliases(newAliases); } compilation = compilation.WithReferences(updatedReferences); updatedReferences.Free(); return compilation; } private static int IndexOfMatchingAssembly(AssemblyIdentity referenceIdentity, ImmutableArray<Symbol> assembliesAndModules, AssemblyIdentityComparer assemblyIdentityComparer) { for (int i = 0; i < assembliesAndModules.Length; i++) { if (assembliesAndModules[i] is AssemblySymbol assembly && assemblyIdentityComparer.ReferenceMatchesDefinition(referenceIdentity, assembly.Identity)) { return i; } } return -1; } private static Binder ExtendBinderChain( CSharpSyntaxNode syntax, ImmutableArray<Alias> aliases, EEMethodSymbol method, Binder binder, bool hasDisplayClassThis, bool methodNotType, out ImmutableArray<LocalSymbol> declaredLocals) { var substitutedSourceMethod = GetSubstitutedSourceMethod(method.SubstitutedSourceMethod, hasDisplayClassThis); var substitutedSourceType = substitutedSourceMethod.ContainingType; var stack = ArrayBuilder<NamedTypeSymbol>.GetInstance(); for (var type = substitutedSourceType; type is object; type = type.ContainingType) { stack.Add(type); } while (stack.Count > 0) { substitutedSourceType = stack.Pop(); binder = new InContainerBinder(substitutedSourceType, binder); if (substitutedSourceType.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, binder); } } stack.Free(); if (substitutedSourceMethod.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceMethod.TypeArgumentsWithAnnotations, binder); } // Method locals and parameters shadow pseudo-variables. // That is why we place PlaceholderLocalBinder and ExecutableCodeBinder before EEMethodBinder. if (methodNotType) { var typeNameDecoder = new EETypeNameDecoder(binder.Compilation, (PEModuleSymbol)substitutedSourceMethod.ContainingModule); binder = new PlaceholderLocalBinder( syntax, aliases, method, typeNameDecoder, binder); } binder = new EEMethodBinder(method, substitutedSourceMethod, binder); if (methodNotType) { binder = new SimpleLocalScopeBinder(method.LocalsForBinding, binder); } Binder? actualRootBinder = null; SyntaxNode? declaredLocalsScopeDesignator = null; var executableBinder = new ExecutableCodeBinder(syntax, substitutedSourceMethod, binder, (rootBinder, declaredLocalsScopeDesignatorOpt) => { actualRootBinder = rootBinder; declaredLocalsScopeDesignator = declaredLocalsScopeDesignatorOpt; }); // We just need to trigger the process of building the binder map // so that the lambda above was executed. executableBinder.GetBinder(syntax); RoslynDebug.AssertNotNull(actualRootBinder); if (declaredLocalsScopeDesignator != null) { declaredLocals = actualRootBinder.GetDeclaredLocalsForScope(declaredLocalsScopeDesignator); } else { declaredLocals = ImmutableArray<LocalSymbol>.Empty; } return actualRootBinder; } private static Imports BuildImports(CSharpCompilation compilation, ImmutableArray<ImportRecord> importRecords, InContainerBinder binder) { // We make a first pass to extract all of the extern aliases because other imports may depend on them. var externsBuilder = ArrayBuilder<AliasAndExternAliasDirective>.GetInstance(); foreach (var importRecord in importRecords) { if (importRecord.TargetKind != ImportTargetKind.Assembly) { continue; } var alias = importRecord.Alias; RoslynDebug.AssertNotNull(alias); if (!TryParseIdentifierNameSyntax(alias, out var aliasNameSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{alias}'"); continue; } NamespaceSymbol target; compilation.GetExternAliasTarget(aliasNameSyntax.Identifier.ValueText, out target); Debug.Assert(target.IsGlobalNamespace); var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(target, aliasNameSyntax.Identifier, binder.ContainingMemberOrLambda, isExtern: true); externsBuilder.Add(new AliasAndExternAliasDirective(aliasSymbol, externAliasDirective: null, skipInLookup: false)); } var externs = externsBuilder.ToImmutableAndFree(); if (externs.Any()) { // NB: This binder (and corresponding Imports) is only used to bind the other imports. // We'll merge the externs into a final Imports object and return that to be used in // the actual binder chain. binder = new InContainerBinder( binder.Container, WithExternAliasesBinder.Create(externs, binder)); } var usingAliases = ImmutableDictionary.CreateBuilder<string, AliasAndUsingDirective>(); var usingsBuilder = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance(); foreach (var importRecord in importRecords) { switch (importRecord.TargetKind) { case ImportTargetKind.Type: { var typeSymbol = (TypeSymbol?)importRecord.TargetType; RoslynDebug.AssertNotNull(typeSymbol); if (typeSymbol.IsErrorType()) { // Type is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } else if (importRecord.Alias == null && !typeSymbol.IsStatic) { // Only static types can be directly imported. continue; } if (!TryAddImport(importRecord.Alias, typeSymbol, usingsBuilder, usingAliases, binder, importRecord)) { continue; } break; } case ImportTargetKind.Namespace: { var namespaceName = importRecord.TargetString; RoslynDebug.AssertNotNull(namespaceName); if (!SyntaxHelpers.TryParseDottedName(namespaceName, out _)) { // DevDiv #999086: Some previous version of VS apparently generated type aliases as "UA{alias} T{alias-qualified type name}". // Neither Roslyn nor Dev12 parses such imports. However, Roslyn discards them, rather than interpreting them as "UA{alias}" // (which will rarely work and never be correct). Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid target '{importRecord.TargetString}'"); continue; } NamespaceSymbol globalNamespace; var targetAssembly = (AssemblySymbol?)importRecord.TargetAssembly; if (targetAssembly is object) { if (targetAssembly.IsMissing) { Debug.WriteLine($"Import record '{importRecord}' has invalid assembly reference '{targetAssembly.Identity}'"); continue; } globalNamespace = targetAssembly.GlobalNamespace; } else if (importRecord.TargetAssemblyAlias != null) { if (!TryParseIdentifierNameSyntax(importRecord.TargetAssemblyAlias, out var externAliasSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{importRecord.TargetAssemblyAlias}'"); continue; } var aliasSymbol = (AliasSymbol)binder.BindNamespaceAliasSymbol(externAliasSyntax, BindingDiagnosticBag.Discarded); if (aliasSymbol is null) { Debug.WriteLine($"Import record '{importRecord}' requires unknown extern alias '{importRecord.TargetAssemblyAlias}'"); continue; } globalNamespace = (NamespaceSymbol)aliasSymbol.Target; } else { globalNamespace = compilation.GlobalNamespace; } var namespaceSymbol = BindNamespace(namespaceName, globalNamespace); if (namespaceSymbol is null) { // Namespace is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } if (!TryAddImport(importRecord.Alias, namespaceSymbol, usingsBuilder, usingAliases, binder, importRecord)) { continue; } break; } case ImportTargetKind.Assembly: // Handled in first pass (above). break; default: throw ExceptionUtilities.UnexpectedValue(importRecord.TargetKind); } } return Imports.Create(usingAliases.ToImmutableDictionary(), usingsBuilder.ToImmutableAndFree(), externs); } private static NamespaceSymbol? BindNamespace(string namespaceName, NamespaceSymbol globalNamespace) { NamespaceSymbol? namespaceSymbol = globalNamespace; foreach (var name in namespaceName.Split('.')) { var members = namespaceSymbol.GetMembers(name); namespaceSymbol = (members.Length == 1) ? members[0] as NamespaceSymbol : null; if (namespaceSymbol is null) { break; } } return namespaceSymbol; } private static bool TryAddImport( string? alias, NamespaceOrTypeSymbol targetSymbol, ArrayBuilder<NamespaceOrTypeAndUsingDirective> usingsBuilder, ImmutableDictionary<string, AliasAndUsingDirective>.Builder usingAliases, InContainerBinder binder, ImportRecord importRecord) { if (alias == null) { usingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(targetSymbol, usingDirective: null, dependencies: default)); } else { if (!TryParseIdentifierNameSyntax(alias, out var aliasSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid alias '{alias}'"); return false; } var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(targetSymbol, aliasSyntax.Identifier, binder.ContainingMemberOrLambda, isExtern: false); usingAliases.Add(alias, new AliasAndUsingDirective(aliasSymbol, usingDirective: null)); } return true; } private static bool TryParseIdentifierNameSyntax(string name, [NotNullWhen(true)] out IdentifierNameSyntax? syntax) { if (name == MetadataReferenceProperties.GlobalAlias) { syntax = SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); return true; } if (!SyntaxHelpers.TryParseDottedName(name, out var nameSyntax) || nameSyntax.Kind() != SyntaxKind.IdentifierName) { syntax = null; return false; } syntax = (IdentifierNameSyntax)nameSyntax; return true; } internal CommonMessageProvider MessageProvider { get { return Compilation.MessageProvider; } } private static DkmClrCompilationResultFlags GetLocalResultFlags(LocalSymbol local) { // CONSIDER: We might want to prevent the user from modifying pinned locals - // that's pretty dangerous. return local.IsConst ? DkmClrCompilationResultFlags.ReadOnlyResult : DkmClrCompilationResultFlags.None; } /// <summary> /// Generate the set of locals to use for binding. /// </summary> private static ImmutableArray<LocalSymbol> GetLocalsForBinding( ImmutableArray<LocalSymbol> locals, ImmutableArray<string> displayClassVariableNamesInOrder, ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { var builder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var local in locals) { var name = local.Name; if (name == null) { continue; } if (GeneratedNameParser.GetKind(name) != GeneratedNameKind.None) { continue; } // Although Roslyn doesn't name synthesized locals unless they are well-known to EE, // Dev12 did so we need to skip them here. if (GeneratedNameParser.IsSynthesizedLocalName(name)) { continue; } builder.Add(local); } foreach (var variableName in displayClassVariableNamesInOrder) { var variable = displayClassVariables[variableName]; switch (variable.Kind) { case DisplayClassVariableKind.Local: case DisplayClassVariableKind.Parameter: builder.Add(new EEDisplayClassFieldLocalSymbol(variable)); break; } } return builder.ToImmutableAndFree(); } private static ImmutableArray<string> GetSourceMethodParametersInOrder( MethodSymbol method, MethodSymbol? sourceMethod) { var containingType = method.ContainingType; bool isIteratorOrAsyncMethod = IsDisplayClassType(containingType) && GeneratedNameParser.GetKind(containingType.Name) == GeneratedNameKind.StateMachineType; var parameterNamesInOrder = ArrayBuilder<string>.GetInstance(); // For version before .NET 4.5, we cannot find the sourceMethod properly: // The source method coincides with the original method in the case. // Therefore, for iterators and async state machines, we have to get parameters from the containingType. // This does not guarantee the proper order of parameters. if (isIteratorOrAsyncMethod && method == sourceMethod) { Debug.Assert(IsDisplayClassType(containingType)); foreach (var member in containingType.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldName = field.Name; if (GeneratedNameParser.GetKind(fieldName) == GeneratedNameKind.None) { parameterNamesInOrder.Add(fieldName); } } } else { if (sourceMethod is object) { foreach (var p in sourceMethod.Parameters) { parameterNamesInOrder.Add(p.Name); } } } return parameterNamesInOrder.ToImmutableAndFree(); } /// <summary> /// Return a mapping of captured variables (parameters, locals, and /// "this") to locals. The mapping is needed to expose the original /// local identifiers (those from source) in the binder. /// </summary> private static void GetDisplayClassVariables( MethodSymbol method, ImmutableArray<LocalSymbol> locals, ImmutableSortedSet<int> inScopeHoistedLocalSlots, ImmutableArray<string> parameterNamesInOrder, out ImmutableArray<string> displayClassVariableNamesInOrder, out ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { // Calculate the shortest paths from locals to instances of display // classes. There should not be two instances of the same display // class immediately within any particular method. var displayClassInstances = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance(); foreach (var parameter in method.Parameters) { if (GeneratedNameParser.GetKind(parameter.Name) == GeneratedNameKind.TransparentIdentifier || IsDisplayClassParameter(parameter)) { var instance = new DisplayClassInstanceFromParameter(parameter); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } } if (IsDisplayClassType(method.ContainingType) && !method.IsStatic) { // Add "this" display class instance. var instance = new DisplayClassInstanceFromParameter(method.ThisParameter); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } var displayClassTypes = PooledHashSet<TypeSymbol>.GetInstance(); foreach (var instance in displayClassInstances) { displayClassTypes.Add(instance.Instance.Type); } // Find any additional display class instances. GetAdditionalDisplayClassInstances(displayClassTypes, displayClassInstances, startIndex: 0); // Add any display class instances from locals (these will contain any hoisted locals). // Locals are only added after finding all display class instances reachable from // parameters because locals may be null (temporary locals in async state machine // for instance) so we prefer parameters to locals. int startIndex = displayClassInstances.Count; foreach (var local in locals) { var name = local.Name; if (name != null && GeneratedNameParser.GetKind(name) == GeneratedNameKind.DisplayClassLocalOrField) { var localType = local.Type; if (localType is object && displayClassTypes.Add(localType)) { var instance = new DisplayClassInstanceFromLocal((EELocalSymbol)local); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } } } GetAdditionalDisplayClassInstances(displayClassTypes, displayClassInstances, startIndex); displayClassTypes.Free(); if (displayClassInstances.Any()) { var parameterNames = PooledHashSet<string>.GetInstance(); foreach (var name in parameterNamesInOrder) { parameterNames.Add(name); } // The locals are the set of all fields from the display classes. var displayClassVariableNamesInOrderBuilder = ArrayBuilder<string>.GetInstance(); var displayClassVariablesBuilder = PooledDictionary<string, DisplayClassVariable>.GetInstance(); foreach (var instance in displayClassInstances) { GetDisplayClassVariables( displayClassVariableNamesInOrderBuilder, displayClassVariablesBuilder, parameterNames, inScopeHoistedLocalSlots, instance); } displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree(); displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary(); displayClassVariablesBuilder.Free(); parameterNames.Free(); } else { displayClassVariableNamesInOrder = ImmutableArray<string>.Empty; displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; } displayClassInstances.Free(); } private static void GetAdditionalDisplayClassInstances( HashSet<TypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, int startIndex) { // Find any additional display class instances breadth first. for (int i = startIndex; i < displayClassInstances.Count; i++) { GetDisplayClassInstances(displayClassTypes, displayClassInstances, displayClassInstances[i]); } } private static void GetDisplayClassInstances( HashSet<TypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, DisplayClassInstanceAndFields instance) { // Display class instance. The display class fields are variables. foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldType = field.Type; var fieldName = field.Name; TryParseGeneratedName(fieldName, out var fieldKind, out var part); switch (fieldKind) { case GeneratedNameKind.DisplayClassLocalOrField: case GeneratedNameKind.TransparentIdentifier: break; case GeneratedNameKind.AnonymousTypeField: RoslynDebug.AssertNotNull(part); if (GeneratedNameParser.GetKind(part) != GeneratedNameKind.TransparentIdentifier) { continue; } break; case GeneratedNameKind.ThisProxyField: if (GeneratedNameParser.GetKind(fieldType.Name) != GeneratedNameKind.LambdaDisplayClass) { continue; } // Async lambda case. break; default: continue; } Debug.Assert(!field.IsStatic); // A hoisted local that is itself a display class instance. if (displayClassTypes.Add(fieldType)) { var other = instance.FromField(field); displayClassInstances.Add(other); } } } /// <summary> /// Returns true if the parameter is a synthesized parameter representing /// a display class instance (used to pass hoisted symbols to local functions). /// </summary> private static bool IsDisplayClassParameter(ParameterSymbol parameter) { var type = parameter.Type; var result = type.Kind == SymbolKind.NamedType && IsDisplayClassType((NamedTypeSymbol)type); Debug.Assert(!result || parameter.MetadataName == ""); return result; } private static void GetDisplayClassVariables( ArrayBuilder<string> displayClassVariableNamesInOrderBuilder, Dictionary<string, DisplayClassVariable> displayClassVariablesBuilder, HashSet<string> parameterNames, ImmutableSortedSet<int> inScopeHoistedLocalSlots, DisplayClassInstanceAndFields instance) { // Display class instance. The display class fields are variables. foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldName = field.Name; REPARSE: DisplayClassVariableKind variableKind; string variableName; TryParseGeneratedName(fieldName, out var fieldKind, out var part); switch (fieldKind) { case GeneratedNameKind.AnonymousTypeField: RoslynDebug.AssertNotNull(part); Debug.Assert(fieldName == field.Name); // This only happens once. fieldName = part; goto REPARSE; case GeneratedNameKind.TransparentIdentifier: // A transparent identifier (field) in an anonymous type synthesized for a transparent identifier. Debug.Assert(!field.IsStatic); continue; case GeneratedNameKind.DisplayClassLocalOrField: // A local that is itself a display class instance. Debug.Assert(!field.IsStatic); continue; case GeneratedNameKind.HoistedLocalField: RoslynDebug.AssertNotNull(part); // Filter out hoisted locals that are known to be out-of-scope at the current IL offset. // Hoisted locals with invalid indices will be included since more information is better // than less in error scenarios. if (GeneratedNameParser.TryParseSlotIndex(fieldName, out int slotIndex) && !inScopeHoistedLocalSlots.Contains(slotIndex)) { continue; } variableName = part; variableKind = DisplayClassVariableKind.Local; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.ThisProxyField: // A reference to "this". variableName = ""; // Should not be referenced by name. variableKind = DisplayClassVariableKind.This; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.None: // A reference to a parameter or local. variableName = fieldName; variableKind = parameterNames.Contains(variableName) ? DisplayClassVariableKind.Parameter : DisplayClassVariableKind.Local; Debug.Assert(!field.IsStatic); break; default: continue; } if (displayClassVariablesBuilder.ContainsKey(variableName)) { // Only expecting duplicates for async state machine // fields (that should be at the top-level). Debug.Assert(displayClassVariablesBuilder[variableName].DisplayClassFields.Count() == 1); if (!instance.Fields.Any()) { // Prefer parameters over locals. Debug.Assert(instance.Instance is DisplayClassInstanceFromLocal); } else { Debug.Assert(instance.Fields.Count() >= 1); // greater depth Debug.Assert(variableKind == DisplayClassVariableKind.Parameter || variableKind == DisplayClassVariableKind.This); if (variableKind == DisplayClassVariableKind.Parameter && GeneratedNameParser.GetKind(instance.Type.Name) == GeneratedNameKind.LambdaDisplayClass) { displayClassVariablesBuilder[variableName] = instance.ToVariable(variableName, variableKind, field); } } } else if (variableKind != DisplayClassVariableKind.This || GeneratedNameParser.GetKind(instance.Type.ContainingType.Name) != GeneratedNameKind.LambdaDisplayClass) { // In async lambdas, the hoisted "this" field in the state machine type will point to the display class instance, if there is one. // In such cases, we want to add the display class "this" to the map instead (or nothing, if it lacks one). displayClassVariableNamesInOrderBuilder.Add(variableName); displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field)); } } } private static void TryParseGeneratedName(string name, out GeneratedNameKind kind, out string? part) { _ = GeneratedNameParser.TryParseGeneratedName(name, out kind, out int openBracketOffset, out int closeBracketOffset); switch (kind) { case GeneratedNameKind.AnonymousTypeField: case GeneratedNameKind.HoistedLocalField: part = name.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); break; default: part = null; break; } } private static bool IsDisplayClassType(TypeSymbol type) { switch (GeneratedNameParser.GetKind(type.Name)) { case GeneratedNameKind.LambdaDisplayClass: case GeneratedNameKind.StateMachineType: return true; default: return false; } } internal static DisplayClassVariable GetThisProxy(ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { return displayClassVariables.Values.FirstOrDefault(v => v.Kind == DisplayClassVariableKind.This); } private static NamedTypeSymbol GetNonDisplayClassContainer(NamedTypeSymbol type) { // 1) Display class and state machine types are always nested within the types // that use them (so that they can access private members of those types). // 2) The native compiler used to produce nested display classes for nested lambdas, // so we may have to walk out more than one level. while (IsDisplayClassType(type)) { type = type.ContainingType!; } return type; } /// <summary> /// Identifies the method in which binding should occur. /// </summary> /// <param name="candidateSubstitutedSourceMethod"> /// The symbol of the method that is currently on top of the callstack, with /// EE type parameters substituted in place of the original type parameters. /// </param> /// <param name="sourceMethodMustBeInstance"> /// True if "this" is available via a display class in the current context. /// </param> /// <returns> /// If <paramref name="candidateSubstitutedSourceMethod"/> is compiler-generated, /// then we will attempt to determine which user-defined method caused it to be /// generated. For example, if <paramref name="candidateSubstitutedSourceMethod"/> /// is a state machine MoveNext method, then we will try to find the iterator or /// async method for which it was generated. If we are able to find the original /// method, then we will substitute in the EE type parameters. Otherwise, we will /// return <paramref name="candidateSubstitutedSourceMethod"/>. /// </returns> /// <remarks> /// In the event that the original method is overloaded, we may not be able to determine /// which overload actually corresponds to the state machine. In particular, we do not /// have information about the signature of the original method (i.e. number of parameters, /// parameter types and ref-kinds, return type). However, we conjecture that this /// level of uncertainty is acceptable, since parameters are managed by a separate binder /// in the synthesized binder chain and we have enough information to check the other method /// properties that are used during binding (e.g. static-ness, generic arity, type parameter /// constraints). /// </remarks> internal static MethodSymbol GetSubstitutedSourceMethod( MethodSymbol candidateSubstitutedSourceMethod, bool sourceMethodMustBeInstance) { var candidateSubstitutedSourceType = candidateSubstitutedSourceMethod.ContainingType; string? desiredMethodName; if (GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceType.Name, GeneratedNameKind.StateMachineType, out desiredMethodName) || GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LambdaMethod, out desiredMethodName) || GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LocalFunction, out desiredMethodName)) { // We could be in the MoveNext method of an async lambda. string? tempMethodName; if (GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LambdaMethod, out tempMethodName) || GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LocalFunction, out tempMethodName)) { desiredMethodName = tempMethodName; var containing = candidateSubstitutedSourceType.ContainingType; RoslynDebug.AssertNotNull(containing); if (GeneratedNameParser.GetKind(containing.Name) == GeneratedNameKind.LambdaDisplayClass) { candidateSubstitutedSourceType = containing; sourceMethodMustBeInstance = candidateSubstitutedSourceType.MemberNames.Select(GeneratedNameParser.GetKind).Contains(GeneratedNameKind.ThisProxyField); } } var desiredTypeParameters = candidateSubstitutedSourceType.OriginalDefinition.TypeParameters; // Type containing the original iterator, async, or lambda-containing method. var substitutedSourceType = GetNonDisplayClassContainer(candidateSubstitutedSourceType); foreach (var candidateMethod in substitutedSourceType.GetMembers().OfType<MethodSymbol>()) { if (IsViableSourceMethod(candidateMethod, desiredMethodName, desiredTypeParameters, sourceMethodMustBeInstance)) { return desiredTypeParameters.Length == 0 ? candidateMethod : candidateMethod.Construct(candidateSubstitutedSourceType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics); } } Debug.Fail("Why didn't we find a substituted source method for " + candidateSubstitutedSourceMethod + "?"); } return candidateSubstitutedSourceMethod; } private static bool IsViableSourceMethod( MethodSymbol candidateMethod, string desiredMethodName, ImmutableArray<TypeParameterSymbol> desiredTypeParameters, bool desiredMethodMustBeInstance) { return !candidateMethod.IsAbstract && !(desiredMethodMustBeInstance && candidateMethod.IsStatic) && candidateMethod.Name == desiredMethodName && HaveSameConstraints(candidateMethod.TypeParameters, desiredTypeParameters); } private static bool HaveSameConstraints(ImmutableArray<TypeParameterSymbol> candidateTypeParameters, ImmutableArray<TypeParameterSymbol> desiredTypeParameters) { int arity = candidateTypeParameters.Length; if (arity != desiredTypeParameters.Length) { return false; } if (arity == 0) { return true; } var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var candidateTypeMap = new TypeMap(candidateTypeParameters, indexedTypeParameters, allowAlpha: true); var desiredTypeMap = new TypeMap(desiredTypeParameters, indexedTypeParameters, allowAlpha: true); return MemberSignatureComparer.HaveSameConstraints(candidateTypeParameters, candidateTypeMap, desiredTypeParameters, desiredTypeMap); } [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] private readonly struct DisplayClassInstanceAndFields { internal readonly DisplayClassInstance Instance; internal readonly ConsList<FieldSymbol> Fields; internal DisplayClassInstanceAndFields(DisplayClassInstance instance) : this(instance, ConsList<FieldSymbol>.Empty) { Debug.Assert(IsDisplayClassType(instance.Type) || GeneratedNameParser.GetKind(instance.Type.Name) == GeneratedNameKind.AnonymousType); } private DisplayClassInstanceAndFields(DisplayClassInstance instance, ConsList<FieldSymbol> fields) { Instance = instance; Fields = fields; } internal TypeSymbol Type => Fields.Any() ? Fields.Head.Type : Instance.Type; internal int Depth => Fields.Count(); internal DisplayClassInstanceAndFields FromField(FieldSymbol field) { Debug.Assert(IsDisplayClassType(field.Type) || GeneratedNameParser.GetKind(field.Type.Name) == GeneratedNameKind.AnonymousType); return new DisplayClassInstanceAndFields(Instance, Fields.Prepend(field)); } internal DisplayClassVariable ToVariable(string name, DisplayClassVariableKind kind, FieldSymbol field) { return new DisplayClassVariable(name, kind, Instance, Fields.Prepend(field)); } private string GetDebuggerDisplay() { return Instance.GetDebuggerDisplay(Fields); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class CompilationContext { internal readonly CSharpCompilation Compilation; internal readonly Binder NamespaceBinder; // Internal for test purposes. private readonly MethodSymbol _currentFrame; private readonly ImmutableArray<LocalSymbol> _locals; private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables; private readonly ImmutableArray<string> _sourceMethodParametersInOrder; private readonly ImmutableArray<LocalSymbol> _localsForBinding; private readonly bool _methodNotType; /// <summary> /// Create a context to compile expressions within a method scope. /// </summary> internal CompilationContext( CSharpCompilation compilation, MethodSymbol currentFrame, MethodSymbol? currentSourceMethod, ImmutableArray<LocalSymbol> locals, ImmutableSortedSet<int> inScopeHoistedLocalSlots, MethodDebugInfo<TypeSymbol, LocalSymbol> methodDebugInfo) { _currentFrame = currentFrame; _methodNotType = !locals.IsDefault; // NOTE: Since this is done within CompilationContext, it will not be cached. // CONSIDER: The values should be the same everywhere in the module, so they // could be cached. // (Catch: what happens in a type context without a method def?) Compilation = GetCompilationWithExternAliases(compilation, methodDebugInfo.ExternAliasRecords); // Each expression compile should use a unique compilation // to ensure expression-specific synthesized members can be // added (anonymous types, for instance). Debug.Assert(Compilation != compilation); NamespaceBinder = CreateBinderChain( Compilation, currentFrame.ContainingNamespace, methodDebugInfo.ImportRecordGroups); if (_methodNotType) { _locals = locals; _sourceMethodParametersInOrder = GetSourceMethodParametersInOrder(currentFrame, currentSourceMethod); GetDisplayClassVariables( currentFrame, _locals, inScopeHoistedLocalSlots, _sourceMethodParametersInOrder, out var displayClassVariableNamesInOrder, out _displayClassVariables); Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count); _localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables); } else { _locals = ImmutableArray<LocalSymbol>.Empty; _displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; _localsForBinding = ImmutableArray<LocalSymbol>.Empty; } // Assert that the cheap check for "this" is equivalent to the expensive check for "this". Debug.Assert( (GetThisProxy(_displayClassVariables) != null) == _displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This)); } internal bool TryCompileExpressions( ImmutableArray<CSharpSyntaxNode> syntaxNodes, string typeNameBase, string methodName, DiagnosticBag diagnostics, [NotNullWhen(true)] out CommonPEModuleBuilder? module) { // Create a separate synthesized type for each evaluation method. // (Necessary for VB in particular since the EENamedTypeSymbol.Locations // is tied to the expression syntax in VB.) var synthesizedTypes = syntaxNodes.SelectAsArray( (syntax, i, _) => (NamedTypeSymbol)CreateSynthesizedType(syntax, typeNameBase + i, methodName, ImmutableArray<Alias>.Empty), arg: (object?)null); if (synthesizedTypes.Length == 0) { module = null; return false; } module = CreateModuleBuilder( Compilation, additionalTypes: synthesizedTypes, testData: null, diagnostics: diagnostics); Compilation.Compile( module, emittingPdb: false, diagnostics: diagnostics, filterOpt: null, CancellationToken.None); return !diagnostics.HasAnyErrors(); } internal bool TryCompileExpression( CSharpSyntaxNode syntax, string typeName, string methodName, ImmutableArray<Alias> aliases, CompilationTestData? testData, DiagnosticBag diagnostics, [NotNullWhen(true)] out CommonPEModuleBuilder? module, [NotNullWhen(true)] out EEMethodSymbol? synthesizedMethod) { var synthesizedType = CreateSynthesizedType(syntax, typeName, methodName, aliases); module = CreateModuleBuilder( Compilation, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), testData, diagnostics); Compilation.Compile( module, emittingPdb: false, diagnostics, filterOpt: null, CancellationToken.None); if (diagnostics.HasAnyErrors()) { module = null; synthesizedMethod = null; return false; } synthesizedMethod = GetSynthesizedMethod(synthesizedType); return true; } private EENamedTypeSymbol CreateSynthesizedType( CSharpSyntaxNode syntax, string typeName, string methodName, ImmutableArray<Alias> aliases) { var objectType = Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, syntax, _currentFrame, typeName, methodName, this, (EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { var hasDisplayClassThis = GetThisProxy(_displayClassVariables) != null; var binder = ExtendBinderChain( syntax, aliases, method, NamespaceBinder, hasDisplayClassThis, _methodNotType, out declaredLocals); return (syntax is StatementSyntax statementSyntax) ? BindStatement(binder, statementSyntax, diags, out properties) : BindExpression(binder, (ExpressionSyntax)syntax, diags, out properties); }); return synthesizedType; } internal bool TryCompileAssignment( ExpressionSyntax syntax, string typeName, string methodName, ImmutableArray<Alias> aliases, CompilationTestData? testData, DiagnosticBag diagnostics, [NotNullWhen(true)] out CommonPEModuleBuilder? module, [NotNullWhen(true)] out EEMethodSymbol? synthesizedMethod) { var objectType = Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, syntax, _currentFrame, typeName, methodName, this, (EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { var hasDisplayClassThis = GetThisProxy(_displayClassVariables) != null; var binder = ExtendBinderChain( syntax, aliases, method, NamespaceBinder, hasDisplayClassThis, methodNotType: true, out declaredLocals); properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect); return BindAssignment(binder, syntax, diags); }); module = CreateModuleBuilder( Compilation, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), testData, diagnostics); Compilation.Compile( module, emittingPdb: false, diagnostics, filterOpt: null, CancellationToken.None); if (diagnostics.HasAnyErrors()) { module = null; synthesizedMethod = null; return false; } synthesizedMethod = GetSynthesizedMethod(synthesizedType); return true; } private static EEMethodSymbol GetSynthesizedMethod(EENamedTypeSymbol synthesizedType) => (EEMethodSymbol)synthesizedType.Methods[0]; private static string GetNextMethodName(ArrayBuilder<MethodSymbol> builder) => "<>m" + builder.Count; /// <summary> /// Generate a class containing methods that represent /// the set of arguments and locals at the current scope. /// </summary> internal CommonPEModuleBuilder? CompileGetLocals( string typeName, ArrayBuilder<LocalAndMethod> localBuilder, bool argumentsOnly, ImmutableArray<Alias> aliases, CompilationTestData? testData, DiagnosticBag diagnostics) { var objectType = Compilation.GetSpecialType(SpecialType.System_Object); var allTypeParameters = _currentFrame.GetAllTypeParameters(); var additionalTypes = ArrayBuilder<NamedTypeSymbol>.GetInstance(); EENamedTypeSymbol? typeVariablesType = null; if (!argumentsOnly && allTypeParameters.Length > 0) { // Generate a generic type with matching type parameters. // A null instance of the type will be used to represent the // "Type variables" local. typeVariablesType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, _currentFrame, ExpressionCompilerConstants.TypeVariablesClassName, (m, t) => ImmutableArray.Create<MethodSymbol>(new EEConstructorSymbol(t)), allTypeParameters, (t1, t2) => allTypeParameters.SelectAsArray((tp, i, t) => (TypeParameterSymbol)new SimpleTypeParameterSymbol(t, i, tp.Name), t2)); additionalTypes.Add(typeVariablesType); } var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, _currentFrame, typeName, (m, container) => { var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance(); if (!argumentsOnly) { // Pseudo-variables: $exception, $ReturnValue, etc. if (aliases.Length > 0) { var sourceAssembly = Compilation.SourceAssembly; var typeNameDecoder = new EETypeNameDecoder(Compilation, (PEModuleSymbol)_currentFrame.ContainingModule); foreach (var alias in aliases) { if (alias.IsReturnValueWithoutIndex()) { Debug.Assert(aliases.Count(a => a.Kind == DkmClrAliasKind.ReturnValue) > 1); continue; } var local = PlaceholderLocalSymbol.Create( typeNameDecoder, _currentFrame, sourceAssembly, alias); // Skip pseudo-variables with errors. if (local.HasUseSiteError) { continue; } var methodName = GetNextMethodName(methodBuilder); var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); var aliasMethod = CreateMethod( container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var expression = new BoundLocal(syntax, local, constantValueOpt: null, type: local.Type); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); var flags = local.IsWritableVariable ? DkmClrCompilationResultFlags.None : DkmClrCompilationResultFlags.ReadOnlyResult; localBuilder.Add(MakeLocalAndMethod(local, aliasMethod, flags)); methodBuilder.Add(aliasMethod); } } // "this" for non-static methods that are not display class methods or // display class methods where the display class contains "<>4__this". if (!m.IsStatic && !IsDisplayClassType(m.ContainingType) || GetThisProxy(_displayClassVariables) != null) { var methodName = GetNextMethodName(methodBuilder); var method = GetThisMethod(container, methodName); localBuilder.Add(new CSharpLocalAndMethod("this", "this", method, DkmClrCompilationResultFlags.None)); // Note: writable in dev11. methodBuilder.Add(method); } } var itemsAdded = PooledHashSet<string>.GetInstance(); // Method parameters int parameterIndex = m.IsStatic ? 0 : 1; foreach (var parameter in m.Parameters) { var parameterName = parameter.Name; if (GeneratedNameParser.GetKind(parameterName) == GeneratedNameKind.None && !IsDisplayClassParameter(parameter)) { itemsAdded.Add(parameterName); AppendParameterAndMethod(localBuilder, methodBuilder, parameter, container, parameterIndex); } parameterIndex++; } // In case of iterator or async state machine, the 'm' method has no parameters // but the source method can have parameters to iterate over. if (itemsAdded.Count == 0 && _sourceMethodParametersInOrder.Length != 0) { var localsDictionary = PooledDictionary<string, (LocalSymbol, int)>.GetInstance(); int localIndex = 0; foreach (var local in _localsForBinding) { localsDictionary.Add(local.Name, (local, localIndex)); localIndex++; } foreach (var argumentName in _sourceMethodParametersInOrder) { (LocalSymbol local, int localIndex) localSymbolAndIndex; if (localsDictionary.TryGetValue(argumentName, out localSymbolAndIndex)) { itemsAdded.Add(argumentName); var local = localSymbolAndIndex.local; AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localSymbolAndIndex.localIndex, GetLocalResultFlags(local)); } } localsDictionary.Free(); } if (!argumentsOnly) { // Locals which were not added as parameters or parameters of the source method. int localIndex = 0; foreach (var local in _localsForBinding) { if (!itemsAdded.Contains(local.Name)) { AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local)); } localIndex++; } // "Type variables". if (typeVariablesType is object) { var methodName = GetNextMethodName(methodBuilder); var returnType = typeVariablesType.Construct(allTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>()); var method = GetTypeVariablesMethod(container, methodName, returnType); localBuilder.Add(new CSharpLocalAndMethod( ExpressionCompilerConstants.TypeVariablesLocalName, ExpressionCompilerConstants.TypeVariablesLocalName, method, DkmClrCompilationResultFlags.ReadOnlyResult)); methodBuilder.Add(method); } } itemsAdded.Free(); return methodBuilder.ToImmutableAndFree(); }); additionalTypes.Add(synthesizedType); var module = CreateModuleBuilder( Compilation, additionalTypes.ToImmutableAndFree(), testData, diagnostics); RoslynDebug.AssertNotNull(module); Compilation.Compile( module, emittingPdb: false, diagnostics, filterOpt: null, CancellationToken.None); return diagnostics.HasAnyErrors() ? null : module; } private void AppendLocalAndMethod( ArrayBuilder<LocalAndMethod> localBuilder, ArrayBuilder<MethodSymbol> methodBuilder, LocalSymbol local, EENamedTypeSymbol container, int localIndex, DkmClrCompilationResultFlags resultFlags) { var methodName = GetNextMethodName(methodBuilder); var method = GetLocalMethod(container, methodName, local.Name, localIndex); localBuilder.Add(MakeLocalAndMethod(local, method, resultFlags)); methodBuilder.Add(method); } private void AppendParameterAndMethod( ArrayBuilder<LocalAndMethod> localBuilder, ArrayBuilder<MethodSymbol> methodBuilder, ParameterSymbol parameter, EENamedTypeSymbol container, int parameterIndex) { // Note: The native EE doesn't do this, but if we don't escape keyword identifiers, // the ResultProvider needs to be able to disambiguate cases like "this" and "@this", // which it can't do correctly without semantic information. var name = SyntaxHelpers.EscapeKeywordIdentifiers(parameter.Name); var methodName = GetNextMethodName(methodBuilder); var method = GetParameterMethod(container, methodName, name, parameterIndex); localBuilder.Add(new CSharpLocalAndMethod(name, name, method, DkmClrCompilationResultFlags.None)); methodBuilder.Add(method); } private static LocalAndMethod MakeLocalAndMethod(LocalSymbol local, MethodSymbol method, DkmClrCompilationResultFlags flags) { // Note: The native EE doesn't do this, but if we don't escape keyword identifiers, // the ResultProvider needs to be able to disambiguate cases like "this" and "@this", // which it can't do correctly without semantic information. var escapedName = SyntaxHelpers.EscapeKeywordIdentifiers(local.Name); var displayName = (local as PlaceholderLocalSymbol)?.DisplayName ?? escapedName; return new CSharpLocalAndMethod(escapedName, displayName, method, flags); } private static EEAssemblyBuilder CreateModuleBuilder( CSharpCompilation compilation, ImmutableArray<NamedTypeSymbol> additionalTypes, CompilationTestData? testData, DiagnosticBag diagnostics) { // Each assembly must have a unique name. var emitOptions = new EmitOptions(outputNameOverride: ExpressionCompilerUtilities.GenerateUniqueName()); string? runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics); var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion); return new EEAssemblyBuilder( compilation.SourceAssembly, emitOptions, serializationProperties, additionalTypes, contextType => GetNonDisplayClassContainer(((EENamedTypeSymbol)contextType).SubstitutedSourceType), testData); } internal EEMethodSymbol CreateMethod( EENamedTypeSymbol container, string methodName, CSharpSyntaxNode syntax, GenerateMethodBody generateMethodBody) { return new EEMethodSymbol( container, methodName, syntax.Location, _currentFrame, _locals, _localsForBinding, _displayClassVariables, generateMethodBody); } private EEMethodSymbol GetLocalMethod(EENamedTypeSymbol container, string methodName, string localName, int localIndex) { var syntax = SyntaxFactory.IdentifierName(localName); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var local = method.LocalsForBinding[localIndex]; var expression = new BoundLocal(syntax, local, constantValueOpt: local.GetConstantValue(null, null, new BindingDiagnosticBag(diagnostics)), type: local.Type); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetParameterMethod(EENamedTypeSymbol container, string methodName, string parameterName, int parameterIndex) { var syntax = SyntaxFactory.IdentifierName(parameterName); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var parameter = method.Parameters[parameterIndex]; var expression = new BoundParameter(syntax, parameter); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetThisMethod(EENamedTypeSymbol container, string methodName) { var syntax = SyntaxFactory.ThisExpression(); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var expression = new BoundThisReference(syntax, GetNonDisplayClassContainer(container.SubstitutedSourceType)); properties = default; return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetTypeVariablesMethod(EENamedTypeSymbol container, string methodName, NamedTypeSymbol typeVariablesType) { var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) => { declaredLocals = ImmutableArray<LocalSymbol>.Empty; var type = method.TypeMap.SubstituteNamedType(typeVariablesType); var expression = new BoundObjectCreationExpression(syntax, type.InstanceConstructors[0]); var statement = new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; properties = default; return statement; }); } private static BoundStatement? BindExpression(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics, out ResultProperties resultProperties) { var flags = DkmClrCompilationResultFlags.None; var bindingDiagnostics = new BindingDiagnosticBag(diagnostics); // In addition to C# expressions, the native EE also supports // type names which are bound to a representation of the type // (but not System.Type) that the user can expand to see the // base type. Instead, we only allow valid C# expressions. var expression = IsDeconstruction(syntax) ? binder.BindDeconstruction((AssignmentExpressionSyntax)syntax, bindingDiagnostics, resultIsUsedOverride: true) : binder.BindRValueWithoutTargetType(syntax, bindingDiagnostics); if (diagnostics.HasAnyErrors()) { resultProperties = default; return null; } try { if (MayHaveSideEffectsVisitor.MayHaveSideEffects(expression)) { flags |= DkmClrCompilationResultFlags.PotentialSideEffect; } } catch (BoundTreeVisitor.CancelledByStackGuardException ex) { ex.AddAnError(diagnostics); resultProperties = default; return null; } var expressionType = expression.Type; if (expressionType is null) { expression = binder.CreateReturnConversion( syntax, bindingDiagnostics, expression, RefKind.None, binder.Compilation.GetSpecialType(SpecialType.System_Object)); if (diagnostics.HasAnyErrors()) { resultProperties = default; return null; } } else if (expressionType.SpecialType == SpecialType.System_Void) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; Debug.Assert(expression.ConstantValue == null); resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, isConstant: false); return new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true }; } else if (expressionType.SpecialType == SpecialType.System_Boolean) { flags |= DkmClrCompilationResultFlags.BoolResult; } if (!IsAssignableExpression(binder, expression)) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; } resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, expression.ConstantValue != null); return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; } private static bool IsDeconstruction(ExpressionSyntax syntax) { if (syntax.Kind() != SyntaxKind.SimpleAssignmentExpression) { return false; } var node = (AssignmentExpressionSyntax)syntax; return node.Left.Kind() == SyntaxKind.TupleExpression || node.Left.Kind() == SyntaxKind.DeclarationExpression; } private static BoundStatement BindStatement(Binder binder, StatementSyntax syntax, DiagnosticBag diagnostics, out ResultProperties properties) { properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); return binder.BindStatement(syntax, new BindingDiagnosticBag(diagnostics)); } private static bool IsAssignableExpression(Binder binder, BoundExpression expression) { var result = binder.CheckValueKind(expression.Syntax, expression, Binder.BindValueKind.Assignable, checkingReceiver: false, BindingDiagnosticBag.Discarded); return result; } private static BoundStatement? BindAssignment(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics) { var expression = binder.BindValue(syntax, new BindingDiagnosticBag(diagnostics), Binder.BindValueKind.RValue); if (diagnostics.HasAnyErrors()) { return null; } return new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true }; } private static Binder CreateBinderChain( CSharpCompilation compilation, NamespaceSymbol @namespace, ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups) { var stack = ArrayBuilder<string>.GetInstance(); while (@namespace is object) { stack.Push(@namespace.Name); @namespace = @namespace.ContainingNamespace; } Binder binder = new BuckStopsHereBinder(compilation); var hasImports = !importRecordGroups.IsDefaultOrEmpty; var numImportStringGroups = hasImports ? importRecordGroups.Length : 0; var currentStringGroup = numImportStringGroups - 1; // PERF: We used to call compilation.GetCompilationNamespace on every iteration, // but that involved walking up to the global namespace, which we have to do // anyway. Instead, we'll inline the functionality into our own walk of the // namespace chain. @namespace = compilation.GlobalNamespace; while (stack.Count > 0) { var namespaceName = stack.Pop(); if (namespaceName.Length > 0) { // We're re-getting the namespace, rather than using the one containing // the current frame method, because we want the merged namespace. @namespace = @namespace.GetNestedNamespace(namespaceName); RoslynDebug.AssertNotNull(@namespace); } else { Debug.Assert((object)@namespace == compilation.GlobalNamespace); } if (hasImports) { if (currentStringGroup < 0) { Debug.WriteLine($"No import string group for namespace '{@namespace}'"); break; } var importsBinder = new InContainerBinder(@namespace, binder); Imports imports = BuildImports(compilation, importRecordGroups[currentStringGroup], importsBinder); currentStringGroup--; binder = WithExternAndUsingAliasesBinder.Create(imports.ExternAliases, imports.UsingAliases, WithUsingNamespacesAndTypesBinder.Create(imports.Usings, binder)); } binder = new InContainerBinder(@namespace, binder); } stack.Free(); if (currentStringGroup >= 0) { // CONSIDER: We could lump these into the outermost namespace. It's probably not worthwhile since // the usings are already for the wrong method. Debug.WriteLine($"Found {currentStringGroup + 1} import string groups without corresponding namespaces"); } return binder; } private static CSharpCompilation GetCompilationWithExternAliases(CSharpCompilation compilation, ImmutableArray<ExternAliasRecord> externAliasRecords) { if (externAliasRecords.IsDefaultOrEmpty) { return compilation.Clone(); } var updatedReferences = ArrayBuilder<MetadataReference>.GetInstance(); var assembliesAndModulesBuilder = ArrayBuilder<Symbol>.GetInstance(); foreach (var reference in compilation.References) { updatedReferences.Add(reference); assembliesAndModulesBuilder.Add(compilation.GetAssemblyOrModuleSymbol(reference)!); } Debug.Assert(assembliesAndModulesBuilder.Count == updatedReferences.Count); var assembliesAndModules = assembliesAndModulesBuilder.ToImmutableAndFree(); foreach (var externAliasRecord in externAliasRecords) { var targetAssembly = externAliasRecord.TargetAssembly as AssemblySymbol; int index; if (targetAssembly != null) { index = assembliesAndModules.IndexOf(targetAssembly); } else { index = IndexOfMatchingAssembly((AssemblyIdentity)externAliasRecord.TargetAssembly, assembliesAndModules, compilation.Options.AssemblyIdentityComparer); } if (index < 0) { Debug.WriteLine($"Unable to find corresponding assembly reference for extern alias '{externAliasRecord}'"); continue; } var externAlias = externAliasRecord.Alias; var assemblyReference = updatedReferences[index]; var oldAliases = assemblyReference.Properties.Aliases; var newAliases = oldAliases.IsEmpty ? ImmutableArray.Create(MetadataReferenceProperties.GlobalAlias, externAlias) : oldAliases.Concat(ImmutableArray.Create(externAlias)); // NOTE: Dev12 didn't emit custom debug info about "global", so we don't have // a good way to distinguish between a module aliased with both (e.g.) "X" and // "global" and a module aliased with only "X". As in Dev12, we assume that // "global" is a valid alias to remain at least as permissive as source. // NOTE: In the event that this introduces ambiguities between two assemblies // (e.g. because one was "global" in source and the other was "X"), it should be // possible to disambiguate as long as each assembly has a distinct extern alias, // not necessarily used in source. Debug.Assert(newAliases.Contains(MetadataReferenceProperties.GlobalAlias)); // Replace the value in the map with the updated reference. updatedReferences[index] = assemblyReference.WithAliases(newAliases); } compilation = compilation.WithReferences(updatedReferences); updatedReferences.Free(); return compilation; } private static int IndexOfMatchingAssembly(AssemblyIdentity referenceIdentity, ImmutableArray<Symbol> assembliesAndModules, AssemblyIdentityComparer assemblyIdentityComparer) { for (int i = 0; i < assembliesAndModules.Length; i++) { if (assembliesAndModules[i] is AssemblySymbol assembly && assemblyIdentityComparer.ReferenceMatchesDefinition(referenceIdentity, assembly.Identity)) { return i; } } return -1; } private static Binder ExtendBinderChain( CSharpSyntaxNode syntax, ImmutableArray<Alias> aliases, EEMethodSymbol method, Binder binder, bool hasDisplayClassThis, bool methodNotType, out ImmutableArray<LocalSymbol> declaredLocals) { var substitutedSourceMethod = GetSubstitutedSourceMethod(method.SubstitutedSourceMethod, hasDisplayClassThis); var substitutedSourceType = substitutedSourceMethod.ContainingType; var stack = ArrayBuilder<NamedTypeSymbol>.GetInstance(); for (var type = substitutedSourceType; type is object; type = type.ContainingType) { stack.Add(type); } while (stack.Count > 0) { substitutedSourceType = stack.Pop(); binder = new InContainerBinder(substitutedSourceType, binder); if (substitutedSourceType.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, binder); } } stack.Free(); if (substitutedSourceMethod.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceMethod.TypeArgumentsWithAnnotations, binder); } // Method locals and parameters shadow pseudo-variables. // That is why we place PlaceholderLocalBinder and ExecutableCodeBinder before EEMethodBinder. if (methodNotType) { var typeNameDecoder = new EETypeNameDecoder(binder.Compilation, (PEModuleSymbol)substitutedSourceMethod.ContainingModule); binder = new PlaceholderLocalBinder( syntax, aliases, method, typeNameDecoder, binder); } binder = new EEMethodBinder(method, substitutedSourceMethod, binder); if (methodNotType) { binder = new SimpleLocalScopeBinder(method.LocalsForBinding, binder); } Binder? actualRootBinder = null; SyntaxNode? declaredLocalsScopeDesignator = null; var executableBinder = new ExecutableCodeBinder(syntax, substitutedSourceMethod, binder, (rootBinder, declaredLocalsScopeDesignatorOpt) => { actualRootBinder = rootBinder; declaredLocalsScopeDesignator = declaredLocalsScopeDesignatorOpt; }); // We just need to trigger the process of building the binder map // so that the lambda above was executed. executableBinder.GetBinder(syntax); RoslynDebug.AssertNotNull(actualRootBinder); if (declaredLocalsScopeDesignator != null) { declaredLocals = actualRootBinder.GetDeclaredLocalsForScope(declaredLocalsScopeDesignator); } else { declaredLocals = ImmutableArray<LocalSymbol>.Empty; } return actualRootBinder; } private static Imports BuildImports(CSharpCompilation compilation, ImmutableArray<ImportRecord> importRecords, InContainerBinder binder) { // We make a first pass to extract all of the extern aliases because other imports may depend on them. var externsBuilder = ArrayBuilder<AliasAndExternAliasDirective>.GetInstance(); foreach (var importRecord in importRecords) { if (importRecord.TargetKind != ImportTargetKind.Assembly) { continue; } var alias = importRecord.Alias; RoslynDebug.AssertNotNull(alias); if (!TryParseIdentifierNameSyntax(alias, out var aliasNameSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{alias}'"); continue; } NamespaceSymbol target; compilation.GetExternAliasTarget(aliasNameSyntax.Identifier.ValueText, out target); Debug.Assert(target.IsGlobalNamespace); var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(target, aliasNameSyntax.Identifier, binder.ContainingMemberOrLambda, isExtern: true); externsBuilder.Add(new AliasAndExternAliasDirective(aliasSymbol, externAliasDirective: null, skipInLookup: false)); } var externs = externsBuilder.ToImmutableAndFree(); if (externs.Any()) { // NB: This binder (and corresponding Imports) is only used to bind the other imports. // We'll merge the externs into a final Imports object and return that to be used in // the actual binder chain. binder = new InContainerBinder( binder.Container, WithExternAliasesBinder.Create(externs, binder)); } var usingAliases = ImmutableDictionary.CreateBuilder<string, AliasAndUsingDirective>(); var usingsBuilder = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance(); foreach (var importRecord in importRecords) { switch (importRecord.TargetKind) { case ImportTargetKind.Type: { var typeSymbol = (TypeSymbol?)importRecord.TargetType; RoslynDebug.AssertNotNull(typeSymbol); if (typeSymbol.IsErrorType()) { // Type is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } else if (importRecord.Alias == null && !typeSymbol.IsStatic) { // Only static types can be directly imported. continue; } if (!TryAddImport(importRecord.Alias, typeSymbol, usingsBuilder, usingAliases, binder, importRecord)) { continue; } break; } case ImportTargetKind.Namespace: { var namespaceName = importRecord.TargetString; RoslynDebug.AssertNotNull(namespaceName); if (!SyntaxHelpers.TryParseDottedName(namespaceName, out _)) { // DevDiv #999086: Some previous version of VS apparently generated type aliases as "UA{alias} T{alias-qualified type name}". // Neither Roslyn nor Dev12 parses such imports. However, Roslyn discards them, rather than interpreting them as "UA{alias}" // (which will rarely work and never be correct). Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid target '{importRecord.TargetString}'"); continue; } NamespaceSymbol globalNamespace; var targetAssembly = (AssemblySymbol?)importRecord.TargetAssembly; if (targetAssembly is object) { if (targetAssembly.IsMissing) { Debug.WriteLine($"Import record '{importRecord}' has invalid assembly reference '{targetAssembly.Identity}'"); continue; } globalNamespace = targetAssembly.GlobalNamespace; } else if (importRecord.TargetAssemblyAlias != null) { if (!TryParseIdentifierNameSyntax(importRecord.TargetAssemblyAlias, out var externAliasSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{importRecord.TargetAssemblyAlias}'"); continue; } var aliasSymbol = (AliasSymbol)binder.BindNamespaceAliasSymbol(externAliasSyntax, BindingDiagnosticBag.Discarded); if (aliasSymbol is null) { Debug.WriteLine($"Import record '{importRecord}' requires unknown extern alias '{importRecord.TargetAssemblyAlias}'"); continue; } globalNamespace = (NamespaceSymbol)aliasSymbol.Target; } else { globalNamespace = compilation.GlobalNamespace; } var namespaceSymbol = BindNamespace(namespaceName, globalNamespace); if (namespaceSymbol is null) { // Namespace is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } if (!TryAddImport(importRecord.Alias, namespaceSymbol, usingsBuilder, usingAliases, binder, importRecord)) { continue; } break; } case ImportTargetKind.Assembly: // Handled in first pass (above). break; default: throw ExceptionUtilities.UnexpectedValue(importRecord.TargetKind); } } return Imports.Create(usingAliases.ToImmutableDictionary(), usingsBuilder.ToImmutableAndFree(), externs); } private static NamespaceSymbol? BindNamespace(string namespaceName, NamespaceSymbol globalNamespace) { NamespaceSymbol? namespaceSymbol = globalNamespace; foreach (var name in namespaceName.Split('.')) { var members = namespaceSymbol.GetMembers(name); namespaceSymbol = (members.Length == 1) ? members[0] as NamespaceSymbol : null; if (namespaceSymbol is null) { break; } } return namespaceSymbol; } private static bool TryAddImport( string? alias, NamespaceOrTypeSymbol targetSymbol, ArrayBuilder<NamespaceOrTypeAndUsingDirective> usingsBuilder, ImmutableDictionary<string, AliasAndUsingDirective>.Builder usingAliases, InContainerBinder binder, ImportRecord importRecord) { if (alias == null) { usingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(targetSymbol, usingDirective: null, dependencies: default)); } else { if (!TryParseIdentifierNameSyntax(alias, out var aliasSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid alias '{alias}'"); return false; } var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(targetSymbol, aliasSyntax.Identifier, binder.ContainingMemberOrLambda, isExtern: false); usingAliases.Add(alias, new AliasAndUsingDirective(aliasSymbol, usingDirective: null)); } return true; } private static bool TryParseIdentifierNameSyntax(string name, [NotNullWhen(true)] out IdentifierNameSyntax? syntax) { if (name == MetadataReferenceProperties.GlobalAlias) { syntax = SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); return true; } if (!SyntaxHelpers.TryParseDottedName(name, out var nameSyntax) || nameSyntax.Kind() != SyntaxKind.IdentifierName) { syntax = null; return false; } syntax = (IdentifierNameSyntax)nameSyntax; return true; } internal CommonMessageProvider MessageProvider { get { return Compilation.MessageProvider; } } private static DkmClrCompilationResultFlags GetLocalResultFlags(LocalSymbol local) { // CONSIDER: We might want to prevent the user from modifying pinned locals - // that's pretty dangerous. return local.IsConst ? DkmClrCompilationResultFlags.ReadOnlyResult : DkmClrCompilationResultFlags.None; } /// <summary> /// Generate the set of locals to use for binding. /// </summary> private static ImmutableArray<LocalSymbol> GetLocalsForBinding( ImmutableArray<LocalSymbol> locals, ImmutableArray<string> displayClassVariableNamesInOrder, ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { var builder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var local in locals) { var name = local.Name; if (name == null) { continue; } if (GeneratedNameParser.GetKind(name) != GeneratedNameKind.None) { continue; } // Although Roslyn doesn't name synthesized locals unless they are well-known to EE, // Dev12 did so we need to skip them here. if (GeneratedNameParser.IsSynthesizedLocalName(name)) { continue; } builder.Add(local); } foreach (var variableName in displayClassVariableNamesInOrder) { var variable = displayClassVariables[variableName]; switch (variable.Kind) { case DisplayClassVariableKind.Local: case DisplayClassVariableKind.Parameter: builder.Add(new EEDisplayClassFieldLocalSymbol(variable)); break; } } return builder.ToImmutableAndFree(); } private static ImmutableArray<string> GetSourceMethodParametersInOrder( MethodSymbol method, MethodSymbol? sourceMethod) { var containingType = method.ContainingType; bool isIteratorOrAsyncMethod = IsDisplayClassType(containingType) && GeneratedNameParser.GetKind(containingType.Name) == GeneratedNameKind.StateMachineType; var parameterNamesInOrder = ArrayBuilder<string>.GetInstance(); // For version before .NET 4.5, we cannot find the sourceMethod properly: // The source method coincides with the original method in the case. // Therefore, for iterators and async state machines, we have to get parameters from the containingType. // This does not guarantee the proper order of parameters. if (isIteratorOrAsyncMethod && method == sourceMethod) { Debug.Assert(IsDisplayClassType(containingType)); foreach (var member in containingType.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldName = field.Name; if (GeneratedNameParser.GetKind(fieldName) == GeneratedNameKind.None) { parameterNamesInOrder.Add(fieldName); } } } else { if (sourceMethod is object) { foreach (var p in sourceMethod.Parameters) { parameterNamesInOrder.Add(p.Name); } } } return parameterNamesInOrder.ToImmutableAndFree(); } /// <summary> /// Return a mapping of captured variables (parameters, locals, and /// "this") to locals. The mapping is needed to expose the original /// local identifiers (those from source) in the binder. /// </summary> private static void GetDisplayClassVariables( MethodSymbol method, ImmutableArray<LocalSymbol> locals, ImmutableSortedSet<int> inScopeHoistedLocalSlots, ImmutableArray<string> parameterNamesInOrder, out ImmutableArray<string> displayClassVariableNamesInOrder, out ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { // Calculate the shortest paths from locals to instances of display // classes. There should not be two instances of the same display // class immediately within any particular method. var displayClassInstances = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance(); foreach (var parameter in method.Parameters) { if (GeneratedNameParser.GetKind(parameter.Name) == GeneratedNameKind.TransparentIdentifier || IsDisplayClassParameter(parameter)) { var instance = new DisplayClassInstanceFromParameter(parameter); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } } if (IsDisplayClassType(method.ContainingType) && !method.IsStatic) { // Add "this" display class instance. var instance = new DisplayClassInstanceFromParameter(method.ThisParameter); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } var displayClassTypes = PooledHashSet<TypeSymbol>.GetInstance(); foreach (var instance in displayClassInstances) { displayClassTypes.Add(instance.Instance.Type); } // Find any additional display class instances. GetAdditionalDisplayClassInstances(displayClassTypes, displayClassInstances, startIndex: 0); // Add any display class instances from locals (these will contain any hoisted locals). // Locals are only added after finding all display class instances reachable from // parameters because locals may be null (temporary locals in async state machine // for instance) so we prefer parameters to locals. int startIndex = displayClassInstances.Count; foreach (var local in locals) { var name = local.Name; if (name != null && GeneratedNameParser.GetKind(name) == GeneratedNameKind.DisplayClassLocalOrField) { var localType = local.Type; if (localType is object && displayClassTypes.Add(localType)) { var instance = new DisplayClassInstanceFromLocal((EELocalSymbol)local); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } } } GetAdditionalDisplayClassInstances(displayClassTypes, displayClassInstances, startIndex); displayClassTypes.Free(); if (displayClassInstances.Any()) { var parameterNames = PooledHashSet<string>.GetInstance(); foreach (var name in parameterNamesInOrder) { parameterNames.Add(name); } // The locals are the set of all fields from the display classes. var displayClassVariableNamesInOrderBuilder = ArrayBuilder<string>.GetInstance(); var displayClassVariablesBuilder = PooledDictionary<string, DisplayClassVariable>.GetInstance(); foreach (var instance in displayClassInstances) { GetDisplayClassVariables( displayClassVariableNamesInOrderBuilder, displayClassVariablesBuilder, parameterNames, inScopeHoistedLocalSlots, instance); } displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree(); displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary(); displayClassVariablesBuilder.Free(); parameterNames.Free(); } else { displayClassVariableNamesInOrder = ImmutableArray<string>.Empty; displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; } displayClassInstances.Free(); } private static void GetAdditionalDisplayClassInstances( HashSet<TypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, int startIndex) { // Find any additional display class instances breadth first. for (int i = startIndex; i < displayClassInstances.Count; i++) { GetDisplayClassInstances(displayClassTypes, displayClassInstances, displayClassInstances[i]); } } private static void GetDisplayClassInstances( HashSet<TypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, DisplayClassInstanceAndFields instance) { // Display class instance. The display class fields are variables. foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldType = field.Type; var fieldName = field.Name; TryParseGeneratedName(fieldName, out var fieldKind, out var part); switch (fieldKind) { case GeneratedNameKind.DisplayClassLocalOrField: case GeneratedNameKind.TransparentIdentifier: break; case GeneratedNameKind.AnonymousTypeField: RoslynDebug.AssertNotNull(part); if (GeneratedNameParser.GetKind(part) != GeneratedNameKind.TransparentIdentifier) { continue; } break; case GeneratedNameKind.ThisProxyField: if (GeneratedNameParser.GetKind(fieldType.Name) != GeneratedNameKind.LambdaDisplayClass) { continue; } // Async lambda case. break; default: continue; } Debug.Assert(!field.IsStatic); // A hoisted local that is itself a display class instance. if (displayClassTypes.Add(fieldType)) { var other = instance.FromField(field); displayClassInstances.Add(other); } } } /// <summary> /// Returns true if the parameter is a synthesized parameter representing /// a display class instance (used to pass hoisted symbols to local functions). /// </summary> private static bool IsDisplayClassParameter(ParameterSymbol parameter) { var type = parameter.Type; var result = type.Kind == SymbolKind.NamedType && IsDisplayClassType((NamedTypeSymbol)type); Debug.Assert(!result || parameter.MetadataName == ""); return result; } private static void GetDisplayClassVariables( ArrayBuilder<string> displayClassVariableNamesInOrderBuilder, Dictionary<string, DisplayClassVariable> displayClassVariablesBuilder, HashSet<string> parameterNames, ImmutableSortedSet<int> inScopeHoistedLocalSlots, DisplayClassInstanceAndFields instance) { // Display class instance. The display class fields are variables. foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldName = field.Name; REPARSE: DisplayClassVariableKind variableKind; string variableName; TryParseGeneratedName(fieldName, out var fieldKind, out var part); switch (fieldKind) { case GeneratedNameKind.AnonymousTypeField: RoslynDebug.AssertNotNull(part); Debug.Assert(fieldName == field.Name); // This only happens once. fieldName = part; goto REPARSE; case GeneratedNameKind.TransparentIdentifier: // A transparent identifier (field) in an anonymous type synthesized for a transparent identifier. Debug.Assert(!field.IsStatic); continue; case GeneratedNameKind.DisplayClassLocalOrField: // A local that is itself a display class instance. Debug.Assert(!field.IsStatic); continue; case GeneratedNameKind.HoistedLocalField: RoslynDebug.AssertNotNull(part); // Filter out hoisted locals that are known to be out-of-scope at the current IL offset. // Hoisted locals with invalid indices will be included since more information is better // than less in error scenarios. if (GeneratedNameParser.TryParseSlotIndex(fieldName, out int slotIndex) && !inScopeHoistedLocalSlots.Contains(slotIndex)) { continue; } variableName = part; variableKind = DisplayClassVariableKind.Local; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.ThisProxyField: // A reference to "this". variableName = ""; // Should not be referenced by name. variableKind = DisplayClassVariableKind.This; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.None: // A reference to a parameter or local. variableName = fieldName; variableKind = parameterNames.Contains(variableName) ? DisplayClassVariableKind.Parameter : DisplayClassVariableKind.Local; Debug.Assert(!field.IsStatic); break; default: continue; } if (displayClassVariablesBuilder.ContainsKey(variableName)) { // Only expecting duplicates for async state machine // fields (that should be at the top-level). Debug.Assert(displayClassVariablesBuilder[variableName].DisplayClassFields.Count() == 1); if (!instance.Fields.Any()) { // Prefer parameters over locals. Debug.Assert(instance.Instance is DisplayClassInstanceFromLocal); } else { Debug.Assert(instance.Fields.Count() >= 1); // greater depth Debug.Assert(variableKind == DisplayClassVariableKind.Parameter || variableKind == DisplayClassVariableKind.This); if (variableKind == DisplayClassVariableKind.Parameter && GeneratedNameParser.GetKind(instance.Type.Name) == GeneratedNameKind.LambdaDisplayClass) { displayClassVariablesBuilder[variableName] = instance.ToVariable(variableName, variableKind, field); } } } else if (variableKind != DisplayClassVariableKind.This || GeneratedNameParser.GetKind(instance.Type.ContainingType.Name) != GeneratedNameKind.LambdaDisplayClass) { // In async lambdas, the hoisted "this" field in the state machine type will point to the display class instance, if there is one. // In such cases, we want to add the display class "this" to the map instead (or nothing, if it lacks one). displayClassVariableNamesInOrderBuilder.Add(variableName); displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field)); } } } private static void TryParseGeneratedName(string name, out GeneratedNameKind kind, out string? part) { _ = GeneratedNameParser.TryParseGeneratedName(name, out kind, out int openBracketOffset, out int closeBracketOffset); switch (kind) { case GeneratedNameKind.AnonymousTypeField: case GeneratedNameKind.HoistedLocalField: part = name.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); break; default: part = null; break; } } private static bool IsDisplayClassType(TypeSymbol type) { switch (GeneratedNameParser.GetKind(type.Name)) { case GeneratedNameKind.LambdaDisplayClass: case GeneratedNameKind.StateMachineType: return true; default: return false; } } internal static DisplayClassVariable GetThisProxy(ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { return displayClassVariables.Values.FirstOrDefault(v => v.Kind == DisplayClassVariableKind.This); } private static NamedTypeSymbol GetNonDisplayClassContainer(NamedTypeSymbol type) { // 1) Display class and state machine types are always nested within the types // that use them (so that they can access private members of those types). // 2) The native compiler used to produce nested display classes for nested lambdas, // so we may have to walk out more than one level. while (IsDisplayClassType(type)) { type = type.ContainingType!; } return type; } /// <summary> /// Identifies the method in which binding should occur. /// </summary> /// <param name="candidateSubstitutedSourceMethod"> /// The symbol of the method that is currently on top of the callstack, with /// EE type parameters substituted in place of the original type parameters. /// </param> /// <param name="sourceMethodMustBeInstance"> /// True if "this" is available via a display class in the current context. /// </param> /// <returns> /// If <paramref name="candidateSubstitutedSourceMethod"/> is compiler-generated, /// then we will attempt to determine which user-defined method caused it to be /// generated. For example, if <paramref name="candidateSubstitutedSourceMethod"/> /// is a state machine MoveNext method, then we will try to find the iterator or /// async method for which it was generated. If we are able to find the original /// method, then we will substitute in the EE type parameters. Otherwise, we will /// return <paramref name="candidateSubstitutedSourceMethod"/>. /// </returns> /// <remarks> /// In the event that the original method is overloaded, we may not be able to determine /// which overload actually corresponds to the state machine. In particular, we do not /// have information about the signature of the original method (i.e. number of parameters, /// parameter types and ref-kinds, return type). However, we conjecture that this /// level of uncertainty is acceptable, since parameters are managed by a separate binder /// in the synthesized binder chain and we have enough information to check the other method /// properties that are used during binding (e.g. static-ness, generic arity, type parameter /// constraints). /// </remarks> internal static MethodSymbol GetSubstitutedSourceMethod( MethodSymbol candidateSubstitutedSourceMethod, bool sourceMethodMustBeInstance) { var candidateSubstitutedSourceType = candidateSubstitutedSourceMethod.ContainingType; string? desiredMethodName; if (GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceType.Name, GeneratedNameKind.StateMachineType, out desiredMethodName) || GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LambdaMethod, out desiredMethodName) || GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LocalFunction, out desiredMethodName)) { // We could be in the MoveNext method of an async lambda. string? tempMethodName; if (GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LambdaMethod, out tempMethodName) || GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LocalFunction, out tempMethodName)) { desiredMethodName = tempMethodName; var containing = candidateSubstitutedSourceType.ContainingType; RoslynDebug.AssertNotNull(containing); if (GeneratedNameParser.GetKind(containing.Name) == GeneratedNameKind.LambdaDisplayClass) { candidateSubstitutedSourceType = containing; sourceMethodMustBeInstance = candidateSubstitutedSourceType.MemberNames.Select(GeneratedNameParser.GetKind).Contains(GeneratedNameKind.ThisProxyField); } } var desiredTypeParameters = candidateSubstitutedSourceType.OriginalDefinition.TypeParameters; // Type containing the original iterator, async, or lambda-containing method. var substitutedSourceType = GetNonDisplayClassContainer(candidateSubstitutedSourceType); foreach (var candidateMethod in substitutedSourceType.GetMembers().OfType<MethodSymbol>()) { if (IsViableSourceMethod(candidateMethod, desiredMethodName, desiredTypeParameters, sourceMethodMustBeInstance)) { return desiredTypeParameters.Length == 0 ? candidateMethod : candidateMethod.Construct(candidateSubstitutedSourceType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics); } } Debug.Fail("Why didn't we find a substituted source method for " + candidateSubstitutedSourceMethod + "?"); } return candidateSubstitutedSourceMethod; } private static bool IsViableSourceMethod( MethodSymbol candidateMethod, string desiredMethodName, ImmutableArray<TypeParameterSymbol> desiredTypeParameters, bool desiredMethodMustBeInstance) { return !candidateMethod.IsAbstract && !(desiredMethodMustBeInstance && candidateMethod.IsStatic) && candidateMethod.Name == desiredMethodName && HaveSameConstraints(candidateMethod.TypeParameters, desiredTypeParameters); } private static bool HaveSameConstraints(ImmutableArray<TypeParameterSymbol> candidateTypeParameters, ImmutableArray<TypeParameterSymbol> desiredTypeParameters) { int arity = candidateTypeParameters.Length; if (arity != desiredTypeParameters.Length) { return false; } if (arity == 0) { return true; } var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var candidateTypeMap = new TypeMap(candidateTypeParameters, indexedTypeParameters, allowAlpha: true); var desiredTypeMap = new TypeMap(desiredTypeParameters, indexedTypeParameters, allowAlpha: true); return MemberSignatureComparer.HaveSameConstraints(candidateTypeParameters, candidateTypeMap, desiredTypeParameters, desiredTypeMap); } [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] private readonly struct DisplayClassInstanceAndFields { internal readonly DisplayClassInstance Instance; internal readonly ConsList<FieldSymbol> Fields; internal DisplayClassInstanceAndFields(DisplayClassInstance instance) : this(instance, ConsList<FieldSymbol>.Empty) { Debug.Assert(IsDisplayClassType(instance.Type) || GeneratedNameParser.GetKind(instance.Type.Name) == GeneratedNameKind.AnonymousType); } private DisplayClassInstanceAndFields(DisplayClassInstance instance, ConsList<FieldSymbol> fields) { Instance = instance; Fields = fields; } internal TypeSymbol Type => Fields.Any() ? Fields.Head.Type : Instance.Type; internal int Depth => Fields.Count(); internal DisplayClassInstanceAndFields FromField(FieldSymbol field) { Debug.Assert(IsDisplayClassType(field.Type) || GeneratedNameParser.GetKind(field.Type.Name) == GeneratedNameKind.AnonymousType); return new DisplayClassInstanceAndFields(Instance, Fields.Prepend(field)); } internal DisplayClassVariable ToVariable(string name, DisplayClassVariableKind kind, FieldSymbol field) { return new DisplayClassVariable(name, kind, Instance, Fields.Prepend(field)); } private string GetDebuggerDisplay() { return Instance.GetDebuggerDisplay(Fields); } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/Remote/RemoteServiceConnection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.IO.Pipelines; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Abstracts a connection to a legacy remote service. /// </summary> internal abstract class RemoteServiceConnection : IDisposable { public abstract void Dispose(); public abstract Task RunRemoteAsync(string targetName, Solution? solution, IReadOnlyList<object?> arguments, CancellationToken cancellationToken); public abstract Task<T> RunRemoteAsync<T>(string targetName, Solution? solution, IReadOnlyList<object?> arguments, Func<Stream, CancellationToken, Task<T>>? dataReader, CancellationToken cancellationToken); public Task<T> RunRemoteAsync<T>(string targetName, Solution? solution, IReadOnlyList<object?> arguments, CancellationToken cancellationToken) => RunRemoteAsync<T>(targetName, solution, arguments, dataReader: null, cancellationToken); } /// <summary> /// Abstracts a connection to a service implementing type <typeparamref name="TService"/>. /// </summary> /// <typeparam name="TService">Remote interface type of the service.</typeparam> internal abstract class RemoteServiceConnection<TService> : IDisposable where TService : class { public abstract void Dispose(); // no solution, no callback public abstract ValueTask<bool> TryInvokeAsync( Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Func<TService, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken); // no solution, callback public abstract ValueTask<bool> TryInvokeAsync( Func<TService, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Func<TService, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // solution, no callback public abstract ValueTask<bool> TryInvokeAsync( Solution solution, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Solution solution, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // project, no callback public abstract ValueTask<bool> TryInvokeAsync( Project project, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Project project, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // solution, callback public abstract ValueTask<bool> TryInvokeAsync( Solution solution, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Solution solution, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // project, callback public abstract ValueTask<bool> TryInvokeAsync( Project project, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Project project, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // streaming public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Solution solution, Func<TService, PinnedSolutionInfo, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Project project, Func<TService, PinnedSolutionInfo, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.IO.Pipelines; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Abstracts a connection to a legacy remote service. /// </summary> internal abstract class RemoteServiceConnection : IDisposable { public abstract void Dispose(); public abstract Task RunRemoteAsync(string targetName, Solution? solution, IReadOnlyList<object?> arguments, CancellationToken cancellationToken); public abstract Task<T> RunRemoteAsync<T>(string targetName, Solution? solution, IReadOnlyList<object?> arguments, Func<Stream, CancellationToken, Task<T>>? dataReader, CancellationToken cancellationToken); public Task<T> RunRemoteAsync<T>(string targetName, Solution? solution, IReadOnlyList<object?> arguments, CancellationToken cancellationToken) => RunRemoteAsync<T>(targetName, solution, arguments, dataReader: null, cancellationToken); } /// <summary> /// Abstracts a connection to a service implementing type <typeparamref name="TService"/>. /// </summary> /// <typeparam name="TService">Remote interface type of the service.</typeparam> internal abstract class RemoteServiceConnection<TService> : IDisposable where TService : class { public abstract void Dispose(); // no solution, no callback public abstract ValueTask<bool> TryInvokeAsync( Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Func<TService, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken); // no solution, callback public abstract ValueTask<bool> TryInvokeAsync( Func<TService, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Func<TService, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // solution, no callback public abstract ValueTask<bool> TryInvokeAsync( Solution solution, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Solution solution, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // project, no callback public abstract ValueTask<bool> TryInvokeAsync( Project project, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Project project, Func<TService, PinnedSolutionInfo, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // solution, callback public abstract ValueTask<bool> TryInvokeAsync( Solution solution, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Solution solution, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // project, callback public abstract ValueTask<bool> TryInvokeAsync( Project project, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Project project, Func<TService, PinnedSolutionInfo, RemoteServiceCallbackId, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken); // streaming public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Solution solution, Func<TService, PinnedSolutionInfo, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken); public abstract ValueTask<Optional<TResult>> TryInvokeAsync<TResult>( Project project, Func<TService, PinnedSolutionInfo, PipeWriter, CancellationToken, ValueTask> invocation, Func<PipeReader, CancellationToken, ValueTask<TResult>> reader, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/Shared/Extensions/INamespaceSymbolExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class INamespaceSymbolExtensions { private static readonly ConditionalWeakTable<INamespaceSymbol, List<string>> s_namespaceToNameMap = new(); public static readonly Comparison<INamespaceSymbol> CompareNamespaces = CompareTo; public static readonly IEqualityComparer<INamespaceSymbol> EqualityComparer = new Comparer(); private static List<string> GetNameParts(INamespaceSymbol? namespaceSymbol) { var result = new List<string>(); GetNameParts(namespaceSymbol, result); return result; } private static void GetNameParts(INamespaceSymbol? namespaceSymbol, List<string> result) { if (namespaceSymbol == null || namespaceSymbol.IsGlobalNamespace) { return; } GetNameParts(namespaceSymbol.ContainingNamespace, result); result.Add(namespaceSymbol.Name); } public static int CompareTo(this INamespaceSymbol n1, INamespaceSymbol n2) { var names1 = s_namespaceToNameMap.GetValue(n1, GetNameParts); var names2 = s_namespaceToNameMap.GetValue(n2, GetNameParts); for (var i = 0; i < Math.Min(names1.Count, names2.Count); i++) { var comp = names1[i].CompareTo(names2[i]); if (comp != 0) { return comp; } } return names1.Count - names2.Count; } public static IEnumerable<INamespaceOrTypeSymbol> GetAllNamespacesAndTypes( this INamespaceSymbol namespaceSymbol, CancellationToken cancellationToken) { var stack = new Stack<INamespaceOrTypeSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); if (current is INamespaceSymbol childNamespace) { stack.Push(childNamespace.GetMembers().AsEnumerable()); yield return childNamespace; } else { var child = (INamedTypeSymbol)current; stack.Push(child.GetTypeMembers()); yield return child; } } } public static IEnumerable<INamespaceSymbol> GetAllNamespaces( this INamespaceSymbol namespaceSymbol, CancellationToken cancellationToken) { var stack = new Stack<INamespaceSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); if (current is INamespaceSymbol childNamespace) { stack.Push(childNamespace.GetNamespaceMembers()); yield return childNamespace; } } } public static IEnumerable<INamedTypeSymbol> GetAllTypes( this IEnumerable<INamespaceSymbol> namespaceSymbols, CancellationToken cancellationToken) { return namespaceSymbols.SelectMany(n => n.GetAllTypes(cancellationToken)); } /// <summary> /// Searches the namespace for namespaces with the provided name. /// </summary> public static IEnumerable<INamespaceSymbol> FindNamespaces( this INamespaceSymbol namespaceSymbol, string namespaceName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var stack = new Stack<INamespaceSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); var matchingChildren = current.GetMembers(namespaceName).OfType<INamespaceSymbol>(); foreach (var child in matchingChildren) { yield return child; } stack.Push(current.GetNamespaceMembers()); } } public static bool ContainsAccessibleTypesOrNamespaces( this INamespaceSymbol namespaceSymbol, IAssemblySymbol assembly) { using var namespaceQueue = SharedPools.Default<Queue<INamespaceOrTypeSymbol>>().GetPooledObject(); return ContainsAccessibleTypesOrNamespacesWorker(namespaceSymbol, assembly, namespaceQueue.Object); } public static INamespaceSymbol? GetQualifiedNamespace( this INamespaceSymbol globalNamespace, string namespaceName) { var namespaceSymbol = globalNamespace; foreach (var name in namespaceName.Split('.')) { var members = namespaceSymbol.GetMembers(name); namespaceSymbol = members.Count() == 1 ? members.First() as INamespaceSymbol : null; if (namespaceSymbol is null) { break; } } return namespaceSymbol; } private static bool ContainsAccessibleTypesOrNamespacesWorker( this INamespaceSymbol namespaceSymbol, IAssemblySymbol assembly, Queue<INamespaceOrTypeSymbol> namespaceQueue) { // Note: we only store INamespaceSymbols in here, even though we type it as // INamespaceOrTypeSymbol. This is because when we call GetMembers below we // want it to return an ImmutableArray so we don't incur any costs to iterate // over it. foreach (var constituent in namespaceSymbol.ConstituentNamespaces) { // Assume that any namespace in our own assembly is accessible to us. This saves a // lot of cpu time checking namespaces. if (Equals(constituent.ContainingAssembly, assembly)) { return true; } namespaceQueue.Enqueue(constituent); } while (namespaceQueue.Count > 0) { var ns = namespaceQueue.Dequeue(); // Upcast so we call the 'GetMembers' method that returns an ImmutableArray. var members = ns.GetMembers(); foreach (var namespaceOrType in members) { if (namespaceOrType.Kind == SymbolKind.NamedType) { if (namespaceOrType.IsAccessibleWithin(assembly)) { return true; } } else { namespaceQueue.Enqueue((INamespaceSymbol)namespaceOrType); } } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class INamespaceSymbolExtensions { private static readonly ConditionalWeakTable<INamespaceSymbol, List<string>> s_namespaceToNameMap = new(); public static readonly Comparison<INamespaceSymbol> CompareNamespaces = CompareTo; public static readonly IEqualityComparer<INamespaceSymbol> EqualityComparer = new Comparer(); private static List<string> GetNameParts(INamespaceSymbol? namespaceSymbol) { var result = new List<string>(); GetNameParts(namespaceSymbol, result); return result; } private static void GetNameParts(INamespaceSymbol? namespaceSymbol, List<string> result) { if (namespaceSymbol == null || namespaceSymbol.IsGlobalNamespace) { return; } GetNameParts(namespaceSymbol.ContainingNamespace, result); result.Add(namespaceSymbol.Name); } public static int CompareTo(this INamespaceSymbol n1, INamespaceSymbol n2) { var names1 = s_namespaceToNameMap.GetValue(n1, GetNameParts); var names2 = s_namespaceToNameMap.GetValue(n2, GetNameParts); for (var i = 0; i < Math.Min(names1.Count, names2.Count); i++) { var comp = names1[i].CompareTo(names2[i]); if (comp != 0) { return comp; } } return names1.Count - names2.Count; } public static IEnumerable<INamespaceOrTypeSymbol> GetAllNamespacesAndTypes( this INamespaceSymbol namespaceSymbol, CancellationToken cancellationToken) { var stack = new Stack<INamespaceOrTypeSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); if (current is INamespaceSymbol childNamespace) { stack.Push(childNamespace.GetMembers().AsEnumerable()); yield return childNamespace; } else { var child = (INamedTypeSymbol)current; stack.Push(child.GetTypeMembers()); yield return child; } } } public static IEnumerable<INamespaceSymbol> GetAllNamespaces( this INamespaceSymbol namespaceSymbol, CancellationToken cancellationToken) { var stack = new Stack<INamespaceSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); if (current is INamespaceSymbol childNamespace) { stack.Push(childNamespace.GetNamespaceMembers()); yield return childNamespace; } } } public static IEnumerable<INamedTypeSymbol> GetAllTypes( this IEnumerable<INamespaceSymbol> namespaceSymbols, CancellationToken cancellationToken) { return namespaceSymbols.SelectMany(n => n.GetAllTypes(cancellationToken)); } /// <summary> /// Searches the namespace for namespaces with the provided name. /// </summary> public static IEnumerable<INamespaceSymbol> FindNamespaces( this INamespaceSymbol namespaceSymbol, string namespaceName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var stack = new Stack<INamespaceSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); var matchingChildren = current.GetMembers(namespaceName).OfType<INamespaceSymbol>(); foreach (var child in matchingChildren) { yield return child; } stack.Push(current.GetNamespaceMembers()); } } public static bool ContainsAccessibleTypesOrNamespaces( this INamespaceSymbol namespaceSymbol, IAssemblySymbol assembly) { using var namespaceQueue = SharedPools.Default<Queue<INamespaceOrTypeSymbol>>().GetPooledObject(); return ContainsAccessibleTypesOrNamespacesWorker(namespaceSymbol, assembly, namespaceQueue.Object); } public static INamespaceSymbol? GetQualifiedNamespace( this INamespaceSymbol globalNamespace, string namespaceName) { var namespaceSymbol = globalNamespace; foreach (var name in namespaceName.Split('.')) { var members = namespaceSymbol.GetMembers(name); namespaceSymbol = members.Count() == 1 ? members.First() as INamespaceSymbol : null; if (namespaceSymbol is null) { break; } } return namespaceSymbol; } private static bool ContainsAccessibleTypesOrNamespacesWorker( this INamespaceSymbol namespaceSymbol, IAssemblySymbol assembly, Queue<INamespaceOrTypeSymbol> namespaceQueue) { // Note: we only store INamespaceSymbols in here, even though we type it as // INamespaceOrTypeSymbol. This is because when we call GetMembers below we // want it to return an ImmutableArray so we don't incur any costs to iterate // over it. foreach (var constituent in namespaceSymbol.ConstituentNamespaces) { // Assume that any namespace in our own assembly is accessible to us. This saves a // lot of cpu time checking namespaces. if (Equals(constituent.ContainingAssembly, assembly)) { return true; } namespaceQueue.Enqueue(constituent); } while (namespaceQueue.Count > 0) { var ns = namespaceQueue.Dequeue(); // Upcast so we call the 'GetMembers' method that returns an ImmutableArray. var members = ns.GetMembers(); foreach (var namespaceOrType in members) { if (namespaceOrType.Kind == SymbolKind.NamedType) { if (namespaceOrType.IsAccessibleWithin(assembly)) { return true; } } else { namespaceQueue.Enqueue((INamespaceSymbol)namespaceOrType); } } } return false; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/SolutionChangeAccumulator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// A little helper type to hold onto the <see cref="Solution"/> being updated in a batch, which also /// keeps track of the right <see cref="CodeAnalysis.WorkspaceChangeKind"/> to raise when we are done. /// </summary> internal class SolutionChangeAccumulator { /// <summary> /// The kind that encompasses all the changes we've made. It's null if no changes have been made, /// and <see cref="WorkspaceChangeKind.ProjectChanged"/> or /// <see cref="WorkspaceChangeKind.SolutionChanged"/> if we can't give a more precise type. /// </summary> private WorkspaceChangeKind? _workspaceChangeKind; private readonly List<DocumentId> _documentIdsRemoved = new(); public SolutionChangeAccumulator(Solution startingSolution) => Solution = startingSolution; public Solution Solution { get; private set; } public IEnumerable<DocumentId> DocumentIdsRemoved => _documentIdsRemoved; public bool HasChange => _workspaceChangeKind.HasValue; public WorkspaceChangeKind WorkspaceChangeKind => _workspaceChangeKind!.Value; public ProjectId? WorkspaceChangeProjectId { get; private set; } public DocumentId? WorkspaceChangeDocumentId { get; private set; } public void UpdateSolutionForDocumentAction(Solution newSolution, WorkspaceChangeKind changeKind, IEnumerable<DocumentId> documentIds) { // If the newSolution is the same as the current solution, there's nothing to actually do if (Solution == newSolution) { return; } Solution = newSolution; foreach (var documentId in documentIds) { // If we don't previously have change, this is our new change if (!_workspaceChangeKind.HasValue) { _workspaceChangeKind = changeKind; WorkspaceChangeProjectId = documentId.ProjectId; WorkspaceChangeDocumentId = documentId; } else { // We do have a new change. At this point, the change is spanning multiple documents or projects we // will coalesce accordingly if (documentId.ProjectId == WorkspaceChangeProjectId) { // It's the same project, at least, so project change it is _workspaceChangeKind = WorkspaceChangeKind.ProjectChanged; WorkspaceChangeDocumentId = null; } else { // Multiple projects have changed, so it's a generic solution change. At this point // we can bail from the loop, because this is already our most general case. _workspaceChangeKind = WorkspaceChangeKind.SolutionChanged; WorkspaceChangeProjectId = null; WorkspaceChangeDocumentId = null; break; } } } } /// <summary> /// The same as <see cref="UpdateSolutionForDocumentAction(Solution, WorkspaceChangeKind, IEnumerable{DocumentId})" /> but also records /// the removed documents into <see cref="DocumentIdsRemoved"/>. /// </summary> public void UpdateSolutionForRemovedDocumentAction(Solution solution, WorkspaceChangeKind removeDocumentChangeKind, IEnumerable<DocumentId> documentIdsRemoved) { UpdateSolutionForDocumentAction(solution, removeDocumentChangeKind, documentIdsRemoved); _documentIdsRemoved.AddRange(documentIdsRemoved); } /// <summary> /// Should be called to update the solution if there isn't a specific document change kind that should be /// given to <see cref="UpdateSolutionForDocumentAction"/> /// </summary> public void UpdateSolutionForProjectAction(ProjectId projectId, Solution newSolution) { // If the newSolution is the same as the current solution, there's nothing to actually do if (Solution == newSolution) { return; } Solution = newSolution; // Since we're changing a project, we definitely have no DocumentId anymore WorkspaceChangeDocumentId = null; if (!_workspaceChangeKind.HasValue || WorkspaceChangeProjectId == projectId) { // We can count this as a generic project change _workspaceChangeKind = WorkspaceChangeKind.ProjectChanged; WorkspaceChangeProjectId = projectId; } else { _workspaceChangeKind = WorkspaceChangeKind.SolutionChanged; WorkspaceChangeProjectId = null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// A little helper type to hold onto the <see cref="Solution"/> being updated in a batch, which also /// keeps track of the right <see cref="CodeAnalysis.WorkspaceChangeKind"/> to raise when we are done. /// </summary> internal class SolutionChangeAccumulator { /// <summary> /// The kind that encompasses all the changes we've made. It's null if no changes have been made, /// and <see cref="WorkspaceChangeKind.ProjectChanged"/> or /// <see cref="WorkspaceChangeKind.SolutionChanged"/> if we can't give a more precise type. /// </summary> private WorkspaceChangeKind? _workspaceChangeKind; private readonly List<DocumentId> _documentIdsRemoved = new(); public SolutionChangeAccumulator(Solution startingSolution) => Solution = startingSolution; public Solution Solution { get; private set; } public IEnumerable<DocumentId> DocumentIdsRemoved => _documentIdsRemoved; public bool HasChange => _workspaceChangeKind.HasValue; public WorkspaceChangeKind WorkspaceChangeKind => _workspaceChangeKind!.Value; public ProjectId? WorkspaceChangeProjectId { get; private set; } public DocumentId? WorkspaceChangeDocumentId { get; private set; } public void UpdateSolutionForDocumentAction(Solution newSolution, WorkspaceChangeKind changeKind, IEnumerable<DocumentId> documentIds) { // If the newSolution is the same as the current solution, there's nothing to actually do if (Solution == newSolution) { return; } Solution = newSolution; foreach (var documentId in documentIds) { // If we don't previously have change, this is our new change if (!_workspaceChangeKind.HasValue) { _workspaceChangeKind = changeKind; WorkspaceChangeProjectId = documentId.ProjectId; WorkspaceChangeDocumentId = documentId; } else { // We do have a new change. At this point, the change is spanning multiple documents or projects we // will coalesce accordingly if (documentId.ProjectId == WorkspaceChangeProjectId) { // It's the same project, at least, so project change it is _workspaceChangeKind = WorkspaceChangeKind.ProjectChanged; WorkspaceChangeDocumentId = null; } else { // Multiple projects have changed, so it's a generic solution change. At this point // we can bail from the loop, because this is already our most general case. _workspaceChangeKind = WorkspaceChangeKind.SolutionChanged; WorkspaceChangeProjectId = null; WorkspaceChangeDocumentId = null; break; } } } } /// <summary> /// The same as <see cref="UpdateSolutionForDocumentAction(Solution, WorkspaceChangeKind, IEnumerable{DocumentId})" /> but also records /// the removed documents into <see cref="DocumentIdsRemoved"/>. /// </summary> public void UpdateSolutionForRemovedDocumentAction(Solution solution, WorkspaceChangeKind removeDocumentChangeKind, IEnumerable<DocumentId> documentIdsRemoved) { UpdateSolutionForDocumentAction(solution, removeDocumentChangeKind, documentIdsRemoved); _documentIdsRemoved.AddRange(documentIdsRemoved); } /// <summary> /// Should be called to update the solution if there isn't a specific document change kind that should be /// given to <see cref="UpdateSolutionForDocumentAction"/> /// </summary> public void UpdateSolutionForProjectAction(ProjectId projectId, Solution newSolution) { // If the newSolution is the same as the current solution, there's nothing to actually do if (Solution == newSolution) { return; } Solution = newSolution; // Since we're changing a project, we definitely have no DocumentId anymore WorkspaceChangeDocumentId = null; if (!_workspaceChangeKind.HasValue || WorkspaceChangeProjectId == projectId) { // We can count this as a generic project change _workspaceChangeKind = WorkspaceChangeKind.ProjectChanged; WorkspaceChangeProjectId = projectId; } else { _workspaceChangeKind = WorkspaceChangeKind.SolutionChanged; WorkspaceChangeProjectId = null; } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/Core/Portable/CommandLine/TouchedFileLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; using System.IO; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Used for logging all the paths which are "touched" (used) in any way /// in the process of compilation. /// </summary> internal class TouchedFileLogger { private ConcurrentSet<string> _readFiles; private ConcurrentSet<string> _writtenFiles; public TouchedFileLogger() { _readFiles = new ConcurrentSet<string>(); _writtenFiles = new ConcurrentSet<string>(); } /// <summary> /// Adds a fully-qualified path to the Logger for a read file. /// Semantics are undefined after a call to <see cref="WriteReadPaths(TextWriter)" />. /// </summary> public void AddRead(string path) { if (path == null) throw new ArgumentNullException(path); _readFiles.Add(path); } /// <summary> /// Adds a fully-qualified path to the Logger for a written file. /// Semantics are undefined after a call to <see cref="WriteWrittenPaths(TextWriter)" />. /// </summary> public void AddWritten(string path) { if (path == null) throw new ArgumentNullException(path); _writtenFiles.Add(path); } /// <summary> /// Adds a fully-qualified path to the Logger for a read and written /// file. Semantics are undefined after a call to /// <see cref="WriteWrittenPaths(TextWriter)" />. /// </summary> public void AddReadWritten(string path) { AddRead(path); AddWritten(path); } /// <summary> /// Writes all of the paths the TouchedFileLogger to the given /// TextWriter in upper case. After calling this method the /// logger is in an undefined state. /// </summary> public void WriteReadPaths(TextWriter s) { var temp = new string[_readFiles.Count]; int i = 0; var readFiles = Interlocked.Exchange( ref _readFiles, null!); foreach (var path in readFiles) { temp[i] = path.ToUpperInvariant(); i++; } Array.Sort<string>(temp); foreach (var path in temp) { s.WriteLine(path); } } /// <summary> /// Writes all of the paths the TouchedFileLogger to the given /// TextWriter in upper case. After calling this method the /// logger is in an undefined state. /// </summary> public void WriteWrittenPaths(TextWriter s) { var temp = new string[_writtenFiles.Count]; int i = 0; var writtenFiles = Interlocked.Exchange( ref _writtenFiles, null!); foreach (var path in writtenFiles) { temp[i] = path.ToUpperInvariant(); i++; } Array.Sort<string>(temp); foreach (var path in temp) { s.WriteLine(path); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; using System.IO; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Used for logging all the paths which are "touched" (used) in any way /// in the process of compilation. /// </summary> internal class TouchedFileLogger { private ConcurrentSet<string> _readFiles; private ConcurrentSet<string> _writtenFiles; public TouchedFileLogger() { _readFiles = new ConcurrentSet<string>(); _writtenFiles = new ConcurrentSet<string>(); } /// <summary> /// Adds a fully-qualified path to the Logger for a read file. /// Semantics are undefined after a call to <see cref="WriteReadPaths(TextWriter)" />. /// </summary> public void AddRead(string path) { if (path == null) throw new ArgumentNullException(path); _readFiles.Add(path); } /// <summary> /// Adds a fully-qualified path to the Logger for a written file. /// Semantics are undefined after a call to <see cref="WriteWrittenPaths(TextWriter)" />. /// </summary> public void AddWritten(string path) { if (path == null) throw new ArgumentNullException(path); _writtenFiles.Add(path); } /// <summary> /// Adds a fully-qualified path to the Logger for a read and written /// file. Semantics are undefined after a call to /// <see cref="WriteWrittenPaths(TextWriter)" />. /// </summary> public void AddReadWritten(string path) { AddRead(path); AddWritten(path); } /// <summary> /// Writes all of the paths the TouchedFileLogger to the given /// TextWriter in upper case. After calling this method the /// logger is in an undefined state. /// </summary> public void WriteReadPaths(TextWriter s) { var temp = new string[_readFiles.Count]; int i = 0; var readFiles = Interlocked.Exchange( ref _readFiles, null!); foreach (var path in readFiles) { temp[i] = path.ToUpperInvariant(); i++; } Array.Sort<string>(temp); foreach (var path in temp) { s.WriteLine(path); } } /// <summary> /// Writes all of the paths the TouchedFileLogger to the given /// TextWriter in upper case. After calling this method the /// logger is in an undefined state. /// </summary> public void WriteWrittenPaths(TextWriter s) { var temp = new string[_writtenFiles.Count]; int i = 0; var writtenFiles = Interlocked.Exchange( ref _writtenFiles, null!); foreach (var path in writtenFiles) { temp[i] = path.ToUpperInvariant(); i++; } Array.Sort<string>(temp); foreach (var path in temp) { s.WriteLine(path); } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/ExpressionEvaluator/Core/Test/FunctionResolver/FunctionResolverTestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Text; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { public abstract class FunctionResolverTestBase : CSharpTestBase { internal static void Resolve(Process process, Resolver resolver, RequestSignature signature, string[] expectedSignatures) { var request = new Request(null, signature); resolver.EnableResolution(process, request); VerifySignatures(request, expectedSignatures); } internal static void VerifySignatures(Request request, params string[] expectedSignatures) { var actualSignatures = request.GetResolvedAddresses().Select(a => GetMethodSignature(a.Module, a.Token)); AssertEx.Equal(expectedSignatures, actualSignatures); } private static string GetMethodSignature(Module module, int token) { var reader = module.GetMetadataReader(); return GetMethodSignature(reader, MetadataTokens.MethodDefinitionHandle(token)); } private static string GetMethodSignature(MetadataReader reader, MethodDefinitionHandle handle) { var methodDef = reader.GetMethodDefinition(handle); var builder = new StringBuilder(); var typeDef = reader.GetTypeDefinition(methodDef.GetDeclaringType()); var allTypeParameters = typeDef.GetGenericParameters(); AppendTypeName(builder, reader, typeDef); builder.Append('.'); builder.Append(reader.GetString(methodDef.Name)); var methodTypeParameters = methodDef.GetGenericParameters(); AppendTypeParameters(builder, DecodeTypeParameters(reader, offset: 0, typeParameters: methodTypeParameters)); var decoder = new MetadataDecoder( reader, GetTypeParameterNames(reader, allTypeParameters), 0, GetTypeParameterNames(reader, methodTypeParameters)); try { AppendParameters(builder, decoder.DecodeParameters(methodDef)); } catch (NotSupportedException) { builder.Append("([notsupported])"); } return builder.ToString(); } private static ImmutableArray<string> GetTypeParameterNames(MetadataReader reader, GenericParameterHandleCollection handles) { return ImmutableArray.CreateRange(handles.Select(h => reader.GetString(reader.GetGenericParameter(h).Name))); } private static void AppendTypeName(StringBuilder builder, MetadataReader reader, TypeDefinition typeDef) { var declaringTypeHandle = typeDef.GetDeclaringType(); int declaringTypeArity; if (declaringTypeHandle.IsNil) { declaringTypeArity = 0; var namespaceName = reader.GetString(typeDef.Namespace); if (!string.IsNullOrEmpty(namespaceName)) { builder.Append(namespaceName); builder.Append('.'); } } else { var declaringType = reader.GetTypeDefinition(declaringTypeHandle); declaringTypeArity = declaringType.GetGenericParameters().Count; AppendTypeName(builder, reader, declaringType); builder.Append('.'); } var typeName = reader.GetString(typeDef.Name); int index = typeName.IndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } builder.Append(typeName); AppendTypeParameters(builder, DecodeTypeParameters(reader, declaringTypeArity, typeDef.GetGenericParameters())); } private static void AppendTypeParameters(StringBuilder builder, ImmutableArray<string> typeParameters) { if (typeParameters.Length > 0) { builder.Append('<'); AppendCommaSeparatedList(builder, typeParameters, (b, t) => b.Append(t)); builder.Append('>'); } } private static void AppendParameters(StringBuilder builder, ImmutableArray<ParameterSignature> parameters) { builder.Append('('); AppendCommaSeparatedList(builder, parameters, AppendParameter); builder.Append(')'); } private static void AppendParameter(StringBuilder builder, ParameterSignature signature) { if (signature.IsByRef) { builder.Append("ref "); } AppendType(builder, signature.Type); } private static void AppendType(StringBuilder builder, TypeSignature signature) { switch (signature.Kind) { case TypeSignatureKind.GenericType: { var genericName = (GenericTypeSignature)signature; AppendType(builder, genericName.QualifiedName); AppendTypeArguments(builder, genericName.TypeArguments); } break; case TypeSignatureKind.QualifiedType: { var qualifiedName = (QualifiedTypeSignature)signature; var qualifier = qualifiedName.Qualifier; if (qualifier != null) { AppendType(builder, qualifier); builder.Append('.'); } builder.Append(qualifiedName.Name); } break; case TypeSignatureKind.ArrayType: { var arrayType = (ArrayTypeSignature)signature; AppendType(builder, arrayType.ElementType); builder.Append('['); builder.Append(',', arrayType.Rank - 1); builder.Append(']'); } break; case TypeSignatureKind.PointerType: AppendType(builder, ((PointerTypeSignature)signature).PointedAtType); builder.Append('*'); break; default: throw new System.NotImplementedException(); } } private static void AppendTypeArguments(StringBuilder builder, ImmutableArray<TypeSignature> typeArguments) { if (typeArguments.Length > 0) { builder.Append('<'); AppendCommaSeparatedList(builder, typeArguments, AppendType); builder.Append('>'); } } private static void AppendCommaSeparatedList<T>(StringBuilder builder, ImmutableArray<T> items, Action<StringBuilder, T> appendItem) { bool any = false; foreach (var item in items) { if (any) { builder.Append(", "); } appendItem(builder, item); any = true; } } private static ImmutableArray<string> DecodeTypeParameters(MetadataReader reader, int offset, GenericParameterHandleCollection typeParameters) { int arity = typeParameters.Count - offset; Debug.Assert(arity >= 0); if (arity == 0) { return ImmutableArray<string>.Empty; } var builder = ImmutableArray.CreateBuilder<string>(arity); for (int i = 0; i < arity; i++) { var handle = typeParameters[offset + i]; var typeParameter = reader.GetGenericParameter(handle); builder.Add(reader.GetString(typeParameter.Name)); } return builder.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Text; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { public abstract class FunctionResolverTestBase : CSharpTestBase { internal static void Resolve(Process process, Resolver resolver, RequestSignature signature, string[] expectedSignatures) { var request = new Request(null, signature); resolver.EnableResolution(process, request); VerifySignatures(request, expectedSignatures); } internal static void VerifySignatures(Request request, params string[] expectedSignatures) { var actualSignatures = request.GetResolvedAddresses().Select(a => GetMethodSignature(a.Module, a.Token)); AssertEx.Equal(expectedSignatures, actualSignatures); } private static string GetMethodSignature(Module module, int token) { var reader = module.GetMetadataReader(); return GetMethodSignature(reader, MetadataTokens.MethodDefinitionHandle(token)); } private static string GetMethodSignature(MetadataReader reader, MethodDefinitionHandle handle) { var methodDef = reader.GetMethodDefinition(handle); var builder = new StringBuilder(); var typeDef = reader.GetTypeDefinition(methodDef.GetDeclaringType()); var allTypeParameters = typeDef.GetGenericParameters(); AppendTypeName(builder, reader, typeDef); builder.Append('.'); builder.Append(reader.GetString(methodDef.Name)); var methodTypeParameters = methodDef.GetGenericParameters(); AppendTypeParameters(builder, DecodeTypeParameters(reader, offset: 0, typeParameters: methodTypeParameters)); var decoder = new MetadataDecoder( reader, GetTypeParameterNames(reader, allTypeParameters), 0, GetTypeParameterNames(reader, methodTypeParameters)); try { AppendParameters(builder, decoder.DecodeParameters(methodDef)); } catch (NotSupportedException) { builder.Append("([notsupported])"); } return builder.ToString(); } private static ImmutableArray<string> GetTypeParameterNames(MetadataReader reader, GenericParameterHandleCollection handles) { return ImmutableArray.CreateRange(handles.Select(h => reader.GetString(reader.GetGenericParameter(h).Name))); } private static void AppendTypeName(StringBuilder builder, MetadataReader reader, TypeDefinition typeDef) { var declaringTypeHandle = typeDef.GetDeclaringType(); int declaringTypeArity; if (declaringTypeHandle.IsNil) { declaringTypeArity = 0; var namespaceName = reader.GetString(typeDef.Namespace); if (!string.IsNullOrEmpty(namespaceName)) { builder.Append(namespaceName); builder.Append('.'); } } else { var declaringType = reader.GetTypeDefinition(declaringTypeHandle); declaringTypeArity = declaringType.GetGenericParameters().Count; AppendTypeName(builder, reader, declaringType); builder.Append('.'); } var typeName = reader.GetString(typeDef.Name); int index = typeName.IndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } builder.Append(typeName); AppendTypeParameters(builder, DecodeTypeParameters(reader, declaringTypeArity, typeDef.GetGenericParameters())); } private static void AppendTypeParameters(StringBuilder builder, ImmutableArray<string> typeParameters) { if (typeParameters.Length > 0) { builder.Append('<'); AppendCommaSeparatedList(builder, typeParameters, (b, t) => b.Append(t)); builder.Append('>'); } } private static void AppendParameters(StringBuilder builder, ImmutableArray<ParameterSignature> parameters) { builder.Append('('); AppendCommaSeparatedList(builder, parameters, AppendParameter); builder.Append(')'); } private static void AppendParameter(StringBuilder builder, ParameterSignature signature) { if (signature.IsByRef) { builder.Append("ref "); } AppendType(builder, signature.Type); } private static void AppendType(StringBuilder builder, TypeSignature signature) { switch (signature.Kind) { case TypeSignatureKind.GenericType: { var genericName = (GenericTypeSignature)signature; AppendType(builder, genericName.QualifiedName); AppendTypeArguments(builder, genericName.TypeArguments); } break; case TypeSignatureKind.QualifiedType: { var qualifiedName = (QualifiedTypeSignature)signature; var qualifier = qualifiedName.Qualifier; if (qualifier != null) { AppendType(builder, qualifier); builder.Append('.'); } builder.Append(qualifiedName.Name); } break; case TypeSignatureKind.ArrayType: { var arrayType = (ArrayTypeSignature)signature; AppendType(builder, arrayType.ElementType); builder.Append('['); builder.Append(',', arrayType.Rank - 1); builder.Append(']'); } break; case TypeSignatureKind.PointerType: AppendType(builder, ((PointerTypeSignature)signature).PointedAtType); builder.Append('*'); break; default: throw new System.NotImplementedException(); } } private static void AppendTypeArguments(StringBuilder builder, ImmutableArray<TypeSignature> typeArguments) { if (typeArguments.Length > 0) { builder.Append('<'); AppendCommaSeparatedList(builder, typeArguments, AppendType); builder.Append('>'); } } private static void AppendCommaSeparatedList<T>(StringBuilder builder, ImmutableArray<T> items, Action<StringBuilder, T> appendItem) { bool any = false; foreach (var item in items) { if (any) { builder.Append(", "); } appendItem(builder, item); any = true; } } private static ImmutableArray<string> DecodeTypeParameters(MetadataReader reader, int offset, GenericParameterHandleCollection typeParameters) { int arity = typeParameters.Count - offset; Debug.Assert(arity >= 0); if (arity == 0) { return ImmutableArray<string>.Empty; } var builder = ImmutableArray.CreateBuilder<string>(arity); for (int i = 0; i < arity; i++) { var handle = typeParameters[offset + i]; var typeParameter = reader.GetGenericParameter(handle); builder.Add(reader.GetString(typeParameter.Name)); } return builder.ToImmutable(); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/CSharpTest/MakeMemberStatic/MakeMemberStaticTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.MakeMemberStatic; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeMemberStatic { using VerifyCS = CSharpCodeFixVerifier< EmptyDiagnosticAnalyzer, CSharpMakeMemberStaticCodeFixProvider>; public class MakeMemberStaticTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMemberStatic)] public async Task TestField() { await VerifyCS.VerifyCodeFixAsync( @" public static class Foo { int {|CS0708:i|}; }", @" public static class Foo { static int i; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMemberStatic)] [WorkItem(54202, "https://github.com/dotnet/roslyn/issues/54202")] public async Task TestTrivia() { await VerifyCS.VerifyCodeFixAsync( @" public static class Foo { // comment readonly int {|CS0708:i|}; }", @" public static class Foo { // comment static readonly int i; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMemberStatic)] public async Task TestMethod() { await VerifyCS.VerifyCodeFixAsync( @" public static class Foo { void {|CS0708:M|}() { } }", @" public static class Foo { static void M() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMemberStatic)] public async Task TestProperty() { await VerifyCS.VerifyCodeFixAsync( @" public static class Foo { object {|CS0708:P|} { get; set; } }", @" public static class Foo { static object P { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMemberStatic)] public async Task TestEventField() { await VerifyCS.VerifyCodeFixAsync( @" public static class Foo { event System.Action {|CS0708:E|}; }", @" public static class Foo { static event System.Action E; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMemberStatic)] public async Task FixAll() { await VerifyCS.VerifyCodeFixAsync( @"namespace NS { public static class Foo { int {|CS0708:i|}; void {|CS0708:M|}() { } object {|CS0708:P|} { get; set; } event System.Action {|CS0708:E|}; } }", @"namespace NS { public static class Foo { static int i; static void M() { } static object P { get; set; } static event System.Action E; } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.MakeMemberStatic; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeMemberStatic { using VerifyCS = CSharpCodeFixVerifier< EmptyDiagnosticAnalyzer, CSharpMakeMemberStaticCodeFixProvider>; public class MakeMemberStaticTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMemberStatic)] public async Task TestField() { await VerifyCS.VerifyCodeFixAsync( @" public static class Foo { int {|CS0708:i|}; }", @" public static class Foo { static int i; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMemberStatic)] [WorkItem(54202, "https://github.com/dotnet/roslyn/issues/54202")] public async Task TestTrivia() { await VerifyCS.VerifyCodeFixAsync( @" public static class Foo { // comment readonly int {|CS0708:i|}; }", @" public static class Foo { // comment static readonly int i; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMemberStatic)] public async Task TestMethod() { await VerifyCS.VerifyCodeFixAsync( @" public static class Foo { void {|CS0708:M|}() { } }", @" public static class Foo { static void M() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMemberStatic)] public async Task TestProperty() { await VerifyCS.VerifyCodeFixAsync( @" public static class Foo { object {|CS0708:P|} { get; set; } }", @" public static class Foo { static object P { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMemberStatic)] public async Task TestEventField() { await VerifyCS.VerifyCodeFixAsync( @" public static class Foo { event System.Action {|CS0708:E|}; }", @" public static class Foo { static event System.Action E; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMemberStatic)] public async Task FixAll() { await VerifyCS.VerifyCodeFixAsync( @"namespace NS { public static class Foo { int {|CS0708:i|}; void {|CS0708:M|}() { } object {|CS0708:P|} { get; set; } event System.Action {|CS0708:E|}; } }", @"namespace NS { public static class Foo { static int i; static void M() { } static object P { get; set; } static event System.Action E; } }"); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.zh-Hant.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../WorkspaceExtensionsResources.resx"> <body> <trans-unit id="Compilation_is_required_to_accomplish_the_task_but_is_not_supported_by_project_0"> <source>Compilation is required to accomplish the task but is not supported by project {0}.</source> <target state="translated">必須編譯才能完成工作,但專案 {0} 並不支援。</target> <note /> </trans-unit> <trans-unit id="Fix_all_0"> <source>Fix all '{0}'</source> <target state="translated">修正所有 '{0}'</target> <note /> </trans-unit> <trans-unit id="Fix_all_0_in_1"> <source>Fix all '{0}' in '{1}'</source> <target state="translated">修正 '{1}' 中的所有 '{0}'</target> <note /> </trans-unit> <trans-unit id="Fix_all_0_in_Solution"> <source>Fix all '{0}' in Solution</source> <target state="translated">修正方案中的所有 '{0}'</target> <note /> </trans-unit> <trans-unit id="Project_of_ID_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_solution"> <source>Project of ID {0} is required to accomplish the task but is not available from the solution</source> <target state="translated">完成工作需要識別碼為 {0} 的專案,但是無法從解決方案取得</target> <note /> </trans-unit> <trans-unit id="Supplied_diagnostic_cannot_be_null"> <source>Supplied diagnostic cannot be null.</source> <target state="translated">提供的診斷不可為 null。</target> <note /> </trans-unit> <trans-unit id="SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0"> <source>Syntax tree is required to accomplish the task but is not supported by document {0}.</source> <target state="translated">需要語法樹狀結構才能完成工作,但文件 {0} 並不支援。</target> <note /> </trans-unit> <trans-unit id="The_solution_does_not_contain_the_specified_document"> <source>The solution does not contain the specified document.</source> <target state="translated">此方案不包含指定的文件。</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Declaration_changes_scope_and_may_change_meaning"> <source>Warning: Declaration changes scope and may change meaning.</source> <target state="translated">警告: 宣告會變更範圍,且可能會變更意義。</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../WorkspaceExtensionsResources.resx"> <body> <trans-unit id="Compilation_is_required_to_accomplish_the_task_but_is_not_supported_by_project_0"> <source>Compilation is required to accomplish the task but is not supported by project {0}.</source> <target state="translated">必須編譯才能完成工作,但專案 {0} 並不支援。</target> <note /> </trans-unit> <trans-unit id="Fix_all_0"> <source>Fix all '{0}'</source> <target state="translated">修正所有 '{0}'</target> <note /> </trans-unit> <trans-unit id="Fix_all_0_in_1"> <source>Fix all '{0}' in '{1}'</source> <target state="translated">修正 '{1}' 中的所有 '{0}'</target> <note /> </trans-unit> <trans-unit id="Fix_all_0_in_Solution"> <source>Fix all '{0}' in Solution</source> <target state="translated">修正方案中的所有 '{0}'</target> <note /> </trans-unit> <trans-unit id="Project_of_ID_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_solution"> <source>Project of ID {0} is required to accomplish the task but is not available from the solution</source> <target state="translated">完成工作需要識別碼為 {0} 的專案,但是無法從解決方案取得</target> <note /> </trans-unit> <trans-unit id="Supplied_diagnostic_cannot_be_null"> <source>Supplied diagnostic cannot be null.</source> <target state="translated">提供的診斷不可為 null。</target> <note /> </trans-unit> <trans-unit id="SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0"> <source>Syntax tree is required to accomplish the task but is not supported by document {0}.</source> <target state="translated">需要語法樹狀結構才能完成工作,但文件 {0} 並不支援。</target> <note /> </trans-unit> <trans-unit id="The_solution_does_not_contain_the_specified_document"> <source>The solution does not contain the specified document.</source> <target state="translated">此方案不包含指定的文件。</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Declaration_changes_scope_and_may_change_meaning"> <source>Warning: Declaration changes scope and may change meaning.</source> <target state="translated">警告: 宣告會變更範圍,且可能會變更意義。</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationDestructorSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationDestructorSymbol : CodeGenerationMethodSymbol { public CodeGenerationDestructorSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes) : base(containingType, attributes, Accessibility.NotApplicable, default, returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: string.Empty, typeParameters: ImmutableArray<ITypeParameterSymbol>.Empty, parameters: ImmutableArray<IParameterSymbol>.Empty, returnTypeAttributes: ImmutableArray<AttributeData>.Empty) { } public override MethodKind MethodKind => MethodKind.Destructor; protected override CodeGenerationSymbol Clone() { var result = new CodeGenerationDestructorSymbol(this.ContainingType, this.GetAttributes()); CodeGenerationDestructorInfo.Attach(result, CodeGenerationDestructorInfo.GetTypeName(this), CodeGenerationDestructorInfo.GetStatements(this)); return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationDestructorSymbol : CodeGenerationMethodSymbol { public CodeGenerationDestructorSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes) : base(containingType, attributes, Accessibility.NotApplicable, default, returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: string.Empty, typeParameters: ImmutableArray<ITypeParameterSymbol>.Empty, parameters: ImmutableArray<IParameterSymbol>.Empty, returnTypeAttributes: ImmutableArray<AttributeData>.Empty) { } public override MethodKind MethodKind => MethodKind.Destructor; protected override CodeGenerationSymbol Clone() { var result = new CodeGenerationDestructorSymbol(this.ContainingType, this.GetAttributes()); CodeGenerationDestructorInfo.Attach(result, CodeGenerationDestructorInfo.GetTypeName(this), CodeGenerationDestructorInfo.GetStatements(this)); return result; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/Wrapping/SeparatedSyntaxList/WrappingStyle.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Wrapping.SeparatedSyntaxList { internal enum WrappingStyle { /// <summary> /// Wraps first item. Subsequent items, if wrapped, will be aligned with that first item: /// MethodName( /// int a, int b, int c, int d, int e, /// int f, int g, int h, int i, int j) /// </summary> WrapFirst_IndentRest, /// <summary> /// Unwraps first item. Subsequent items, if wrapped, will be aligned with that first item: /// MethodName(int a, int b, int c, int d, int e, /// int f, int g, int h, int i, int j) /// </summary> UnwrapFirst_AlignRest, /// <summary> /// Unwraps first item. Subsequent items, if wrapped, will be indented: /// MethodName(int a, int b, int c, int d, int e, /// int f, int g, int h, int i, int j) /// </summary> UnwrapFirst_IndentRest, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Wrapping.SeparatedSyntaxList { internal enum WrappingStyle { /// <summary> /// Wraps first item. Subsequent items, if wrapped, will be aligned with that first item: /// MethodName( /// int a, int b, int c, int d, int e, /// int f, int g, int h, int i, int j) /// </summary> WrapFirst_IndentRest, /// <summary> /// Unwraps first item. Subsequent items, if wrapped, will be aligned with that first item: /// MethodName(int a, int b, int c, int d, int e, /// int f, int g, int h, int i, int j) /// </summary> UnwrapFirst_AlignRest, /// <summary> /// Unwraps first item. Subsequent items, if wrapped, will be indented: /// MethodName(int a, int b, int c, int d, int e, /// int f, int g, int h, int i, int j) /// </summary> UnwrapFirst_IndentRest, } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Test/Emit/Emit/DynamicAnalysis/DynamicAnalysisResourceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.DynamicAnalysis.UnitTests { public class DynamicAnalysisResourceTests : CSharpTestBase { const string InstrumentationHelperSource = @" namespace Microsoft.CodeAnalysis.Runtime { public static class Instrumentation { public static bool[] CreatePayload(System.Guid mvid, int methodToken, int fileIndex, ref bool[] payload, int payloadLength) { return payload; } public static bool[] CreatePayload(System.Guid mvid, int methodToken, int[] fileIndices, ref bool[] payload, int payloadLength) { return payload; } public static void FlushPayload() { } } } "; const string ExampleSource = @" using System; public class C { public static void Main() { Console.WriteLine(123); Console.WriteLine(123); } public static int Fred => 3; public static int Barney(int x) => x; public static int Wilma { get { return 12; } set { } } public static int Betty { get; } public static int Pebbles { get; set; } } "; [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)] public void TestSpansPresentInResource() { var c = CreateCompilation(Parse(ExampleSource + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); VerifyDocuments(reader, reader.Documents, @"'C:\myproject\doc1.cs' 44-3F-7C-A1-EF-CA-A8-16-40-D2-09-4F-3E-52-7C-44-8D-22-C8-02 (SHA1)"); Assert.Equal(13, reader.Methods.Length); string[] sourceLines = ExampleSource.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, // Main new SpanResult(5, 4, 9, 5, "public static void Main()"), new SpanResult(7, 8, 7, 31, "Console.WriteLine(123)"), new SpanResult(8, 8, 8, 31, "Console.WriteLine(123)")); VerifySpans(reader, reader.Methods[1], sourceLines, // Fred get new SpanResult(11, 4, 11, 32, "public static int Fred => 3"), new SpanResult(11, 30, 11, 31, "3")); VerifySpans(reader, reader.Methods[2], sourceLines, // Barney new SpanResult(13, 4, 13, 41, "public static int Barney(int x) => x"), new SpanResult(13, 39, 13, 40, "x")); VerifySpans(reader, reader.Methods[3], sourceLines, // Wilma get new SpanResult(17, 8, 17, 26, "get { return 12; }"), new SpanResult(17, 14, 17, 24, "return 12")); VerifySpans(reader, reader.Methods[4], sourceLines, // Wilma set new SpanResult(18, 8, 18, 15, "set { }")); VerifySpans(reader, reader.Methods[5], sourceLines, // Betty get new SpanResult(21, 4, 21, 36, "public static int Betty { get; }"), new SpanResult(21, 30, 21, 34, "get")); VerifySpans(reader, reader.Methods[6], sourceLines, // Pebbles get new SpanResult(23, 4, 23, 43, "public static int Pebbles { get; set; }"), new SpanResult(23, 32, 23, 36, "get")); VerifySpans(reader, reader.Methods[7], sourceLines, // Pebbles set new SpanResult(23, 4, 23, 43, "public static int Pebbles { get; set; }"), new SpanResult(23, 37, 23, 41, "set")); VerifySpans(reader, reader.Methods[8]); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)] public void ResourceStatementKinds() { string source = @" using System; public class C { public static void Main() { int z = 11; int x = z + 10; switch (z) { case 1: break; case 2: break; case 3: break; default: break; } if (x > 10) { x++; } else { x--; } for (int y = 0; y < 50; y++) { if (y < 30) { x++; continue; } else break; } int[] a = new int[] { 1, 2, 3, 4 }; foreach (int i in a) { x++; } while (x < 100) { x++; } try { x++; if (x > 10) { throw new System.Exception(); } x++; } catch (System.Exception e) { x++; } finally { x++; } lock (new object()) { ; } Console.WriteLine(x); try { using ((System.IDisposable)new object()) { ; } } catch (System.Exception e) { } return; } } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); VerifyDocuments(reader, reader.Documents, @"'C:\myproject\doc1.cs' 6A-DC-C0-8A-16-CB-7C-A5-99-8B-2E-0C-3C-81-69-2C-B2-10-EE-F1 (SHA1)"); Assert.Equal(6, reader.Methods.Length); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 89, 5, "public static void Main()"), new SpanResult(7, 8, 7, 19, "int z = 11"), new SpanResult(8, 8, 8, 23, "int x = z + 10"), new SpanResult(12, 16, 12, 22, "break"), new SpanResult(14, 16, 14, 22, "break"), new SpanResult(16, 16, 16, 22, "break"), new SpanResult(18, 16, 18, 22, "break"), new SpanResult(9, 16, 9, 17, "z"), new SpanResult(23, 12, 23, 16, "x++"), new SpanResult(27, 12, 27, 16, "x--"), new SpanResult(21, 12, 21, 18, "x > 10"), new SpanResult(30, 17, 30, 22, "y = 0"), new SpanResult(30, 32, 30, 35, "y++"), new SpanResult(34, 16, 34, 20, "x++"), new SpanResult(35, 16, 35, 25, "continue"), new SpanResult(38, 16, 38, 22, "break"), new SpanResult(32, 16, 32, 22, "y < 30"), new SpanResult(41, 8, 41, 43, "int[] a = new int[] { 1, 2, 3, 4 }"), new SpanResult(44, 12, 44, 16, "x++"), new SpanResult(42, 26, 42, 27, "a"), new SpanResult(49, 12, 49, 16, "x++"), new SpanResult(47, 15, 47, 22, "x < 100"), new SpanResult(54, 12, 54, 16, "x++"), new SpanResult(57, 16, 57, 45, "throw new System.Exception()"), new SpanResult(55, 16, 55, 22, "x > 10"), new SpanResult(59, 12, 59, 16, "x++"), new SpanResult(63, 12, 63, 16, "x++"), new SpanResult(67, 12, 67, 16, "x++"), new SpanResult(72, 12, 72, 13, ";"), new SpanResult(70, 14, 70, 26, "new object()"), new SpanResult(75, 8, 75, 29, "Console.WriteLine(x)"), new SpanResult(81, 16, 81, 17, ";"), new SpanResult(79, 19, 79, 51, "(System.IDisposable)new object()"), new SpanResult(88, 8, 88, 15, "return")); VerifySpans(reader, reader.Methods[1]); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)] public void TestMethodSpansWithAttributes() { string source = @" using System; using System.Security; public class C { static int x; public static void Main() // Method 0 { Fred(); } [Obsolete()] static void Fred() // Method 1 { } static C() // Method 2 { x = 12; } [Obsolete()] public C() // Method 3 { } int Wilma { [SecurityCritical] get { return 12; } // Method 4 } [Obsolete()] int Betty => 13; // Method 5 [SecurityCritical] int Pebbles() // Method 6 { return 3; } [SecurityCritical] ref int BamBam(ref int x) // Method 7 { return ref x; } [SecurityCritical] C(int x) // Method 8 { } [Obsolete()] public int Barney => 13; // Method 9 [SecurityCritical] public static C operator +(C a, C b) // Method 10 { return a; } } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); VerifyDocuments(reader, reader.Documents, @"'C:\myproject\doc1.cs' A3-08-94-55-7C-64-8D-C7-61-7A-11-0B-4B-68-2C-3B-51-C3-C4-58 (SHA1)"); Assert.Equal(15, reader.Methods.Length); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(8, 4, 11, 5, "public static void Main()"), new SpanResult(10, 8, 10, 15, "Fred()")); VerifySpans(reader, reader.Methods[1], sourceLines, new SpanResult(14, 4, 16, 5, "static void Fred()")); VerifySpans(reader, reader.Methods[2], sourceLines, new SpanResult(18, 4, 21, 5, "static C()"), new SpanResult(20, 8, 20, 15, "x = 12")); VerifySpans(reader, reader.Methods[3], sourceLines, new SpanResult(24, 4, 26, 5, "public C()")); VerifySpans(reader, reader.Methods[4], sourceLines, new SpanResult(31, 8, 31, 26, "get {"), new SpanResult(31, 14, 31, 24, "return 12")); VerifySpans(reader, reader.Methods[5], sourceLines, new SpanResult(35, 4, 35, 20, "int Betty"), new SpanResult(35, 17, 35, 19, "13")); VerifySpans(reader, reader.Methods[6], sourceLines, new SpanResult(38, 4, 41, 5, "int Pebbles()"), new SpanResult(40, 8, 40, 17, "return 3")); VerifySpans(reader, reader.Methods[7], sourceLines, new SpanResult(44, 4, 47, 5, "ref int BamBam"), new SpanResult(46, 8, 46, 21, "return ref x")); VerifySpans(reader, reader.Methods[8], sourceLines, new SpanResult(50, 4, 52, 5, "C(int x)")); VerifySpans(reader, reader.Methods[9], sourceLines, new SpanResult(55, 4, 55, 28, "public int Barney"), new SpanResult(55, 25, 55, 27, "13")); VerifySpans(reader, reader.Methods[10], sourceLines, new SpanResult(58, 4, 61, 5, "public static C operator +"), new SpanResult(60, 8, 60, 17, "return a")); } [Fact] public void TestPatternSpans() { string source = @" using System; public class C { public static void Main() // Method 0 { Student s = new Student(); s.Name = ""Bozo""; s.GPA = 2.3; Operate(s); } static string Operate(Person p) // Method 1 { switch (p) { case Student s when s.GPA > 3.5: return $""Student {s.Name} ({s.GPA:N1})""; case Student s when (s.GPA < 2.0): return $""Failing Student {s.Name} ({s.GPA:N1})""; case Student s: return $""Student {s.Name} ({s.GPA:N1})""; case Teacher t: return $""Teacher {t.Name} of {t.Subject}""; default: return $""Person {p.Name}""; } } } class Person { public string Name; } class Teacher : Person { public string Subject; } class Student : Person { public double GPA; } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 11, 5, "public static void Main()"), new SpanResult(7, 8, 7, 34, "Student s = new Student()"), new SpanResult(8, 8, 8, 24, "s.Name = \"Bozo\""), new SpanResult(9, 8, 9, 20, "s.GPA = 2.3"), new SpanResult(10, 8, 10, 19, "Operate(s)")); VerifySpans(reader, reader.Methods[1], sourceLines, new SpanResult(13, 4, 28, 5, "static string Operate(Person p)"), new SpanResult(17, 27, 17, 43, "when s.GPA > 3.5"), new SpanResult(19, 27, 19, 45, "when (s.GPA < 2.0)"), new SpanResult(18, 16, 18, 56, "return $\"Student {s.Name} ({s.GPA:N1})\""), new SpanResult(20, 16, 20, 64, "return $\"Failing Student {s.Name} ({s.GPA:N1})\""), new SpanResult(22, 16, 22, 56, "return $\"Student {s.Name} ({s.GPA:N1})\""), new SpanResult(24, 16, 24, 58, "return $\"Teacher {t.Name} of {t.Subject}\""), new SpanResult(26, 16, 26, 42, "return $\"Person {p.Name}\""), new SpanResult(15, 16, 15, 17, "p")); } [Fact] public void TestDeconstructionSpans() { string source = @" using System; public class C { public static void Main() // Method 1 { var (x, y) = new C(); } public void Deconstruct(out int x, out int y) { x = 1; y = 2; } } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 8, 5, "public static void Main()"), new SpanResult(7, 8, 7, 29, "var (x, y) = new C()")); } [Fact] public void TestForeachSpans() { string source = @" using System; public class C { public static void Main() // Method 1 { C[] a = null; foreach (var x in a) ; } } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 12, 5, "public static void Main()"), new SpanResult(7, 8, 7, 21, "C[] a = null"), new SpanResult(11, 12, 11, 13, ";"), new SpanResult(10, 15, 10, 16, "a") ); } [Fact] public void TestForeachDeconstructionSpans() { string source = @" using System; public class C { public static void Main() // Method 1 { C[] a = null; foreach (var (x, y) in a) ; } public void Deconstruct(out int x, out int y) { x = 1; y = 2; } } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 12, 5, "public static void Main()"), new SpanResult(7, 8, 7, 21, "C[] a = null"), new SpanResult(11, 12, 11, 13, ";"), new SpanResult(10, 15, 10, 16, "a") ); } [Fact] public void TestFieldInitializerSpans() { string source = @" using System; public class C { public static void Main() // Method 0 { TestMain(); } static void TestMain() // Method 1 { C local = new C(); local = new C(1, 2); } static int Init() => 33; // Method 2 C() // Method 3 { _z = 12; } static C() // Method 4 { s_z = 123; } int _x = Init(); int _y = Init() + 12; int _z; static int s_x = Init(); static int s_y = Init() + 153; static int s_z; C(int x) // Method 5 { _z = x; } C(int a, int b) // Method 6 { _z = a + b; } int Prop1 { get; } = 15; static int Prop2 { get; } = 255; } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 8, 5, "public static void Main()"), new SpanResult(7, 8, 7, 19, "TestMain()")); VerifySpans(reader, reader.Methods[1], sourceLines, new SpanResult(10, 4, 13, 5, "static void TestMain()"), new SpanResult(12, 8, 12, 26, "C local = new C()"), new SpanResult(12, 27, 12, 47, "local = new C(1, 2)")); VerifySpans(reader, reader.Methods[2], sourceLines, new SpanResult(15, 4, 15, 28, "static int Init() => 33"), new SpanResult(15, 25, 15, 27, "33")); VerifySpans(reader, reader.Methods[3], sourceLines, new SpanResult(17, 4, 20, 5, "C()"), new SpanResult(27, 13, 27, 19, "Init()"), new SpanResult(28, 13, 28, 24, "Init() + 12"), new SpanResult(44, 25, 44, 27, "15"), new SpanResult(19, 8, 19, 16, "_z = 12")); VerifySpans(reader, reader.Methods[4], sourceLines, new SpanResult(22, 4, 25, 5, "static C()"), new SpanResult(30, 21, 30, 27, "Init()"), new SpanResult(31, 21, 31, 33, "Init() + 153"), new SpanResult(45, 32, 45, 35, "255"), new SpanResult(24, 8, 24, 18, "s_z = 123")); VerifySpans(reader, reader.Methods[5], sourceLines, new SpanResult(34, 4, 37, 5, "C(int x)"), new SpanResult(27, 13, 27, 19, "Init()"), new SpanResult(28, 13, 28, 24, "Init() + 12"), new SpanResult(44, 25, 44, 27, "15"), new SpanResult(36, 8, 36, 15, "_z = x")); VerifySpans(reader, reader.Methods[6], sourceLines, new SpanResult(39, 4, 42, 5, "C(int a, int b)"), new SpanResult(27, 13, 27, 19, "Init()"), new SpanResult(28, 13, 28, 24, "Init() + 12"), new SpanResult(44, 25, 44, 27, "15"), new SpanResult(41, 8, 41, 19, "_z = a + b")); } [Fact] public void TestImplicitConstructorSpans() { string source = @" using System; public class C { public static void Main() // Method 0 { TestMain(); } static void TestMain() // Method 1 { C local = new C(); } static int Init() => 33; // Method 2 int _x = Init(); int _y = Init() + 12; static int s_x = Init(); static int s_y = Init() + 153; static int s_z = 144; int Prop1 { get; } = 15; static int Prop2 { get; } = 255; } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 8, 5, "public static void Main()"), new SpanResult(7, 8, 7, 19, "TestMain()")); VerifySpans(reader, reader.Methods[1], sourceLines, new SpanResult(10, 4, 13, 5, "static void TestMain()"), new SpanResult(12, 8, 12, 26, "C local = new C()")); VerifySpans(reader, reader.Methods[2], sourceLines, new SpanResult(15, 4, 15, 28, "static int Init() => 33"), new SpanResult(15, 25, 15, 27, "33")); VerifySpans(reader, reader.Methods[5], sourceLines, // Synthesized instance constructor new SpanResult(17, 13, 17, 19, "Init()"), new SpanResult(18, 13, 18, 24, "Init() + 12"), new SpanResult(23, 25, 23, 27, "15")); VerifySpans(reader, reader.Methods[6], sourceLines, // Synthesized static constructor new SpanResult(19, 21, 19, 27, "Init()"), new SpanResult(20, 21, 20, 33, "Init() + 153"), new SpanResult(21, 21, 21, 24, "144"), new SpanResult(24, 32, 24, 35, "255")); } [Fact] public void TestImplicitConstructorsWithLambdasSpans() { string source = @" using System; public class C { public static void Main() // Method 0 { TestMain(); } static void TestMain() // Method 1 { int y = s_c._function(); D d = new D(); int z = d._c._function(); int zz = D.s_c._function(); } public C(Func<int> f) // Method 2 { _function = f; } static C s_c = new C(() => 115); Func<int> _function; } class D { public C _c = new C(() => 120); public static C s_c = new C(() => 144); public C _c1 = new C(() => 130); public static C s_c1 = new C(() => 156); } partial struct E { } partial struct E { public static C s_c = new C(() => 1444); public static C s_c1 = new C(() => { return 1567; }); } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 8, 5, "public static void Main()"), new SpanResult(7, 8, 7, 19, "TestMain()")); VerifySpans(reader, reader.Methods[1], sourceLines, new SpanResult(10, 4, 16, 5, "static void TestMain()"), new SpanResult(12, 8, 12, 32, "int y = s_c._function()"), new SpanResult(13, 8, 13, 22, "D d = new D()"), new SpanResult(14, 8, 14, 33, "int z = d._c._function()"), new SpanResult(15, 8, 15, 35, "int zz = D.s_c._function()")); VerifySpans(reader, reader.Methods[2], sourceLines, new SpanResult(18, 4, 21, 5, "public C(Func<int> f)"), new SpanResult(20, 8, 20, 22, "_function = f")); VerifySpans(reader, reader.Methods[3], sourceLines, // Synthesized static constructor for C new SpanResult(23, 31, 23, 34, "115"), new SpanResult(23, 19, 23, 35, "new C(() => 115)")); VerifySpans(reader, reader.Methods[4], sourceLines, // Synthesized instance constructor for D new SpanResult(29, 30, 29, 33, "120"), new SpanResult(31, 31, 31, 34, "130"), new SpanResult(29, 18, 29, 34, "new C(() => 120)"), new SpanResult(31, 19, 31, 35, "new C(() => 130)")); VerifySpans(reader, reader.Methods[5], sourceLines, // Synthesized static constructor for D new SpanResult(30, 38, 30, 41, "144"), new SpanResult(32, 39, 32, 42, "156"), new SpanResult(30, 26, 30, 42, "new C(() => 144)"), new SpanResult(32, 27, 32, 43, "new C(() => 156")); VerifySpans(reader, reader.Methods[6], sourceLines, // Synthesized static constructor for E new SpanResult(41, 38, 41, 42, "1444"), new SpanResult(42, 41, 42, 53, "return 1567"), new SpanResult(41, 26, 41, 43, "new C(() => 1444)"), new SpanResult(42, 27, 42, 56, "new C(() => { return 1567; })")); } [Fact] public void TestLocalFunctionWithLambdaSpans() { string source = @" using System; public class C { public static void Main() // Method 0 { TestMain(); } static void TestMain() // Method 1 { new D().M1(); } } public class D { public void M1() // Method 3 { L1(); void L1() { var f = new Func<int>( () => 1 ); f(); var f1 = new Func<int>( () => { return 2; } ); var f2 = new Func<int, int>( (x) => x + 3 ); var f3 = new Func<int, int>( x => x + 4 ); } } } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 8, 5, "public static void Main()"), new SpanResult(7, 8, 7, 19, "TestMain()")); VerifySpans(reader, reader.Methods[1], sourceLines, new SpanResult(10, 4, 13, 5, "static void TestMain()"), new SpanResult(12, 8, 12, 21, "new D().M1()")); VerifySpans(reader, reader.Methods[3], sourceLines, new SpanResult(18, 4, 41, 5, "public void M1()"), new SpanResult(20, 8, 20, 13, "L1()"), new SpanResult(24, 22, 24, 23, "1"), new SpanResult(23, 12, 25, 14, "var f = new Func<int>"), new SpanResult(27, 12, 27, 16, "f()"), new SpanResult(30, 24, 30, 33, "return 2"), new SpanResult(29, 12, 31, 14, "var f1 = new Func<int>"), new SpanResult(34, 23, 34, 28, "x + 3"), new SpanResult(33, 12, 35, 14, "var f2 = new Func<int, int>"), new SpanResult(38, 21, 38, 26, "x + 4"), new SpanResult(37, 12, 39, 14, "var f3 = new Func<int, int>")); } [Fact] public void TestDynamicAnalysisResourceMissingWhenInstrumentationFlagIsDisabled() { var c = CreateCompilation(Parse(ExampleSource + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); Assert.Null(reader); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void EmptyStaticConstructor_WithEnableTestCoverage() { string source = @" #nullable enable class C { static C() { } static object obj = null!; }" + InstrumentationHelperSource; var emitOptions = EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)); CompileAndVerify(source, emitOptions: emitOptions).VerifyIL("C..cctor()", @"{ // Code size 57 (0x39) .maxstack 5 .locals init (bool[] V_0) IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0005: ldtoken ""C..cctor()"" IL_000a: ldelem.ref IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID"" IL_0014: ldtoken ""C..cctor()"" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0023: ldtoken ""C..cctor()"" IL_0028: ldelema ""bool[]"" IL_002d: ldc.i4.1 IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SynthesizedStaticConstructor_WithEnableTestCoverage() { string source = @" #nullable enable class C { static object obj = null!; }" + InstrumentationHelperSource; var emitOptions = EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)); CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), emitOptions: emitOptions, symbolValidator: validator); void validator(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.Empty(type.GetMembers(".cctor")); } } private class SpanResult { public int StartLine { get; } public int StartColumn { get; } public int EndLine { get; } public int EndColumn { get; } public string TextStart { get; } public SpanResult(int startLine, int startColumn, int endLine, int endColumn, string textStart) { StartLine = startLine; StartColumn = startColumn; EndLine = endLine; EndColumn = endColumn; TextStart = textStart; } } private static void VerifySpans(DynamicAnalysisDataReader reader, DynamicAnalysisMethod methodData, string[] sourceLines, params SpanResult[] expected) { ArrayBuilder<string> expectedSpanSpellings = ArrayBuilder<string>.GetInstance(expected.Length); foreach (SpanResult expectedSpanResult in expected) { Assert.True(sourceLines[expectedSpanResult.StartLine].Substring(expectedSpanResult.StartColumn).StartsWith(expectedSpanResult.TextStart)); expectedSpanSpellings.Add(string.Format("({0},{1})-({2},{3})", expectedSpanResult.StartLine, expectedSpanResult.StartColumn, expectedSpanResult.EndLine, expectedSpanResult.EndColumn)); } VerifySpans(reader, methodData, expectedSpanSpellings.ToArrayAndFree()); } private static void VerifySpans(DynamicAnalysisDataReader reader, DynamicAnalysisMethod methodData, params string[] expected) { AssertEx.Equal(expected, reader.GetSpans(methodData.Blob).Select(s => $"({s.StartLine},{s.StartColumn})-({s.EndLine},{s.EndColumn})")); } private void VerifyDocuments(DynamicAnalysisDataReader reader, ImmutableArray<DynamicAnalysisDocument> documents, params string[] expected) { var sha1 = new Guid("ff1816ec-aa5e-4d10-87f7-6f4963833460"); var actual = from d in documents let name = reader.GetDocumentName(d.Name) let hash = d.Hash.IsNil ? "" : " " + BitConverter.ToString(reader.GetBytes(d.Hash)) let hashAlgGuid = reader.GetGuid(d.HashAlgorithm) let hashAlg = (hashAlgGuid == sha1) ? " (SHA1)" : (hashAlgGuid == default(Guid)) ? "" : " " + hashAlgGuid.ToString() select $"'{name}'{hash}{hashAlg}"; AssertEx.Equal(expected, actual); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.DynamicAnalysis.UnitTests { public class DynamicAnalysisResourceTests : CSharpTestBase { const string InstrumentationHelperSource = @" namespace Microsoft.CodeAnalysis.Runtime { public static class Instrumentation { public static bool[] CreatePayload(System.Guid mvid, int methodToken, int fileIndex, ref bool[] payload, int payloadLength) { return payload; } public static bool[] CreatePayload(System.Guid mvid, int methodToken, int[] fileIndices, ref bool[] payload, int payloadLength) { return payload; } public static void FlushPayload() { } } } "; const string ExampleSource = @" using System; public class C { public static void Main() { Console.WriteLine(123); Console.WriteLine(123); } public static int Fred => 3; public static int Barney(int x) => x; public static int Wilma { get { return 12; } set { } } public static int Betty { get; } public static int Pebbles { get; set; } } "; [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)] public void TestSpansPresentInResource() { var c = CreateCompilation(Parse(ExampleSource + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); VerifyDocuments(reader, reader.Documents, @"'C:\myproject\doc1.cs' 44-3F-7C-A1-EF-CA-A8-16-40-D2-09-4F-3E-52-7C-44-8D-22-C8-02 (SHA1)"); Assert.Equal(13, reader.Methods.Length); string[] sourceLines = ExampleSource.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, // Main new SpanResult(5, 4, 9, 5, "public static void Main()"), new SpanResult(7, 8, 7, 31, "Console.WriteLine(123)"), new SpanResult(8, 8, 8, 31, "Console.WriteLine(123)")); VerifySpans(reader, reader.Methods[1], sourceLines, // Fred get new SpanResult(11, 4, 11, 32, "public static int Fred => 3"), new SpanResult(11, 30, 11, 31, "3")); VerifySpans(reader, reader.Methods[2], sourceLines, // Barney new SpanResult(13, 4, 13, 41, "public static int Barney(int x) => x"), new SpanResult(13, 39, 13, 40, "x")); VerifySpans(reader, reader.Methods[3], sourceLines, // Wilma get new SpanResult(17, 8, 17, 26, "get { return 12; }"), new SpanResult(17, 14, 17, 24, "return 12")); VerifySpans(reader, reader.Methods[4], sourceLines, // Wilma set new SpanResult(18, 8, 18, 15, "set { }")); VerifySpans(reader, reader.Methods[5], sourceLines, // Betty get new SpanResult(21, 4, 21, 36, "public static int Betty { get; }"), new SpanResult(21, 30, 21, 34, "get")); VerifySpans(reader, reader.Methods[6], sourceLines, // Pebbles get new SpanResult(23, 4, 23, 43, "public static int Pebbles { get; set; }"), new SpanResult(23, 32, 23, 36, "get")); VerifySpans(reader, reader.Methods[7], sourceLines, // Pebbles set new SpanResult(23, 4, 23, 43, "public static int Pebbles { get; set; }"), new SpanResult(23, 37, 23, 41, "set")); VerifySpans(reader, reader.Methods[8]); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)] public void ResourceStatementKinds() { string source = @" using System; public class C { public static void Main() { int z = 11; int x = z + 10; switch (z) { case 1: break; case 2: break; case 3: break; default: break; } if (x > 10) { x++; } else { x--; } for (int y = 0; y < 50; y++) { if (y < 30) { x++; continue; } else break; } int[] a = new int[] { 1, 2, 3, 4 }; foreach (int i in a) { x++; } while (x < 100) { x++; } try { x++; if (x > 10) { throw new System.Exception(); } x++; } catch (System.Exception e) { x++; } finally { x++; } lock (new object()) { ; } Console.WriteLine(x); try { using ((System.IDisposable)new object()) { ; } } catch (System.Exception e) { } return; } } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); VerifyDocuments(reader, reader.Documents, @"'C:\myproject\doc1.cs' 6A-DC-C0-8A-16-CB-7C-A5-99-8B-2E-0C-3C-81-69-2C-B2-10-EE-F1 (SHA1)"); Assert.Equal(6, reader.Methods.Length); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 89, 5, "public static void Main()"), new SpanResult(7, 8, 7, 19, "int z = 11"), new SpanResult(8, 8, 8, 23, "int x = z + 10"), new SpanResult(12, 16, 12, 22, "break"), new SpanResult(14, 16, 14, 22, "break"), new SpanResult(16, 16, 16, 22, "break"), new SpanResult(18, 16, 18, 22, "break"), new SpanResult(9, 16, 9, 17, "z"), new SpanResult(23, 12, 23, 16, "x++"), new SpanResult(27, 12, 27, 16, "x--"), new SpanResult(21, 12, 21, 18, "x > 10"), new SpanResult(30, 17, 30, 22, "y = 0"), new SpanResult(30, 32, 30, 35, "y++"), new SpanResult(34, 16, 34, 20, "x++"), new SpanResult(35, 16, 35, 25, "continue"), new SpanResult(38, 16, 38, 22, "break"), new SpanResult(32, 16, 32, 22, "y < 30"), new SpanResult(41, 8, 41, 43, "int[] a = new int[] { 1, 2, 3, 4 }"), new SpanResult(44, 12, 44, 16, "x++"), new SpanResult(42, 26, 42, 27, "a"), new SpanResult(49, 12, 49, 16, "x++"), new SpanResult(47, 15, 47, 22, "x < 100"), new SpanResult(54, 12, 54, 16, "x++"), new SpanResult(57, 16, 57, 45, "throw new System.Exception()"), new SpanResult(55, 16, 55, 22, "x > 10"), new SpanResult(59, 12, 59, 16, "x++"), new SpanResult(63, 12, 63, 16, "x++"), new SpanResult(67, 12, 67, 16, "x++"), new SpanResult(72, 12, 72, 13, ";"), new SpanResult(70, 14, 70, 26, "new object()"), new SpanResult(75, 8, 75, 29, "Console.WriteLine(x)"), new SpanResult(81, 16, 81, 17, ";"), new SpanResult(79, 19, 79, 51, "(System.IDisposable)new object()"), new SpanResult(88, 8, 88, 15, "return")); VerifySpans(reader, reader.Methods[1]); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)] public void TestMethodSpansWithAttributes() { string source = @" using System; using System.Security; public class C { static int x; public static void Main() // Method 0 { Fred(); } [Obsolete()] static void Fred() // Method 1 { } static C() // Method 2 { x = 12; } [Obsolete()] public C() // Method 3 { } int Wilma { [SecurityCritical] get { return 12; } // Method 4 } [Obsolete()] int Betty => 13; // Method 5 [SecurityCritical] int Pebbles() // Method 6 { return 3; } [SecurityCritical] ref int BamBam(ref int x) // Method 7 { return ref x; } [SecurityCritical] C(int x) // Method 8 { } [Obsolete()] public int Barney => 13; // Method 9 [SecurityCritical] public static C operator +(C a, C b) // Method 10 { return a; } } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); VerifyDocuments(reader, reader.Documents, @"'C:\myproject\doc1.cs' A3-08-94-55-7C-64-8D-C7-61-7A-11-0B-4B-68-2C-3B-51-C3-C4-58 (SHA1)"); Assert.Equal(15, reader.Methods.Length); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(8, 4, 11, 5, "public static void Main()"), new SpanResult(10, 8, 10, 15, "Fred()")); VerifySpans(reader, reader.Methods[1], sourceLines, new SpanResult(14, 4, 16, 5, "static void Fred()")); VerifySpans(reader, reader.Methods[2], sourceLines, new SpanResult(18, 4, 21, 5, "static C()"), new SpanResult(20, 8, 20, 15, "x = 12")); VerifySpans(reader, reader.Methods[3], sourceLines, new SpanResult(24, 4, 26, 5, "public C()")); VerifySpans(reader, reader.Methods[4], sourceLines, new SpanResult(31, 8, 31, 26, "get {"), new SpanResult(31, 14, 31, 24, "return 12")); VerifySpans(reader, reader.Methods[5], sourceLines, new SpanResult(35, 4, 35, 20, "int Betty"), new SpanResult(35, 17, 35, 19, "13")); VerifySpans(reader, reader.Methods[6], sourceLines, new SpanResult(38, 4, 41, 5, "int Pebbles()"), new SpanResult(40, 8, 40, 17, "return 3")); VerifySpans(reader, reader.Methods[7], sourceLines, new SpanResult(44, 4, 47, 5, "ref int BamBam"), new SpanResult(46, 8, 46, 21, "return ref x")); VerifySpans(reader, reader.Methods[8], sourceLines, new SpanResult(50, 4, 52, 5, "C(int x)")); VerifySpans(reader, reader.Methods[9], sourceLines, new SpanResult(55, 4, 55, 28, "public int Barney"), new SpanResult(55, 25, 55, 27, "13")); VerifySpans(reader, reader.Methods[10], sourceLines, new SpanResult(58, 4, 61, 5, "public static C operator +"), new SpanResult(60, 8, 60, 17, "return a")); } [Fact] public void TestPatternSpans() { string source = @" using System; public class C { public static void Main() // Method 0 { Student s = new Student(); s.Name = ""Bozo""; s.GPA = 2.3; Operate(s); } static string Operate(Person p) // Method 1 { switch (p) { case Student s when s.GPA > 3.5: return $""Student {s.Name} ({s.GPA:N1})""; case Student s when (s.GPA < 2.0): return $""Failing Student {s.Name} ({s.GPA:N1})""; case Student s: return $""Student {s.Name} ({s.GPA:N1})""; case Teacher t: return $""Teacher {t.Name} of {t.Subject}""; default: return $""Person {p.Name}""; } } } class Person { public string Name; } class Teacher : Person { public string Subject; } class Student : Person { public double GPA; } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 11, 5, "public static void Main()"), new SpanResult(7, 8, 7, 34, "Student s = new Student()"), new SpanResult(8, 8, 8, 24, "s.Name = \"Bozo\""), new SpanResult(9, 8, 9, 20, "s.GPA = 2.3"), new SpanResult(10, 8, 10, 19, "Operate(s)")); VerifySpans(reader, reader.Methods[1], sourceLines, new SpanResult(13, 4, 28, 5, "static string Operate(Person p)"), new SpanResult(17, 27, 17, 43, "when s.GPA > 3.5"), new SpanResult(19, 27, 19, 45, "when (s.GPA < 2.0)"), new SpanResult(18, 16, 18, 56, "return $\"Student {s.Name} ({s.GPA:N1})\""), new SpanResult(20, 16, 20, 64, "return $\"Failing Student {s.Name} ({s.GPA:N1})\""), new SpanResult(22, 16, 22, 56, "return $\"Student {s.Name} ({s.GPA:N1})\""), new SpanResult(24, 16, 24, 58, "return $\"Teacher {t.Name} of {t.Subject}\""), new SpanResult(26, 16, 26, 42, "return $\"Person {p.Name}\""), new SpanResult(15, 16, 15, 17, "p")); } [Fact] public void TestDeconstructionSpans() { string source = @" using System; public class C { public static void Main() // Method 1 { var (x, y) = new C(); } public void Deconstruct(out int x, out int y) { x = 1; y = 2; } } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 8, 5, "public static void Main()"), new SpanResult(7, 8, 7, 29, "var (x, y) = new C()")); } [Fact] public void TestForeachSpans() { string source = @" using System; public class C { public static void Main() // Method 1 { C[] a = null; foreach (var x in a) ; } } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 12, 5, "public static void Main()"), new SpanResult(7, 8, 7, 21, "C[] a = null"), new SpanResult(11, 12, 11, 13, ";"), new SpanResult(10, 15, 10, 16, "a") ); } [Fact] public void TestForeachDeconstructionSpans() { string source = @" using System; public class C { public static void Main() // Method 1 { C[] a = null; foreach (var (x, y) in a) ; } public void Deconstruct(out int x, out int y) { x = 1; y = 2; } } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 12, 5, "public static void Main()"), new SpanResult(7, 8, 7, 21, "C[] a = null"), new SpanResult(11, 12, 11, 13, ";"), new SpanResult(10, 15, 10, 16, "a") ); } [Fact] public void TestFieldInitializerSpans() { string source = @" using System; public class C { public static void Main() // Method 0 { TestMain(); } static void TestMain() // Method 1 { C local = new C(); local = new C(1, 2); } static int Init() => 33; // Method 2 C() // Method 3 { _z = 12; } static C() // Method 4 { s_z = 123; } int _x = Init(); int _y = Init() + 12; int _z; static int s_x = Init(); static int s_y = Init() + 153; static int s_z; C(int x) // Method 5 { _z = x; } C(int a, int b) // Method 6 { _z = a + b; } int Prop1 { get; } = 15; static int Prop2 { get; } = 255; } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 8, 5, "public static void Main()"), new SpanResult(7, 8, 7, 19, "TestMain()")); VerifySpans(reader, reader.Methods[1], sourceLines, new SpanResult(10, 4, 13, 5, "static void TestMain()"), new SpanResult(12, 8, 12, 26, "C local = new C()"), new SpanResult(12, 27, 12, 47, "local = new C(1, 2)")); VerifySpans(reader, reader.Methods[2], sourceLines, new SpanResult(15, 4, 15, 28, "static int Init() => 33"), new SpanResult(15, 25, 15, 27, "33")); VerifySpans(reader, reader.Methods[3], sourceLines, new SpanResult(17, 4, 20, 5, "C()"), new SpanResult(27, 13, 27, 19, "Init()"), new SpanResult(28, 13, 28, 24, "Init() + 12"), new SpanResult(44, 25, 44, 27, "15"), new SpanResult(19, 8, 19, 16, "_z = 12")); VerifySpans(reader, reader.Methods[4], sourceLines, new SpanResult(22, 4, 25, 5, "static C()"), new SpanResult(30, 21, 30, 27, "Init()"), new SpanResult(31, 21, 31, 33, "Init() + 153"), new SpanResult(45, 32, 45, 35, "255"), new SpanResult(24, 8, 24, 18, "s_z = 123")); VerifySpans(reader, reader.Methods[5], sourceLines, new SpanResult(34, 4, 37, 5, "C(int x)"), new SpanResult(27, 13, 27, 19, "Init()"), new SpanResult(28, 13, 28, 24, "Init() + 12"), new SpanResult(44, 25, 44, 27, "15"), new SpanResult(36, 8, 36, 15, "_z = x")); VerifySpans(reader, reader.Methods[6], sourceLines, new SpanResult(39, 4, 42, 5, "C(int a, int b)"), new SpanResult(27, 13, 27, 19, "Init()"), new SpanResult(28, 13, 28, 24, "Init() + 12"), new SpanResult(44, 25, 44, 27, "15"), new SpanResult(41, 8, 41, 19, "_z = a + b")); } [Fact] public void TestImplicitConstructorSpans() { string source = @" using System; public class C { public static void Main() // Method 0 { TestMain(); } static void TestMain() // Method 1 { C local = new C(); } static int Init() => 33; // Method 2 int _x = Init(); int _y = Init() + 12; static int s_x = Init(); static int s_y = Init() + 153; static int s_z = 144; int Prop1 { get; } = 15; static int Prop2 { get; } = 255; } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 8, 5, "public static void Main()"), new SpanResult(7, 8, 7, 19, "TestMain()")); VerifySpans(reader, reader.Methods[1], sourceLines, new SpanResult(10, 4, 13, 5, "static void TestMain()"), new SpanResult(12, 8, 12, 26, "C local = new C()")); VerifySpans(reader, reader.Methods[2], sourceLines, new SpanResult(15, 4, 15, 28, "static int Init() => 33"), new SpanResult(15, 25, 15, 27, "33")); VerifySpans(reader, reader.Methods[5], sourceLines, // Synthesized instance constructor new SpanResult(17, 13, 17, 19, "Init()"), new SpanResult(18, 13, 18, 24, "Init() + 12"), new SpanResult(23, 25, 23, 27, "15")); VerifySpans(reader, reader.Methods[6], sourceLines, // Synthesized static constructor new SpanResult(19, 21, 19, 27, "Init()"), new SpanResult(20, 21, 20, 33, "Init() + 153"), new SpanResult(21, 21, 21, 24, "144"), new SpanResult(24, 32, 24, 35, "255")); } [Fact] public void TestImplicitConstructorsWithLambdasSpans() { string source = @" using System; public class C { public static void Main() // Method 0 { TestMain(); } static void TestMain() // Method 1 { int y = s_c._function(); D d = new D(); int z = d._c._function(); int zz = D.s_c._function(); } public C(Func<int> f) // Method 2 { _function = f; } static C s_c = new C(() => 115); Func<int> _function; } class D { public C _c = new C(() => 120); public static C s_c = new C(() => 144); public C _c1 = new C(() => 130); public static C s_c1 = new C(() => 156); } partial struct E { } partial struct E { public static C s_c = new C(() => 1444); public static C s_c1 = new C(() => { return 1567; }); } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 8, 5, "public static void Main()"), new SpanResult(7, 8, 7, 19, "TestMain()")); VerifySpans(reader, reader.Methods[1], sourceLines, new SpanResult(10, 4, 16, 5, "static void TestMain()"), new SpanResult(12, 8, 12, 32, "int y = s_c._function()"), new SpanResult(13, 8, 13, 22, "D d = new D()"), new SpanResult(14, 8, 14, 33, "int z = d._c._function()"), new SpanResult(15, 8, 15, 35, "int zz = D.s_c._function()")); VerifySpans(reader, reader.Methods[2], sourceLines, new SpanResult(18, 4, 21, 5, "public C(Func<int> f)"), new SpanResult(20, 8, 20, 22, "_function = f")); VerifySpans(reader, reader.Methods[3], sourceLines, // Synthesized static constructor for C new SpanResult(23, 31, 23, 34, "115"), new SpanResult(23, 19, 23, 35, "new C(() => 115)")); VerifySpans(reader, reader.Methods[4], sourceLines, // Synthesized instance constructor for D new SpanResult(29, 30, 29, 33, "120"), new SpanResult(31, 31, 31, 34, "130"), new SpanResult(29, 18, 29, 34, "new C(() => 120)"), new SpanResult(31, 19, 31, 35, "new C(() => 130)")); VerifySpans(reader, reader.Methods[5], sourceLines, // Synthesized static constructor for D new SpanResult(30, 38, 30, 41, "144"), new SpanResult(32, 39, 32, 42, "156"), new SpanResult(30, 26, 30, 42, "new C(() => 144)"), new SpanResult(32, 27, 32, 43, "new C(() => 156")); VerifySpans(reader, reader.Methods[6], sourceLines, // Synthesized static constructor for E new SpanResult(41, 38, 41, 42, "1444"), new SpanResult(42, 41, 42, 53, "return 1567"), new SpanResult(41, 26, 41, 43, "new C(() => 1444)"), new SpanResult(42, 27, 42, 56, "new C(() => { return 1567; })")); } [Fact] public void TestLocalFunctionWithLambdaSpans() { string source = @" using System; public class C { public static void Main() // Method 0 { TestMain(); } static void TestMain() // Method 1 { new D().M1(); } } public class D { public void M1() // Method 3 { L1(); void L1() { var f = new Func<int>( () => 1 ); f(); var f1 = new Func<int>( () => { return 2; } ); var f2 = new Func<int, int>( (x) => x + 3 ); var f3 = new Func<int, int>( x => x + 4 ); } } } "; var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); string[] sourceLines = source.Split('\n'); VerifySpans(reader, reader.Methods[0], sourceLines, new SpanResult(5, 4, 8, 5, "public static void Main()"), new SpanResult(7, 8, 7, 19, "TestMain()")); VerifySpans(reader, reader.Methods[1], sourceLines, new SpanResult(10, 4, 13, 5, "static void TestMain()"), new SpanResult(12, 8, 12, 21, "new D().M1()")); VerifySpans(reader, reader.Methods[3], sourceLines, new SpanResult(18, 4, 41, 5, "public void M1()"), new SpanResult(20, 8, 20, 13, "L1()"), new SpanResult(24, 22, 24, 23, "1"), new SpanResult(23, 12, 25, 14, "var f = new Func<int>"), new SpanResult(27, 12, 27, 16, "f()"), new SpanResult(30, 24, 30, 33, "return 2"), new SpanResult(29, 12, 31, 14, "var f1 = new Func<int>"), new SpanResult(34, 23, 34, 28, "x + 3"), new SpanResult(33, 12, 35, 14, "var f2 = new Func<int, int>"), new SpanResult(38, 21, 38, 26, "x + 4"), new SpanResult(37, 12, 39, 14, "var f3 = new Func<int, int>")); } [Fact] public void TestDynamicAnalysisResourceMissingWhenInstrumentationFlagIsDisabled() { var c = CreateCompilation(Parse(ExampleSource + InstrumentationHelperSource, @"C:\myproject\doc1.cs")); var peImage = c.EmitToArray(EmitOptions.Default); var peReader = new PEReader(peImage); var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>"); Assert.Null(reader); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void EmptyStaticConstructor_WithEnableTestCoverage() { string source = @" #nullable enable class C { static C() { } static object obj = null!; }" + InstrumentationHelperSource; var emitOptions = EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)); CompileAndVerify(source, emitOptions: emitOptions).VerifyIL("C..cctor()", @"{ // Code size 57 (0x39) .maxstack 5 .locals init (bool[] V_0) IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0005: ldtoken ""C..cctor()"" IL_000a: ldelem.ref IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID"" IL_0014: ldtoken ""C..cctor()"" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0023: ldtoken ""C..cctor()"" IL_0028: ldelema ""bool[]"" IL_002d: ldc.i4.1 IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SynthesizedStaticConstructor_WithEnableTestCoverage() { string source = @" #nullable enable class C { static object obj = null!; }" + InstrumentationHelperSource; var emitOptions = EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)); CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), emitOptions: emitOptions, symbolValidator: validator); void validator(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.Empty(type.GetMembers(".cctor")); } } private class SpanResult { public int StartLine { get; } public int StartColumn { get; } public int EndLine { get; } public int EndColumn { get; } public string TextStart { get; } public SpanResult(int startLine, int startColumn, int endLine, int endColumn, string textStart) { StartLine = startLine; StartColumn = startColumn; EndLine = endLine; EndColumn = endColumn; TextStart = textStart; } } private static void VerifySpans(DynamicAnalysisDataReader reader, DynamicAnalysisMethod methodData, string[] sourceLines, params SpanResult[] expected) { ArrayBuilder<string> expectedSpanSpellings = ArrayBuilder<string>.GetInstance(expected.Length); foreach (SpanResult expectedSpanResult in expected) { Assert.True(sourceLines[expectedSpanResult.StartLine].Substring(expectedSpanResult.StartColumn).StartsWith(expectedSpanResult.TextStart)); expectedSpanSpellings.Add(string.Format("({0},{1})-({2},{3})", expectedSpanResult.StartLine, expectedSpanResult.StartColumn, expectedSpanResult.EndLine, expectedSpanResult.EndColumn)); } VerifySpans(reader, methodData, expectedSpanSpellings.ToArrayAndFree()); } private static void VerifySpans(DynamicAnalysisDataReader reader, DynamicAnalysisMethod methodData, params string[] expected) { AssertEx.Equal(expected, reader.GetSpans(methodData.Blob).Select(s => $"({s.StartLine},{s.StartColumn})-({s.EndLine},{s.EndColumn})")); } private void VerifyDocuments(DynamicAnalysisDataReader reader, ImmutableArray<DynamicAnalysisDocument> documents, params string[] expected) { var sha1 = new Guid("ff1816ec-aa5e-4d10-87f7-6f4963833460"); var actual = from d in documents let name = reader.GetDocumentName(d.Name) let hash = d.Hash.IsNil ? "" : " " + BitConverter.ToString(reader.GetBytes(d.Hash)) let hashAlgGuid = reader.GetGuid(d.HashAlgorithm) let hashAlg = (hashAlgGuid == sha1) ? " (SHA1)" : (hashAlgGuid == default(Guid)) ? "" : " " + hashAlgGuid.ToString() select $"'{name}'{hash}{hashAlg}"; AssertEx.Equal(expected, actual); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/Core/Portable/Operations/IConvertibleConversion.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Operations { internal interface IConvertibleConversion { CommonConversion ToCommonConversion(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Operations { internal interface IConvertibleConversion { CommonConversion ToCommonConversion(); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/Core/Def/Implementation/Progression/ProgressionOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal static class ProgressionOptions { private const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Components\Progression\"; public static readonly Option2<bool> SearchUsingNavigateToEngine = new( nameof(ProgressionOptions), nameof(SearchUsingNavigateToEngine), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "SearchUsingNavigateToEngine")); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal static class ProgressionOptions { private const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Components\Progression\"; public static readonly Option2<bool> SearchUsingNavigateToEngine = new( nameof(ProgressionOptions), nameof(SearchUsingNavigateToEngine), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "SearchUsingNavigateToEngine")); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/InheritanceMarginTag.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin { internal class InheritanceMarginTag : IGlyphTag { /// <summary> /// Margin moniker. /// </summary> public ImageMoniker Moniker { get; } /// <summary> /// Members needs to be shown on this line. There might be multiple members. /// For example: /// interface IBar { void Foo1(); void Foo2(); } /// class Bar : IBar { void Foo1() { } void Foo2() { } } /// </summary> public readonly ImmutableArray<InheritanceMarginItem> MembersOnLine; /// <summary> /// Used for accessibility purpose. /// </summary> public readonly int LineNumber; public readonly Workspace Workspace; public InheritanceMarginTag(Workspace workspace, int lineNumber, ImmutableArray<InheritanceMarginItem> membersOnLine) { Contract.ThrowIfTrue(membersOnLine.IsEmpty); Workspace = workspace; LineNumber = lineNumber; MembersOnLine = membersOnLine; // The common case, one line has one member, avoid to use select & aggregate if (membersOnLine.Length == 1) { var member = membersOnLine[0]; var targets = member.TargetItems; var relationship = targets[0].RelationToMember; foreach (var target in targets.Skip(1)) { relationship |= target.RelationToMember; } Moniker = InheritanceMarginHelpers.GetMoniker(relationship); } else { // Multiple members on same line. var aggregateRelationship = membersOnLine .SelectMany(member => member.TargetItems.Select(target => target.RelationToMember)) .Aggregate((r1, r2) => r1 | r2); Moniker = InheritanceMarginHelpers.GetMoniker(aggregateRelationship); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin { internal class InheritanceMarginTag : IGlyphTag { /// <summary> /// Margin moniker. /// </summary> public ImageMoniker Moniker { get; } /// <summary> /// Members needs to be shown on this line. There might be multiple members. /// For example: /// interface IBar { void Foo1(); void Foo2(); } /// class Bar : IBar { void Foo1() { } void Foo2() { } } /// </summary> public readonly ImmutableArray<InheritanceMarginItem> MembersOnLine; /// <summary> /// Used for accessibility purpose. /// </summary> public readonly int LineNumber; public readonly Workspace Workspace; public InheritanceMarginTag(Workspace workspace, int lineNumber, ImmutableArray<InheritanceMarginItem> membersOnLine) { Contract.ThrowIfTrue(membersOnLine.IsEmpty); Workspace = workspace; LineNumber = lineNumber; MembersOnLine = membersOnLine; // The common case, one line has one member, avoid to use select & aggregate if (membersOnLine.Length == 1) { var member = membersOnLine[0]; var targets = member.TargetItems; var relationship = targets[0].RelationToMember; foreach (var target in targets.Skip(1)) { relationship |= target.RelationToMember; } Moniker = InheritanceMarginHelpers.GetMoniker(relationship); } else { // Multiple members on same line. var aggregateRelationship = membersOnLine .SelectMany(member => member.TargetItems.Select(target => target.RelationToMember)) .Aggregate((r1, r2) => r1 | r2); Moniker = InheritanceMarginHelpers.GetMoniker(aggregateRelationship); } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/CSharpTest/Structure/NamespaceDeclarationStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class NamespaceDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<NamespaceDeclarationSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new NamespaceDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespace() { const string code = @" class C { {|hint:$$namespace N{|textspan: { }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithLeadingComments() { const string code = @" class C { {|span1:// Goo // Bar|} {|hint2:$$namespace N{|textspan2: { }|}|} }"; await VerifyBlockSpansAsync(code, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithNestedUsings() { const string code = @" class C { {|hint1:$$namespace N{|textspan1: { {|hint2:using {|textspan2:System; using System.Linq;|}|} }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithNestedUsingsWithLeadingComments() { const string code = @" class C { {|hint1:$$namespace N{|textspan1: { {|span2:// Goo // Bar|} {|hint3:using {|textspan3:System; using System.Linq;|}|} }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("span2", "// Goo ...", autoCollapse: true), Region("textspan3", "hint3", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithNestedComments() { const string code = @" class C { {|hint1:$$namespace N{|textspan1: { {|span2:// Goo // Bar|} }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("span2", "// Goo ...", autoCollapse: true)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class NamespaceDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<NamespaceDeclarationSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new NamespaceDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespace() { const string code = @" class C { {|hint:$$namespace N{|textspan: { }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithLeadingComments() { const string code = @" class C { {|span1:// Goo // Bar|} {|hint2:$$namespace N{|textspan2: { }|}|} }"; await VerifyBlockSpansAsync(code, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithNestedUsings() { const string code = @" class C { {|hint1:$$namespace N{|textspan1: { {|hint2:using {|textspan2:System; using System.Linq;|}|} }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithNestedUsingsWithLeadingComments() { const string code = @" class C { {|hint1:$$namespace N{|textspan1: { {|span2:// Goo // Bar|} {|hint3:using {|textspan3:System; using System.Linq;|}|} }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("span2", "// Goo ...", autoCollapse: true), Region("textspan3", "hint3", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestNamespaceWithNestedComments() { const string code = @" class C { {|hint1:$$namespace N{|textspan1: { {|span2:// Goo // Bar|} }|}|} }"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("span2", "// Goo ...", autoCollapse: true)); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/Core/CodeAnalysisTest/FileSystem/PathUtilitiesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.FileSystem { public class PathUtilitiesTests { private void TestGetDirectoryNameAndCompareToDotnet(string expectedDirectoryName, string fullPath) { var roslynName = PathUtilities.TestAccessor.GetDirectoryName(fullPath, isUnixLike: false); Assert.Equal(expectedDirectoryName, roslynName); var dotnetName = Path.GetDirectoryName(fullPath); Assert.Equal(dotnetName, roslynName); } [ConditionalFact(typeof(WindowsOnly))] public void TestGetDirectoryName_WindowsPaths_Absolute() { TestGetDirectoryNameAndCompareToDotnet(@"C:\temp", @"C:\temp\goo.txt"); TestGetDirectoryNameAndCompareToDotnet(@"C:\temp", @"C:\temp\goo"); TestGetDirectoryNameAndCompareToDotnet(@"C:\temp", @"C:\temp\"); TestGetDirectoryNameAndCompareToDotnet(@"C:\", @"C:\temp"); TestGetDirectoryNameAndCompareToDotnet(null, @"C:\"); TestGetDirectoryNameAndCompareToDotnet(null, @"C:"); // dotnet throws on empty argument. But not on null... go figure. Assert.Null(PathUtilities.TestAccessor.GetDirectoryName(@"", isUnixLike: false)); TestGetDirectoryNameAndCompareToDotnet(null, null); } [ConditionalFact(typeof(WindowsOnly))] public void TestGetDirectoryName_WindowsPaths_Relative() { TestGetDirectoryNameAndCompareToDotnet(@"goo\temp", @"goo\temp\goo.txt"); TestGetDirectoryNameAndCompareToDotnet(@"goo\temp", @"goo\temp\goo"); TestGetDirectoryNameAndCompareToDotnet(@"goo\temp", @"goo\temp\"); TestGetDirectoryNameAndCompareToDotnet(@"goo", @"goo\temp"); TestGetDirectoryNameAndCompareToDotnet(@"goo", @"goo\"); TestGetDirectoryNameAndCompareToDotnet("", @"goo"); } [Fact] public void TestGetDirectoryName_UnixPaths_Absolute() { Assert.Equal( @"/temp", PathUtilities.TestAccessor.GetDirectoryName(@"/temp/goo.txt", isUnixLike: true)); Assert.Equal( @"/temp", PathUtilities.TestAccessor.GetDirectoryName(@"/temp/goo", isUnixLike: true)); Assert.Equal( @"/temp", PathUtilities.TestAccessor.GetDirectoryName(@"/temp/", isUnixLike: true)); Assert.Equal( @"/", PathUtilities.TestAccessor.GetDirectoryName(@"/temp", isUnixLike: true)); Assert.Null( PathUtilities.TestAccessor.GetDirectoryName(@"/", isUnixLike: true)); Assert.Null( PathUtilities.TestAccessor.GetDirectoryName(@"", isUnixLike: true)); Assert.Null( PathUtilities.TestAccessor.GetDirectoryName(null, isUnixLike: true)); } [Fact] public void TestGetDirectoryName_UnixPaths_Relative() { Assert.Equal( @"goo/temp", PathUtilities.TestAccessor.GetDirectoryName(@"goo/temp/goo.txt", isUnixLike: true)); Assert.Equal( @"goo/temp", PathUtilities.TestAccessor.GetDirectoryName(@"goo/temp/goo", isUnixLike: true)); Assert.Equal( @"goo/temp", PathUtilities.TestAccessor.GetDirectoryName(@"goo/temp/", isUnixLike: true)); Assert.Equal( @"goo", PathUtilities.TestAccessor.GetDirectoryName(@"goo/temp", isUnixLike: true)); Assert.Equal( @"goo", PathUtilities.TestAccessor.GetDirectoryName(@"goo/", isUnixLike: true)); Assert.Equal( "", PathUtilities.TestAccessor.GetDirectoryName(@"goo", isUnixLike: true)); Assert.Null( PathUtilities.TestAccessor.GetDirectoryName(@"", isUnixLike: true)); Assert.Null( PathUtilities.TestAccessor.GetDirectoryName(null, isUnixLike: true)); } [ConditionalFact(typeof(WindowsOnly))] public void TestGetDirectoryName_WindowsSharePaths() { TestGetDirectoryNameAndCompareToDotnet(@"\\server\temp", @"\\server\temp\goo.txt"); TestGetDirectoryNameAndCompareToDotnet(@"\\server\temp", @"\\server\temp\goo"); TestGetDirectoryNameAndCompareToDotnet(@"\\server\temp", @"\\server\temp\"); TestGetDirectoryNameAndCompareToDotnet(null, @"\\server\temp"); TestGetDirectoryNameAndCompareToDotnet(null, @"\\server\"); TestGetDirectoryNameAndCompareToDotnet(null, @"\\server"); TestGetDirectoryNameAndCompareToDotnet(null, @"\\"); TestGetDirectoryNameAndCompareToDotnet(null, @"\"); } [ConditionalFact(typeof(WindowsOnly))] public void TestGetDirectoryName_EsotericCases() { TestGetDirectoryNameAndCompareToDotnet(@"C:\temp", @"C:\temp\\goo.txt"); TestGetDirectoryNameAndCompareToDotnet(@"C:\temp", @"C:\temp\\\goo.txt"); // Dotnet does normalization of dots, so we can't compare against it here. Assert.Equal( @"C:\temp\..", PathUtilities.TestAccessor.GetDirectoryName(@"C:\temp\..\goo.txt", isUnixLike: false)); Assert.Equal( @"C:\temp", PathUtilities.TestAccessor.GetDirectoryName(@"C:\temp\..", isUnixLike: false)); Assert.Equal( @"C:\temp\.", PathUtilities.TestAccessor.GetDirectoryName(@"C:\temp\.\goo.txt", isUnixLike: false)); Assert.Equal( @"C:\temp", PathUtilities.TestAccessor.GetDirectoryName(@"C:\temp\.", isUnixLike: false)); TestGetDirectoryNameAndCompareToDotnet(@"C:temp", @"C:temp\\goo.txt"); TestGetDirectoryNameAndCompareToDotnet(@"C:temp", @"C:temp\\\goo.txt"); Assert.Equal( @"C:temp\..", PathUtilities.TestAccessor.GetDirectoryName(@"C:temp\..\goo.txt", isUnixLike: false)); Assert.Equal( @"C:temp", PathUtilities.TestAccessor.GetDirectoryName(@"C:temp\..", isUnixLike: false)); Assert.Equal( @"C:temp\.", PathUtilities.TestAccessor.GetDirectoryName(@"C:temp\.\goo.txt", isUnixLike: false)); Assert.Equal( @"C:temp", PathUtilities.TestAccessor.GetDirectoryName(@"C:temp\.", isUnixLike: false)); TestGetDirectoryNameAndCompareToDotnet(@"C:temp", @"C:temp\"); TestGetDirectoryNameAndCompareToDotnet(@"C:", @"C:temp"); TestGetDirectoryNameAndCompareToDotnet(null, @"C:"); } [ConditionalFact(typeof(WindowsOnly))] public void TestContainsPathComponent() { Assert.True( PathUtilities.ContainsPathComponent(@"c:\packages\temp", "packages", ignoreCase: true)); Assert.True( PathUtilities.ContainsPathComponent(@"\\server\packages\temp", "packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"\\packages\temp", "packages", ignoreCase: true)); Assert.True( PathUtilities.ContainsPathComponent(@"c:\packages", "packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\packages1\temp", "packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\package\temp", "packages", ignoreCase: true)); Assert.True( PathUtilities.ContainsPathComponent(@"c:\packages\temp", "packages", ignoreCase: false)); Assert.True( PathUtilities.ContainsPathComponent(@"\\server\packages\temp", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"\\packages\temp", "packages", ignoreCase: false)); Assert.True( PathUtilities.ContainsPathComponent(@"c:\packages", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\packages1\temp", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\package\temp", "packages", ignoreCase: false)); Assert.True( PathUtilities.ContainsPathComponent(@"c:\packages\temp", "Packages", ignoreCase: true)); Assert.True( PathUtilities.ContainsPathComponent(@"\\server\packages\temp", "Packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"\\packages\temp", "Packages", ignoreCase: true)); Assert.True( PathUtilities.ContainsPathComponent(@"c:\packages", "Packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\packages1\temp", "Packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\package\temp", "Packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\packages\temp", "Packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"\\server\packages\temp", "Packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"\\packages\temp", "Packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\packages", "Packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\packages1\temp", "Packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\package\temp", "Packages", ignoreCase: false)); Assert.True( PathUtilities.ContainsPathComponent(@"c:\Packages\temp", "packages", ignoreCase: true)); Assert.True( PathUtilities.ContainsPathComponent(@"\\server\Packages\temp", "packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"\\Packages\temp", "packages", ignoreCase: true)); Assert.True( PathUtilities.ContainsPathComponent(@"c:\Packages", "packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\Packages1\temp", "packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\Package\temp", "packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\Packages\temp", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"\\server\Packages\temp", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"\\Packages\temp", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\Packages", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\Packages1\temp", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\Package\temp", "packages", ignoreCase: false)); } [ConditionalFact(typeof(WindowsOnly))] public void IsSameDirectoryOrChildOfHandlesDifferentSlashes() { Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\", @"C:")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\", @"C:\")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:", @"C:")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:", @"C:\")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH", @"C:")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH", @"C:\")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH\", @"C:")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH\", @"C:\")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH", @"C:\ABCD")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH", @"C:\ABCD\")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH\", @"C:\ABCD")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH\", @"C:\ABCD\")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH", @"C:\ABCD\EFGH")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH", @"C:\ABCD\EFGH\")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH\", @"C:\ABCD\EFGH")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH\", @"C:\ABCD\EFGH\")); } [Fact] public void IsSameDirectoryOrChildOfNegativeTests() { Assert.False(PathUtilities.IsSameDirectoryOrChildOf(@"C:\", @"C:\ABCD")); Assert.False(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABC", @"C:\ABCD")); Assert.False(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCDE", @"C:\ABCD")); Assert.False(PathUtilities.IsSameDirectoryOrChildOf(@"C:\A\B\C", @"C:\A\B\C\D")); } [Fact] public void IsValidFilePath() { var cases = new[] { ("test/data1.txt", true), ("test\\data1.txt", true), ("data1.txt", true), ("data1", true), ("data1\\", PathUtilities.IsUnixLikePlatform), ("data1//", false), (null, false), ("", false), (" ", ExecutionConditionUtil.IsCoreClrUnix), ("path/?.txt", !ExecutionConditionUtil.IsWindowsDesktop), ("path/*.txt", !ExecutionConditionUtil.IsWindowsDesktop), ("path/:.txt", !ExecutionConditionUtil.IsWindowsDesktop), ("path/\".txt", !ExecutionConditionUtil.IsWindowsDesktop), ("IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII" + "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII" + "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII" + "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII" + "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII.txt", !ExecutionConditionUtil.IsWindowsDesktop) }; foreach (var (path, isValid) in cases) { Assert.True(isValid == PathUtilities.IsValidFilePath(path), $"Expected {isValid} for \"{path}\""); } } [ConditionalTheory(typeof(WindowsOnly))] [InlineData(@"C:\", "B")] [InlineData(@"C:\A", "B")] [InlineData(@"C:\A\", "B")] [InlineData(@"C:A\", "B")] [InlineData(@"\A", "B")] [InlineData(@"\\A\B\C", "B")] [InlineData(@"C", @"B:\")] [InlineData(@"C:", @"B:\")] [InlineData(@"C:\", @"B:\")] [InlineData(@"C:\A", @"B:\")] [InlineData(@"C:\A\", @"B:\")] [InlineData(@"C:A\", @"B:\")] [InlineData(@"\A", @"B:\")] [InlineData(@"\\A\B\C", @"B:\")] [InlineData("", @"B:\")] [InlineData(" ", @"B:\")] public void CombinePaths_SameAsPathCombine_Windows(string path1, string path2) { Assert.Equal(Path.Combine(path1, path2), PathUtilities.CombinePaths(path1, path2)); } [ConditionalTheory(typeof(UnixLikeOnly))] [InlineData("C", "B")] [InlineData("C/", "\t")] [InlineData("C/", "B")] [InlineData("/C", "B")] [InlineData("/C/", "B")] [InlineData("C", "/B")] [InlineData("C/", "/B")] [InlineData("/C", "/B")] [InlineData("/C/", "/B")] [InlineData("", "/B/")] [InlineData(" ", "/B/")] public void CombinePaths_SameAsPathCombine_Linux(string path1, string path2) { Assert.Equal(Path.Combine(path1, path2), PathUtilities.CombinePaths(path1, path2)); } [Theory] [InlineData("C", " ")] [InlineData("C", "B")] [InlineData("", "")] [InlineData(" ", " ")] [InlineData("", "B")] [InlineData(" ", "B")] public void CombinePaths_SameAsPathCombine_Common(string path1, string path2) { Assert.Equal(Path.Combine(path1, path2), PathUtilities.CombinePaths(path1, path2)); } [ConditionalTheory(typeof(WindowsOnly))] [InlineData(@"C:\|\<>", @"C:\|", "<>")] [InlineData("C:\\\t", @"C:\", "\t")] [InlineData("C", "C", null)] [InlineData("C:B", "C:", "B")] [InlineData(null, null, null)] [InlineData("B", null, "B")] public void CombinePaths_DifferentFromPathCombine(string expected, string path1, string path2) { Assert.Equal(expected, PathUtilities.CombinePaths(path1, path2)); } [ConditionalFact(typeof(WindowsOnly)), WorkItem(51602, @"https://github.com/dotnet/roslyn/issues/51602")] public void GetRelativePath_EnsureNo_IndexOutOfRangeException_Windows() { var expected = ""; var result = PathUtilities.GetRelativePath(@"C:\A\B\", @"C:\A\B"); Assert.Equal(expected, result); } [ConditionalFact(typeof(UnixLikeOnly)), WorkItem(51602, @"https://github.com/dotnet/roslyn/issues/51602")] public void GetRelativePath_EnsureNo_IndexOutOfRangeException_Unix() { var expected = ""; var result = PathUtilities.GetRelativePath(@"/A/B/", @"/A/B"); Assert.Equal(expected, result); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.FileSystem { public class PathUtilitiesTests { private void TestGetDirectoryNameAndCompareToDotnet(string expectedDirectoryName, string fullPath) { var roslynName = PathUtilities.TestAccessor.GetDirectoryName(fullPath, isUnixLike: false); Assert.Equal(expectedDirectoryName, roslynName); var dotnetName = Path.GetDirectoryName(fullPath); Assert.Equal(dotnetName, roslynName); } [ConditionalFact(typeof(WindowsOnly))] public void TestGetDirectoryName_WindowsPaths_Absolute() { TestGetDirectoryNameAndCompareToDotnet(@"C:\temp", @"C:\temp\goo.txt"); TestGetDirectoryNameAndCompareToDotnet(@"C:\temp", @"C:\temp\goo"); TestGetDirectoryNameAndCompareToDotnet(@"C:\temp", @"C:\temp\"); TestGetDirectoryNameAndCompareToDotnet(@"C:\", @"C:\temp"); TestGetDirectoryNameAndCompareToDotnet(null, @"C:\"); TestGetDirectoryNameAndCompareToDotnet(null, @"C:"); // dotnet throws on empty argument. But not on null... go figure. Assert.Null(PathUtilities.TestAccessor.GetDirectoryName(@"", isUnixLike: false)); TestGetDirectoryNameAndCompareToDotnet(null, null); } [ConditionalFact(typeof(WindowsOnly))] public void TestGetDirectoryName_WindowsPaths_Relative() { TestGetDirectoryNameAndCompareToDotnet(@"goo\temp", @"goo\temp\goo.txt"); TestGetDirectoryNameAndCompareToDotnet(@"goo\temp", @"goo\temp\goo"); TestGetDirectoryNameAndCompareToDotnet(@"goo\temp", @"goo\temp\"); TestGetDirectoryNameAndCompareToDotnet(@"goo", @"goo\temp"); TestGetDirectoryNameAndCompareToDotnet(@"goo", @"goo\"); TestGetDirectoryNameAndCompareToDotnet("", @"goo"); } [Fact] public void TestGetDirectoryName_UnixPaths_Absolute() { Assert.Equal( @"/temp", PathUtilities.TestAccessor.GetDirectoryName(@"/temp/goo.txt", isUnixLike: true)); Assert.Equal( @"/temp", PathUtilities.TestAccessor.GetDirectoryName(@"/temp/goo", isUnixLike: true)); Assert.Equal( @"/temp", PathUtilities.TestAccessor.GetDirectoryName(@"/temp/", isUnixLike: true)); Assert.Equal( @"/", PathUtilities.TestAccessor.GetDirectoryName(@"/temp", isUnixLike: true)); Assert.Null( PathUtilities.TestAccessor.GetDirectoryName(@"/", isUnixLike: true)); Assert.Null( PathUtilities.TestAccessor.GetDirectoryName(@"", isUnixLike: true)); Assert.Null( PathUtilities.TestAccessor.GetDirectoryName(null, isUnixLike: true)); } [Fact] public void TestGetDirectoryName_UnixPaths_Relative() { Assert.Equal( @"goo/temp", PathUtilities.TestAccessor.GetDirectoryName(@"goo/temp/goo.txt", isUnixLike: true)); Assert.Equal( @"goo/temp", PathUtilities.TestAccessor.GetDirectoryName(@"goo/temp/goo", isUnixLike: true)); Assert.Equal( @"goo/temp", PathUtilities.TestAccessor.GetDirectoryName(@"goo/temp/", isUnixLike: true)); Assert.Equal( @"goo", PathUtilities.TestAccessor.GetDirectoryName(@"goo/temp", isUnixLike: true)); Assert.Equal( @"goo", PathUtilities.TestAccessor.GetDirectoryName(@"goo/", isUnixLike: true)); Assert.Equal( "", PathUtilities.TestAccessor.GetDirectoryName(@"goo", isUnixLike: true)); Assert.Null( PathUtilities.TestAccessor.GetDirectoryName(@"", isUnixLike: true)); Assert.Null( PathUtilities.TestAccessor.GetDirectoryName(null, isUnixLike: true)); } [ConditionalFact(typeof(WindowsOnly))] public void TestGetDirectoryName_WindowsSharePaths() { TestGetDirectoryNameAndCompareToDotnet(@"\\server\temp", @"\\server\temp\goo.txt"); TestGetDirectoryNameAndCompareToDotnet(@"\\server\temp", @"\\server\temp\goo"); TestGetDirectoryNameAndCompareToDotnet(@"\\server\temp", @"\\server\temp\"); TestGetDirectoryNameAndCompareToDotnet(null, @"\\server\temp"); TestGetDirectoryNameAndCompareToDotnet(null, @"\\server\"); TestGetDirectoryNameAndCompareToDotnet(null, @"\\server"); TestGetDirectoryNameAndCompareToDotnet(null, @"\\"); TestGetDirectoryNameAndCompareToDotnet(null, @"\"); } [ConditionalFact(typeof(WindowsOnly))] public void TestGetDirectoryName_EsotericCases() { TestGetDirectoryNameAndCompareToDotnet(@"C:\temp", @"C:\temp\\goo.txt"); TestGetDirectoryNameAndCompareToDotnet(@"C:\temp", @"C:\temp\\\goo.txt"); // Dotnet does normalization of dots, so we can't compare against it here. Assert.Equal( @"C:\temp\..", PathUtilities.TestAccessor.GetDirectoryName(@"C:\temp\..\goo.txt", isUnixLike: false)); Assert.Equal( @"C:\temp", PathUtilities.TestAccessor.GetDirectoryName(@"C:\temp\..", isUnixLike: false)); Assert.Equal( @"C:\temp\.", PathUtilities.TestAccessor.GetDirectoryName(@"C:\temp\.\goo.txt", isUnixLike: false)); Assert.Equal( @"C:\temp", PathUtilities.TestAccessor.GetDirectoryName(@"C:\temp\.", isUnixLike: false)); TestGetDirectoryNameAndCompareToDotnet(@"C:temp", @"C:temp\\goo.txt"); TestGetDirectoryNameAndCompareToDotnet(@"C:temp", @"C:temp\\\goo.txt"); Assert.Equal( @"C:temp\..", PathUtilities.TestAccessor.GetDirectoryName(@"C:temp\..\goo.txt", isUnixLike: false)); Assert.Equal( @"C:temp", PathUtilities.TestAccessor.GetDirectoryName(@"C:temp\..", isUnixLike: false)); Assert.Equal( @"C:temp\.", PathUtilities.TestAccessor.GetDirectoryName(@"C:temp\.\goo.txt", isUnixLike: false)); Assert.Equal( @"C:temp", PathUtilities.TestAccessor.GetDirectoryName(@"C:temp\.", isUnixLike: false)); TestGetDirectoryNameAndCompareToDotnet(@"C:temp", @"C:temp\"); TestGetDirectoryNameAndCompareToDotnet(@"C:", @"C:temp"); TestGetDirectoryNameAndCompareToDotnet(null, @"C:"); } [ConditionalFact(typeof(WindowsOnly))] public void TestContainsPathComponent() { Assert.True( PathUtilities.ContainsPathComponent(@"c:\packages\temp", "packages", ignoreCase: true)); Assert.True( PathUtilities.ContainsPathComponent(@"\\server\packages\temp", "packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"\\packages\temp", "packages", ignoreCase: true)); Assert.True( PathUtilities.ContainsPathComponent(@"c:\packages", "packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\packages1\temp", "packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\package\temp", "packages", ignoreCase: true)); Assert.True( PathUtilities.ContainsPathComponent(@"c:\packages\temp", "packages", ignoreCase: false)); Assert.True( PathUtilities.ContainsPathComponent(@"\\server\packages\temp", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"\\packages\temp", "packages", ignoreCase: false)); Assert.True( PathUtilities.ContainsPathComponent(@"c:\packages", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\packages1\temp", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\package\temp", "packages", ignoreCase: false)); Assert.True( PathUtilities.ContainsPathComponent(@"c:\packages\temp", "Packages", ignoreCase: true)); Assert.True( PathUtilities.ContainsPathComponent(@"\\server\packages\temp", "Packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"\\packages\temp", "Packages", ignoreCase: true)); Assert.True( PathUtilities.ContainsPathComponent(@"c:\packages", "Packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\packages1\temp", "Packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\package\temp", "Packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\packages\temp", "Packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"\\server\packages\temp", "Packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"\\packages\temp", "Packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\packages", "Packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\packages1\temp", "Packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\package\temp", "Packages", ignoreCase: false)); Assert.True( PathUtilities.ContainsPathComponent(@"c:\Packages\temp", "packages", ignoreCase: true)); Assert.True( PathUtilities.ContainsPathComponent(@"\\server\Packages\temp", "packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"\\Packages\temp", "packages", ignoreCase: true)); Assert.True( PathUtilities.ContainsPathComponent(@"c:\Packages", "packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\Packages1\temp", "packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\Package\temp", "packages", ignoreCase: true)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\Packages\temp", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"\\server\Packages\temp", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"\\Packages\temp", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\Packages", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\Packages1\temp", "packages", ignoreCase: false)); Assert.False( PathUtilities.ContainsPathComponent(@"c:\Package\temp", "packages", ignoreCase: false)); } [ConditionalFact(typeof(WindowsOnly))] public void IsSameDirectoryOrChildOfHandlesDifferentSlashes() { Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\", @"C:")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\", @"C:\")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:", @"C:")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:", @"C:\")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH", @"C:")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH", @"C:\")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH\", @"C:")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH\", @"C:\")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH", @"C:\ABCD")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH", @"C:\ABCD\")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH\", @"C:\ABCD")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH\", @"C:\ABCD\")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH", @"C:\ABCD\EFGH")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH", @"C:\ABCD\EFGH\")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH\", @"C:\ABCD\EFGH")); Assert.True(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCD\EFGH\", @"C:\ABCD\EFGH\")); } [Fact] public void IsSameDirectoryOrChildOfNegativeTests() { Assert.False(PathUtilities.IsSameDirectoryOrChildOf(@"C:\", @"C:\ABCD")); Assert.False(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABC", @"C:\ABCD")); Assert.False(PathUtilities.IsSameDirectoryOrChildOf(@"C:\ABCDE", @"C:\ABCD")); Assert.False(PathUtilities.IsSameDirectoryOrChildOf(@"C:\A\B\C", @"C:\A\B\C\D")); } [Fact] public void IsValidFilePath() { var cases = new[] { ("test/data1.txt", true), ("test\\data1.txt", true), ("data1.txt", true), ("data1", true), ("data1\\", PathUtilities.IsUnixLikePlatform), ("data1//", false), (null, false), ("", false), (" ", ExecutionConditionUtil.IsCoreClrUnix), ("path/?.txt", !ExecutionConditionUtil.IsWindowsDesktop), ("path/*.txt", !ExecutionConditionUtil.IsWindowsDesktop), ("path/:.txt", !ExecutionConditionUtil.IsWindowsDesktop), ("path/\".txt", !ExecutionConditionUtil.IsWindowsDesktop), ("IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII" + "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII" + "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII" + "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII" + "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII.txt", !ExecutionConditionUtil.IsWindowsDesktop) }; foreach (var (path, isValid) in cases) { Assert.True(isValid == PathUtilities.IsValidFilePath(path), $"Expected {isValid} for \"{path}\""); } } [ConditionalTheory(typeof(WindowsOnly))] [InlineData(@"C:\", "B")] [InlineData(@"C:\A", "B")] [InlineData(@"C:\A\", "B")] [InlineData(@"C:A\", "B")] [InlineData(@"\A", "B")] [InlineData(@"\\A\B\C", "B")] [InlineData(@"C", @"B:\")] [InlineData(@"C:", @"B:\")] [InlineData(@"C:\", @"B:\")] [InlineData(@"C:\A", @"B:\")] [InlineData(@"C:\A\", @"B:\")] [InlineData(@"C:A\", @"B:\")] [InlineData(@"\A", @"B:\")] [InlineData(@"\\A\B\C", @"B:\")] [InlineData("", @"B:\")] [InlineData(" ", @"B:\")] public void CombinePaths_SameAsPathCombine_Windows(string path1, string path2) { Assert.Equal(Path.Combine(path1, path2), PathUtilities.CombinePaths(path1, path2)); } [ConditionalTheory(typeof(UnixLikeOnly))] [InlineData("C", "B")] [InlineData("C/", "\t")] [InlineData("C/", "B")] [InlineData("/C", "B")] [InlineData("/C/", "B")] [InlineData("C", "/B")] [InlineData("C/", "/B")] [InlineData("/C", "/B")] [InlineData("/C/", "/B")] [InlineData("", "/B/")] [InlineData(" ", "/B/")] public void CombinePaths_SameAsPathCombine_Linux(string path1, string path2) { Assert.Equal(Path.Combine(path1, path2), PathUtilities.CombinePaths(path1, path2)); } [Theory] [InlineData("C", " ")] [InlineData("C", "B")] [InlineData("", "")] [InlineData(" ", " ")] [InlineData("", "B")] [InlineData(" ", "B")] public void CombinePaths_SameAsPathCombine_Common(string path1, string path2) { Assert.Equal(Path.Combine(path1, path2), PathUtilities.CombinePaths(path1, path2)); } [ConditionalTheory(typeof(WindowsOnly))] [InlineData(@"C:\|\<>", @"C:\|", "<>")] [InlineData("C:\\\t", @"C:\", "\t")] [InlineData("C", "C", null)] [InlineData("C:B", "C:", "B")] [InlineData(null, null, null)] [InlineData("B", null, "B")] public void CombinePaths_DifferentFromPathCombine(string expected, string path1, string path2) { Assert.Equal(expected, PathUtilities.CombinePaths(path1, path2)); } [ConditionalFact(typeof(WindowsOnly)), WorkItem(51602, @"https://github.com/dotnet/roslyn/issues/51602")] public void GetRelativePath_EnsureNo_IndexOutOfRangeException_Windows() { var expected = ""; var result = PathUtilities.GetRelativePath(@"C:\A\B\", @"C:\A\B"); Assert.Equal(expected, result); } [ConditionalFact(typeof(UnixLikeOnly)), WorkItem(51602, @"https://github.com/dotnet/roslyn/issues/51602")] public void GetRelativePath_EnsureNo_IndexOutOfRangeException_Unix() { var expected = ""; var result = PathUtilities.GetRelativePath(@"/A/B/", @"/A/B"); Assert.Equal(expected, result); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Test/Syntax/Syntax/ChildSyntaxListTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ChildSyntaxListTests : CSharpTestBase { [Fact] public void Equality() { var node1 = SyntaxFactory.ReturnStatement(); var node2 = SyntaxFactory.ReturnStatement(); EqualityTesting.AssertEqual(default(ChildSyntaxList), default(ChildSyntaxList)); EqualityTesting.AssertEqual(new ChildSyntaxList(node1), new ChildSyntaxList(node1)); } [Fact] public void Reverse_Equality() { var node1 = SyntaxFactory.ReturnStatement(); var node2 = SyntaxFactory.ReturnStatement(); EqualityTesting.AssertEqual(default(ChildSyntaxList.Reversed), default(ChildSyntaxList.Reversed)); EqualityTesting.AssertEqual(new ChildSyntaxList(node1).Reverse(), new ChildSyntaxList(node1).Reverse()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ChildSyntaxListTests : CSharpTestBase { [Fact] public void Equality() { var node1 = SyntaxFactory.ReturnStatement(); var node2 = SyntaxFactory.ReturnStatement(); EqualityTesting.AssertEqual(default(ChildSyntaxList), default(ChildSyntaxList)); EqualityTesting.AssertEqual(new ChildSyntaxList(node1), new ChildSyntaxList(node1)); } [Fact] public void Reverse_Equality() { var node1 = SyntaxFactory.ReturnStatement(); var node2 = SyntaxFactory.ReturnStatement(); EqualityTesting.AssertEqual(default(ChildSyntaxList.Reversed), default(ChildSyntaxList.Reversed)); EqualityTesting.AssertEqual(new ChildSyntaxList(node1).Reverse(), new ChildSyntaxList(node1).Reverse()); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/QuickInfo/QuickInfoContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; namespace Microsoft.CodeAnalysis.QuickInfo { /// <summary> /// The context presented to a <see cref="QuickInfoProvider"/> when providing quick info. /// </summary> internal sealed class QuickInfoContext { /// <summary> /// The document that quick info was requested within. /// </summary> public Document Document { get; } /// <summary> /// The caret position where quick info was requested from. /// </summary> public int Position { get; } /// <summary> /// The cancellation token to use for this operation. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Creates a <see cref="QuickInfoContext"/> instance. /// </summary> public QuickInfoContext( Document document, int position, CancellationToken cancellationToken) { Document = document ?? throw new ArgumentNullException(nameof(document)); Position = position; CancellationToken = cancellationToken; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; namespace Microsoft.CodeAnalysis.QuickInfo { /// <summary> /// The context presented to a <see cref="QuickInfoProvider"/> when providing quick info. /// </summary> internal sealed class QuickInfoContext { /// <summary> /// The document that quick info was requested within. /// </summary> public Document Document { get; } /// <summary> /// The caret position where quick info was requested from. /// </summary> public int Position { get; } /// <summary> /// The cancellation token to use for this operation. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Creates a <see cref="QuickInfoContext"/> instance. /// </summary> public QuickInfoContext( Document document, int position, CancellationToken cancellationToken) { Document = document ?? throw new ArgumentNullException(nameof(document)); Position = position; CancellationToken = cancellationToken; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/Completion/CompletionTags.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel; using Microsoft.CodeAnalysis.Tags; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// The set of well known tags used for the <see cref="CompletionItem.Tags"/> property. /// These tags influence the presentation of items in the list. /// </summary> [Obsolete("Use Microsoft.CodeAnalysis.Tags.WellKnownTags instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public static class CompletionTags { // accessibility public const string Public = WellKnownTags.Public; public const string Protected = WellKnownTags.Protected; public const string Private = WellKnownTags.Private; public const string Internal = WellKnownTags.Internal; // project elements public const string File = WellKnownTags.File; public const string Project = WellKnownTags.Project; public const string Folder = WellKnownTags.Folder; public const string Assembly = WellKnownTags.Assembly; // language elements public const string Class = WellKnownTags.Class; public const string Constant = WellKnownTags.Constant; public const string Delegate = WellKnownTags.Delegate; public const string Enum = WellKnownTags.Enum; public const string EnumMember = WellKnownTags.EnumMember; public const string Event = WellKnownTags.Event; public const string ExtensionMethod = WellKnownTags.ExtensionMethod; public const string Field = WellKnownTags.Field; public const string Interface = WellKnownTags.Interface; public const string Intrinsic = WellKnownTags.Intrinsic; public const string Keyword = WellKnownTags.Keyword; public const string Label = WellKnownTags.Label; public const string Local = WellKnownTags.Local; public const string Namespace = WellKnownTags.Namespace; public const string Method = WellKnownTags.Method; public const string Module = WellKnownTags.Module; public const string Operator = WellKnownTags.Operator; public const string Parameter = WellKnownTags.Parameter; public const string Property = WellKnownTags.Property; public const string RangeVariable = WellKnownTags.RangeVariable; public const string Reference = WellKnownTags.Reference; public const string Structure = WellKnownTags.Structure; public const string TypeParameter = WellKnownTags.TypeParameter; // other public const string Snippet = WellKnownTags.Snippet; public const string Error = WellKnownTags.Error; public const string Warning = WellKnownTags.Warning; internal const string StatusInformation = WellKnownTags.StatusInformation; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel; using Microsoft.CodeAnalysis.Tags; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// The set of well known tags used for the <see cref="CompletionItem.Tags"/> property. /// These tags influence the presentation of items in the list. /// </summary> [Obsolete("Use Microsoft.CodeAnalysis.Tags.WellKnownTags instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public static class CompletionTags { // accessibility public const string Public = WellKnownTags.Public; public const string Protected = WellKnownTags.Protected; public const string Private = WellKnownTags.Private; public const string Internal = WellKnownTags.Internal; // project elements public const string File = WellKnownTags.File; public const string Project = WellKnownTags.Project; public const string Folder = WellKnownTags.Folder; public const string Assembly = WellKnownTags.Assembly; // language elements public const string Class = WellKnownTags.Class; public const string Constant = WellKnownTags.Constant; public const string Delegate = WellKnownTags.Delegate; public const string Enum = WellKnownTags.Enum; public const string EnumMember = WellKnownTags.EnumMember; public const string Event = WellKnownTags.Event; public const string ExtensionMethod = WellKnownTags.ExtensionMethod; public const string Field = WellKnownTags.Field; public const string Interface = WellKnownTags.Interface; public const string Intrinsic = WellKnownTags.Intrinsic; public const string Keyword = WellKnownTags.Keyword; public const string Label = WellKnownTags.Label; public const string Local = WellKnownTags.Local; public const string Namespace = WellKnownTags.Namespace; public const string Method = WellKnownTags.Method; public const string Module = WellKnownTags.Module; public const string Operator = WellKnownTags.Operator; public const string Parameter = WellKnownTags.Parameter; public const string Property = WellKnownTags.Property; public const string RangeVariable = WellKnownTags.RangeVariable; public const string Reference = WellKnownTags.Reference; public const string Structure = WellKnownTags.Structure; public const string TypeParameter = WellKnownTags.TypeParameter; // other public const string Snippet = WellKnownTags.Snippet; public const string Error = WellKnownTags.Error; public const string Warning = WellKnownTags.Warning; internal const string StatusInformation = WellKnownTags.StatusInformation; } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Test/Perf/Utilities/Logger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Text; namespace Roslyn.Test.Performance.Utilities { /// <summary> /// An interface for logging messages. A global ILogger implementation /// exists at Roslyn.Test.Performance.Utilities.RuntimeSettings.logger. /// </summary> public interface ILogger { /// <summary> /// Logs a string through the logger. /// </summary> /// <param name="v"></param> void Log(string v); /// <summary> /// Flushes the cache (if one exists). /// </summary> void Flush(); } /// <summary> /// An implementation of ILogger that prints to the console, and also /// writes to a file. /// </summary> public class ConsoleAndFileLogger : ILogger { private readonly string _file; private readonly StringBuilder _buffer = new StringBuilder(); /// <summary> /// Constructs a new ConsoleAndFileLogger with a default log /// file of 'log.txt'. /// </summary> public ConsoleAndFileLogger() { if (Directory.Exists(TestUtilities.GetCPCDirectoryPath())) { _file = Path.Combine(TestUtilities.GetCPCDirectoryPath(), "perf-log.txt"); } else { _file = "./perf-log.txt"; } } void ILogger.Flush() { File.AppendAllText(_file, _buffer.ToString()); _buffer.Clear(); } void ILogger.Log(string v) { Console.WriteLine(DateTime.Now + " : " + v); _buffer.AppendLine(DateTime.Now + " : " + v); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Text; namespace Roslyn.Test.Performance.Utilities { /// <summary> /// An interface for logging messages. A global ILogger implementation /// exists at Roslyn.Test.Performance.Utilities.RuntimeSettings.logger. /// </summary> public interface ILogger { /// <summary> /// Logs a string through the logger. /// </summary> /// <param name="v"></param> void Log(string v); /// <summary> /// Flushes the cache (if one exists). /// </summary> void Flush(); } /// <summary> /// An implementation of ILogger that prints to the console, and also /// writes to a file. /// </summary> public class ConsoleAndFileLogger : ILogger { private readonly string _file; private readonly StringBuilder _buffer = new StringBuilder(); /// <summary> /// Constructs a new ConsoleAndFileLogger with a default log /// file of 'log.txt'. /// </summary> public ConsoleAndFileLogger() { if (Directory.Exists(TestUtilities.GetCPCDirectoryPath())) { _file = Path.Combine(TestUtilities.GetCPCDirectoryPath(), "perf-log.txt"); } else { _file = "./perf-log.txt"; } } void ILogger.Flush() { File.AppendAllText(_file, _buffer.ToString()); _buffer.Clear(); } void ILogger.Log(string v) { Console.WriteLine(DateTime.Now + " : " + v); _buffer.AppendLine(DateTime.Now + " : " + v); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/Organizing/IOrganizingService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.Organizing { /// <summary> /// internal interface used to use language specific service from common service layer /// </summary> internal interface IOrganizingService : ILanguageService { /// <summary> /// return default organizers /// </summary> IEnumerable<ISyntaxOrganizer> GetDefaultOrganizers(); /// <summary> /// Organize document /// </summary> Task<Document> OrganizeAsync(Document document, IEnumerable<ISyntaxOrganizer> organizers, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.Organizing { /// <summary> /// internal interface used to use language specific service from common service layer /// </summary> internal interface IOrganizingService : ILanguageService { /// <summary> /// return default organizers /// </summary> IEnumerable<ISyntaxOrganizer> GetDefaultOrganizers(); /// <summary> /// Organize document /// </summary> Task<Document> OrganizeAsync(Document document, IEnumerable<ISyntaxOrganizer> organizers, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/CSharp/Portable/Recommendations/CSharpRecommendationServiceRunner_Conversions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Recommendations { /// <summary> /// Adds user defined and predefined conversions to the unnamed recommendation set. /// </summary> internal partial class CSharpRecommendationServiceRunner { private static readonly ImmutableArray<SpecialType> s_predefinedEnumConversionTargets = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_Decimal, SpecialType.System_Double, SpecialType.System_Single, SpecialType.System_Int32, SpecialType.System_Int64, SpecialType.System_SByte, SpecialType.System_Int16, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UInt16); private static readonly ImmutableArray<SpecialType> s_sbyteConversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UInt16); private static readonly ImmutableArray<SpecialType> s_byteConversions = ImmutableArray.Create( SpecialType.System_Char, SpecialType.System_SByte); private static readonly ImmutableArray<SpecialType> s_int16Conversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UInt16, SpecialType.System_SByte); private static readonly ImmutableArray<SpecialType> s_uint16Conversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_SByte, SpecialType.System_Int16); private static readonly ImmutableArray<SpecialType> s_int32Conversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_SByte, SpecialType.System_Int16, SpecialType.System_UInt32, SpecialType.System_UInt16, SpecialType.System_UInt64); private static readonly ImmutableArray<SpecialType> s_uint32Conversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_Int32, SpecialType.System_SByte, SpecialType.System_Int16, SpecialType.System_UInt16); private static readonly ImmutableArray<SpecialType> s_int64Conversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_Int32, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UInt16, SpecialType.System_SByte, SpecialType.System_Int16); private static readonly ImmutableArray<SpecialType> s_uint64Conversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_Int32, SpecialType.System_Int64, SpecialType.System_UInt32, SpecialType.System_UInt16, SpecialType.System_SByte, SpecialType.System_Int16); private static readonly ImmutableArray<SpecialType> s_charConversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_SByte, SpecialType.System_Int16); private static readonly ImmutableArray<SpecialType> s_singleConversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_Decimal, SpecialType.System_Int32, SpecialType.System_Int64, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UInt16, SpecialType.System_SByte, SpecialType.System_Int16); private static readonly ImmutableArray<SpecialType> s_doubleConversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_Decimal, SpecialType.System_Single, SpecialType.System_Int32, SpecialType.System_Int64, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UInt16, SpecialType.System_SByte, SpecialType.System_Int16); private void AddConversions(ITypeSymbol container, ArrayBuilder<ISymbol> symbols) { if (container.RemoveNullableIfPresent() is INamedTypeSymbol namedType) { AddUserDefinedConversionsOfType(container, namedType, symbols); AddBuiltInNumericConversions(container, namedType, symbols); AddBuiltInEnumConversions(container, namedType, symbols); } } private static ITypeSymbol TryMakeNullable(Compilation compilation, ITypeSymbol container) { return container.IsNonNullableValueType() ? compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(container) : container; } private void AddUserDefinedConversionsOfType( ITypeSymbol container, INamedTypeSymbol containerWithoutNullable, ArrayBuilder<ISymbol> symbols) { var compilation = _context.SemanticModel.Compilation; var containerIsNullable = container.IsNullable(); foreach (var type in containerWithoutNullable.GetBaseTypesAndThis()) { foreach (var member in type.GetMembers(WellKnownMemberNames.ExplicitConversionName)) { if (member is not IMethodSymbol method) continue; if (!method.IsConversion()) continue; if (method.Parameters.Length != 1) continue; // Has to be a conversion that actually converts the type we're operating on. if (!type.Equals(method.Parameters[0].Type)) continue; // If this is a nullable context, then 'lift' the conversion so we offer the nullable form of it to // the user instead. symbols.Add(containerIsNullable && IsLiftableConversion(method) ? LiftConversion(compilation, method) : method); } } return; // https://github.com/dotnet/csharplang/blob/main/spec/conversions.md#lifted-conversion-operators // // Given a user-defined conversion operator that converts from a non-nullable value type S to a non-nullable // value type T, a lifted conversion operator exists that converts from S? to T? static bool IsLiftableConversion(IMethodSymbol method) => method.ReturnType.IsNonNullableValueType() && method.Parameters.Single().Type.IsNonNullableValueType(); } private IMethodSymbol LiftConversion(Compilation compilation, IMethodSymbol method) => CreateConversion( method.ContainingType, TryMakeNullable(compilation, method.Parameters.Single().Type), TryMakeNullable(compilation, method.ReturnType), method.GetDocumentationCommentXml(cancellationToken: _cancellationToken)); private void AddBuiltInNumericConversions( ITypeSymbol container, INamedTypeSymbol containerWithoutNullable, ArrayBuilder<ISymbol> symbols) { var conversions = GetPredefinedNumericConversions(containerWithoutNullable); if (!conversions.HasValue) return; AddCompletionItemsForSpecialTypes(container, containerWithoutNullable, symbols, conversions.Value); } public static ImmutableArray<SpecialType>? GetPredefinedNumericConversions(ITypeSymbol container) => container.SpecialType switch { SpecialType.System_SByte => s_sbyteConversions, SpecialType.System_Byte => s_byteConversions, SpecialType.System_Int16 => s_int16Conversions, SpecialType.System_UInt16 => s_uint16Conversions, SpecialType.System_Int32 => s_int32Conversions, SpecialType.System_UInt32 => s_uint32Conversions, SpecialType.System_Int64 => s_int64Conversions, SpecialType.System_UInt64 => s_uint64Conversions, SpecialType.System_Char => s_charConversions, SpecialType.System_Single => s_singleConversions, SpecialType.System_Double => s_doubleConversions, // Decimal intentionally not here as it exposes its conversions as normal methods in the symbol model. _ => null, }; private void AddCompletionItemsForSpecialTypes( ITypeSymbol container, INamedTypeSymbol containerWithoutNullable, ArrayBuilder<ISymbol> symbols, ImmutableArray<SpecialType> specialTypes) { var compilation = _context.SemanticModel.Compilation; foreach (var specialType in specialTypes) { var targetTypeSymbol = _context.SemanticModel.Compilation.GetSpecialType(specialType); var conversion = CreateConversion( containerWithoutNullable, fromType: containerWithoutNullable, toType: targetTypeSymbol, CreateConversionDocumentationCommentXml(containerWithoutNullable, targetTypeSymbol)); symbols.Add(container.IsNullable() ? LiftConversion(compilation, conversion) : conversion); } return; static string CreateConversionDocumentationCommentXml(ITypeSymbol fromType, ITypeSymbol toType) { var summary = string.Format(WorkspacesResources.Predefined_conversion_from_0_to_1, SeeTag(fromType.GetDocumentationCommentId()), SeeTag(toType.GetDocumentationCommentId())); return $"<summary>{summary}</summary>"; static string SeeTag(string? id) => $@"<see cref=""{id}""/>"; } } private static IMethodSymbol CreateConversion(INamedTypeSymbol containingType, ITypeSymbol fromType, ITypeSymbol toType, string? documentationCommentXml) => CodeGenerationSymbolFactory.CreateConversionSymbol( toType: toType, fromType: CodeGenerationSymbolFactory.CreateParameterSymbol(fromType, "value"), containingType: containingType, documentationCommentXml: documentationCommentXml); private void AddBuiltInEnumConversions( ITypeSymbol container, INamedTypeSymbol containerWithoutNullable, ArrayBuilder<ISymbol> symbols) { // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions#explicit-enumeration-conversions // Three kinds of conversions are defined in the spec. // Suggestion are made for one kind: // * From any enum_type to sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or decimal. // No suggestion for the other two kinds of conversions: // * From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or decimal to any enum_type. // * From any enum_type to any other enum_type. if (containerWithoutNullable.IsEnumType()) AddCompletionItemsForSpecialTypes(container, containerWithoutNullable, symbols, s_predefinedEnumConversionTargets); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Recommendations { /// <summary> /// Adds user defined and predefined conversions to the unnamed recommendation set. /// </summary> internal partial class CSharpRecommendationServiceRunner { private static readonly ImmutableArray<SpecialType> s_predefinedEnumConversionTargets = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_Decimal, SpecialType.System_Double, SpecialType.System_Single, SpecialType.System_Int32, SpecialType.System_Int64, SpecialType.System_SByte, SpecialType.System_Int16, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UInt16); private static readonly ImmutableArray<SpecialType> s_sbyteConversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UInt16); private static readonly ImmutableArray<SpecialType> s_byteConversions = ImmutableArray.Create( SpecialType.System_Char, SpecialType.System_SByte); private static readonly ImmutableArray<SpecialType> s_int16Conversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UInt16, SpecialType.System_SByte); private static readonly ImmutableArray<SpecialType> s_uint16Conversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_SByte, SpecialType.System_Int16); private static readonly ImmutableArray<SpecialType> s_int32Conversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_SByte, SpecialType.System_Int16, SpecialType.System_UInt32, SpecialType.System_UInt16, SpecialType.System_UInt64); private static readonly ImmutableArray<SpecialType> s_uint32Conversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_Int32, SpecialType.System_SByte, SpecialType.System_Int16, SpecialType.System_UInt16); private static readonly ImmutableArray<SpecialType> s_int64Conversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_Int32, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UInt16, SpecialType.System_SByte, SpecialType.System_Int16); private static readonly ImmutableArray<SpecialType> s_uint64Conversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_Int32, SpecialType.System_Int64, SpecialType.System_UInt32, SpecialType.System_UInt16, SpecialType.System_SByte, SpecialType.System_Int16); private static readonly ImmutableArray<SpecialType> s_charConversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_SByte, SpecialType.System_Int16); private static readonly ImmutableArray<SpecialType> s_singleConversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_Decimal, SpecialType.System_Int32, SpecialType.System_Int64, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UInt16, SpecialType.System_SByte, SpecialType.System_Int16); private static readonly ImmutableArray<SpecialType> s_doubleConversions = ImmutableArray.Create( SpecialType.System_Byte, SpecialType.System_Char, SpecialType.System_Decimal, SpecialType.System_Single, SpecialType.System_Int32, SpecialType.System_Int64, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UInt16, SpecialType.System_SByte, SpecialType.System_Int16); private void AddConversions(ITypeSymbol container, ArrayBuilder<ISymbol> symbols) { if (container.RemoveNullableIfPresent() is INamedTypeSymbol namedType) { AddUserDefinedConversionsOfType(container, namedType, symbols); AddBuiltInNumericConversions(container, namedType, symbols); AddBuiltInEnumConversions(container, namedType, symbols); } } private static ITypeSymbol TryMakeNullable(Compilation compilation, ITypeSymbol container) { return container.IsNonNullableValueType() ? compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(container) : container; } private void AddUserDefinedConversionsOfType( ITypeSymbol container, INamedTypeSymbol containerWithoutNullable, ArrayBuilder<ISymbol> symbols) { var compilation = _context.SemanticModel.Compilation; var containerIsNullable = container.IsNullable(); foreach (var type in containerWithoutNullable.GetBaseTypesAndThis()) { foreach (var member in type.GetMembers(WellKnownMemberNames.ExplicitConversionName)) { if (member is not IMethodSymbol method) continue; if (!method.IsConversion()) continue; if (method.Parameters.Length != 1) continue; // Has to be a conversion that actually converts the type we're operating on. if (!type.Equals(method.Parameters[0].Type)) continue; // If this is a nullable context, then 'lift' the conversion so we offer the nullable form of it to // the user instead. symbols.Add(containerIsNullable && IsLiftableConversion(method) ? LiftConversion(compilation, method) : method); } } return; // https://github.com/dotnet/csharplang/blob/main/spec/conversions.md#lifted-conversion-operators // // Given a user-defined conversion operator that converts from a non-nullable value type S to a non-nullable // value type T, a lifted conversion operator exists that converts from S? to T? static bool IsLiftableConversion(IMethodSymbol method) => method.ReturnType.IsNonNullableValueType() && method.Parameters.Single().Type.IsNonNullableValueType(); } private IMethodSymbol LiftConversion(Compilation compilation, IMethodSymbol method) => CreateConversion( method.ContainingType, TryMakeNullable(compilation, method.Parameters.Single().Type), TryMakeNullable(compilation, method.ReturnType), method.GetDocumentationCommentXml(cancellationToken: _cancellationToken)); private void AddBuiltInNumericConversions( ITypeSymbol container, INamedTypeSymbol containerWithoutNullable, ArrayBuilder<ISymbol> symbols) { var conversions = GetPredefinedNumericConversions(containerWithoutNullable); if (!conversions.HasValue) return; AddCompletionItemsForSpecialTypes(container, containerWithoutNullable, symbols, conversions.Value); } public static ImmutableArray<SpecialType>? GetPredefinedNumericConversions(ITypeSymbol container) => container.SpecialType switch { SpecialType.System_SByte => s_sbyteConversions, SpecialType.System_Byte => s_byteConversions, SpecialType.System_Int16 => s_int16Conversions, SpecialType.System_UInt16 => s_uint16Conversions, SpecialType.System_Int32 => s_int32Conversions, SpecialType.System_UInt32 => s_uint32Conversions, SpecialType.System_Int64 => s_int64Conversions, SpecialType.System_UInt64 => s_uint64Conversions, SpecialType.System_Char => s_charConversions, SpecialType.System_Single => s_singleConversions, SpecialType.System_Double => s_doubleConversions, // Decimal intentionally not here as it exposes its conversions as normal methods in the symbol model. _ => null, }; private void AddCompletionItemsForSpecialTypes( ITypeSymbol container, INamedTypeSymbol containerWithoutNullable, ArrayBuilder<ISymbol> symbols, ImmutableArray<SpecialType> specialTypes) { var compilation = _context.SemanticModel.Compilation; foreach (var specialType in specialTypes) { var targetTypeSymbol = _context.SemanticModel.Compilation.GetSpecialType(specialType); var conversion = CreateConversion( containerWithoutNullable, fromType: containerWithoutNullable, toType: targetTypeSymbol, CreateConversionDocumentationCommentXml(containerWithoutNullable, targetTypeSymbol)); symbols.Add(container.IsNullable() ? LiftConversion(compilation, conversion) : conversion); } return; static string CreateConversionDocumentationCommentXml(ITypeSymbol fromType, ITypeSymbol toType) { var summary = string.Format(WorkspacesResources.Predefined_conversion_from_0_to_1, SeeTag(fromType.GetDocumentationCommentId()), SeeTag(toType.GetDocumentationCommentId())); return $"<summary>{summary}</summary>"; static string SeeTag(string? id) => $@"<see cref=""{id}""/>"; } } private static IMethodSymbol CreateConversion(INamedTypeSymbol containingType, ITypeSymbol fromType, ITypeSymbol toType, string? documentationCommentXml) => CodeGenerationSymbolFactory.CreateConversionSymbol( toType: toType, fromType: CodeGenerationSymbolFactory.CreateParameterSymbol(fromType, "value"), containingType: containingType, documentationCommentXml: documentationCommentXml); private void AddBuiltInEnumConversions( ITypeSymbol container, INamedTypeSymbol containerWithoutNullable, ArrayBuilder<ISymbol> symbols) { // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions#explicit-enumeration-conversions // Three kinds of conversions are defined in the spec. // Suggestion are made for one kind: // * From any enum_type to sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or decimal. // No suggestion for the other two kinds of conversions: // * From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or decimal to any enum_type. // * From any enum_type to any other enum_type. if (containerWithoutNullable.IsEnumType()) AddCompletionItemsForSpecialTypes(container, containerWithoutNullable, symbols, s_predefinedEnumConversionTargets); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/UseImplicitTypeCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseType; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.TypeStyle; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseImplicitType { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.UseImplicitType), Shared] internal partial class UseImplicitTypeCodeRefactoringProvider : AbstractUseTypeCodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseImplicitTypeCodeRefactoringProvider() { } protected override string Title => CSharpAnalyzersResources.Use_implicit_type; protected override TypeSyntax FindAnalyzableType(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) => CSharpUseImplicitTypeHelper.Instance.FindAnalyzableType(node, semanticModel, cancellationToken); protected override TypeStyleResult AnalyzeTypeName(TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) => CSharpUseImplicitTypeHelper.Instance.AnalyzeTypeName(typeName, semanticModel, optionSet, cancellationToken); protected override Task HandleDeclarationAsync(Document document, SyntaxEditor editor, TypeSyntax type, CancellationToken cancellationToken) { UseImplicitTypeCodeFixProvider.ReplaceTypeWithVar(editor, type); return Task.CompletedTask; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseType; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.TypeStyle; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseImplicitType { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.UseImplicitType), Shared] internal partial class UseImplicitTypeCodeRefactoringProvider : AbstractUseTypeCodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseImplicitTypeCodeRefactoringProvider() { } protected override string Title => CSharpAnalyzersResources.Use_implicit_type; protected override TypeSyntax FindAnalyzableType(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) => CSharpUseImplicitTypeHelper.Instance.FindAnalyzableType(node, semanticModel, cancellationToken); protected override TypeStyleResult AnalyzeTypeName(TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) => CSharpUseImplicitTypeHelper.Instance.AnalyzeTypeName(typeName, semanticModel, optionSet, cancellationToken); protected override Task HandleDeclarationAsync(Document document, SyntaxEditor editor, TypeSyntax type, CancellationToken cancellationToken) { UseImplicitTypeCodeFixProvider.ReplaceTypeWithVar(editor, type); return Task.CompletedTask; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/SimplifyInterpolation/CSharpSimplifyInterpolationDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Analyzers.SimplifyInterpolation; using Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.SimplifyInterpolation; namespace Microsoft.CodeAnalysis.CSharp.SimplifyInterpolation { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpSimplifyInterpolationDiagnosticAnalyzer : AbstractSimplifyInterpolationDiagnosticAnalyzer< InterpolationSyntax, ExpressionSyntax> { protected override IVirtualCharService GetVirtualCharService() => CSharpVirtualCharService.Instance; protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override AbstractSimplifyInterpolationHelpers GetHelpers() => CSharpSimplifyInterpolationHelpers.Instance; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Analyzers.SimplifyInterpolation; using Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.SimplifyInterpolation; namespace Microsoft.CodeAnalysis.CSharp.SimplifyInterpolation { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpSimplifyInterpolationDiagnosticAnalyzer : AbstractSimplifyInterpolationDiagnosticAnalyzer< InterpolationSyntax, ExpressionSyntax> { protected override IVirtualCharService GetVirtualCharService() => CSharpVirtualCharService.Instance; protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override AbstractSimplifyInterpolationHelpers GetHelpers() => CSharpSimplifyInterpolationHelpers.Instance; } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/CodeStyle/VisualBasic/Analyzers/xlf/VBCodeStyleResources.zh-Hans.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hans" original="../VBCodeStyleResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">在添加其他值时删除此值。</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hans" original="../VBCodeStyleResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">在添加其他值时删除此值。</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/ObjectListItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Language.Intellisense; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { using Workspace = Microsoft.CodeAnalysis.Workspace; internal abstract class ObjectListItem { private readonly ProjectId _projectId; private ObjectList _parentList; private readonly ushort _glyphIndex; private readonly bool _isHidden; protected ObjectListItem( ProjectId projectId, StandardGlyphGroup glyphGroup, StandardGlyphItem glyphItem = StandardGlyphItem.GlyphItemPublic, bool isHidden = false) { _projectId = projectId; _glyphIndex = glyphGroup < StandardGlyphGroup.GlyphGroupError ? (ushort)((int)glyphGroup + (int)glyphItem) : (ushort)glyphGroup; _isHidden = isHidden; } internal void SetParentList(ObjectList parentList) { Debug.Assert(_parentList == null); _parentList = parentList; } public virtual bool SupportsGoToDefinition { get { return false; } } public virtual bool SupportsFindAllReferences { get { return false; } } public abstract string DisplayText { get; } public abstract string FullNameText { get; } public abstract string SearchText { get; } public override string ToString() => DisplayText; public ObjectList ParentList { get { return _parentList; } } public ObjectListKind ParentListKind { get { return _parentList != null ? _parentList.Kind : ObjectListKind.None; } } public ProjectId ProjectId { get { return _projectId; } } public Compilation GetCompilation(Workspace workspace) { var project = workspace.CurrentSolution.GetProject(_projectId); if (project == null) { return null; } return project .GetCompilationAsync(CancellationToken.None) .WaitAndGetResult_ObjectBrowser(CancellationToken.None); } public ushort GlyphIndex { get { return _glyphIndex; } } public bool IsHidden { get { return _isHidden; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Language.Intellisense; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { using Workspace = Microsoft.CodeAnalysis.Workspace; internal abstract class ObjectListItem { private readonly ProjectId _projectId; private ObjectList _parentList; private readonly ushort _glyphIndex; private readonly bool _isHidden; protected ObjectListItem( ProjectId projectId, StandardGlyphGroup glyphGroup, StandardGlyphItem glyphItem = StandardGlyphItem.GlyphItemPublic, bool isHidden = false) { _projectId = projectId; _glyphIndex = glyphGroup < StandardGlyphGroup.GlyphGroupError ? (ushort)((int)glyphGroup + (int)glyphItem) : (ushort)glyphGroup; _isHidden = isHidden; } internal void SetParentList(ObjectList parentList) { Debug.Assert(_parentList == null); _parentList = parentList; } public virtual bool SupportsGoToDefinition { get { return false; } } public virtual bool SupportsFindAllReferences { get { return false; } } public abstract string DisplayText { get; } public abstract string FullNameText { get; } public abstract string SearchText { get; } public override string ToString() => DisplayText; public ObjectList ParentList { get { return _parentList; } } public ObjectListKind ParentListKind { get { return _parentList != null ? _parentList.Kind : ObjectListKind.None; } } public ProjectId ProjectId { get { return _projectId; } } public Compilation GetCompilation(Workspace workspace) { var project = workspace.CurrentSolution.GetProject(_projectId); if (project == null) { return null; } return project .GetCompilationAsync(CancellationToken.None) .WaitAndGetResult_ObjectBrowser(CancellationToken.None); } public ushort GlyphIndex { get { return _glyphIndex; } } public bool IsHidden { get { return _isHidden; } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/UserDefinedExplicitConversions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.CSharp { internal partial class ConversionsBase { private UserDefinedConversionResult AnalyzeExplicitUserDefinedConversions( BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)target != null); // SPEC: A user-defined explicit conversion from type S to type T is processed // SPEC: as follows: // SPEC: Find the set of types D from which user-defined conversion operators // SPEC: will be considered... var d = ArrayBuilder<TypeSymbol>.GetInstance(); ComputeUserDefinedExplicitConversionTypeSet(source, target, d, ref useSiteInfo); // SPEC: Find the set of applicable user-defined and lifted conversion operators, U... var ubuild = ArrayBuilder<UserDefinedConversionAnalysis>.GetInstance(); ComputeApplicableUserDefinedExplicitConversionSet(sourceExpression, source, target, d, ubuild, ref useSiteInfo); d.Free(); ImmutableArray<UserDefinedConversionAnalysis> u = ubuild.ToImmutableAndFree(); // SPEC: If U is empty, the conversion is undefined and a compile-time error occurs. if (u.Length == 0) { return UserDefinedConversionResult.NoApplicableOperators(u); } // SPEC: Find the most specific source type SX of the operators in U... TypeSymbol sx = MostSpecificSourceTypeForExplicitUserDefinedConversion(u, sourceExpression, source, ref useSiteInfo); if ((object)sx == null) { return UserDefinedConversionResult.NoBestSourceType(u); } // SPEC: Find the most specific target type TX of the operators in U... TypeSymbol tx = MostSpecificTargetTypeForExplicitUserDefinedConversion(u, target, ref useSiteInfo); if ((object)tx == null) { return UserDefinedConversionResult.NoBestTargetType(u); } int? best = MostSpecificConversionOperator(sx, tx, u); if (best == null) { return UserDefinedConversionResult.Ambiguous(u); } return UserDefinedConversionResult.Valid(u, best.Value); } private static void ComputeUserDefinedExplicitConversionTypeSet(TypeSymbol source, TypeSymbol target, ArrayBuilder<TypeSymbol> d, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Spec 6.4.5: User-defined explicit conversions // Find the set of types, D, from which user-defined conversion operators will be considered. // This set consists of S0 (if S0 is a class or struct), the base classes of S0 (if S0 is a class), // T0 (if T0 is a class or struct), and the base classes of T0 (if T0 is a class). AddTypesParticipatingInUserDefinedConversion(d, source, includeBaseTypes: true, useSiteInfo: ref useSiteInfo); AddTypesParticipatingInUserDefinedConversion(d, target, includeBaseTypes: true, useSiteInfo: ref useSiteInfo); } private void ComputeApplicableUserDefinedExplicitConversionSet( BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ArrayBuilder<TypeSymbol> d, ArrayBuilder<UserDefinedConversionAnalysis> u, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)target != null); Debug.Assert(d != null); Debug.Assert(u != null); HashSet<NamedTypeSymbol> lookedInInterfaces = null; foreach (TypeSymbol declaringType in d) { if (declaringType is TypeParameterSymbol typeParameter) { ImmutableArray<NamedTypeSymbol> interfaceTypes = typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); if (!interfaceTypes.IsEmpty) { lookedInInterfaces ??= new HashSet<NamedTypeSymbol>(Symbols.SymbolEqualityComparer.AllIgnoreOptions); // Equivalent to has identity conversion check foreach (var interfaceType in interfaceTypes) { if (lookedInInterfaces.Add(interfaceType)) { addCandidatesFromType(constrainedToTypeOpt: typeParameter, interfaceType, sourceExpression, source, target, u, ref useSiteInfo); } } } } else { addCandidatesFromType(constrainedToTypeOpt: null, (NamedTypeSymbol)declaringType, sourceExpression, source, target, u, ref useSiteInfo); } } void addCandidatesFromType( TypeParameterSymbol constrainedToTypeOpt, NamedTypeSymbol declaringType, BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ArrayBuilder<UserDefinedConversionAnalysis> u, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { AddUserDefinedConversionsToExplicitCandidateSet(sourceExpression, source, target, u, constrainedToTypeOpt, declaringType, WellKnownMemberNames.ExplicitConversionName, ref useSiteInfo); AddUserDefinedConversionsToExplicitCandidateSet(sourceExpression, source, target, u, constrainedToTypeOpt, declaringType, WellKnownMemberNames.ImplicitConversionName, ref useSiteInfo); } } private void AddUserDefinedConversionsToExplicitCandidateSet( BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ArrayBuilder<UserDefinedConversionAnalysis> u, TypeParameterSymbol constrainedToTypeOpt, NamedTypeSymbol declaringType, string operatorName, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)target != null); Debug.Assert(u != null); Debug.Assert((object)declaringType != null); Debug.Assert(operatorName != null); // SPEC: Find the set of applicable user-defined and lifted conversion operators, U. // SPEC: The set consists of the user-defined and lifted implicit or explicit // SPEC: conversion operators declared by the classes and structs in D that convert // SPEC: from a type encompassing E or encompassed by S (if it exists) to a type // SPEC: encompassing or encompassed by T. // DELIBERATE SPEC VIOLATION: // // The spec here essentially says that we add an applicable "regular" conversion and // an applicable lifted conversion, if there is one, to the candidate set, and then // let them duke it out to determine which one is "best". // // This is not at all what the native compiler does, and attempting to implement // the specification, or slight variations on it, produces too many backwards-compatibility // breaking changes. // // The native compiler deviates from the specification in two major ways here. // First, it does not add *both* the regular and lifted forms to the candidate set. // Second, the way it characterizes a "lifted" form is very, very different from // how the specification characterizes a lifted form. // // An operation, in this case, X-->Y, is properly said to be "lifted" to X?-->Y? via // the rule that X?-->Y? matches the behavior of X-->Y for non-null X, and converts // null X to null Y otherwise. // // The native compiler, by contrast, takes the existing operator and "lifts" either // the operator's parameter type or the operator's return type to nullable. For // example, a conversion from X?-->Y would be "lifted" to X?-->Y? by making the // conversion from X? to Y, and then from Y to Y?. No "lifting" semantics // are imposed; we do not check to see if the X? is null. This operator is not // actually "lifted" at all; rather, an implicit conversion is applied to the // output. **The native compiler considers the result type Y? of that standard implicit // conversion to be the result type of the "lifted" conversion**, rather than // properly considering Y to be the result type of the conversion for the purposes // of computing the best output type. // // Moreover: the native compiler actually *does* implement nullable lifting semantics // in the case where the input type of the user-defined conversion is a non-nullable // value type and the output type is a nullable value type **or pointer type, or // reference type**. This is an enormous departure from the specification; the // native compiler will take a user-defined conversion from X-->Y? or X-->C and "lift" // it to a conversion from X?-->Y? or X?-->C that has nullable semantics. // // This is quite confusing. In this code we will classify the conversion as either // "normal" or "lifted" on the basis of *whether or not special lifting semantics // are to be applied*. That is, whether or not a later rewriting pass is going to // need to insert a check to see if the source expression is null, and decide // whether or not to call the underlying unlifted conversion or produce a null // value without calling the unlifted conversion. // DELIBERATE SPEC VIOLATION: See the comment regarding bug 17021 in // UserDefinedImplicitConversions.cs. if ((object)source != null && source.IsInterfaceType() || target.IsInterfaceType()) { return; } foreach (MethodSymbol op in declaringType.GetOperators(operatorName)) { // We might have a bad operator and be in an error recovery situation. Ignore it. if (op.ReturnsVoid || op.ParameterCount != 1 || op.ReturnType.TypeKind == TypeKind.Error) { continue; } TypeSymbol convertsFrom = op.GetParameterType(0); TypeSymbol convertsTo = op.ReturnType; Conversion fromConversion = EncompassingExplicitConversion(sourceExpression, source, convertsFrom, ref useSiteInfo); Conversion toConversion = EncompassingExplicitConversion(null, convertsTo, target, ref useSiteInfo); // We accept candidates for which the parameter type encompasses the *underlying* source type. if (!fromConversion.Exists && (object)source != null && source.IsNullableType() && EncompassingExplicitConversion(null, source.GetNullableUnderlyingType(), convertsFrom, ref useSiteInfo).Exists) { fromConversion = ClassifyBuiltInConversion(source, convertsFrom, ref useSiteInfo); } // As in dev11 (and the revised spec), we also accept candidates for which the return type is encompassed by the *stripped* target type. if (!toConversion.Exists && (object)target != null && target.IsNullableType() && EncompassingExplicitConversion(null, convertsTo, target.GetNullableUnderlyingType(), ref useSiteInfo).Exists) { toConversion = ClassifyBuiltInConversion(convertsTo, target, ref useSiteInfo); } // In the corresponding implicit conversion code we can get away with first // checking to see if standard implicit conversions exist from the source type // to the parameter type, and from the return type to the target type. If not, // then we can check for a lifted operator. // // That's not going to cut it in the explicit conversion code. Suppose we have // a conversion X-->Y and have source type X? and target type Y?. There *are* // standard explicit conversions from X?-->X and Y?-->Y, but we do not want // to bind this as an *unlifted* conversion from X? to Y?; we want such a thing // to be a *lifted* conversion from X? to Y?, that checks for null on the source // and decides to not call the underlying user-defined conversion if it is null. // // We therefore cannot do what we do in the implicit conversions, where we check // to see if the unlifted conversion works, and if it does, then don't add the lifted // conversion at all. Rather, we have to see if what we're building here is a // lifted conversion or not. // // Under what circumstances is this conversion a lifted conversion? (In the // "spec" sense of a lifted conversion; that is, that we check for null // and skip the user-defined conversion if necessary). // // * The source type must be a nullable value type. // * The parameter type must be a non-nullable value type. // * The target type must be able to take on a null value. if (fromConversion.Exists && toConversion.Exists) { if ((object)source != null && source.IsNullableType() && convertsFrom.IsNonNullableValueType() && target.CanBeAssignedNull()) { TypeSymbol nullableFrom = MakeNullableType(convertsFrom); TypeSymbol nullableTo = convertsTo.IsNonNullableValueType() ? MakeNullableType(convertsTo) : convertsTo; Conversion liftedFromConversion = EncompassingExplicitConversion(sourceExpression, source, nullableFrom, ref useSiteInfo); Conversion liftedToConversion = EncompassingExplicitConversion(null, nullableTo, target, ref useSiteInfo); Debug.Assert(liftedFromConversion.Exists); Debug.Assert(liftedToConversion.Exists); u.Add(UserDefinedConversionAnalysis.Lifted(constrainedToTypeOpt, op, liftedFromConversion, liftedToConversion, nullableFrom, nullableTo)); } else { // There is an additional spec violation in the native compiler. Suppose // we have a conversion from X-->Y and are asked to do "Y? y = new X();" Clearly // the intention is to convert from X-->Y via the implicit conversion, and then // stick a standard implicit conversion from Y-->Y? on the back end. **In this // situation, the native compiler treats the conversion as though it were // actually X-->Y? in source for the purposes of determining the best target // type of a set of operators. // // Similarly, if we have a conversion from X-->Y and are asked to do // an explicit conversion from X? to Y then we treat the conversion as // though it really were X?-->Y for the purposes of determining the best // source type of a set of operators. // // We perpetuate these fictions here. if (target.IsNullableType() && convertsTo.IsNonNullableValueType()) { convertsTo = MakeNullableType(convertsTo); toConversion = EncompassingExplicitConversion(null, convertsTo, target, ref useSiteInfo); } if ((object)source != null && source.IsNullableType() && convertsFrom.IsNonNullableValueType()) { convertsFrom = MakeNullableType(convertsFrom); fromConversion = EncompassingExplicitConversion(null, convertsFrom, source, ref useSiteInfo); } u.Add(UserDefinedConversionAnalysis.Normal(constrainedToTypeOpt, op, fromConversion, toConversion, convertsFrom, convertsTo)); } } } } private TypeSymbol MostSpecificSourceTypeForExplicitUserDefinedConversion( ImmutableArray<UserDefinedConversionAnalysis> u, BoundExpression sourceExpression, TypeSymbol source, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: If any of the operators in U convert from S then SX is S. // SPEC: Otherwise, if any of the operators in U convert from types // SPEC: that encompass E, then SX is the most encompassed type // SPEC: in the combined set of the source types of these operators. // SPEC: If no most encompassed type can be found then the // SPEC: conversion is ambiguous and a compile-time error occurs. // SPEC: Otherwise, SX is the most encompassing type in the combined // SPEC: set of the source types of these operators. If exactly one // SPEC: most encompassing type cannot be found then the conversion // SPEC: is ambiguous and a compile-time error occurs. // DELIBERATE SPEC VIOLATION: // The native compiler deviates from the specification in the way it // determines what the "converts from" type is. The specification is pretty // clear that the "converts from" type is the actual parameter type of the // conversion operator, or, in the case of a lifted operator, the lifted-to- // nullable type. That is, if we have X-->Y then the converts-to type of // the operator in its normal form is Y, and the converts-to type of the // operator in its lifted form is Y?. // // The native compiler does not do this. Suppose we have a user-defined // conversion X-->Y, and the cast (Y)(some_nullable_x). The native // compiler will consider the converts-from type of X-->Y to be X?, surprisingly // enough. // // We have already written the "FromType" into the conversion analysis to // perpetuate this fiction. if ((object)source != null) { if (u.Any(conv => TypeSymbol.Equals(conv.FromType, source, TypeCompareKind.ConsiderEverything2))) { return source; } CompoundUseSiteInfo<AssemblySymbol> inLambdaUseSiteInfo = useSiteInfo; System.Func<UserDefinedConversionAnalysis, bool> isValid = conv => IsEncompassedBy(sourceExpression, source, conv.FromType, ref inLambdaUseSiteInfo); if (u.Any(isValid)) { var result = MostEncompassedType(u, isValid, conv => conv.FromType, ref inLambdaUseSiteInfo); useSiteInfo = inLambdaUseSiteInfo; return result; } useSiteInfo = inLambdaUseSiteInfo; } return MostEncompassingType(u, conv => conv.FromType, ref useSiteInfo); } private TypeSymbol MostSpecificTargetTypeForExplicitUserDefinedConversion( ImmutableArray<UserDefinedConversionAnalysis> u, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: If any of the operators in U convert to T then TX is T. // SPEC: Otherwise, if any of the operators in U convert to types that are // SPEC: encompassed by T then TX is the most encompassing type in the combined // SPEC: set of target types of those operators. If exactly one most encompassing // SPEC: type cannot be found then the conversion is ambiguous and a compile-time // SPEC: error occurs. // SPEC: Otherwise, Tx is the most encompassed type in the combined set of target // SPEC: types of the operators in U. If no most encompassed type can be found, // SPEC: then the conversion is ambiguous and a compile-time error occurs. // DELIBERATE SPEC VIOLATION: // The native compiler deviates from the specification in the way it // determines what the "converts to" type is. The specification is pretty // clear that the "converts to" type is the actual return type of the // conversion operator, or, in the case of a lifted operator, the lifted-to- // nullable type. That is, if we have X-->Y then the converts-to type of // the operator in its normal form is Y, and the converts-to type of the // operator in its lifted form is Y?. // // The native compiler does not do this. Suppose we have a user-defined // conversion X-->Y, and the assignment Y? y = new X(); -- the native // compiler will consider the converts-to type of X-->Y to be Y?, surprisingly // enough. // // We have already written the "ToType" into the conversion analysis to // perpetuate this fiction. if (u.Any(conv => TypeSymbol.Equals(conv.ToType, target, TypeCompareKind.ConsiderEverything2))) { return target; } CompoundUseSiteInfo<AssemblySymbol> inLambdaUseSiteInfo = useSiteInfo; System.Func<UserDefinedConversionAnalysis, bool> isValid = conv => IsEncompassedBy(null, conv.ToType, target, ref inLambdaUseSiteInfo); if (u.Any(isValid)) { var result = MostEncompassingType(u, isValid, conv => conv.ToType, ref inLambdaUseSiteInfo); useSiteInfo = inLambdaUseSiteInfo; return result; } useSiteInfo = inLambdaUseSiteInfo; return MostEncompassedType(u, conv => conv.ToType, ref useSiteInfo); } private Conversion EncompassingExplicitConversion(BoundExpression expr, TypeSymbol a, TypeSymbol b, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(expr != null || (object)a != null); Debug.Assert((object)b != null); // SPEC: If a standard implicit conversion exists from a type A to a type B // SPEC: and if neither A nor B is an interface type then A is said to be // SPEC: encompassed by B, and B is said to encompass A. // DELIBERATE SPEC VIOLATION: We should be checking to see if A and B are // interface types here. See the comment regarding bug 17021 in // UserDefinedImplicitConversions.cs // DELIBERATE SPEC VIOLATION: // We do not support an encompassing implicit conversion from a zero constant // to an enum type, because the native compiler did not. It would be a breaking // change. var result = ClassifyStandardConversion(expr, a, b, ref useSiteInfo); return result.IsEnumeration ? Conversion.NoConversion : result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.CSharp { internal partial class ConversionsBase { private UserDefinedConversionResult AnalyzeExplicitUserDefinedConversions( BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)target != null); // SPEC: A user-defined explicit conversion from type S to type T is processed // SPEC: as follows: // SPEC: Find the set of types D from which user-defined conversion operators // SPEC: will be considered... var d = ArrayBuilder<TypeSymbol>.GetInstance(); ComputeUserDefinedExplicitConversionTypeSet(source, target, d, ref useSiteInfo); // SPEC: Find the set of applicable user-defined and lifted conversion operators, U... var ubuild = ArrayBuilder<UserDefinedConversionAnalysis>.GetInstance(); ComputeApplicableUserDefinedExplicitConversionSet(sourceExpression, source, target, d, ubuild, ref useSiteInfo); d.Free(); ImmutableArray<UserDefinedConversionAnalysis> u = ubuild.ToImmutableAndFree(); // SPEC: If U is empty, the conversion is undefined and a compile-time error occurs. if (u.Length == 0) { return UserDefinedConversionResult.NoApplicableOperators(u); } // SPEC: Find the most specific source type SX of the operators in U... TypeSymbol sx = MostSpecificSourceTypeForExplicitUserDefinedConversion(u, sourceExpression, source, ref useSiteInfo); if ((object)sx == null) { return UserDefinedConversionResult.NoBestSourceType(u); } // SPEC: Find the most specific target type TX of the operators in U... TypeSymbol tx = MostSpecificTargetTypeForExplicitUserDefinedConversion(u, target, ref useSiteInfo); if ((object)tx == null) { return UserDefinedConversionResult.NoBestTargetType(u); } int? best = MostSpecificConversionOperator(sx, tx, u); if (best == null) { return UserDefinedConversionResult.Ambiguous(u); } return UserDefinedConversionResult.Valid(u, best.Value); } private static void ComputeUserDefinedExplicitConversionTypeSet(TypeSymbol source, TypeSymbol target, ArrayBuilder<TypeSymbol> d, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Spec 6.4.5: User-defined explicit conversions // Find the set of types, D, from which user-defined conversion operators will be considered. // This set consists of S0 (if S0 is a class or struct), the base classes of S0 (if S0 is a class), // T0 (if T0 is a class or struct), and the base classes of T0 (if T0 is a class). AddTypesParticipatingInUserDefinedConversion(d, source, includeBaseTypes: true, useSiteInfo: ref useSiteInfo); AddTypesParticipatingInUserDefinedConversion(d, target, includeBaseTypes: true, useSiteInfo: ref useSiteInfo); } private void ComputeApplicableUserDefinedExplicitConversionSet( BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ArrayBuilder<TypeSymbol> d, ArrayBuilder<UserDefinedConversionAnalysis> u, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)target != null); Debug.Assert(d != null); Debug.Assert(u != null); HashSet<NamedTypeSymbol> lookedInInterfaces = null; foreach (TypeSymbol declaringType in d) { if (declaringType is TypeParameterSymbol typeParameter) { ImmutableArray<NamedTypeSymbol> interfaceTypes = typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); if (!interfaceTypes.IsEmpty) { lookedInInterfaces ??= new HashSet<NamedTypeSymbol>(Symbols.SymbolEqualityComparer.AllIgnoreOptions); // Equivalent to has identity conversion check foreach (var interfaceType in interfaceTypes) { if (lookedInInterfaces.Add(interfaceType)) { addCandidatesFromType(constrainedToTypeOpt: typeParameter, interfaceType, sourceExpression, source, target, u, ref useSiteInfo); } } } } else { addCandidatesFromType(constrainedToTypeOpt: null, (NamedTypeSymbol)declaringType, sourceExpression, source, target, u, ref useSiteInfo); } } void addCandidatesFromType( TypeParameterSymbol constrainedToTypeOpt, NamedTypeSymbol declaringType, BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ArrayBuilder<UserDefinedConversionAnalysis> u, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { AddUserDefinedConversionsToExplicitCandidateSet(sourceExpression, source, target, u, constrainedToTypeOpt, declaringType, WellKnownMemberNames.ExplicitConversionName, ref useSiteInfo); AddUserDefinedConversionsToExplicitCandidateSet(sourceExpression, source, target, u, constrainedToTypeOpt, declaringType, WellKnownMemberNames.ImplicitConversionName, ref useSiteInfo); } } private void AddUserDefinedConversionsToExplicitCandidateSet( BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ArrayBuilder<UserDefinedConversionAnalysis> u, TypeParameterSymbol constrainedToTypeOpt, NamedTypeSymbol declaringType, string operatorName, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)target != null); Debug.Assert(u != null); Debug.Assert((object)declaringType != null); Debug.Assert(operatorName != null); // SPEC: Find the set of applicable user-defined and lifted conversion operators, U. // SPEC: The set consists of the user-defined and lifted implicit or explicit // SPEC: conversion operators declared by the classes and structs in D that convert // SPEC: from a type encompassing E or encompassed by S (if it exists) to a type // SPEC: encompassing or encompassed by T. // DELIBERATE SPEC VIOLATION: // // The spec here essentially says that we add an applicable "regular" conversion and // an applicable lifted conversion, if there is one, to the candidate set, and then // let them duke it out to determine which one is "best". // // This is not at all what the native compiler does, and attempting to implement // the specification, or slight variations on it, produces too many backwards-compatibility // breaking changes. // // The native compiler deviates from the specification in two major ways here. // First, it does not add *both* the regular and lifted forms to the candidate set. // Second, the way it characterizes a "lifted" form is very, very different from // how the specification characterizes a lifted form. // // An operation, in this case, X-->Y, is properly said to be "lifted" to X?-->Y? via // the rule that X?-->Y? matches the behavior of X-->Y for non-null X, and converts // null X to null Y otherwise. // // The native compiler, by contrast, takes the existing operator and "lifts" either // the operator's parameter type or the operator's return type to nullable. For // example, a conversion from X?-->Y would be "lifted" to X?-->Y? by making the // conversion from X? to Y, and then from Y to Y?. No "lifting" semantics // are imposed; we do not check to see if the X? is null. This operator is not // actually "lifted" at all; rather, an implicit conversion is applied to the // output. **The native compiler considers the result type Y? of that standard implicit // conversion to be the result type of the "lifted" conversion**, rather than // properly considering Y to be the result type of the conversion for the purposes // of computing the best output type. // // Moreover: the native compiler actually *does* implement nullable lifting semantics // in the case where the input type of the user-defined conversion is a non-nullable // value type and the output type is a nullable value type **or pointer type, or // reference type**. This is an enormous departure from the specification; the // native compiler will take a user-defined conversion from X-->Y? or X-->C and "lift" // it to a conversion from X?-->Y? or X?-->C that has nullable semantics. // // This is quite confusing. In this code we will classify the conversion as either // "normal" or "lifted" on the basis of *whether or not special lifting semantics // are to be applied*. That is, whether or not a later rewriting pass is going to // need to insert a check to see if the source expression is null, and decide // whether or not to call the underlying unlifted conversion or produce a null // value without calling the unlifted conversion. // DELIBERATE SPEC VIOLATION: See the comment regarding bug 17021 in // UserDefinedImplicitConversions.cs. if ((object)source != null && source.IsInterfaceType() || target.IsInterfaceType()) { return; } foreach (MethodSymbol op in declaringType.GetOperators(operatorName)) { // We might have a bad operator and be in an error recovery situation. Ignore it. if (op.ReturnsVoid || op.ParameterCount != 1 || op.ReturnType.TypeKind == TypeKind.Error) { continue; } TypeSymbol convertsFrom = op.GetParameterType(0); TypeSymbol convertsTo = op.ReturnType; Conversion fromConversion = EncompassingExplicitConversion(sourceExpression, source, convertsFrom, ref useSiteInfo); Conversion toConversion = EncompassingExplicitConversion(null, convertsTo, target, ref useSiteInfo); // We accept candidates for which the parameter type encompasses the *underlying* source type. if (!fromConversion.Exists && (object)source != null && source.IsNullableType() && EncompassingExplicitConversion(null, source.GetNullableUnderlyingType(), convertsFrom, ref useSiteInfo).Exists) { fromConversion = ClassifyBuiltInConversion(source, convertsFrom, ref useSiteInfo); } // As in dev11 (and the revised spec), we also accept candidates for which the return type is encompassed by the *stripped* target type. if (!toConversion.Exists && (object)target != null && target.IsNullableType() && EncompassingExplicitConversion(null, convertsTo, target.GetNullableUnderlyingType(), ref useSiteInfo).Exists) { toConversion = ClassifyBuiltInConversion(convertsTo, target, ref useSiteInfo); } // In the corresponding implicit conversion code we can get away with first // checking to see if standard implicit conversions exist from the source type // to the parameter type, and from the return type to the target type. If not, // then we can check for a lifted operator. // // That's not going to cut it in the explicit conversion code. Suppose we have // a conversion X-->Y and have source type X? and target type Y?. There *are* // standard explicit conversions from X?-->X and Y?-->Y, but we do not want // to bind this as an *unlifted* conversion from X? to Y?; we want such a thing // to be a *lifted* conversion from X? to Y?, that checks for null on the source // and decides to not call the underlying user-defined conversion if it is null. // // We therefore cannot do what we do in the implicit conversions, where we check // to see if the unlifted conversion works, and if it does, then don't add the lifted // conversion at all. Rather, we have to see if what we're building here is a // lifted conversion or not. // // Under what circumstances is this conversion a lifted conversion? (In the // "spec" sense of a lifted conversion; that is, that we check for null // and skip the user-defined conversion if necessary). // // * The source type must be a nullable value type. // * The parameter type must be a non-nullable value type. // * The target type must be able to take on a null value. if (fromConversion.Exists && toConversion.Exists) { if ((object)source != null && source.IsNullableType() && convertsFrom.IsNonNullableValueType() && target.CanBeAssignedNull()) { TypeSymbol nullableFrom = MakeNullableType(convertsFrom); TypeSymbol nullableTo = convertsTo.IsNonNullableValueType() ? MakeNullableType(convertsTo) : convertsTo; Conversion liftedFromConversion = EncompassingExplicitConversion(sourceExpression, source, nullableFrom, ref useSiteInfo); Conversion liftedToConversion = EncompassingExplicitConversion(null, nullableTo, target, ref useSiteInfo); Debug.Assert(liftedFromConversion.Exists); Debug.Assert(liftedToConversion.Exists); u.Add(UserDefinedConversionAnalysis.Lifted(constrainedToTypeOpt, op, liftedFromConversion, liftedToConversion, nullableFrom, nullableTo)); } else { // There is an additional spec violation in the native compiler. Suppose // we have a conversion from X-->Y and are asked to do "Y? y = new X();" Clearly // the intention is to convert from X-->Y via the implicit conversion, and then // stick a standard implicit conversion from Y-->Y? on the back end. **In this // situation, the native compiler treats the conversion as though it were // actually X-->Y? in source for the purposes of determining the best target // type of a set of operators. // // Similarly, if we have a conversion from X-->Y and are asked to do // an explicit conversion from X? to Y then we treat the conversion as // though it really were X?-->Y for the purposes of determining the best // source type of a set of operators. // // We perpetuate these fictions here. if (target.IsNullableType() && convertsTo.IsNonNullableValueType()) { convertsTo = MakeNullableType(convertsTo); toConversion = EncompassingExplicitConversion(null, convertsTo, target, ref useSiteInfo); } if ((object)source != null && source.IsNullableType() && convertsFrom.IsNonNullableValueType()) { convertsFrom = MakeNullableType(convertsFrom); fromConversion = EncompassingExplicitConversion(null, convertsFrom, source, ref useSiteInfo); } u.Add(UserDefinedConversionAnalysis.Normal(constrainedToTypeOpt, op, fromConversion, toConversion, convertsFrom, convertsTo)); } } } } private TypeSymbol MostSpecificSourceTypeForExplicitUserDefinedConversion( ImmutableArray<UserDefinedConversionAnalysis> u, BoundExpression sourceExpression, TypeSymbol source, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: If any of the operators in U convert from S then SX is S. // SPEC: Otherwise, if any of the operators in U convert from types // SPEC: that encompass E, then SX is the most encompassed type // SPEC: in the combined set of the source types of these operators. // SPEC: If no most encompassed type can be found then the // SPEC: conversion is ambiguous and a compile-time error occurs. // SPEC: Otherwise, SX is the most encompassing type in the combined // SPEC: set of the source types of these operators. If exactly one // SPEC: most encompassing type cannot be found then the conversion // SPEC: is ambiguous and a compile-time error occurs. // DELIBERATE SPEC VIOLATION: // The native compiler deviates from the specification in the way it // determines what the "converts from" type is. The specification is pretty // clear that the "converts from" type is the actual parameter type of the // conversion operator, or, in the case of a lifted operator, the lifted-to- // nullable type. That is, if we have X-->Y then the converts-to type of // the operator in its normal form is Y, and the converts-to type of the // operator in its lifted form is Y?. // // The native compiler does not do this. Suppose we have a user-defined // conversion X-->Y, and the cast (Y)(some_nullable_x). The native // compiler will consider the converts-from type of X-->Y to be X?, surprisingly // enough. // // We have already written the "FromType" into the conversion analysis to // perpetuate this fiction. if ((object)source != null) { if (u.Any(conv => TypeSymbol.Equals(conv.FromType, source, TypeCompareKind.ConsiderEverything2))) { return source; } CompoundUseSiteInfo<AssemblySymbol> inLambdaUseSiteInfo = useSiteInfo; System.Func<UserDefinedConversionAnalysis, bool> isValid = conv => IsEncompassedBy(sourceExpression, source, conv.FromType, ref inLambdaUseSiteInfo); if (u.Any(isValid)) { var result = MostEncompassedType(u, isValid, conv => conv.FromType, ref inLambdaUseSiteInfo); useSiteInfo = inLambdaUseSiteInfo; return result; } useSiteInfo = inLambdaUseSiteInfo; } return MostEncompassingType(u, conv => conv.FromType, ref useSiteInfo); } private TypeSymbol MostSpecificTargetTypeForExplicitUserDefinedConversion( ImmutableArray<UserDefinedConversionAnalysis> u, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: If any of the operators in U convert to T then TX is T. // SPEC: Otherwise, if any of the operators in U convert to types that are // SPEC: encompassed by T then TX is the most encompassing type in the combined // SPEC: set of target types of those operators. If exactly one most encompassing // SPEC: type cannot be found then the conversion is ambiguous and a compile-time // SPEC: error occurs. // SPEC: Otherwise, Tx is the most encompassed type in the combined set of target // SPEC: types of the operators in U. If no most encompassed type can be found, // SPEC: then the conversion is ambiguous and a compile-time error occurs. // DELIBERATE SPEC VIOLATION: // The native compiler deviates from the specification in the way it // determines what the "converts to" type is. The specification is pretty // clear that the "converts to" type is the actual return type of the // conversion operator, or, in the case of a lifted operator, the lifted-to- // nullable type. That is, if we have X-->Y then the converts-to type of // the operator in its normal form is Y, and the converts-to type of the // operator in its lifted form is Y?. // // The native compiler does not do this. Suppose we have a user-defined // conversion X-->Y, and the assignment Y? y = new X(); -- the native // compiler will consider the converts-to type of X-->Y to be Y?, surprisingly // enough. // // We have already written the "ToType" into the conversion analysis to // perpetuate this fiction. if (u.Any(conv => TypeSymbol.Equals(conv.ToType, target, TypeCompareKind.ConsiderEverything2))) { return target; } CompoundUseSiteInfo<AssemblySymbol> inLambdaUseSiteInfo = useSiteInfo; System.Func<UserDefinedConversionAnalysis, bool> isValid = conv => IsEncompassedBy(null, conv.ToType, target, ref inLambdaUseSiteInfo); if (u.Any(isValid)) { var result = MostEncompassingType(u, isValid, conv => conv.ToType, ref inLambdaUseSiteInfo); useSiteInfo = inLambdaUseSiteInfo; return result; } useSiteInfo = inLambdaUseSiteInfo; return MostEncompassedType(u, conv => conv.ToType, ref useSiteInfo); } private Conversion EncompassingExplicitConversion(BoundExpression expr, TypeSymbol a, TypeSymbol b, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(expr != null || (object)a != null); Debug.Assert((object)b != null); // SPEC: If a standard implicit conversion exists from a type A to a type B // SPEC: and if neither A nor B is an interface type then A is said to be // SPEC: encompassed by B, and B is said to encompass A. // DELIBERATE SPEC VIOLATION: We should be checking to see if A and B are // interface types here. See the comment regarding bug 17021 in // UserDefinedImplicitConversions.cs // DELIBERATE SPEC VIOLATION: // We do not support an encompassing implicit conversion from a zero constant // to an enum type, because the native compiler did not. It would be a breaking // change. var result = ClassifyStandardConversion(expr, a, b, ref useSiteInfo); return result.IsEnumeration ? Conversion.NoConversion : result; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Tools/ExternalAccess/FSharp/Structure/FSharpBlockStructure.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Structure { internal class FSharpBlockStructure { public ImmutableArray<FSharpBlockSpan> Spans { get; } public FSharpBlockStructure(ImmutableArray<FSharpBlockSpan> spans) { Spans = spans; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Structure { internal class FSharpBlockStructure { public ImmutableArray<FSharpBlockSpan> Spans { get; } public FSharpBlockStructure(ImmutableArray<FSharpBlockSpan> spans) { Spans = spans; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/Workspace/Solution/VersionStamp.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// VersionStamp should be only used to compare versions returned by same API. /// </summary> public readonly struct VersionStamp : IEquatable<VersionStamp>, IObjectWritable { public static VersionStamp Default => default; private const int GlobalVersionMarker = -1; private const int InitialGlobalVersion = 10000; /// <summary> /// global counter to avoid collision within same session. /// it starts with a big initial number just for a clarity in debugging /// </summary> private static int s_globalVersion = InitialGlobalVersion; /// <summary> /// time stamp /// </summary> private readonly DateTime _utcLastModified; /// <summary> /// indicate whether there was a collision on same item /// </summary> private readonly int _localIncrement; /// <summary> /// unique version in same session /// </summary> private readonly int _globalIncrement; private VersionStamp(DateTime utcLastModified) : this(utcLastModified, 0) { } private VersionStamp(DateTime utcLastModified, int localIncrement) : this(utcLastModified, localIncrement, GetNextGlobalVersion()) { } private VersionStamp(DateTime utcLastModified, int localIncrement, int globalIncrement) { if (utcLastModified != default && utcLastModified.Kind != DateTimeKind.Utc) { throw new ArgumentException(WorkspacesResources.DateTimeKind_must_be_Utc, nameof(utcLastModified)); } _utcLastModified = utcLastModified; _localIncrement = localIncrement; _globalIncrement = globalIncrement; } /// <summary> /// Creates a new instance of a VersionStamp. /// </summary> public static VersionStamp Create() => new(DateTime.UtcNow); /// <summary> /// Creates a new instance of a version stamp based on the specified DateTime. /// </summary> public static VersionStamp Create(DateTime utcTimeLastModified) => new(utcTimeLastModified); /// <summary> /// compare two different versions and return either one of the versions if there is no collision, otherwise, create a new version /// that can be used later to compare versions between different items /// </summary> public VersionStamp GetNewerVersion(VersionStamp version) { // * NOTE * // in current design/implementation, there are 4 possible ways for a version to be created. // // 1. created from a file stamp (most likely by starting a new session). "increment" will have 0 as value // 2. created by modifying existing item (text changes, project changes etc). // "increment" will have either 0 or previous increment + 1 if there was a collision. // 3. created from deserialization (probably by using persistent service). // 4. created by accumulating versions of multiple items. // // and this method is the one that is responsible for #4 case. if (_utcLastModified > version._utcLastModified) { return this; } if (_utcLastModified == version._utcLastModified) { var thisGlobalVersion = GetGlobalVersion(this); var thatGlobalVersion = GetGlobalVersion(version); if (thisGlobalVersion == thatGlobalVersion) { // given versions are same one return this; } // mark it as global version // global version can't be moved to newer version. return new VersionStamp(_utcLastModified, (thisGlobalVersion > thatGlobalVersion) ? thisGlobalVersion : thatGlobalVersion, GlobalVersionMarker); } return version; } /// <summary> /// Gets a new VersionStamp that is guaranteed to be newer than its base one /// this should only be used for same item to move it to newer version /// </summary> public VersionStamp GetNewerVersion() { // global version can't be moved to newer version Debug.Assert(_globalIncrement != GlobalVersionMarker); var now = DateTime.UtcNow; var incr = (now == _utcLastModified) ? _localIncrement + 1 : 0; return new VersionStamp(now, incr); } /// <summary> /// Returns the serialized text form of the VersionStamp. /// </summary> public override string ToString() { // 'o' is the roundtrip format that captures the most detail. return _utcLastModified.ToString("o") + "-" + _globalIncrement + "-" + _localIncrement; } public override int GetHashCode() => Hash.Combine(_utcLastModified.GetHashCode(), _localIncrement); public override bool Equals(object? obj) { if (obj is VersionStamp v) { return this.Equals(v); } return false; } public bool Equals(VersionStamp version) { if (_utcLastModified == version._utcLastModified) { return GetGlobalVersion(this) == GetGlobalVersion(version); } return false; } public static bool operator ==(VersionStamp left, VersionStamp right) => left.Equals(right); public static bool operator !=(VersionStamp left, VersionStamp right) => !left.Equals(right); /// <summary> /// Check whether given persisted version is re-usable. Used by VS for Mac /// </summary> internal static bool CanReusePersistedVersion(VersionStamp baseVersion, VersionStamp persistedVersion) { if (baseVersion == persistedVersion) { return true; } // there was a collision, we can't use these if (baseVersion._localIncrement != 0 || persistedVersion._localIncrement != 0) { return false; } return baseVersion._utcLastModified == persistedVersion._utcLastModified; } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) => WriteTo(writer); internal void WriteTo(ObjectWriter writer) { writer.WriteInt64(_utcLastModified.ToBinary()); writer.WriteInt32(_localIncrement); writer.WriteInt32(_globalIncrement); } internal static VersionStamp ReadFrom(ObjectReader reader) { var raw = reader.ReadInt64(); var localIncrement = reader.ReadInt32(); var globalIncrement = reader.ReadInt32(); return new VersionStamp(DateTime.FromBinary(raw), localIncrement, globalIncrement); } private static int GetGlobalVersion(VersionStamp version) { // global increment < 0 means it is a global version which has its global increment in local increment return version._globalIncrement >= 0 ? version._globalIncrement : version._localIncrement; } private static int GetNextGlobalVersion() { // REVIEW: not sure what is best way to wrap it when it overflows. should I just throw or don't care. // with 50ms (typing) as an interval for a new version, it gives more than 1 year before int32 to overflow. // with 5ms as an interval, it gives more than 120 days before it overflows. // since global version is only for per VS session, I think we don't need to worry about overflow. // or we could use Int64 which will give more than a million years turn around even on 1ms interval. // this will let versions to be compared safely between multiple items // without worrying about collision within same session var globalVersion = Interlocked.Increment(ref VersionStamp.s_globalVersion); return globalVersion; } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly VersionStamp _versionStamp; public TestAccessor(in VersionStamp versionStamp) => _versionStamp = versionStamp; /// <summary> /// True if this VersionStamp is newer than the specified one. /// </summary> internal bool IsNewerThan(in VersionStamp version) { if (_versionStamp._utcLastModified > version._utcLastModified) { return true; } if (_versionStamp._utcLastModified == version._utcLastModified) { return GetGlobalVersion(_versionStamp) > GetGlobalVersion(version); } return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// VersionStamp should be only used to compare versions returned by same API. /// </summary> public readonly struct VersionStamp : IEquatable<VersionStamp>, IObjectWritable { public static VersionStamp Default => default; private const int GlobalVersionMarker = -1; private const int InitialGlobalVersion = 10000; /// <summary> /// global counter to avoid collision within same session. /// it starts with a big initial number just for a clarity in debugging /// </summary> private static int s_globalVersion = InitialGlobalVersion; /// <summary> /// time stamp /// </summary> private readonly DateTime _utcLastModified; /// <summary> /// indicate whether there was a collision on same item /// </summary> private readonly int _localIncrement; /// <summary> /// unique version in same session /// </summary> private readonly int _globalIncrement; private VersionStamp(DateTime utcLastModified) : this(utcLastModified, 0) { } private VersionStamp(DateTime utcLastModified, int localIncrement) : this(utcLastModified, localIncrement, GetNextGlobalVersion()) { } private VersionStamp(DateTime utcLastModified, int localIncrement, int globalIncrement) { if (utcLastModified != default && utcLastModified.Kind != DateTimeKind.Utc) { throw new ArgumentException(WorkspacesResources.DateTimeKind_must_be_Utc, nameof(utcLastModified)); } _utcLastModified = utcLastModified; _localIncrement = localIncrement; _globalIncrement = globalIncrement; } /// <summary> /// Creates a new instance of a VersionStamp. /// </summary> public static VersionStamp Create() => new(DateTime.UtcNow); /// <summary> /// Creates a new instance of a version stamp based on the specified DateTime. /// </summary> public static VersionStamp Create(DateTime utcTimeLastModified) => new(utcTimeLastModified); /// <summary> /// compare two different versions and return either one of the versions if there is no collision, otherwise, create a new version /// that can be used later to compare versions between different items /// </summary> public VersionStamp GetNewerVersion(VersionStamp version) { // * NOTE * // in current design/implementation, there are 4 possible ways for a version to be created. // // 1. created from a file stamp (most likely by starting a new session). "increment" will have 0 as value // 2. created by modifying existing item (text changes, project changes etc). // "increment" will have either 0 or previous increment + 1 if there was a collision. // 3. created from deserialization (probably by using persistent service). // 4. created by accumulating versions of multiple items. // // and this method is the one that is responsible for #4 case. if (_utcLastModified > version._utcLastModified) { return this; } if (_utcLastModified == version._utcLastModified) { var thisGlobalVersion = GetGlobalVersion(this); var thatGlobalVersion = GetGlobalVersion(version); if (thisGlobalVersion == thatGlobalVersion) { // given versions are same one return this; } // mark it as global version // global version can't be moved to newer version. return new VersionStamp(_utcLastModified, (thisGlobalVersion > thatGlobalVersion) ? thisGlobalVersion : thatGlobalVersion, GlobalVersionMarker); } return version; } /// <summary> /// Gets a new VersionStamp that is guaranteed to be newer than its base one /// this should only be used for same item to move it to newer version /// </summary> public VersionStamp GetNewerVersion() { // global version can't be moved to newer version Debug.Assert(_globalIncrement != GlobalVersionMarker); var now = DateTime.UtcNow; var incr = (now == _utcLastModified) ? _localIncrement + 1 : 0; return new VersionStamp(now, incr); } /// <summary> /// Returns the serialized text form of the VersionStamp. /// </summary> public override string ToString() { // 'o' is the roundtrip format that captures the most detail. return _utcLastModified.ToString("o") + "-" + _globalIncrement + "-" + _localIncrement; } public override int GetHashCode() => Hash.Combine(_utcLastModified.GetHashCode(), _localIncrement); public override bool Equals(object? obj) { if (obj is VersionStamp v) { return this.Equals(v); } return false; } public bool Equals(VersionStamp version) { if (_utcLastModified == version._utcLastModified) { return GetGlobalVersion(this) == GetGlobalVersion(version); } return false; } public static bool operator ==(VersionStamp left, VersionStamp right) => left.Equals(right); public static bool operator !=(VersionStamp left, VersionStamp right) => !left.Equals(right); /// <summary> /// Check whether given persisted version is re-usable. Used by VS for Mac /// </summary> internal static bool CanReusePersistedVersion(VersionStamp baseVersion, VersionStamp persistedVersion) { if (baseVersion == persistedVersion) { return true; } // there was a collision, we can't use these if (baseVersion._localIncrement != 0 || persistedVersion._localIncrement != 0) { return false; } return baseVersion._utcLastModified == persistedVersion._utcLastModified; } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) => WriteTo(writer); internal void WriteTo(ObjectWriter writer) { writer.WriteInt64(_utcLastModified.ToBinary()); writer.WriteInt32(_localIncrement); writer.WriteInt32(_globalIncrement); } internal static VersionStamp ReadFrom(ObjectReader reader) { var raw = reader.ReadInt64(); var localIncrement = reader.ReadInt32(); var globalIncrement = reader.ReadInt32(); return new VersionStamp(DateTime.FromBinary(raw), localIncrement, globalIncrement); } private static int GetGlobalVersion(VersionStamp version) { // global increment < 0 means it is a global version which has its global increment in local increment return version._globalIncrement >= 0 ? version._globalIncrement : version._localIncrement; } private static int GetNextGlobalVersion() { // REVIEW: not sure what is best way to wrap it when it overflows. should I just throw or don't care. // with 50ms (typing) as an interval for a new version, it gives more than 1 year before int32 to overflow. // with 5ms as an interval, it gives more than 120 days before it overflows. // since global version is only for per VS session, I think we don't need to worry about overflow. // or we could use Int64 which will give more than a million years turn around even on 1ms interval. // this will let versions to be compared safely between multiple items // without worrying about collision within same session var globalVersion = Interlocked.Increment(ref VersionStamp.s_globalVersion); return globalVersion; } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly VersionStamp _versionStamp; public TestAccessor(in VersionStamp versionStamp) => _versionStamp = versionStamp; /// <summary> /// True if this VersionStamp is newer than the specified one. /// </summary> internal bool IsNewerThan(in VersionStamp version) { if (_versionStamp._utcLastModified > version._utcLastModified) { return true; } if (_versionStamp._utcLastModified == version._utcLastModified) { return GetGlobalVersion(_versionStamp) > GetGlobalVersion(version); } return false; } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Scripting/CoreTest/Microsoft.CodeAnalysis.Scripting.UnitTests.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.Scripting.Test</RootNamespace> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\CoreTestUtilities\Microsoft.CodeAnalysis.Scripting.TestUtilities.csproj" /> <ProjectReference Include="..\Core\Microsoft.CodeAnalysis.Scripting.csproj"> <Aliases>global,Scripting</Aliases> </ProjectReference> <ProjectReference Include="..\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" /> <ProjectReference Include="..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Scripting.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.Scripting.Test</RootNamespace> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\CoreTestUtilities\Microsoft.CodeAnalysis.Scripting.TestUtilities.csproj" /> <ProjectReference Include="..\Core\Microsoft.CodeAnalysis.Scripting.csproj"> <Aliases>global,Scripting</Aliases> </ProjectReference> <ProjectReference Include="..\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" /> <ProjectReference Include="..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Scripting.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Tools/AnalyzerRunner/Options.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.IO; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.SolutionCrawler; namespace AnalyzerRunner { public sealed class Options { public readonly string AnalyzerPath; public readonly string SolutionPath; public readonly ImmutableHashSet<string> AnalyzerNames; public readonly ImmutableHashSet<string> RefactoringNodes; public readonly bool RunConcurrent; public readonly bool ReportSuppressedDiagnostics; public readonly bool ApplyChanges; public readonly bool UseAll; public readonly int Iterations; // Options specific to incremental analyzers public readonly bool UsePersistentStorage; public readonly ImmutableArray<string> IncrementalAnalyzerNames; public readonly bool FullSolutionAnalysis; // Options used by AnalyzerRunner CLI only internal readonly bool ShowStats; internal readonly bool ShowCompilerDiagnostics; internal readonly bool TestDocuments; internal readonly Func<string, bool> TestDocumentMatch; internal readonly int TestDocumentIterations; internal readonly string LogFileName; internal readonly string ProfileRoot; internal BackgroundAnalysisScope AnalysisScope => FullSolutionAnalysis ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default; public Options( string analyzerPath, string solutionPath, ImmutableHashSet<string> analyzerIds, ImmutableHashSet<string> refactoringNodes, bool runConcurrent, bool reportSuppressedDiagnostics, bool applyChanges, bool useAll, int iterations, bool usePersistentStorage, bool fullSolutionAnalysis, ImmutableArray<string> incrementalAnalyzerNames) : this(analyzerPath, solutionPath, analyzerIds, refactoringNodes, runConcurrent, reportSuppressedDiagnostics, applyChanges, showStats: false, showCompilerDiagnostics: false, useAll, iterations, testDocuments: false, testDocumentMatch: _ => false, testDocumentIterations: 0, logFileName: null, profileRoot: null, usePersistentStorage, fullSolutionAnalysis, incrementalAnalyzerNames) { } internal Options( string analyzerPath, string solutionPath, ImmutableHashSet<string> analyzerIds, ImmutableHashSet<string> refactoringNodes, bool runConcurrent, bool reportSuppressedDiagnostics, bool applyChanges, bool showStats, bool showCompilerDiagnostics, bool useAll, int iterations, bool testDocuments, Func<string, bool> testDocumentMatch, int testDocumentIterations, string logFileName, string profileRoot, bool usePersistentStorage, bool fullSolutionAnalysis, ImmutableArray<string> incrementalAnalyzerNames) { AnalyzerPath = analyzerPath; SolutionPath = solutionPath; AnalyzerNames = analyzerIds; RefactoringNodes = refactoringNodes; RunConcurrent = runConcurrent; ReportSuppressedDiagnostics = reportSuppressedDiagnostics; ApplyChanges = applyChanges; ShowStats = showStats; ShowCompilerDiagnostics = showCompilerDiagnostics; UseAll = useAll; Iterations = iterations; TestDocuments = testDocuments; TestDocumentMatch = testDocumentMatch; TestDocumentIterations = testDocumentIterations; LogFileName = logFileName; ProfileRoot = profileRoot; UsePersistentStorage = usePersistentStorage; FullSolutionAnalysis = fullSolutionAnalysis; IncrementalAnalyzerNames = incrementalAnalyzerNames; } internal static Options Create(string[] args) { string analyzerPath = null; string solutionPath = null; var builder = ImmutableHashSet.CreateBuilder<string>(); var refactoringBuilder = ImmutableHashSet.CreateBuilder<string>(); bool runConcurrent = false; bool reportSuppressedDiagnostics = false; bool applyChanges = false; bool showStats = false; bool showCompilerDiagnostics = false; bool useAll = false; int iterations = 1; bool testDocuments = false; Func<string, bool> testDocumentMatch = _ => true; int testDocumentIterations = 10; string logFileName = null; string profileRoot = null; var usePersistentStorage = false; var fullSolutionAnalysis = false; var incrementalAnalyzerNames = ImmutableArray.CreateBuilder<string>(); int i = 0; while (i < args.Length) { var arg = args[i++]; string ReadValue() => (i < args.Length) ? args[i++] : throw new InvalidDataException($"Missing value for option {arg}"); switch (arg) { case "/all": useAll = true; break; case "/stats": showStats = true; break; case "/compilerStats": showCompilerDiagnostics = true; break; case "/concurrent": runConcurrent = true; break; case "/editperf": testDocuments = true; break; case var _ when arg.StartsWith("/editperf:"): testDocuments = true; var expression = new Regex(arg.Substring("/editperf:".Length), RegexOptions.Compiled | RegexOptions.IgnoreCase); testDocumentMatch = documentPath => expression.IsMatch(documentPath); break; case var _ when arg.StartsWith("/edititer:"): testDocumentIterations = int.Parse(arg.Substring("/edititer:".Length)); break; case var _ when arg.StartsWith("/iter:"): iterations = int.Parse(arg.Substring("/iter:".Length)); break; case "/suppressed": reportSuppressedDiagnostics = true; break; case "/apply": applyChanges = true; break; case "/a": builder.Add(ReadValue()); break; case "/refactor": refactoringBuilder.Add(ReadValue()); break; case "/log": logFileName = ReadValue(); break; case "/profileroot": profileRoot = ReadValue(); break; case "/persist": usePersistentStorage = true; break; case "/fsa": fullSolutionAnalysis = true; break; case "/ia": incrementalAnalyzerNames.Add(ReadValue()); break; default: if (analyzerPath == null) { analyzerPath = arg; } else if (solutionPath == null) { solutionPath = arg; } else { throw new InvalidDataException((arg.StartsWith("/", StringComparison.Ordinal) ? "Unrecognized option " + arg : "Unrecognized parameter " + arg)); } break; } } if (analyzerPath == null) { throw new InvalidDataException("Missing analyzer path"); } if (solutionPath == null) { throw new InvalidDataException("Missing solution path"); } return new Options( analyzerPath: analyzerPath, solutionPath: solutionPath, analyzerIds: builder.ToImmutableHashSet(), refactoringNodes: refactoringBuilder.ToImmutableHashSet(), runConcurrent: runConcurrent, reportSuppressedDiagnostics: reportSuppressedDiagnostics, applyChanges: applyChanges, showStats: showStats, showCompilerDiagnostics: showCompilerDiagnostics, useAll: useAll, iterations: iterations, testDocuments: testDocuments, testDocumentMatch: testDocumentMatch, testDocumentIterations: testDocumentIterations, logFileName: logFileName, profileRoot: profileRoot, usePersistentStorage: usePersistentStorage, fullSolutionAnalysis: fullSolutionAnalysis, incrementalAnalyzerNames: incrementalAnalyzerNames.ToImmutable()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.IO; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.SolutionCrawler; namespace AnalyzerRunner { public sealed class Options { public readonly string AnalyzerPath; public readonly string SolutionPath; public readonly ImmutableHashSet<string> AnalyzerNames; public readonly ImmutableHashSet<string> RefactoringNodes; public readonly bool RunConcurrent; public readonly bool ReportSuppressedDiagnostics; public readonly bool ApplyChanges; public readonly bool UseAll; public readonly int Iterations; // Options specific to incremental analyzers public readonly bool UsePersistentStorage; public readonly ImmutableArray<string> IncrementalAnalyzerNames; public readonly bool FullSolutionAnalysis; // Options used by AnalyzerRunner CLI only internal readonly bool ShowStats; internal readonly bool ShowCompilerDiagnostics; internal readonly bool TestDocuments; internal readonly Func<string, bool> TestDocumentMatch; internal readonly int TestDocumentIterations; internal readonly string LogFileName; internal readonly string ProfileRoot; internal BackgroundAnalysisScope AnalysisScope => FullSolutionAnalysis ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default; public Options( string analyzerPath, string solutionPath, ImmutableHashSet<string> analyzerIds, ImmutableHashSet<string> refactoringNodes, bool runConcurrent, bool reportSuppressedDiagnostics, bool applyChanges, bool useAll, int iterations, bool usePersistentStorage, bool fullSolutionAnalysis, ImmutableArray<string> incrementalAnalyzerNames) : this(analyzerPath, solutionPath, analyzerIds, refactoringNodes, runConcurrent, reportSuppressedDiagnostics, applyChanges, showStats: false, showCompilerDiagnostics: false, useAll, iterations, testDocuments: false, testDocumentMatch: _ => false, testDocumentIterations: 0, logFileName: null, profileRoot: null, usePersistentStorage, fullSolutionAnalysis, incrementalAnalyzerNames) { } internal Options( string analyzerPath, string solutionPath, ImmutableHashSet<string> analyzerIds, ImmutableHashSet<string> refactoringNodes, bool runConcurrent, bool reportSuppressedDiagnostics, bool applyChanges, bool showStats, bool showCompilerDiagnostics, bool useAll, int iterations, bool testDocuments, Func<string, bool> testDocumentMatch, int testDocumentIterations, string logFileName, string profileRoot, bool usePersistentStorage, bool fullSolutionAnalysis, ImmutableArray<string> incrementalAnalyzerNames) { AnalyzerPath = analyzerPath; SolutionPath = solutionPath; AnalyzerNames = analyzerIds; RefactoringNodes = refactoringNodes; RunConcurrent = runConcurrent; ReportSuppressedDiagnostics = reportSuppressedDiagnostics; ApplyChanges = applyChanges; ShowStats = showStats; ShowCompilerDiagnostics = showCompilerDiagnostics; UseAll = useAll; Iterations = iterations; TestDocuments = testDocuments; TestDocumentMatch = testDocumentMatch; TestDocumentIterations = testDocumentIterations; LogFileName = logFileName; ProfileRoot = profileRoot; UsePersistentStorage = usePersistentStorage; FullSolutionAnalysis = fullSolutionAnalysis; IncrementalAnalyzerNames = incrementalAnalyzerNames; } internal static Options Create(string[] args) { string analyzerPath = null; string solutionPath = null; var builder = ImmutableHashSet.CreateBuilder<string>(); var refactoringBuilder = ImmutableHashSet.CreateBuilder<string>(); bool runConcurrent = false; bool reportSuppressedDiagnostics = false; bool applyChanges = false; bool showStats = false; bool showCompilerDiagnostics = false; bool useAll = false; int iterations = 1; bool testDocuments = false; Func<string, bool> testDocumentMatch = _ => true; int testDocumentIterations = 10; string logFileName = null; string profileRoot = null; var usePersistentStorage = false; var fullSolutionAnalysis = false; var incrementalAnalyzerNames = ImmutableArray.CreateBuilder<string>(); int i = 0; while (i < args.Length) { var arg = args[i++]; string ReadValue() => (i < args.Length) ? args[i++] : throw new InvalidDataException($"Missing value for option {arg}"); switch (arg) { case "/all": useAll = true; break; case "/stats": showStats = true; break; case "/compilerStats": showCompilerDiagnostics = true; break; case "/concurrent": runConcurrent = true; break; case "/editperf": testDocuments = true; break; case var _ when arg.StartsWith("/editperf:"): testDocuments = true; var expression = new Regex(arg.Substring("/editperf:".Length), RegexOptions.Compiled | RegexOptions.IgnoreCase); testDocumentMatch = documentPath => expression.IsMatch(documentPath); break; case var _ when arg.StartsWith("/edititer:"): testDocumentIterations = int.Parse(arg.Substring("/edititer:".Length)); break; case var _ when arg.StartsWith("/iter:"): iterations = int.Parse(arg.Substring("/iter:".Length)); break; case "/suppressed": reportSuppressedDiagnostics = true; break; case "/apply": applyChanges = true; break; case "/a": builder.Add(ReadValue()); break; case "/refactor": refactoringBuilder.Add(ReadValue()); break; case "/log": logFileName = ReadValue(); break; case "/profileroot": profileRoot = ReadValue(); break; case "/persist": usePersistentStorage = true; break; case "/fsa": fullSolutionAnalysis = true; break; case "/ia": incrementalAnalyzerNames.Add(ReadValue()); break; default: if (analyzerPath == null) { analyzerPath = arg; } else if (solutionPath == null) { solutionPath = arg; } else { throw new InvalidDataException((arg.StartsWith("/", StringComparison.Ordinal) ? "Unrecognized option " + arg : "Unrecognized parameter " + arg)); } break; } } if (analyzerPath == null) { throw new InvalidDataException("Missing analyzer path"); } if (solutionPath == null) { throw new InvalidDataException("Missing solution path"); } return new Options( analyzerPath: analyzerPath, solutionPath: solutionPath, analyzerIds: builder.ToImmutableHashSet(), refactoringNodes: refactoringBuilder.ToImmutableHashSet(), runConcurrent: runConcurrent, reportSuppressedDiagnostics: reportSuppressedDiagnostics, applyChanges: applyChanges, showStats: showStats, showCompilerDiagnostics: showCompilerDiagnostics, useAll: useAll, iterations: iterations, testDocuments: testDocuments, testDocumentMatch: testDocumentMatch, testDocumentIterations: testDocumentIterations, logFileName: logFileName, profileRoot: profileRoot, usePersistentStorage: usePersistentStorage, fullSolutionAnalysis: fullSolutionAnalysis, incrementalAnalyzerNames: incrementalAnalyzerNames.ToImmutable()); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/CSharp/Portable/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeStyleProvider_Fixing.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBodyForLambda { // Code for the CodeFixProvider ("Fixing") portion of the feature. internal partial class UseExpressionBodyForLambdaCodeStyleProvider { protected override Task<ImmutableArray<CodeAction>> ComputeCodeActionsAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { var codeAction = new MyCodeAction( diagnostic.GetMessage(), c => FixWithSyntaxEditorAsync(document, diagnostic, c)); return Task.FromResult(ImmutableArray.Create<CodeAction>(codeAction)); } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var diagnostic in diagnostics) { cancellationToken.ThrowIfCancellationRequested(); AddEdits(editor, semanticModel, diagnostic, cancellationToken); } } private static void AddEdits( SyntaxEditor editor, SemanticModel semanticModel, Diagnostic diagnostic, CancellationToken cancellationToken) { var declarationLocation = diagnostic.AdditionalLocations[0]; var originalDeclaration = (LambdaExpressionSyntax)declarationLocation.FindNode(getInnermostNodeForTie: true, cancellationToken); editor.ReplaceNode( originalDeclaration, (current, _) => Update(semanticModel, originalDeclaration, (LambdaExpressionSyntax)current)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBodyForLambda { // Code for the CodeFixProvider ("Fixing") portion of the feature. internal partial class UseExpressionBodyForLambdaCodeStyleProvider { protected override Task<ImmutableArray<CodeAction>> ComputeCodeActionsAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { var codeAction = new MyCodeAction( diagnostic.GetMessage(), c => FixWithSyntaxEditorAsync(document, diagnostic, c)); return Task.FromResult(ImmutableArray.Create<CodeAction>(codeAction)); } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var diagnostic in diagnostics) { cancellationToken.ThrowIfCancellationRequested(); AddEdits(editor, semanticModel, diagnostic, cancellationToken); } } private static void AddEdits( SyntaxEditor editor, SemanticModel semanticModel, Diagnostic diagnostic, CancellationToken cancellationToken) { var declarationLocation = diagnostic.AdditionalLocations[0]; var originalDeclaration = (LambdaExpressionSyntax)declarationLocation.FindNode(getInnermostNodeForTie: true, cancellationToken); editor.ReplaceNode( originalDeclaration, (current, _) => Update(semanticModel, originalDeclaration, (LambdaExpressionSyntax)current)); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Portable/Compiler/AnonymousTypeMethodBodySynthesizer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { private sealed partial class AnonymousTypeConstructorSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { // Method body: // // { // Object..ctor(); // this.backingField_1 = arg1; // ... // this.backingField_N = argN; // } SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); int paramCount = this.ParameterCount; // List of statements BoundStatement[] statements = new BoundStatement[paramCount + 2]; int statementIndex = 0; // explicit base constructor call Debug.Assert(ContainingType.BaseTypeNoUseSiteDiagnostics.SpecialType == SpecialType.System_Object); BoundExpression call = MethodCompiler.GenerateBaseParameterlessConstructorInitializer(this, diagnostics); if (call == null) { // This may happen if Object..ctor is not found or is inaccessible return; } statements[statementIndex++] = F.ExpressionStatement(call); if (paramCount > 0) { AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; Debug.Assert(anonymousType.Properties.Length == paramCount); // Assign fields for (int index = 0; index < this.ParameterCount; index++) { // Generate 'field' = 'parameter' statement statements[statementIndex++] = F.Assignment(F.Field(F.This(), anonymousType.Properties[index].BackingField), F.Parameter(_parameters[index])); } } // Final return statement statements[statementIndex++] = F.Return(); // Create a bound block F.CloseMethod(F.Block(statements)); } internal override bool HasSpecialName { get { return true; } } } private sealed partial class AnonymousTypePropertyGetAccessorSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { // Method body: // // { // return this.backingField; // } SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); F.CloseMethod(F.Block(F.Return(F.Field(F.This(), _property.BackingField)))); } internal override bool HasSpecialName { get { return true; } } } private sealed partial class AnonymousTypeEqualsMethodSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)this.ContainingType).Manager; SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); // Method body: // // { // $anonymous$ local = value as $anonymous$; // return (object)local == this || (local != null // && System.Collections.Generic.EqualityComparer<T_1>.Default.Equals(this.backingFld_1, local.backingFld_1) // ... // && System.Collections.Generic.EqualityComparer<T_N>.Default.Equals(this.backingFld_N, local.backingFld_N)); // } // Type and type expression AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; // local BoundAssignmentOperator assignmentToTemp; BoundLocal boundLocal = F.StoreToTemp(F.As(F.Parameter(_parameters[0]), anonymousType), out assignmentToTemp); // Generate: statement <= 'local = value as $anonymous$' BoundStatement assignment = F.ExpressionStatement(assignmentToTemp); // Generate expression for return statement // retExpression <= 'local != null' BoundExpression retExpression = F.Binary(BinaryOperatorKind.ObjectNotEqual, manager.System_Boolean, F.Convert(manager.System_Object, boundLocal), F.Null(manager.System_Object)); // Compare fields if (anonymousType.Properties.Length > 0) { var fields = ArrayBuilder<FieldSymbol>.GetInstance(anonymousType.Properties.Length); foreach (var prop in anonymousType.Properties) { fields.Add(prop.BackingField); } retExpression = MethodBodySynthesizer.GenerateFieldEquals(retExpression, boundLocal, fields, F); fields.Free(); } // Compare references retExpression = F.LogicalOr(F.ObjectEqual(F.This(), boundLocal), retExpression); // Final return statement BoundStatement retStatement = F.Return(retExpression); // Create a bound block F.CloseMethod(F.Block(ImmutableArray.Create<LocalSymbol>(boundLocal.LocalSymbol), assignment, retStatement)); } internal override bool HasSpecialName { get { return false; } } } private sealed partial class AnonymousTypeGetHashCodeMethodSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)this.ContainingType).Manager; SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); // Method body: // // HASH_FACTOR = 0xa5555529; // INIT_HASH = (...((0 * HASH_FACTOR) + GetFNVHashCode(backingFld_1.Name)) * HASH_FACTOR // + GetFNVHashCode(backingFld_2.Name)) * HASH_FACTOR // + ... // + GetFNVHashCode(backingFld_N.Name) // // { // return (...((INITIAL_HASH * HASH_FACTOR) + EqualityComparer<T_1>.Default.GetHashCode(this.backingFld_1)) * HASH_FACTOR // + EqualityComparer<T_2>.Default.GetHashCode(this.backingFld_2)) * HASH_FACTOR // ... // + EqualityComparer<T_N>.Default.GetHashCode(this.backingFld_N) // } // // Where GetFNVHashCode is the FNV-1a hash code. // Type expression AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; // INIT_HASH int initHash = 0; foreach (var property in anonymousType.Properties) { initHash = unchecked(initHash * MethodBodySynthesizer.HASH_FACTOR + Hash.GetFNVHashCode(property.BackingField.Name)); } // Generate expression for return statement // retExpression <= 'INITIAL_HASH' BoundExpression retExpression = F.Literal(initHash); // prepare symbols MethodSymbol equalityComparer_GetHashCode = manager.System_Collections_Generic_EqualityComparer_T__GetHashCode; MethodSymbol equalityComparer_get_Default = manager.System_Collections_Generic_EqualityComparer_T__get_Default; // bound HASH_FACTOR BoundLiteral boundHashFactor = null; // Process fields for (int index = 0; index < anonymousType.Properties.Length; index++) { retExpression = MethodBodySynthesizer.GenerateHashCombine(retExpression, equalityComparer_GetHashCode, equalityComparer_get_Default, ref boundHashFactor, F.Field(F.This(), anonymousType.Properties[index].BackingField), F); } // Create a bound block F.CloseMethod(F.Block(F.Return(retExpression))); } internal override bool HasSpecialName { get { return false; } } } private sealed partial class AnonymousTypeToStringMethodSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)this.ContainingType).Manager; SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); // Method body: // // { // return String.Format( // "{ <name1> = {0}", <name2> = {1}", ... <nameN> = {N-1}", // this.backingFld_1, // this.backingFld_2, // ... // this.backingFld_N // } // Type expression AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; // build arguments int fieldCount = anonymousType.Properties.Length; BoundExpression retExpression = null; if (fieldCount > 0) { // we do have fields, so have to use String.Format(...) BoundExpression[] arguments = new BoundExpression[fieldCount]; // process properties PooledStringBuilder formatString = PooledStringBuilder.GetInstance(); for (int i = 0; i < fieldCount; i++) { AnonymousTypePropertySymbol property = anonymousType.Properties[i]; // build format string formatString.Builder.AppendFormat(i == 0 ? "{{{{ {0} = {{{1}}}" : ", {0} = {{{1}}}", property.Name, i); // build argument arguments[i] = F.Convert(manager.System_Object, new BoundLoweredConditionalAccess(F.Syntax, F.Field(F.This(), property.BackingField), null, F.Call(new BoundConditionalReceiver( F.Syntax, id: i, type: property.BackingField.Type), manager.System_Object__ToString), null, id: i, type: manager.System_String), Conversion.ImplicitReference); } formatString.Builder.Append(" }}"); // add format string argument BoundExpression format = F.Literal(formatString.ToStringAndFree()); // Generate expression for return statement // retExpression <= System.String.Format(args) var formatMethod = manager.System_String__Format_IFormatProvider; retExpression = F.StaticCall(manager.System_String, formatMethod, F.Null(formatMethod.Parameters[0].Type), format, F.ArrayOrEmpty(manager.System_Object, arguments)); } else { // this is an empty anonymous type, just return "{ }" retExpression = F.Literal("{ }"); } F.CloseMethod(F.Block(F.Return(retExpression))); } internal override bool HasSpecialName { get { return false; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { private sealed partial class AnonymousTypeConstructorSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { // Method body: // // { // Object..ctor(); // this.backingField_1 = arg1; // ... // this.backingField_N = argN; // } SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); int paramCount = this.ParameterCount; // List of statements BoundStatement[] statements = new BoundStatement[paramCount + 2]; int statementIndex = 0; // explicit base constructor call Debug.Assert(ContainingType.BaseTypeNoUseSiteDiagnostics.SpecialType == SpecialType.System_Object); BoundExpression call = MethodCompiler.GenerateBaseParameterlessConstructorInitializer(this, diagnostics); if (call == null) { // This may happen if Object..ctor is not found or is inaccessible return; } statements[statementIndex++] = F.ExpressionStatement(call); if (paramCount > 0) { AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; Debug.Assert(anonymousType.Properties.Length == paramCount); // Assign fields for (int index = 0; index < this.ParameterCount; index++) { // Generate 'field' = 'parameter' statement statements[statementIndex++] = F.Assignment(F.Field(F.This(), anonymousType.Properties[index].BackingField), F.Parameter(_parameters[index])); } } // Final return statement statements[statementIndex++] = F.Return(); // Create a bound block F.CloseMethod(F.Block(statements)); } internal override bool HasSpecialName { get { return true; } } } private sealed partial class AnonymousTypePropertyGetAccessorSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { // Method body: // // { // return this.backingField; // } SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); F.CloseMethod(F.Block(F.Return(F.Field(F.This(), _property.BackingField)))); } internal override bool HasSpecialName { get { return true; } } } private sealed partial class AnonymousTypeEqualsMethodSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)this.ContainingType).Manager; SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); // Method body: // // { // $anonymous$ local = value as $anonymous$; // return (object)local == this || (local != null // && System.Collections.Generic.EqualityComparer<T_1>.Default.Equals(this.backingFld_1, local.backingFld_1) // ... // && System.Collections.Generic.EqualityComparer<T_N>.Default.Equals(this.backingFld_N, local.backingFld_N)); // } // Type and type expression AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; // local BoundAssignmentOperator assignmentToTemp; BoundLocal boundLocal = F.StoreToTemp(F.As(F.Parameter(_parameters[0]), anonymousType), out assignmentToTemp); // Generate: statement <= 'local = value as $anonymous$' BoundStatement assignment = F.ExpressionStatement(assignmentToTemp); // Generate expression for return statement // retExpression <= 'local != null' BoundExpression retExpression = F.Binary(BinaryOperatorKind.ObjectNotEqual, manager.System_Boolean, F.Convert(manager.System_Object, boundLocal), F.Null(manager.System_Object)); // Compare fields if (anonymousType.Properties.Length > 0) { var fields = ArrayBuilder<FieldSymbol>.GetInstance(anonymousType.Properties.Length); foreach (var prop in anonymousType.Properties) { fields.Add(prop.BackingField); } retExpression = MethodBodySynthesizer.GenerateFieldEquals(retExpression, boundLocal, fields, F); fields.Free(); } // Compare references retExpression = F.LogicalOr(F.ObjectEqual(F.This(), boundLocal), retExpression); // Final return statement BoundStatement retStatement = F.Return(retExpression); // Create a bound block F.CloseMethod(F.Block(ImmutableArray.Create<LocalSymbol>(boundLocal.LocalSymbol), assignment, retStatement)); } internal override bool HasSpecialName { get { return false; } } } private sealed partial class AnonymousTypeGetHashCodeMethodSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)this.ContainingType).Manager; SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); // Method body: // // HASH_FACTOR = 0xa5555529; // INIT_HASH = (...((0 * HASH_FACTOR) + GetFNVHashCode(backingFld_1.Name)) * HASH_FACTOR // + GetFNVHashCode(backingFld_2.Name)) * HASH_FACTOR // + ... // + GetFNVHashCode(backingFld_N.Name) // // { // return (...((INITIAL_HASH * HASH_FACTOR) + EqualityComparer<T_1>.Default.GetHashCode(this.backingFld_1)) * HASH_FACTOR // + EqualityComparer<T_2>.Default.GetHashCode(this.backingFld_2)) * HASH_FACTOR // ... // + EqualityComparer<T_N>.Default.GetHashCode(this.backingFld_N) // } // // Where GetFNVHashCode is the FNV-1a hash code. // Type expression AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; // INIT_HASH int initHash = 0; foreach (var property in anonymousType.Properties) { initHash = unchecked(initHash * MethodBodySynthesizer.HASH_FACTOR + Hash.GetFNVHashCode(property.BackingField.Name)); } // Generate expression for return statement // retExpression <= 'INITIAL_HASH' BoundExpression retExpression = F.Literal(initHash); // prepare symbols MethodSymbol equalityComparer_GetHashCode = manager.System_Collections_Generic_EqualityComparer_T__GetHashCode; MethodSymbol equalityComparer_get_Default = manager.System_Collections_Generic_EqualityComparer_T__get_Default; // bound HASH_FACTOR BoundLiteral boundHashFactor = null; // Process fields for (int index = 0; index < anonymousType.Properties.Length; index++) { retExpression = MethodBodySynthesizer.GenerateHashCombine(retExpression, equalityComparer_GetHashCode, equalityComparer_get_Default, ref boundHashFactor, F.Field(F.This(), anonymousType.Properties[index].BackingField), F); } // Create a bound block F.CloseMethod(F.Block(F.Return(retExpression))); } internal override bool HasSpecialName { get { return false; } } } private sealed partial class AnonymousTypeToStringMethodSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)this.ContainingType).Manager; SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); // Method body: // // { // return String.Format( // "{ <name1> = {0}", <name2> = {1}", ... <nameN> = {N-1}", // this.backingFld_1, // this.backingFld_2, // ... // this.backingFld_N // } // Type expression AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; // build arguments int fieldCount = anonymousType.Properties.Length; BoundExpression retExpression = null; if (fieldCount > 0) { // we do have fields, so have to use String.Format(...) BoundExpression[] arguments = new BoundExpression[fieldCount]; // process properties PooledStringBuilder formatString = PooledStringBuilder.GetInstance(); for (int i = 0; i < fieldCount; i++) { AnonymousTypePropertySymbol property = anonymousType.Properties[i]; // build format string formatString.Builder.AppendFormat(i == 0 ? "{{{{ {0} = {{{1}}}" : ", {0} = {{{1}}}", property.Name, i); // build argument arguments[i] = F.Convert(manager.System_Object, new BoundLoweredConditionalAccess(F.Syntax, F.Field(F.This(), property.BackingField), null, F.Call(new BoundConditionalReceiver( F.Syntax, id: i, type: property.BackingField.Type), manager.System_Object__ToString), null, id: i, type: manager.System_String), Conversion.ImplicitReference); } formatString.Builder.Append(" }}"); // add format string argument BoundExpression format = F.Literal(formatString.ToStringAndFree()); // Generate expression for return statement // retExpression <= System.String.Format(args) var formatMethod = manager.System_String__Format_IFormatProvider; retExpression = F.StaticCall(manager.System_String, formatMethod, F.Null(formatMethod.Parameters[0].Type), format, F.ArrayOrEmpty(manager.System_Object, arguments)); } else { // this is an empty anonymous type, just return "{ }" retExpression = F.Literal("{ }"); } F.CloseMethod(F.Block(F.Return(retExpression))); } internal override bool HasSpecialName { get { return false; } } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingChecksumWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal readonly struct UnitTestingChecksumWrapper { private Checksum UnderlyingObject { get; } public UnitTestingChecksumWrapper(Checksum underlyingObject) => UnderlyingObject = underlyingObject ?? throw new ArgumentNullException(nameof(underlyingObject)); public bool IsEqualTo(UnitTestingChecksumWrapper other) => other.UnderlyingObject == UnderlyingObject; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal readonly struct UnitTestingChecksumWrapper { private Checksum UnderlyingObject { get; } public UnitTestingChecksumWrapper(Checksum underlyingObject) => UnderlyingObject = underlyingObject ?? throw new ArgumentNullException(nameof(underlyingObject)); public bool IsEqualTo(UnitTestingChecksumWrapper other) => other.UnderlyingObject == UnderlyingObject; } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/Navigation/IDocumentNavigationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Navigation { internal interface IDocumentNavigationService : IWorkspaceService { /// <summary> /// Determines whether it is possible to navigate to the given position in the specified document. /// </summary> bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given line/offset in the specified document. /// </summary> bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given virtual position in the specified document. /// </summary> bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken); /// <summary> /// Navigates to the given position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken); /// <summary> /// Navigates to the given line/offset in the specified document, opening it if necessary. /// </summary> bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken); /// <summary> /// Navigates to the given virtual position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken); } internal static class IDocumentNavigationServiceExtensions { public static bool CanNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.CanNavigateToPosition(workspace, documentId, position, virtualSpace: 0, cancellationToken); public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options: null, cancellationToken); public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options, allowInvalidSpan: false, cancellationToken); public static bool TryNavigateToLineAndOffset(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => service.TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options: null, cancellationToken); public static bool TryNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.TryNavigateToPosition(workspace, documentId, position, virtualSpace: 0, options: null, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Navigation { internal interface IDocumentNavigationService : IWorkspaceService { /// <summary> /// Determines whether it is possible to navigate to the given position in the specified document. /// </summary> bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given line/offset in the specified document. /// </summary> bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given virtual position in the specified document. /// </summary> bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken); /// <summary> /// Navigates to the given position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken); /// <summary> /// Navigates to the given line/offset in the specified document, opening it if necessary. /// </summary> bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken); /// <summary> /// Navigates to the given virtual position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken); } internal static class IDocumentNavigationServiceExtensions { public static bool CanNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.CanNavigateToPosition(workspace, documentId, position, virtualSpace: 0, cancellationToken); public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options: null, cancellationToken); public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options, allowInvalidSpan: false, cancellationToken); public static bool TryNavigateToLineAndOffset(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => service.TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options: null, cancellationToken); public static bool TryNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.TryNavigateToPosition(workspace, documentId, position, virtualSpace: 0, options: null, cancellationToken); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/MemberInfo/TypeImpl.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using Microsoft.VisualStudio.Debugger.Metadata; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal class TypeImpl : Type { internal readonly System.Type Type; internal TypeImpl(System.Type type) { Debug.Assert(type != null); this.Type = type; } public static explicit operator TypeImpl(System.Type type) { return type == null ? null : new TypeImpl(type); } public override Assembly Assembly { get { return new AssemblyImpl(this.Type.Assembly); } } public override string AssemblyQualifiedName { get { throw new NotImplementedException(); } } public override Type BaseType { get { return (TypeImpl)this.Type.BaseType; } } public override bool ContainsGenericParameters { get { throw new NotImplementedException(); } } public override Type DeclaringType { get { return (TypeImpl)this.Type.DeclaringType; } } public override bool IsEquivalentTo(MemberInfo other) { throw new NotImplementedException(); } public override string FullName { get { return this.Type.FullName; } } public override Guid GUID { get { throw new NotImplementedException(); } } public override MemberTypes MemberType { get { return (MemberTypes)this.Type.MemberType; } } public override int MetadataToken { get { throw new NotImplementedException(); } } public override Module Module { get { return new ModuleImpl(this.Type.Module); } } public override string Name { get { return Type.Name; } } public override string Namespace { get { return Type.Namespace; } } public override Type ReflectedType { get { throw new NotImplementedException(); } } public override Type UnderlyingSystemType { get { return (TypeImpl)Type.UnderlyingSystemType; } } public override bool Equals(Type o) { return o != null && o.GetType() == this.GetType() && ((TypeImpl)o).Type == this.Type; } public override bool Equals(object objOther) { return Equals(objOther as Type); } public override int GetHashCode() { return Type.GetHashCode(); } public override int GetArrayRank() { return Type.GetArrayRank(); } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return Type.GetConstructors((System.Reflection.BindingFlags)bindingAttr).Select(c => new ConstructorInfoImpl(c)).ToArray(); } public override object[] GetCustomAttributes(bool inherit) { throw new NotImplementedException(); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override IList<CustomAttributeData> GetCustomAttributesData() { return Type.GetCustomAttributesData().Select(a => new CustomAttributeDataImpl(a)).ToArray(); } public override Type GetElementType() { return (TypeImpl)(Type.GetElementType()); } public override EventInfo GetEvent(string name, BindingFlags flags) { throw new NotImplementedException(); } public override EventInfo[] GetEvents(BindingFlags flags) { throw new NotImplementedException(); } public override FieldInfo GetField(string name, BindingFlags bindingAttr) { var field = Type.GetField(name, (System.Reflection.BindingFlags)bindingAttr); return (field == null) ? null : new FieldInfoImpl(field); } public override FieldInfo[] GetFields(BindingFlags flags) { return Type.GetFields((System.Reflection.BindingFlags)flags).Select(f => new FieldInfoImpl(f)).ToArray(); } public override Type GetGenericTypeDefinition() { return (TypeImpl)this.Type.GetGenericTypeDefinition(); } public override Type[] GetGenericArguments() { return Type.GetGenericArguments().Select(t => new TypeImpl(t)).ToArray(); } public override Type GetInterface(string name, bool ignoreCase) { throw new NotImplementedException(); } public override Type[] GetInterfaces() { return Type.GetInterfaces().Select(i => new TypeImpl(i)).ToArray(); } public override System.Reflection.InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotImplementedException(); } public override MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { return Type.GetMember(name, (System.Reflection.BindingFlags)bindingAttr).Select(GetMember).ToArray(); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return Type.GetMembers((System.Reflection.BindingFlags)bindingAttr).Select(GetMember).ToArray(); } private static MemberInfo GetMember(System.Reflection.MemberInfo member) { switch (member.MemberType) { case System.Reflection.MemberTypes.Constructor: return new ConstructorInfoImpl((System.Reflection.ConstructorInfo)member); case System.Reflection.MemberTypes.Event: return new EventInfoImpl((System.Reflection.EventInfo)member); case System.Reflection.MemberTypes.Field: return new FieldInfoImpl((System.Reflection.FieldInfo)member); case System.Reflection.MemberTypes.Method: return new MethodInfoImpl((System.Reflection.MethodInfo)member); case System.Reflection.MemberTypes.NestedType: return new TypeImpl((System.Reflection.TypeInfo)member); case System.Reflection.MemberTypes.Property: return new PropertyInfoImpl((System.Reflection.PropertyInfo)member); default: throw new NotImplementedException(member.MemberType.ToString()); } } public override MethodInfo[] GetMethods(BindingFlags flags) { return this.Type.GetMethods((System.Reflection.BindingFlags)flags).Select(m => new MethodInfoImpl(m)).ToArray(); } public override Type GetNestedType(string name, BindingFlags bindingAttr) { throw new NotImplementedException(); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotImplementedException(); } public override PropertyInfo[] GetProperties(BindingFlags flags) { throw new NotImplementedException(); } 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 IsAssignableFrom(Type c) { throw new NotImplementedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override bool IsEnum { get { return this.Type.IsEnum; } } public override bool IsGenericParameter { get { return Type.IsGenericParameter; } } public override bool IsGenericType { get { return Type.IsGenericType; } } public override bool IsGenericTypeDefinition { get { return Type.IsGenericTypeDefinition; } } public override int GenericParameterPosition { get { return Type.GenericParameterPosition; } } public override ExplicitInterfaceInfo[] GetExplicitInterfaceImplementations() { var interfaceMaps = Type.GetInterfaces().Select(i => Type.GetInterfaceMap(i)); // A dot is neither necessary nor sufficient for determining whether a member explicitly // implements an interface member, but it does characterize the set of members we're // interested in displaying differently. For example, if the property is from VB, it will // be an explicit interface implementation, but will not have a dot. Therefore, this is // good enough for our mock implementation. var infos = interfaceMaps.SelectMany(map => map.InterfaceMethods.Zip(map.TargetMethods, (interfaceMethod, implementingMethod) => implementingMethod.Name.Contains(".") ? MakeExplicitInterfaceInfo(interfaceMethod, implementingMethod) : null)); return infos.Where(i => i != null).ToArray(); } private static ExplicitInterfaceInfo MakeExplicitInterfaceInfo(System.Reflection.MethodInfo interfaceMethod, System.Reflection.MethodInfo implementingMethod) { return (ExplicitInterfaceInfo)typeof(ExplicitInterfaceInfo).Instantiate( new MethodInfoImpl(interfaceMethod), new MethodInfoImpl(implementingMethod)); } public override bool IsInstanceOfType(object o) { throw new NotImplementedException(); } public override bool IsSubclassOf(Type c) { throw new NotImplementedException(); } public override Type MakeArrayType() { return (TypeImpl)this.Type.MakeArrayType(); } public override Type MakeArrayType(int rank) { return (TypeImpl)this.Type.MakeArrayType(rank); } public override Type MakeByRefType() { throw new NotImplementedException(); } public override Type MakeGenericType(params Type[] argTypes) { return (TypeImpl)this.Type.MakeGenericType(argTypes.Select(t => ((TypeImpl)t).Type).ToArray()); } public override Type MakePointerType() { return (TypeImpl)this.Type.MakePointerType(); } protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { System.Reflection.TypeAttributes result = 0; if (this.Type.IsClass) { result |= System.Reflection.TypeAttributes.Class; } if (this.Type.IsInterface) { result |= System.Reflection.TypeAttributes.Interface; } if (this.Type.IsAbstract) { result |= System.Reflection.TypeAttributes.Abstract; } if (this.Type.IsSealed) { result |= System.Reflection.TypeAttributes.Sealed; } return result; } protected override bool IsValueTypeImpl() { return this.Type.IsValueType; } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { Debug.Assert(binder == null, "NYI"); Debug.Assert(returnType == null, "NYI"); Debug.Assert(types == null, "NYI"); Debug.Assert(modifiers == null, "NYI"); return new PropertyInfoImpl(Type.GetProperty(name, (System.Reflection.BindingFlags)bindingAttr, binder: null, returnType: null, types: new System.Type[0], modifiers: new System.Reflection.ParameterModifier[0])); } protected override TypeCode GetTypeCodeImpl() { return (TypeCode)System.Type.GetTypeCode(this.Type); } protected override bool HasElementTypeImpl() { return this.Type.HasElementType; } protected override bool IsArrayImpl() { return Type.IsArray; } protected override bool IsByRefImpl() { return Type.IsByRef; } protected override bool IsCOMObjectImpl() { throw new NotImplementedException(); } protected override bool IsContextfulImpl() { throw new NotImplementedException(); } protected override bool IsMarshalByRefImpl() { throw new NotImplementedException(); } protected override bool IsPointerImpl() { return Type.IsPointer; } protected override bool IsPrimitiveImpl() { throw new NotImplementedException(); } public override bool IsAssignableTo(Type c) { throw new NotImplementedException(); } public override string ToString() { return this.Type.ToString(); } public override Type[] GetInterfacesOnType() { var t = this.Type; var builder = ArrayBuilder<Type>.GetInstance(); foreach (var @interface in t.GetInterfaces()) { var map = t.GetInterfaceMap(@interface); if (map.TargetMethods.Any(m => m.DeclaringType == t)) { builder.Add((TypeImpl)@interface); } } return builder.ToArrayAndFree(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using Microsoft.VisualStudio.Debugger.Metadata; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal class TypeImpl : Type { internal readonly System.Type Type; internal TypeImpl(System.Type type) { Debug.Assert(type != null); this.Type = type; } public static explicit operator TypeImpl(System.Type type) { return type == null ? null : new TypeImpl(type); } public override Assembly Assembly { get { return new AssemblyImpl(this.Type.Assembly); } } public override string AssemblyQualifiedName { get { throw new NotImplementedException(); } } public override Type BaseType { get { return (TypeImpl)this.Type.BaseType; } } public override bool ContainsGenericParameters { get { throw new NotImplementedException(); } } public override Type DeclaringType { get { return (TypeImpl)this.Type.DeclaringType; } } public override bool IsEquivalentTo(MemberInfo other) { throw new NotImplementedException(); } public override string FullName { get { return this.Type.FullName; } } public override Guid GUID { get { throw new NotImplementedException(); } } public override MemberTypes MemberType { get { return (MemberTypes)this.Type.MemberType; } } public override int MetadataToken { get { throw new NotImplementedException(); } } public override Module Module { get { return new ModuleImpl(this.Type.Module); } } public override string Name { get { return Type.Name; } } public override string Namespace { get { return Type.Namespace; } } public override Type ReflectedType { get { throw new NotImplementedException(); } } public override Type UnderlyingSystemType { get { return (TypeImpl)Type.UnderlyingSystemType; } } public override bool Equals(Type o) { return o != null && o.GetType() == this.GetType() && ((TypeImpl)o).Type == this.Type; } public override bool Equals(object objOther) { return Equals(objOther as Type); } public override int GetHashCode() { return Type.GetHashCode(); } public override int GetArrayRank() { return Type.GetArrayRank(); } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return Type.GetConstructors((System.Reflection.BindingFlags)bindingAttr).Select(c => new ConstructorInfoImpl(c)).ToArray(); } public override object[] GetCustomAttributes(bool inherit) { throw new NotImplementedException(); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override IList<CustomAttributeData> GetCustomAttributesData() { return Type.GetCustomAttributesData().Select(a => new CustomAttributeDataImpl(a)).ToArray(); } public override Type GetElementType() { return (TypeImpl)(Type.GetElementType()); } public override EventInfo GetEvent(string name, BindingFlags flags) { throw new NotImplementedException(); } public override EventInfo[] GetEvents(BindingFlags flags) { throw new NotImplementedException(); } public override FieldInfo GetField(string name, BindingFlags bindingAttr) { var field = Type.GetField(name, (System.Reflection.BindingFlags)bindingAttr); return (field == null) ? null : new FieldInfoImpl(field); } public override FieldInfo[] GetFields(BindingFlags flags) { return Type.GetFields((System.Reflection.BindingFlags)flags).Select(f => new FieldInfoImpl(f)).ToArray(); } public override Type GetGenericTypeDefinition() { return (TypeImpl)this.Type.GetGenericTypeDefinition(); } public override Type[] GetGenericArguments() { return Type.GetGenericArguments().Select(t => new TypeImpl(t)).ToArray(); } public override Type GetInterface(string name, bool ignoreCase) { throw new NotImplementedException(); } public override Type[] GetInterfaces() { return Type.GetInterfaces().Select(i => new TypeImpl(i)).ToArray(); } public override System.Reflection.InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotImplementedException(); } public override MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { return Type.GetMember(name, (System.Reflection.BindingFlags)bindingAttr).Select(GetMember).ToArray(); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return Type.GetMembers((System.Reflection.BindingFlags)bindingAttr).Select(GetMember).ToArray(); } private static MemberInfo GetMember(System.Reflection.MemberInfo member) { switch (member.MemberType) { case System.Reflection.MemberTypes.Constructor: return new ConstructorInfoImpl((System.Reflection.ConstructorInfo)member); case System.Reflection.MemberTypes.Event: return new EventInfoImpl((System.Reflection.EventInfo)member); case System.Reflection.MemberTypes.Field: return new FieldInfoImpl((System.Reflection.FieldInfo)member); case System.Reflection.MemberTypes.Method: return new MethodInfoImpl((System.Reflection.MethodInfo)member); case System.Reflection.MemberTypes.NestedType: return new TypeImpl((System.Reflection.TypeInfo)member); case System.Reflection.MemberTypes.Property: return new PropertyInfoImpl((System.Reflection.PropertyInfo)member); default: throw new NotImplementedException(member.MemberType.ToString()); } } public override MethodInfo[] GetMethods(BindingFlags flags) { return this.Type.GetMethods((System.Reflection.BindingFlags)flags).Select(m => new MethodInfoImpl(m)).ToArray(); } public override Type GetNestedType(string name, BindingFlags bindingAttr) { throw new NotImplementedException(); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotImplementedException(); } public override PropertyInfo[] GetProperties(BindingFlags flags) { throw new NotImplementedException(); } 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 IsAssignableFrom(Type c) { throw new NotImplementedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override bool IsEnum { get { return this.Type.IsEnum; } } public override bool IsGenericParameter { get { return Type.IsGenericParameter; } } public override bool IsGenericType { get { return Type.IsGenericType; } } public override bool IsGenericTypeDefinition { get { return Type.IsGenericTypeDefinition; } } public override int GenericParameterPosition { get { return Type.GenericParameterPosition; } } public override ExplicitInterfaceInfo[] GetExplicitInterfaceImplementations() { var interfaceMaps = Type.GetInterfaces().Select(i => Type.GetInterfaceMap(i)); // A dot is neither necessary nor sufficient for determining whether a member explicitly // implements an interface member, but it does characterize the set of members we're // interested in displaying differently. For example, if the property is from VB, it will // be an explicit interface implementation, but will not have a dot. Therefore, this is // good enough for our mock implementation. var infos = interfaceMaps.SelectMany(map => map.InterfaceMethods.Zip(map.TargetMethods, (interfaceMethod, implementingMethod) => implementingMethod.Name.Contains(".") ? MakeExplicitInterfaceInfo(interfaceMethod, implementingMethod) : null)); return infos.Where(i => i != null).ToArray(); } private static ExplicitInterfaceInfo MakeExplicitInterfaceInfo(System.Reflection.MethodInfo interfaceMethod, System.Reflection.MethodInfo implementingMethod) { return (ExplicitInterfaceInfo)typeof(ExplicitInterfaceInfo).Instantiate( new MethodInfoImpl(interfaceMethod), new MethodInfoImpl(implementingMethod)); } public override bool IsInstanceOfType(object o) { throw new NotImplementedException(); } public override bool IsSubclassOf(Type c) { throw new NotImplementedException(); } public override Type MakeArrayType() { return (TypeImpl)this.Type.MakeArrayType(); } public override Type MakeArrayType(int rank) { return (TypeImpl)this.Type.MakeArrayType(rank); } public override Type MakeByRefType() { throw new NotImplementedException(); } public override Type MakeGenericType(params Type[] argTypes) { return (TypeImpl)this.Type.MakeGenericType(argTypes.Select(t => ((TypeImpl)t).Type).ToArray()); } public override Type MakePointerType() { return (TypeImpl)this.Type.MakePointerType(); } protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { System.Reflection.TypeAttributes result = 0; if (this.Type.IsClass) { result |= System.Reflection.TypeAttributes.Class; } if (this.Type.IsInterface) { result |= System.Reflection.TypeAttributes.Interface; } if (this.Type.IsAbstract) { result |= System.Reflection.TypeAttributes.Abstract; } if (this.Type.IsSealed) { result |= System.Reflection.TypeAttributes.Sealed; } return result; } protected override bool IsValueTypeImpl() { return this.Type.IsValueType; } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { Debug.Assert(binder == null, "NYI"); Debug.Assert(returnType == null, "NYI"); Debug.Assert(types == null, "NYI"); Debug.Assert(modifiers == null, "NYI"); return new PropertyInfoImpl(Type.GetProperty(name, (System.Reflection.BindingFlags)bindingAttr, binder: null, returnType: null, types: new System.Type[0], modifiers: new System.Reflection.ParameterModifier[0])); } protected override TypeCode GetTypeCodeImpl() { return (TypeCode)System.Type.GetTypeCode(this.Type); } protected override bool HasElementTypeImpl() { return this.Type.HasElementType; } protected override bool IsArrayImpl() { return Type.IsArray; } protected override bool IsByRefImpl() { return Type.IsByRef; } protected override bool IsCOMObjectImpl() { throw new NotImplementedException(); } protected override bool IsContextfulImpl() { throw new NotImplementedException(); } protected override bool IsMarshalByRefImpl() { throw new NotImplementedException(); } protected override bool IsPointerImpl() { return Type.IsPointer; } protected override bool IsPrimitiveImpl() { throw new NotImplementedException(); } public override bool IsAssignableTo(Type c) { throw new NotImplementedException(); } public override string ToString() { return this.Type.ToString(); } public override Type[] GetInterfacesOnType() { var t = this.Type; var builder = ArrayBuilder<Type>.GetInstance(); foreach (var @interface in t.GetInterfaces()) { var map = t.GetInterfaceMap(@interface); if (map.TargetMethods.Any(m => m.DeclaringType == t)) { builder.Add((TypeImpl)@interface); } } return builder.ToArrayAndFree(); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./docs/compilers/API Notes/10-29-19.md
## API Review Notes for September 30th, 2019 ### Changes reviewed Starting commit: `38c90f8401f9e3ee5fb7c82aac36f6b85fdda979` Ending Commit: `b8a5611e3db4f7ac3b5e1404b129304b5baf843e` ### Notes IVariableDeclarationOperation: - What does scripting do for using local declarations in IOperation? VariableDeclarationKind - Is Default the right kind? Should we use Other instead? - Documentation on Default isn't great because everything is also a declaration - Should we add other kinds for foreach, pattern, using statement - Action: Add new parent node to represent IUsingDeclarationOperation to parent the IVariableDeclarationGroupOperation, remove VariableDeclarationKind Simplifier.AddImportsAnnotation - Should we use `Using` or `Imports`? - We have existing precedent for using C# where in conflict, but the existing stuff around using also uses Imports. We'll stick with the name Are we holding these meetings too late? - Probably. We should look at holding these before ask mode ends in the future, rather than monthy.
## API Review Notes for September 30th, 2019 ### Changes reviewed Starting commit: `38c90f8401f9e3ee5fb7c82aac36f6b85fdda979` Ending Commit: `b8a5611e3db4f7ac3b5e1404b129304b5baf843e` ### Notes IVariableDeclarationOperation: - What does scripting do for using local declarations in IOperation? VariableDeclarationKind - Is Default the right kind? Should we use Other instead? - Documentation on Default isn't great because everything is also a declaration - Should we add other kinds for foreach, pattern, using statement - Action: Add new parent node to represent IUsingDeclarationOperation to parent the IVariableDeclarationGroupOperation, remove VariableDeclarationKind Simplifier.AddImportsAnnotation - Should we use `Using` or `Imports`? - We have existing precedent for using C# where in conflict, but the existing stuff around using also uses Imports. We'll stick with the name Are we holding these meetings too late? - Probably. We should look at holding these before ask mode ends in the future, rather than monthy.
-1